Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(redbark): add australian bank sync (redbark) (#2794)

Oscarc6a240a18351
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index d5bdde8bf0..c745d3caa3 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -16,6 +16,7 @@ class AccountsController < ApplicationController
@plaid_items = visible_provider_items(family.plaid_items.ordered.with_attached_logo.includes(:plaid_accounts))
@simplefin_items = visible_provider_items(family.simplefin_items.ordered.with_attached_logo)
@lunchflow_items = visible_provider_items(family.lunchflow_items.ordered.with_attached_logo.includes(:lunchflow_accounts))
+ @redbark_items = visible_provider_items(family.redbark_items.ordered.with_attached_logo.includes(:redbark_accounts))
@akahu_items = visible_provider_items(family.akahu_items.ordered.with_attached_logo.includes(:akahu_accounts))
@up_items = visible_provider_items(family.up_items.ordered.with_attached_logo.includes(:up_accounts))
@enable_banking_items = visible_provider_items(family.enable_banking_items.ordered.with_attached_logo)
@@ -262,6 +263,7 @@ class AccountsController < ApplicationController
@plaid_items,
@simplefin_items,
@lunchflow_items,
+ @redbark_items,
@akahu_items,
@up_items,
@enable_banking_items,
@@ -430,6 +432,13 @@ class AccountsController < ApplicationController
@sophtron_sync_stats_map[item.id] = latest_sync&.sync_stats || {}
end
+ # Redbark sync stats
+ @redbark_sync_stats_map = {}
+ @redbark_items.each do |item|
+ latest_sync = item.latest_sync_record
+ @redbark_sync_stats_map[item.id] = latest_sync&.sync_stats || {}
+ end
+
# Mercury sync stats
@mercury_sync_stats_map = {}
@mercury_items.each do |item|
diff --git a/app/controllers/redbark_items_controller.rb b/app/controllers/redbark_items_controller.rb
new file mode 100644
index 0000000000..0076a03027
--- /dev/null
+++ b/app/controllers/redbark_items_controller.rb
@@ -0,0 +1,360 @@
+# frozen_string_literal: true
+
+class RedbarkItemsController < ApplicationController
+ ALLOWED_ACCOUNTABLE_TYPES = %w[Depository CreditCard Investment Loan OtherAsset OtherLiability Crypto Property Vehicle].freeze
+
+ before_action :set_redbark_item, only: [ :update, :destroy, :sync, :setup_accounts, :complete_account_setup ]
+ before_action :require_admin!, only: [ :create, :select_accounts, :select_existing_account, :link_existing_account, :update, :destroy, :sync, :setup_accounts, :complete_account_setup ]
+
+ def create
+ @redbark_item = Current.family.redbark_items.build(redbark_item_params)
+ @redbark_item.name ||= t("redbark_items.default_name")
+
+ if @redbark_item.save
+ # Trigger the initial sync so accounts appear without a manual refresh
+ @redbark_item.sync_later
+
+ if turbo_frame_request?
+ flash.now[:notice] = t(".success")
+ @redbark_items = Current.family.redbark_items.ordered
+ render turbo_stream: [
+ turbo_stream.replace(
+ "redbark-providers-panel",
+ partial: "settings/providers/redbark_panel",
+ locals: { redbark_items: @redbark_items }
+ ),
+ *flash_notification_stream_items
+ ]
+ else
+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other
+ end
+ else
+ @error_message = @redbark_item.errors.full_messages.join(", ")
+
+ if turbo_frame_request?
+ render turbo_stream: turbo_stream.replace(
+ "redbark-providers-panel",
+ partial: "settings/providers/redbark_panel",
+ locals: { error_message: @error_message }
+ ), status: :unprocessable_entity
+ else
+ redirect_to settings_providers_path, alert: @error_message, status: :see_other
+ end
+ end
+ end
+
+ def update
+ update_params = redbark_item_params
+ # A fresh key means the connection can be retried - clear requires_update
+ update_params = update_params.merge(status: :good) if update_params[:api_key].present?
+
+ if @redbark_item.update(update_params)
+ # Rotated credentials should be exercised right away
+ @redbark_item.sync_later if update_params[:api_key].present? && !@redbark_item.syncing?
+
+ if turbo_frame_request?
+ flash.now[:notice] = t(".success")
+ @redbark_items = Current.family.redbark_items.ordered
+ render turbo_stream: [
+ turbo_stream.replace(
+ "redbark-providers-panel",
+ partial: "settings/providers/redbark_panel",
+ locals: { redbark_items: @redbark_items }
+ ),
+ *flash_notification_stream_items
+ ]
+ else
+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other
+ end
+ else
+ @error_message = @redbark_item.errors.full_messages.join(", ")
+
+ if turbo_frame_request?
+ render turbo_stream: turbo_stream.replace(
+ "redbark-providers-panel",
+ partial: "settings/providers/redbark_panel",
+ locals: { error_message: @error_message }
+ ), status: :unprocessable_entity
+ else
+ redirect_to settings_providers_path, alert: @error_message, status: :see_other
+ end
+ end
+ end
+
+ def destroy
+ # Detach provider links before scheduling deletion; abort if anything
+ # failed to unlink so we never orphan holdings or provider links
+ unlink_results = @redbark_item.unlink_all!(dry_run: false)
+ failed = unlink_results.select { |r| r[:error].present? }
+
+ if failed.any?
+ redirect_to settings_providers_path, alert: t(".unlink_failed", count: failed.count), status: :see_other
+ return
+ end
+
+ @redbark_item.destroy_later
+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other
+ end
+
+ def sync
+ unless @redbark_item.syncing?
+ @redbark_item.sync_later
+ end
+
+ respond_to do |format|
+ format.html { redirect_back_or_to accounts_path }
+ format.json { head :ok }
+ end
+ end
+
+ # Collection actions for account linking flow
+
+ def select_accounts
+ redbark_item = Current.family.redbark_items.first
+ unless redbark_item&.credentials_configured?
+ if turbo_frame_request?
+ render partial: "redbark_items/setup_required", layout: false
+ else
+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")
+ end
+ return
+ end
+
+ # The account-linking UI lives in the setup_accounts view
+ redirect_to setup_accounts_redbark_item_path(redbark_item, return_to: safe_return_to_path)
+ end
+
+ def select_existing_account
+ @account = Current.family.accounts.find(params[:account_id])
+ @redbark_item = Current.family.redbark_items.first
+
+ unless @redbark_item&.credentials_configured?
+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")
+ return
+ end
+
+ @redbark_accounts = @redbark_item.redbark_accounts
+ .without_linked
+ .order(:name)
+ end
+
+ def link_existing_account
+ account = Current.family.accounts.find(params[:account_id])
+ redbark_item = Current.family.redbark_items.first
+
+ unless redbark_item&.credentials_configured?
+ redirect_to settings_providers_path, alert: t(".no_api_key")
+ return
+ end
+
+ redbark_account = redbark_item.redbark_accounts.find(params[:redbark_account_id])
+
+ if redbark_account.account_provider.present?
+ redirect_to account_path(account), alert: t(".provider_account_already_linked")
+ return
+ end
+
+ if account.account_providers.exists?
+ redirect_to account_path(account), alert: t(".account_already_linked")
+ return
+ end
+
+ redbark_account.ensure_account_provider!(account)
+ redbark_account.update!(ignored: false)
+ redbark_item.sync_later unless redbark_item.syncing?
+
+ redirect_to account_path(account), notice: t(".success", account_name: account.name)
+ end
+
+ def setup_accounts
+ # A fresh connection has no imported accounts yet - fetch them inline so
+ # the setup dialog is usable straight after the API key is saved
+ @api_error = fetch_redbark_accounts_from_api
+
+ @unlinked_accounts = @redbark_item.unlinked_redbark_accounts.order(:name)
+
+ if @unlinked_accounts.empty? && @api_error.nil?
+ redirect_to accounts_path, notice: t(".all_accounts_linked")
+ end
+ end
+
+ def complete_account_setup
+ account_configs = params[:accounts] || {}
+
+ if account_configs.empty?
+ redirect_to setup_accounts_redbark_item_path(@redbark_item), alert: t(".no_accounts")
+ return
+ end
+
+ created_count = 0
+ skipped_count = 0
+ failed_count = 0
+
+ account_configs.each do |redbark_account_id, config|
+ redbark_account = @redbark_item.redbark_accounts.find_by(id: redbark_account_id)
+ next unless redbark_account
+ next if redbark_account.account_provider.present?
+
+ # Remember the user's choice to skip so the account stops resurfacing
+ # as "needs setup" on every sync
+ if config[:account_type] == "skip" || config[:account_type].blank?
+ redbark_account.update!(ignored: true)
+ skipped_count += 1
+ next
+ end
+
+ accountable_type = infer_accountable_type(config[:account_type], config[:subtype])
+
+ # Atomic: roll back the manual account if linking the provider fails
+ ActiveRecord::Base.transaction do
+ account = create_account_from_redbark(redbark_account, accountable_type, config)
+ redbark_account.ensure_account_provider!(account)
+ redbark_account.update!(ignored: false)
+ redbark_account.update!(sync_start_date: config[:sync_start_date]) if config[:sync_start_date].present?
+ end
+ created_count += 1
+ rescue => e
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "error",
+ message: "Redbark account setup failed",
+ source: self.class.name,
+ provider_key: "redbark",
+ family: Current.family,
+ metadata: { redbark_account_id: redbark_account_id, error_class: e.class.name, error: e.message }
+ )
+ failed_count += 1
+ end
+
+ @redbark_item.sync_later if created_count > 0 && !@redbark_item.syncing?
+
+ if failed_count > 0
+ redirect_to setup_accounts_redbark_item_path(@redbark_item), alert: t(".setup_failed", count: failed_count)
+ elsif created_count > 0
+ redirect_to accounts_path, notice: t(".success", count: created_count)
+ elsif skipped_count > 0
+ redirect_to accounts_path, notice: t(".all_skipped")
+ else
+ redirect_to setup_accounts_redbark_item_path(@redbark_item), alert: t(".creation_failed_generic")
+ end
+ end
+
+ private
+
+ def set_redbark_item
+ @redbark_item = Current.family.redbark_items.find(params[:id])
+ end
+
+ # Imports accounts synchronously when the item has none yet.
+ # Returns nil on success, or an error message string on failure.
+ def fetch_redbark_accounts_from_api
+ return nil if @redbark_item.redbark_accounts.any?
+ return t("redbark_items.setup_accounts.no_api_key") unless @redbark_item.credentials_configured?
+
+ @redbark_item.import_latest_redbark_data
+ nil
+ rescue Provider::Redbark::Error => e
+ t("redbark_items.setup_accounts.api_error", message: e.message)
+ rescue StandardError => e
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "error",
+ message: "Inline Redbark account fetch failed",
+ source: self.class.name,
+ provider_key: "redbark",
+ family: Current.family,
+ metadata: { redbark_item_id: @redbark_item.id, error_class: e.class.name, error: e.message }
+ )
+ t("redbark_items.setup_accounts.api_error", message: e.message)
+ end
+
+ # Only allow internal relative paths in return_to
+ def safe_return_to_path
+ return nil if params[:return_to].blank?
+
+ return_to = params[:return_to].to_s
+
+ begin
+ uri = URI.parse(return_to)
+ return nil if uri.scheme.present?
+ return nil if uri.host.present?
+ return nil unless return_to.start_with?("/")
+ return_to
+ rescue URI::InvalidURIError
+ nil
+ end
+ end
+
+ def redbark_item_params
+ params.require(:redbark_item).permit(
+ :name,
+ :sync_start_date,
+ :api_key
+ )
+ end
+
+ def link_redbark_account(redbark_account, accountable_type)
+ accountable_class = validated_accountable_class(accountable_type)
+
+ account = Current.family.accounts.create!(
+ name: redbark_account.name,
+ balance: redbark_account.current_balance || 0,
+ currency: redbark_account.currency || "AUD",
+ accountable: accountable_class.new
+ )
+
+ redbark_account.ensure_account_provider!(account)
+ redbark_account.update!(ignored: false)
+ account
+ end
+
+ def create_account_from_redbark(redbark_account, accountable_type, config)
+ accountable_class = validated_accountable_class(accountable_type)
+ accountable_attrs = {}
+
+ # Set subtype if the accountable supports it
+ if config[:subtype].present? && accountable_class.respond_to?(:subtypes)
+ accountable_attrs[:subtype] = config[:subtype]
+ end
+
+ Current.family.accounts.create!(
+ name: redbark_account.name,
+ balance: config[:balance].present? ? config[:balance].to_d : (redbark_account.current_balance || 0),
+ currency: redbark_account.currency || "AUD",
+ accountable: accountable_class.new(accountable_attrs)
+ )
+ end
+
+ def infer_accountable_type(account_type, subtype = nil)
+ case account_type&.downcase
+ when "depository"
+ "Depository"
+ when "credit_card"
+ "CreditCard"
+ when "investment"
+ "Investment"
+ when "loan"
+ "Loan"
+ when "other_asset"
+ "OtherAsset"
+ when "other_liability"
+ "OtherLiability"
+ when "crypto"
+ "Crypto"
+ when "property"
+ "Property"
+ when "vehicle"
+ "Vehicle"
+ else
+ "Depository"
+ end
+ end
+
+ def validated_accountable_class(accountable_type)
+ unless ALLOWED_ACCOUNTABLE_TYPES.include?(accountable_type)
+ raise ArgumentError, "Invalid accountable type: #{accountable_type}"
+ end
+
+ accountable_type.constantize
+ end
+end
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index a6b05c13f8..a3f968834f 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -185,6 +185,7 @@ class Settings::ProvidersController < ApplicationController
{ key: "akahu", title: "Akahu", turbo_id: "akahu", partial: "akahu_panel" },
{ key: "up", title: "Up", turbo_id: "up", partial: "up_panel" },
{ key: "lunchflow", title: "Lunch Flow", turbo_id: "lunchflow", partial: "lunchflow_panel" },
+ { key: "redbark", title: "Redbark", turbo_id: "redbark", partial: "redbark_panel" },
{ key: "simplefin", title: "SimpleFIN", turbo_id: "simplefin", partial: "simplefin_panel" },
{ key: "enable_banking", title: "Enable Banking", turbo_id: "enable_banking", partial: "enable_banking_panel" },
{ key: "coinstats", title: "CoinStats", turbo_id: "coinstats", partial: "coinstats_panel" },
@@ -210,6 +211,7 @@ class Settings::ProvidersController < ApplicationController
"up" => "UpItem",
"simplefin" => "SimplefinItem",
"lunchflow" => "LunchflowItem",
+ "redbark" => "RedbarkItem",
"enable_banking" => "EnableBankingItem",
"coinstats" => "CoinstatsItem",
"wise" => "WiseItem",
@@ -236,6 +238,8 @@ class Settings::ProvidersController < ApplicationController
@simplefin_items = Current.family.simplefin_items.ordered
when "lunchflow"
@lunchflow_items = Current.family.lunchflow_items.ordered
+ when "redbark"
+ @redbark_items = Current.family.redbark_items.ordered
when "enable_banking"
@enable_banking_items = Current.family.enable_banking_items.ordered
when "coinstats"
@@ -280,6 +284,7 @@ class Settings::ProvidersController < ApplicationController
# Providers page only needs to know whether any SimpleFin/Lunchflow connections exist with valid credentials
@simplefin_items = Current.family.simplefin_items.where.not(access_url: [ nil, "" ]).ordered.select(:id)
@lunchflow_items = Current.family.lunchflow_items.where.not(api_key: [ nil, "" ]).ordered.select(:id)
+ @redbark_items = Current.family.redbark_items.where.not(api_key: [ nil, "" ]).ordered.select(:id)
@enable_banking_items = Current.family.enable_banking_items.ordered # Enable Banking panel needs session info for status display
# Providers page only needs to know whether any Sophtron connections exist with valid credentials
@sophtron_items = Current.family.sophtron_items.where.not(user_id: [ nil, "" ], access_key: [ nil, "" ]).ordered.select(:id)
@@ -316,6 +321,7 @@ class Settings::ProvidersController < ApplicationController
"up" => @up_items,
"simplefin" => @simplefin_items,
"lunchflow" => @lunchflow_items,
+ "redbark" => @redbark_items,
"enable_banking" => @enable_banking_items,
"coinstats" => @coinstats_items,
"wise" => @wise_items,
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 10b880f718..4744ba041a 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -78,6 +78,9 @@ module SettingsHelper
when "mercury"
return { status: :off } unless @mercury_items&.any?
sync_based_summary(key)
+ when "redbark"
+ return { status: :off } unless @redbark_items&.any?
+ sync_based_summary(key)
when "brex"
return { status: :off } unless @brex_items&.any?
sync_based_summary(key)
diff --git a/app/jobs/redbark_connection_cleanup_job.rb b/app/jobs/redbark_connection_cleanup_job.rb
new file mode 100644
index 0000000000..e8e15da8dd
--- /dev/null
+++ b/app/jobs/redbark_connection_cleanup_job.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+class RedbarkConnectionCleanupJob < ApplicationJob
+ queue_as :default
+
+ def perform(redbark_item_id:, account_id:)
+ Rails.logger.info(
+ "RedbarkConnectionCleanupJob - Cleaning up for former account #{account_id}"
+ )
+
+ redbark_item = RedbarkItem.find_by(id: redbark_item_id)
+ return unless redbark_item
+
+ # For banking providers, cleanup is typically simpler since there's no
+ # separate authorization concept - the item itself holds the credentials.
+ # Override this method if your provider needs specific cleanup logic.
+
+ Rails.logger.info("RedbarkConnectionCleanupJob - Cleanup complete for account #{account_id}")
+ rescue => e
+ Rails.logger.warn(
+ "RedbarkConnectionCleanupJob - Failed: #{e.class} - #{e.message}"
+ )
+ # Don't raise - cleanup failures shouldn't block other operations
+ end
+end
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rb
index 1574abda2d..0e3a479ea0 100644
--- a/app/models/account/provider_import_adapter.rb
+++ b/app/models/account/provider_import_adapter.rb
@@ -779,6 +779,7 @@ class Account::ProviderImportAdapter
OR (transactions.extra -> 'akahu' ->> 'pending')::boolean = true
OR (transactions.extra -> 'up' ->> 'pending')::boolean = true
OR (transactions.extra -> 'mercury' ->> 'pending')::boolean = true
+ OR (transactions.extra -> 'redbark' ->> 'pending')::boolean = true
SQL
.order(date: :desc) # Prefer most recent pending transaction
@@ -829,6 +830,7 @@ class Account::ProviderImportAdapter
OR (transactions.extra -> 'akahu' ->> 'pending')::boolean = true
OR (transactions.extra -> 'up' ->> 'pending')::boolean = true
OR (transactions.extra -> 'mercury' ->> 'pending')::boolean = true
+ OR (transactions.extra -> 'redbark' ->> 'pending')::boolean = true
SQL
# If merchant_id is provided, prioritize matching by merchant
@@ -902,6 +904,7 @@ class Account::ProviderImportAdapter
OR (transactions.extra -> 'akahu' ->> 'pending')::boolean = true
OR (transactions.extra -> 'up' ->> 'pending')::boolean = true
OR (transactions.extra -> 'mercury' ->> 'pending')::boolean = true
+ OR (transactions.extra -> 'redbark' ->> 'pending')::boolean = true
SQL
# For low confidence, require BOTH merchant AND name match (stronger signal needed)
diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rb
index 781d9a6dd0..ae29d80dd8 100644
--- a/app/models/data_enrichment.rb
+++ b/app/models/data_enrichment.rb
@@ -17,6 +17,7 @@ class DataEnrichment < ApplicationRecord
indexa_capital: "indexa_capital",
sophtron: "sophtron",
ibkr: "ibkr",
- questrade: "questrade"
+ questrade: "questrade",
+ redbark: "redbark"
}
end
diff --git a/app/models/family.rb b/app/models/family.rb
index c5e7602c05..adec496179 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -6,6 +6,7 @@ class Family < ApplicationRecord
include UpConnectable
include Trading212Connectable
include QuestradeConnectable
+ include RedbarkConnectable
DATE_FORMATS = [
[ "MM-DD-YYYY", "%m-%d-%Y" ],
diff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rb
index dbd9716278..10ef3257de 100644
--- a/app/models/family/financial_data_reset.rb
+++ b/app/models/family/financial_data_reset.rb
@@ -50,6 +50,7 @@ class Family::FinancialDataReset
kraken_items
questrade_items
lunchflow_items
+ redbark_items
mercury_items
plaid_items
simplefin_items
diff --git a/app/models/family/redbark_connectable.rb b/app/models/family/redbark_connectable.rb
new file mode 100644
index 0000000000..03a06c7dc9
--- /dev/null
+++ b/app/models/family/redbark_connectable.rb
@@ -0,0 +1,27 @@
+module Family::RedbarkConnectable
+ extend ActiveSupport::Concern
+
+ included do
+ has_many :redbark_items, dependent: :destroy
+ end
+
+ def can_connect_redbark?
+ # Families can configure their own Redbark credentials
+ true
+ end
+
+ def create_redbark_item!(api_key:, item_name: nil)
+ redbark_item = redbark_items.create!(
+ name: item_name || I18n.t("redbark_items.default_name"),
+ api_key: api_key
+ )
+
+ redbark_item.sync_later
+
+ redbark_item
+ end
+
+ def has_redbark_credentials?
+ redbark_items.where.not(api_key: nil).exists?
+ end
+end
diff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rb
index 132d8eed07..220acb6c18 100644
--- a/app/models/provider/metadata.rb
+++ b/app/models/provider/metadata.rb
@@ -20,7 +20,8 @@ class Provider
trading212: { region: "EU", kinds: %w[Investment], maturity: :alpha, logo_text: "T2", logo_bg: "bg-teal-600" },
plaid: { region: "US", kinds: %w[Bank], maturity: :stable, logo_text: "PL", logo_bg: "bg-indigo-600", tier: "Paid" },
plaid_eu: { region: "EU", kinds: %w[Bank], maturity: :stable, logo_text: "PL", logo_bg: "bg-indigo-600", tier: "Paid", name: "Plaid EU" },
- questrade: { region: "CA", kinds: %w[Investment], maturity: :beta, logo_text: "QT", logo_bg: "bg-teal-600" }
+ questrade: { region: "CA", kinds: %w[Investment], maturity: :beta, logo_text: "QT", logo_bg: "bg-teal-600" },
+ redbark: { region: "AU", kinds: %w[Bank], maturity: :beta, logo_text: "RB", logo_bg: "bg-red-700" }
}.freeze
def self.for(provider_key)
diff --git a/app/models/provider/redbark.rb b/app/models/provider/redbark.rb
new file mode 100644
index 0000000000..fb60ad093c
--- /dev/null
+++ b/app/models/provider/redbark.rb
@@ -0,0 +1,262 @@
+# frozen_string_literal: true
+
+class Provider::Redbark
+ include HTTParty
+
+ headers "User-Agent" => "Sure Finance Redbark Client"
+ default_options.merge!(verify: true, ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER, timeout: 120)
+
+ BASE_URL = "https://api.redbark.com/v1"
+
+ # Server-side maximums for limit/offset pagination
+ ACCOUNTS_PAGE_SIZE = 200
+ TRANSACTIONS_PAGE_SIZE = 500
+
+ class Error < StandardError
+ attr_reader :error_type
+
+ def initialize(message, error_type = :unknown)
+ super(message)
+ @error_type = error_type
+ end
+ end
+
+ class ConfigurationError < Error; end
+ class AuthenticationError < Error; end
+ class RateLimitError < Error; end
+ class ServerError < Error; end
+
+ attr_reader :api_key
+
+ def initialize(api_key:)
+ @api_key = api_key
+ validate_configuration!
+ end
+
+ # Returns all accounts across the user's connections.
+ # Response items: { id, connectionId, provider, name, type, institutionName, accountNumber, currency }
+ def list_accounts
+ results, truncated = paginate("list_accounts", "#{BASE_URL}/accounts", page_size: ACCOUNTS_PAGE_SIZE)
+
+ # A partial account list must never reach downstream pruning
+ raise Error.new("list_accounts returned a truncated account list", :truncated) if truncated
+
+ results
+ end
+
+ # Returns all connections: { id, provider, category, institutionId, institutionName,
+ # institutionLogo, status, lastRefreshedAt, createdAt }
+ def list_connections
+ with_retries("list_connections") do
+ response = self.class.get("#{BASE_URL}/connections", headers: auth_headers)
+ handle_response(response)[:data] || []
+ end
+ end
+
+ # Returns balances for the given account ids.
+ # Response items: { accountId, currentBalance, availableBalance, currency }
+ def get_balances(account_ids:)
+ return [] if account_ids.blank?
+
+ with_retries("get_balances") do
+ response = self.class.get(
+ "#{BASE_URL}/balances",
+ headers: auth_headers,
+ query: { accountIds: Array(account_ids).join(",") }
+ )
+ handle_response(response)[:data] || []
+ end
+ end
+
+ # Returns all transactions for one account within the date range.
+ # Both connection_id and account_id are required by the API.
+ # Response items: { id, accountId, accountName, status, date, datetime, postDate,
+ # postDatetime, valueDate, valueDatetime, description, amount, direction, category,
+ # merchantName, merchantCategoryCode }
+ # Amounts are pre-signed decimal strings: positive = credit (money in), negative = debit.
+ def get_transactions(connection_id:, account_id:, start_date: nil, end_date: nil, include_pending: false)
+ query = {
+ connectionId: connection_id,
+ accountId: account_id
+ }
+ fetch_transactions_window(
+ connection_id: connection_id,
+ account_id: account_id,
+ start_date: start_date&.to_date,
+ end_date: end_date&.to_date,
+ include_pending: include_pending,
+ splits_left: MAX_WINDOW_SPLITS
+ )
+ end
+
+ private
+
+ RETRYABLE_ERRORS = [
+ SocketError, Net::OpenTimeout, Net::ReadTimeout,
+ Errno::ECONNRESET, Errno::ECONNREFUSED, Errno::ETIMEDOUT, EOFError
+ ].freeze
+
+ MAX_RETRIES = 3
+ INITIAL_RETRY_DELAY = 2 # seconds
+ MAX_PAGES = 50 # safety cap so a bad hasMore can never loop forever
+ MAX_WINDOW_SPLITS = 6 # bounds recursion when halving a truncated date window
+
+ def validate_configuration!
+ raise ConfigurationError, "Api key is required" if @api_key.blank?
+ end
+
+ # A truncated window cannot be paged past the row ceiling; halve the date
+ # range and recurse until every window fits, raising once it cannot narrow
+ def fetch_transactions_window(connection_id:, account_id:, start_date:, end_date:, include_pending:, splits_left:)
+ query = {
+ connectionId: connection_id,
+ accountId: account_id
+ }
+ query[:from] = start_date.to_s if start_date
+ query[:to] = end_date.to_s if end_date
+ query[:includePending] = "true" if include_pending
+
+ results, truncated = paginate("get_transactions", "#{BASE_URL}/transactions", page_size: TRANSACTIONS_PAGE_SIZE, query: query)
+ return results unless truncated
+
+ if start_date.nil? || end_date.nil? || splits_left <= 0 || start_date >= end_date
+ raise Error.new("get_transactions hit the server row ceiling and the date window cannot be narrowed further", :truncated)
+ end
+
+ mid = start_date + ((end_date - start_date) / 2).to_i
+ Rails.logger.info "Redbark API: get_transactions window #{start_date}..#{end_date} truncated, splitting at #{mid}"
+
+ first_half = fetch_transactions_window(
+ connection_id: connection_id, account_id: account_id,
+ start_date: start_date, end_date: mid,
+ include_pending: include_pending, splits_left: splits_left - 1
+ )
+ second_half = fetch_transactions_window(
+ connection_id: connection_id, account_id: account_id,
+ start_date: mid + 1, end_date: end_date,
+ include_pending: include_pending, splits_left: splits_left - 1
+ )
+
+ (first_half + second_half).uniq { |t| t[:id] || t }
+ end
+
+ # Follows limit/offset pagination until hasMore is false. Returns
+ # [results, truncated] - truncated means the server row ceiling fired
+ # (X-Redbark-Truncated) and the caller decides how to recover
+ def paginate(operation_name, url, page_size:, query: {})
+ results = []
+ offset = 0
+ exhausted = false
+
+ MAX_PAGES.times do
+ page, headers = with_retries(operation_name) do
+ response = self.class.get(
+ url,
+ headers: auth_headers,
+ query: query.merge(limit: page_size, offset: offset)
+ )
+ [ handle_response(response), response.headers ]
+ end
+
+ data = page[:data] || []
+ results.concat(data)
+
+ if headers["x-redbark-truncated"].to_s == "true"
+ return [ results, true ]
+ end
+
+ pagination = page[:pagination] || {}
+ unless pagination[:hasMore]
+ exhausted = true
+ break
+ end
+
+ # hasMore with an empty page means the server stopped early
+ if data.empty?
+ raise Error.new("#{operation_name} returned an empty page while reporting more results", :truncated)
+ end
+
+ offset += data.size
+ end
+
+ unless exhausted
+ raise Error.new("#{operation_name} exceeded #{MAX_PAGES} pages without exhausting results", :too_many_pages)
+ end
+
+ [ results, false ]
+ end
+
+ def with_retries(operation_name, max_retries: MAX_RETRIES)
+ retries = 0
+
+ begin
+ yield
+ rescue *RETRYABLE_ERRORS, RateLimitError, ServerError => e
+ retries += 1
+
+ if retries <= max_retries
+ delay = calculate_retry_delay(retries)
+ Rails.logger.warn(
+ "Redbark API: #{operation_name} failed (attempt #{retries}/#{max_retries}): " \
+ "#{e.class}: #{e.message}. Retrying in #{delay}s..."
+ )
+ sleep(delay)
+ retry
+ else
+ Rails.logger.error(
+ "Redbark API: #{operation_name} failed after #{max_retries} retries: " \
+ "#{e.class}: #{e.message}"
+ )
+ raise e if e.is_a?(Error)
+ raise Error.new("Network error after #{max_retries} retries: #{e.message}", :network_error)
+ end
+ end
+ end
+
+ def calculate_retry_delay(retry_count)
+ base_delay = INITIAL_RETRY_DELAY * (2 ** (retry_count - 1))
+ jitter = base_delay * rand * 0.25
+ [ base_delay + jitter, 30 ].min
+ end
+
+ def auth_headers
+ {
+ "Authorization" => "Bearer #{@api_key}",
+ "Content-Type" => "application/json",
+ "Accept" => "application/json"
+ }
+ end
+
+ # Redbark error envelope: { error: { message, code, details } }
+ # Error messages carry the parsed provider message only, never the raw
+ # response body - callers log and re-log these strings.
+ def handle_response(response)
+ case response.code
+ when 200, 201
+ JSON.parse(response.body, symbolize_names: true)
+ when 400
+ raise Error.new("Bad request: #{error_message_from(response)}", :bad_request)
+ when 401
+ raise AuthenticationError.new("Invalid API key", :unauthorized)
+ when 403
+ raise AuthenticationError.new("Access forbidden - your Redbark plan may not include API access", :access_forbidden)
+ when 404
+ raise Error.new("Resource not found", :not_found)
+ when 410
+ raise Error.new("Endpoint requires an accountId: #{error_message_from(response)}", :bad_request)
+ when 429
+ raise RateLimitError.new("Rate limit exceeded", :rate_limited)
+ when 500..599
+ raise ServerError.new("Redbark server error (#{response.code})", :server_error)
+ else
+ raise Error.new("Unexpected response #{response.code}: #{error_message_from(response)}", :unknown)
+ end
+ end
+
+ def error_message_from(response)
+ parsed = JSON.parse(response.body)
+ parsed.dig("error", "message") || "no error message provided"
+ rescue JSON::ParserError
+ "unparseable error response"
+ end
+end
diff --git a/app/models/provider/redbark_adapter.rb b/app/models/provider/redbark_adapter.rb
new file mode 100644
index 0000000000..67f112f790
--- /dev/null
+++ b/app/models/provider/redbark_adapter.rb
@@ -0,0 +1,98 @@
+class Provider::RedbarkAdapter < Provider::Base
+ include Provider::Syncable
+ include Provider::InstitutionMetadata
+
+ # Register this adapter with the factory
+ Provider::Factory.register("RedbarkAccount", self)
+
+ # Define which account types this provider supports
+ def self.supported_account_types
+ %w[Depository CreditCard Loan]
+ end
+
+ # Returns connection configurations for this provider
+ def self.connection_configs(family:)
+ return [] unless family.can_connect_redbark?
+
+ [ {
+ key: "redbark",
+ name: "Redbark",
+ description: "Connect your Australian bank accounts via Redbark",
+ can_connect: true,
+ new_account_path: ->(accountable_type, return_to) {
+ Rails.application.routes.url_helpers.select_accounts_redbark_items_path(
+ accountable_type: accountable_type,
+ return_to: return_to
+ )
+ },
+ existing_account_path: ->(account_id) {
+ Rails.application.routes.url_helpers.select_existing_account_redbark_items_path(
+ account_id: account_id
+ )
+ }
+ } ]
+ end
+
+ def provider_name
+ "redbark"
+ end
+
+ # Build a Redbark provider instance with family-specific credentials
+ # @param family [Family] The family to get credentials for (required)
+ # @return [Provider::Redbark, nil] Returns nil if credentials are not configured
+ def self.build_provider(family: nil)
+ return nil unless family.present?
+
+ # Get family-specific credentials
+ redbark_item = family.redbark_items.where.not(api_key: nil).first
+ return nil unless redbark_item&.credentials_configured?
+
+ Provider::Redbark.new(api_key: redbark_item.api_key)
+ end
+
+ def sync_path
+ Rails.application.routes.url_helpers.sync_redbark_item_path(item)
+ end
+
+ def item
+ provider_account.redbark_item
+ end
+
+
+ def institution_domain
+ metadata = provider_account.institution_metadata
+ return nil unless metadata.present?
+
+ domain = metadata["domain"]
+ url = metadata["url"]
+
+ # Derive domain from URL if missing
+ if domain.blank? && url.present?
+ begin
+ domain = URI.parse(url).host&.gsub(/^www\./, "")
+ rescue URI::InvalidURIError
+ Rails.logger.warn("Invalid institution URL for Redbark account #{provider_account.id}: #{url}")
+ end
+ end
+
+ domain
+ end
+
+ def institution_name
+ metadata = provider_account.institution_metadata
+ return nil unless metadata.present?
+
+ metadata["name"] || item&.institution_name
+ end
+
+ def institution_url
+ metadata = provider_account.institution_metadata
+ return nil unless metadata.present?
+
+ metadata["url"] || item&.institution_url
+ end
+
+ def institution_color
+ item&.institution_color
+ end
+end
diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rb
index 0bb684e18c..89ee10382e 100644
--- a/app/models/provider_connection_status.rb
+++ b/app/models/provider_connection_status.rb
@@ -20,6 +20,7 @@ class ProviderConnectionStatus
{ key: "indexa_capital", type: "IndexaCapitalItem", association: :indexa_capital_items, accounts: :indexa_capital_accounts },
{ key: "trading212", type: "Trading212Item", association: :trading212_items, accounts: :trading212_accounts },
{ key: "questrade", type: "QuestradeItem", association: :questrade_items, accounts: :questrade_accounts },
+ { key: "redbark", type: "RedbarkItem", association: :redbark_items, accounts: :redbark_accounts },
{ key: "wise", type: "WiseItem", association: :wise_items, accounts: :wise_accounts }
].freeze
diff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rb
index 54515e5bbd..be22bd7786 100644
--- a/app/models/provider_merchant.rb
+++ b/app/models/provider_merchant.rb
@@ -1,5 +1,5 @@
class ProviderMerchant < Merchant
- enum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade" }
+ enum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade", redbark: "redbark" }
validates :name, uniqueness: { scope: [ :source ] }
validates :source, presence: true
diff --git a/app/models/redbark_account.rb b/app/models/redbark_account.rb
new file mode 100644
index 0000000000..8a54ae4ffb
--- /dev/null
+++ b/app/models/redbark_account.rb
@@ -0,0 +1,104 @@
+# frozen_string_literal: true
+
+class RedbarkAccount < ApplicationRecord
+ include CurrencyNormalizable, Encryptable
+ include RedbarkAccount::DataHelpers
+
+ # Encrypt raw payloads if ActiveRecord encryption is configured
+ if encryption_ready?
+ encrypts :raw_payload
+ encrypts :raw_transactions_payload
+ end
+
+ belongs_to :redbark_item
+
+ # Association through account_providers
+ has_one :account_provider, as: :provider, dependent: :destroy
+ has_one :account, through: :account_provider, source: :account
+ has_one :linked_account, through: :account_provider, source: :account
+
+ validates :name, :currency, :redbark_account_id, presence: true
+ validates :redbark_account_id, uniqueness: { scope: :redbark_item_id }
+
+ # Scopes
+ scope :with_linked, -> { joins(:account_provider) }
+ scope :without_linked, -> { left_joins(:account_provider).where(account_providers: { id: nil }) }
+ scope :needs_setup, -> { without_linked.where(ignored: false) }
+ scope :ordered, -> { order(created_at: :desc) }
+
+ # Callbacks
+ after_destroy :enqueue_connection_cleanup
+
+ # Helper to get account using account_providers system
+ def current_account
+ account
+ end
+
+ # Idempotently create or update AccountProvider link
+ # CRITICAL: After creation, reload association to avoid stale nil
+ def ensure_account_provider!(linked_account)
+ return nil unless linked_account
+
+ provider = account_provider || build_account_provider
+ provider.account = linked_account
+ provider.save!
+
+ # Reload to clear cached nil value
+ reload_account_provider
+ account_provider
+ end
+
+ # Redbark accounts endpoint returns:
+ # { id, connectionId, provider, name, type, institutionName, accountNumber, currency }
+ # Balance is not included there - it comes from the balances endpoint and is
+ # written separately by the importer, so it is deliberately not touched here.
+ def upsert_from_redbark!(account_data, connection_data: nil)
+ data = sdk_object_to_hash(account_data).with_indifferent_access
+ connection = connection_data.present? ? sdk_object_to_hash(connection_data).with_indifferent_access : {}
+
+ display_name = if data[:institutionName].present?
+ "#{data[:institutionName]} - #{data[:name]}"
+ else
+ data[:name]
+ end
+
+ update!(
+ redbark_account_id: data[:id]&.to_s,
+ connection_id: data[:connectionId]&.to_s,
+ name: display_name,
+ account_number: data[:accountNumber],
+ currency: extract_currency(data, fallback: parse_currency(currency) || "AUD"),
+ account_status: connection[:status],
+ account_type: data[:type],
+ provider: data[:provider],
+ institution_metadata: {
+ name: data[:institutionName] || connection[:institutionName],
+ logo: connection[:institutionLogo]
+ }.compact,
+ raw_payload: account_data
+ )
+ end
+
+ def upsert_redbark_transactions_snapshot!(transactions_snapshot)
+ assign_attributes(
+ raw_transactions_payload: transactions_snapshot
+ )
+
+ save!
+ end
+
+ private
+
+ def enqueue_connection_cleanup
+ return unless redbark_item
+
+ RedbarkConnectionCleanupJob.perform_later(
+ redbark_item_id: redbark_item.id,
+ account_id: id
+ )
+ end
+
+ def log_invalid_currency(currency_value)
+ Rails.logger.warn("Invalid currency code '#{currency_value}' for Redbark account #{id}, defaulting to AUD")
+ end
+end
diff --git a/app/models/redbark_account/data_helpers.rb b/app/models/redbark_account/data_helpers.rb
new file mode 100644
index 0000000000..29bf4b8054
--- /dev/null
+++ b/app/models/redbark_account/data_helpers.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+module RedbarkAccount::DataHelpers
+ extend ActiveSupport::Concern
+
+ private
+
+ # Convert SDK objects to hashes via JSON round-trip
+ # Many SDKs return objects that don't have proper #to_h methods
+ def sdk_object_to_hash(obj)
+ return obj if obj.is_a?(Hash)
+
+ if obj.respond_to?(:to_json)
+ JSON.parse(obj.to_json)
+ elsif obj.respond_to?(:to_h)
+ obj.to_h
+ else
+ obj
+ end
+ rescue JSON::ParserError, TypeError
+ obj.respond_to?(:to_h) ? obj.to_h : {}
+ end
+
+ def parse_decimal(value)
+ return nil if value.nil?
+
+ case value
+ when BigDecimal
+ value
+ when String
+ BigDecimal(value)
+ when Numeric
+ BigDecimal(value.to_s)
+ else
+ nil
+ end
+ rescue ArgumentError => e
+ Rails.logger.error("RedbarkAccount::DataHelpers - Failed to parse decimal value: #{value.inspect} - #{e.message}")
+ nil
+ end
+
+ def parse_date(date_value)
+ return nil if date_value.nil?
+
+ case date_value
+ when Date
+ date_value
+ when String
+ # Use Time.zone.parse for external timestamps (Rails timezone guidelines)
+ Time.zone.parse(date_value)&.to_date
+ when Time, DateTime, ActiveSupport::TimeWithZone
+ date_value.to_date
+ else
+ nil
+ end
+ rescue ArgumentError, TypeError => e
+ Rails.logger.error("RedbarkAccount::DataHelpers - Failed to parse date: #{date_value.inspect} - #{e.message}")
+ nil
+ end
+
+ # Handle currency as string or object (API inconsistency)
+ def extract_currency(data, fallback: nil)
+ data = data.with_indifferent_access if data.respond_to?(:with_indifferent_access)
+
+ currency_data = data[:currency]
+ return fallback if currency_data.blank?
+
+ if currency_data.is_a?(Hash)
+ currency_data.with_indifferent_access[:code] || fallback
+ elsif currency_data.is_a?(String)
+ currency_data.upcase
+ else
+ fallback
+ end
+ end
+end
diff --git a/app/models/redbark_account/processor.rb b/app/models/redbark_account/processor.rb
new file mode 100644
index 0000000000..a136f4ac12
--- /dev/null
+++ b/app/models/redbark_account/processor.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+class RedbarkAccount::Processor
+ include RedbarkAccount::DataHelpers
+
+ attr_reader :redbark_account
+
+ def initialize(redbark_account)
+ @redbark_account = redbark_account
+ end
+
+ def process
+ account = redbark_account.current_account
+ return unless account
+
+ Rails.logger.info "RedbarkAccount::Processor - Processing account #{redbark_account.id} -> Sure account #{account.id}"
+
+ # Update account balance FIRST (before processing transactions/holdings/activities)
+ update_account_balance(account)
+
+ # Process transactions
+ transactions_count = redbark_account.raw_transactions_payload&.size || 0
+ Rails.logger.info "RedbarkAccount::Processor - Transactions payload has #{transactions_count} items"
+
+ if redbark_account.raw_transactions_payload.present?
+ Rails.logger.info "RedbarkAccount::Processor - Processing transactions..."
+ RedbarkAccount::Transactions::Processor.new(redbark_account).process
+ else
+ Rails.logger.warn "RedbarkAccount::Processor - No transactions payload to process"
+ end
+
+ # Trigger immediate UI refresh so entries appear in the activity feed
+ account.broadcast_sync_complete
+ Rails.logger.info "RedbarkAccount::Processor - Broadcast sync complete for account #{account.id}"
+
+ { transactions_processed: transactions_count > 0 }
+ end
+
+ private
+
+ def update_account_balance(account)
+ balance = redbark_account.current_balance
+
+ # A nil current_balance means no balances fetch has succeeded for this
+ # account yet. Writing 0 here would clobber a healthy balance (or the
+ # opening balance the user typed during setup) and anchor a $0
+ # valuation, so leave the account untouched instead.
+ if balance.nil?
+ Rails.logger.warn "RedbarkAccount::Processor - No balance available for redbark_account #{redbark_account.id}, skipping balance update"
+ return
+ end
+
+ # Banking sign convention:
+ # - CreditCard and Loan accounts may need sign inversion
+ # Provider returns negative for positive balance, so we negate it
+ if account.accountable_type == "CreditCard" || account.accountable_type == "Loan"
+ balance = -balance
+ end
+
+ Rails.logger.info "RedbarkAccount::Processor - Balance update: #{balance}"
+
+ account.assign_attributes(
+ balance: balance,
+ cash_balance: balance,
+ currency: redbark_account.currency || account.currency
+ )
+ account.save!
+
+ # Create or update the current balance anchor valuation for linked accounts
+ # This is critical for reverse sync to work correctly
+ account.set_current_balance(balance)
+ end
+end
diff --git a/app/models/redbark_account/transactions/processor.rb b/app/models/redbark_account/transactions/processor.rb
new file mode 100644
index 0000000000..6d2ad8e61b
--- /dev/null
+++ b/app/models/redbark_account/transactions/processor.rb
@@ -0,0 +1,177 @@
+# frozen_string_literal: true
+
+require "digest"
+
+class RedbarkAccount::Transactions::Processor
+ include RedbarkAccount::DataHelpers
+
+ attr_reader :redbark_account
+
+ def initialize(redbark_account)
+ @redbark_account = redbark_account
+ end
+
+ def process
+ unless redbark_account.raw_transactions_payload.present?
+ Rails.logger.info "RedbarkAccount::Transactions::Processor - No transactions in raw_transactions_payload for redbark_account #{redbark_account.id}"
+ return { success: true, total: 0, imported: 0, skipped: 0, failed: 0, errors: [] }
+ end
+
+ total_count = redbark_account.raw_transactions_payload.count
+ Rails.logger.info "RedbarkAccount::Transactions::Processor - Processing #{total_count} transactions for redbark_account #{redbark_account.id}"
+
+ imported_count = 0
+ skipped_count = 0
+ failed_count = 0
+ errors = []
+
+ # Each entry is processed inside a transaction, but to avoid locking up the DB when
+ # there are hundreds or thousands of transactions, we process them individually.
+ redbark_account.raw_transactions_payload.each_with_index do |transaction_data, index|
+ begin
+ result = process_transaction(transaction_data)
+
+ if result.nil?
+ # Benign skip (no linked account, blank id, unparseable amount/date)
+ skipped_count += 1
+ else
+ imported_count += 1
+ end
+ rescue ArgumentError => e
+ # Validation error - log and continue
+ failed_count += 1
+ transaction_id = transaction_data.try(:[], :id) || transaction_data.try(:[], "id") || "unknown"
+ error_message = "Validation error: #{e.message}"
+ Rails.logger.error "RedbarkAccount::Transactions::Processor - #{error_message} (transaction #{transaction_id})"
+ errors << { index: index, transaction_id: transaction_id, error: error_message }
+ rescue => e
+ # Unexpected error - log with full context and continue
+ failed_count += 1
+ transaction_id = transaction_data.try(:[], :id) || transaction_data.try(:[], "id") || "unknown"
+ error_message = "#{e.class}: #{e.message}"
+ Rails.logger.error "RedbarkAccount::Transactions::Processor - Error processing transaction #{transaction_id}: #{error_message}"
+ Rails.logger.error e.backtrace.join("\n")
+ errors << { index: index, transaction_id: transaction_id, error: error_message }
+ end
+ end
+
+ result = {
+ success: failed_count == 0,
+ total: total_count,
+ imported: imported_count,
+ skipped: skipped_count,
+ failed: failed_count,
+ errors: errors
+ }
+
+ if failed_count > 0 || skipped_count > 0
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: failed_count > 0 ? "warn" : "info",
+ message: "Redbark transaction processing completed with skipped or failed rows",
+ source: self.class.name,
+ provider_key: "redbark",
+ family: redbark_account.redbark_item.family,
+ metadata: { redbark_account_id: redbark_account.id, total: total_count, imported: imported_count, skipped: skipped_count, failed: failed_count, errors: errors.first(10) }
+ )
+ end
+
+ if failed_count > 0
+ Rails.logger.warn "RedbarkAccount::Transactions::Processor - Completed with #{failed_count} failures out of #{total_count} transactions"
+ else
+ Rails.logger.info "RedbarkAccount::Transactions::Processor - Successfully processed #{imported_count} transactions (#{skipped_count} skipped)"
+ end
+
+ result
+ end
+
+ private
+
+ def account
+ @redbark_account.current_account
+ end
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+
+ # Redbark transaction shape:
+ # { id, accountId, accountName, status, date, datetime, postDate, description,
+ # amount, direction, category, merchantName, merchantCategoryCode }
+ def process_transaction(transaction_data)
+ return nil unless account.present?
+
+ data = transaction_data.with_indifferent_access
+
+ redbark_id = data[:id].to_s
+ return nil if redbark_id.blank?
+
+ external_id = "redbark_#{redbark_id}"
+
+ amount = parse_transaction_amount(data)
+ return nil if amount.nil?
+
+ date = parse_date(data[:date] || data[:postDate])
+ return nil if date.nil?
+
+ name = data[:merchantName].presence || data[:description].presence || "Transaction"
+ # Transactions carry no per-item currency; they are in the account's currency
+ currency = account.currency
+
+ extra = build_extra_metadata(data)
+
+ Rails.logger.debug "RedbarkAccount::Transactions::Processor - Importing transaction: id=#{external_id} date=#{date}"
+
+ # Use ProviderImportAdapter for proper deduplication via external_id + source
+ import_adapter.import_transaction(
+ external_id: external_id,
+ amount: amount,
+ currency: currency,
+ date: date,
+ name: name[0..254], # Limit to 255 chars
+ source: "redbark",
+ merchant: merchant_for(data),
+ notes: data[:description].presence,
+ extra: extra
+ )
+ end
+
+ def parse_transaction_amount(data)
+ amount = parse_decimal(data[:amount])
+ return nil if amount.nil?
+
+ # Redbark returns CDR pre-signed amounts: positive = credit (money in),
+ # negative = debit (money out). Sure expects the opposite (positive =
+ # money out), so negate.
+ -amount
+ end
+
+ def merchant_for(data)
+ merchant_name = data[:merchantName].to_s.strip
+ return nil if merchant_name.blank?
+
+ merchant_id = Digest::SHA256.hexdigest(merchant_name.downcase)[0, 32]
+
+ import_adapter.find_or_create_merchant(
+ provider_merchant_id: "redbark_merchant_#{merchant_id}",
+ name: merchant_name,
+ source: "redbark"
+ )
+ rescue ActiveRecord::RecordInvalid => e
+ Rails.logger.error "RedbarkAccount::Transactions::Processor - Failed to create merchant '#{merchant_name}': #{e.message}"
+ nil
+ end
+
+ def build_extra_metadata(data)
+ {
+ "redbark" => {
+ "id" => data[:id],
+ "pending" => data[:status].to_s == "pending",
+ "merchant" => data[:merchantName],
+ "category" => data[:category],
+ "merchant_category_code" => data[:merchantCategoryCode],
+ "direction" => data[:direction]
+ }.compact
+ }
+ end
+end
diff --git a/app/models/redbark_item.rb b/app/models/redbark_item.rb
new file mode 100644
index 0000000000..01a4b53b9b
--- /dev/null
+++ b/app/models/redbark_item.rb
@@ -0,0 +1,208 @@
+# frozen_string_literal: true
+
+class RedbarkItem < ApplicationRecord
+ include Syncable, Provided, Unlinking, Encryptable
+
+ enum :status, { good: "good", requires_update: "requires_update" }, default: :good
+
+ # Encrypt sensitive credentials and raw payloads if ActiveRecord encryption is configured
+ if encryption_ready?
+ encrypts :api_key, deterministic: true
+ encrypts :raw_payload
+ encrypts :raw_institution_payload
+ end
+
+ validates :name, presence: true
+ # Validate on every save, not just create - an update must never blank the key
+ validates :api_key, presence: true
+
+ belongs_to :family
+ has_one_attached :logo, dependent: :purge_later
+
+ has_many :redbark_accounts, dependent: :destroy
+ has_many :accounts, through: :redbark_accounts
+
+ scope :active, -> { where(scheduled_for_deletion: false) }
+ scope :syncable, -> { active }
+ scope :ordered, -> { order(created_at: :desc) }
+ scope :needs_update, -> { where(status: :requires_update) }
+
+ def syncer
+ RedbarkItem::Syncer.new(self)
+ end
+
+ # Deliberately not transactional - the job must enqueue after the flag commits
+ def destroy_later
+ update!(scheduled_for_deletion: true)
+ DestroyJob.perform_later(self)
+ end
+
+
+ # Import data from provider API
+ def import_latest_redbark_data(sync: nil)
+ provider = redbark_provider
+ unless provider
+ Rails.logger.error "RedbarkItem #{id} - Cannot import: provider is not configured"
+ raise StandardError, I18n.t("redbark_items.errors.provider_not_configured")
+ end
+
+ RedbarkItem::Importer.new(self, redbark_provider: provider, sync: sync).import
+ rescue => e
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "error",
+ message: "Redbark import failed",
+ source: self.class.name,
+ provider_key: "redbark",
+ family: family,
+ metadata: { redbark_item_id: id, error_class: e.class.name, error: e.message }
+ )
+ Rails.logger.error "RedbarkItem #{id} - Failed to import data: #{e.message}"
+ raise
+ end
+
+ # Process linked accounts after data import
+ def process_accounts
+ return [] if redbark_accounts.empty?
+
+ results = []
+ linked_redbark_accounts.includes(account_provider: :account).each do |redbark_account|
+ begin
+ result = RedbarkAccount::Processor.new(redbark_account).process
+ results << { redbark_account_id: redbark_account.id, success: true, result: result }
+ rescue => e
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "error",
+ message: "Failed to process Redbark account",
+ source: self.class.name,
+ provider_key: "redbark",
+ family: family,
+ metadata: { redbark_account_id: redbark_account.id, error_class: e.class.name, error: e.message }
+ )
+ results << { redbark_account_id: redbark_account.id, success: false, error: e.message }
+ end
+ end
+
+ results
+ end
+
+ # Schedule sync jobs for all linked accounts
+ 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
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "error",
+ message: "Redbark account sync scheduling failed",
+ source: self.class.name,
+ provider_key: "redbark",
+ family: family,
+ metadata: { redbark_item_id: id, account_id: account.id, error_class: e.class.name, error: e.message }
+ )
+ Rails.logger.error "RedbarkItem #{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_redbark_snapshot!(accounts_snapshot)
+ assign_attributes(
+ raw_payload: accounts_snapshot
+ )
+
+ save!
+ end
+
+ def has_completed_initial_setup?
+ accounts.any?
+ end
+
+ # Linked accounts (have AccountProvider association)
+ def linked_redbark_accounts
+ redbark_accounts.joins(:account_provider)
+ end
+
+ # Unlinked accounts still awaiting setup (no AccountProvider link, not skipped by the user)
+ def unlinked_redbark_accounts
+ redbark_accounts.needs_setup
+ end
+
+ def sync_status_summary
+ if account_counts[:total] == 0
+ I18n.t("redbark_items.sync_status.no_accounts")
+ elsif account_counts[:needs_setup] == 0
+ I18n.t("redbark_items.sync_status.synced", count: account_counts[:linked])
+ else
+ I18n.t("redbark_items.sync_status.synced_with_setup", linked: account_counts[:linked], unlinked: account_counts[:needs_setup])
+ end
+ end
+
+ def linked_accounts_count
+ account_counts[:linked]
+ end
+
+ def unlinked_accounts_count
+ account_counts[:needs_setup]
+ end
+
+ def total_accounts_count
+ account_counts[:total]
+ end
+
+ def institution_display_name
+ institution_name.presence || institution_domain.presence || name
+ end
+
+ def connected_institutions
+ redbark_accounts.includes(:account)
+ .where.not(institution_metadata: nil)
+ .map { |acc| acc.institution_metadata }
+ .uniq { |inst| inst["name"] || inst["institution_name"] }
+ end
+
+ def institution_summary
+ institutions = connected_institutions
+ case institutions.count
+ when 0
+ I18n.t("redbark_items.institution_summary.none")
+ else
+ I18n.t("redbark_items.institution_summary.count", count: institutions.count)
+ end
+ end
+
+ def credentials_configured?
+ api_key.present?
+ end
+
+ private
+
+ # One grouped query instead of separate COUNTs for each of the
+ # linked/unlinked/total figures the accounts index partial reads.
+ def account_counts
+ @account_counts ||= begin
+ rows = redbark_accounts
+ .left_joins(:account_provider)
+ .group(:ignored, Arel.sql("account_providers.id IS NULL"))
+ .count
+
+ {
+ total: rows.values.sum,
+ linked: rows.sum { |(_ignored, unlinked), count| unlinked ? 0 : count },
+ needs_setup: rows.sum { |(ignored, unlinked), count| unlinked && !ignored ? count : 0 }
+ }
+ end
+ end
+end
diff --git a/app/models/redbark_item/importer.rb b/app/models/redbark_item/importer.rb
new file mode 100644
index 0000000000..08c8111e6a
--- /dev/null
+++ b/app/models/redbark_item/importer.rb
@@ -0,0 +1,356 @@
+# frozen_string_literal: true
+
+class RedbarkItem::Importer
+ include SyncStats::Collector
+ include RedbarkAccount::DataHelpers
+ include CurrencyNormalizable
+
+ attr_reader :redbark_item, :redbark_provider, :sync
+
+ def initialize(redbark_item, redbark_provider:, sync: nil)
+ @redbark_item = redbark_item
+ @redbark_provider = redbark_provider
+ @sync = sync
+ end
+
+ def import
+ Rails.logger.info "RedbarkItem::Importer - Starting import for item #{redbark_item.id}"
+
+ # Step 1: Fetch and store all accounts (with connection metadata for institutions)
+ import_accounts
+
+ # Step 2: For linked accounts only, fetch transactions and balances.
+ # Unlinked accounts just need basic info (name, institution) for the setup modal.
+ linked_accounts = redbark_item.linked_redbark_accounts.to_a
+
+ Rails.logger.info "RedbarkItem::Importer - Found #{linked_accounts.count} linked accounts to process"
+
+ linked_accounts.each do |redbark_account|
+ import_transactions(redbark_account)
+ end
+
+ import_balances(linked_accounts)
+
+ # Store import stats on the item as the raw snapshot
+ redbark_item.upsert_redbark_snapshot!(stats)
+
+ stats
+ rescue Provider::Redbark::AuthenticationError
+ redbark_item.update!(status: :requires_update)
+ raise
+ end
+
+ private
+
+ def stats
+ @stats ||= {}
+ end
+
+ def persist_stats!
+ return unless sync&.respond_to?(:sync_stats)
+ merged = (sync.sync_stats || {}).merge(stats)
+ sync.update_columns(sync_stats: merged)
+ end
+
+ def connections_by_id
+ @connections_by_id ||= begin
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+ redbark_provider.list_connections.index_by { |c| c[:id].to_s }
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue => e
+ capture_failure("Connections fetch failed; institution metadata will be limited", e)
+ {}
+ end
+ end
+
+ def import_accounts
+ Rails.logger.info "RedbarkItem::Importer - Fetching accounts"
+
+ accounts_data = redbark_provider.list_accounts
+
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+ stats["total_accounts"] = accounts_data.size
+
+ # Fetch connections once, before the per-account rescue below - an auth
+ # failure here must propagate and mark the item requires_update, not get
+ # swallowed as N per-account errors
+ connections_by_id
+
+ upstream_account_ids = []
+
+ accounts_data.each do |account_data|
+ begin
+ account_id = account_data[:id]&.to_s
+ next if account_id.blank?
+ next if account_data[:name].blank?
+
+ # Only banking and documents connections carry transactions;
+ # brokerage accounts belong to /v1/trades and are out of scope here
+ connection = connections_by_id[account_data[:connectionId].to_s]
+ next unless transactable_connection?(connection)
+
+ upstream_account_ids << account_id
+
+ redbark_account = redbark_item.redbark_accounts.find_or_initialize_by(
+ redbark_account_id: account_id
+ )
+ redbark_account.upsert_from_redbark!(account_data, connection_data: connection)
+
+ stats["accounts_imported"] = stats.fetch("accounts_imported", 0) + 1
+ rescue => e
+ capture_failure("Account import failed", e, account_id: account_data[:id])
+ stats["accounts_skipped"] = stats.fetch("accounts_skipped", 0) + 1
+ register_error(e, account_id: account_data[:id])
+ end
+ end
+
+ persist_stats!
+
+ @upstream_account_ids = upstream_account_ids
+
+ prune_removed_accounts(upstream_account_ids)
+ end
+
+ def import_transactions(redbark_account)
+ Rails.logger.info "RedbarkItem::Importer - Fetching transactions for account #{redbark_account.id}"
+
+ if redbark_account.connection_id.blank?
+ Rails.logger.warn "RedbarkItem::Importer - Account #{redbark_account.id} has no connection_id, skipping transactions"
+ return
+ end
+
+ # A linked account can still sit on a non-transactable connection
+ # (e.g. brokerage rows linked before this guard existed) - the
+ # transactions endpoint rejects those outright
+ connection = connections_by_id[redbark_account.connection_id.to_s]
+ unless transactable_connection?(connection)
+ Rails.logger.info "RedbarkItem::Importer - Skipping transactions for non-banking account #{redbark_account.id}"
+ return
+ end
+
+ begin
+ start_date = calculate_transaction_start_date(redbark_account)
+
+ transactions_data = redbark_provider.get_transactions(
+ connection_id: redbark_account.connection_id,
+ account_id: redbark_account.redbark_account_id,
+ start_date: start_date,
+ end_date: Date.current,
+ include_pending: Rails.configuration.x.redbark.include_pending
+ )
+
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+
+ if transactions_data.any?
+ transactions_hashes = transactions_data.map { |t| sdk_object_to_hash(t) }
+ merged = merge_transactions(
+ redbark_account.raw_transactions_payload || [],
+ transactions_hashes,
+ window_start: start_date
+ )
+ redbark_account.upsert_redbark_transactions_snapshot!(merged)
+ stats["transactions_found"] = stats.fetch("transactions_found", 0) + transactions_data.size
+ end
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue => e
+ capture_failure("Transactions fetch failed", e, account_id: redbark_account.redbark_account_id)
+ register_error(e, context: "transactions", account_id: redbark_account.id)
+ end
+ end
+
+ # One balances call covers every eligible linked account. A failed fetch
+ # leaves current_balance untouched so the processor keeps the previous
+ # balance instead of writing zeros.
+ def import_balances(linked_accounts)
+ eligible_accounts = balance_eligible_accounts(linked_accounts)
+ account_ids = eligible_accounts.map(&:redbark_account_id).compact
+ return if account_ids.empty?
+
+ begin
+ balances = fetch_balances_with_fallback(account_ids)
+
+ balances_by_id = balances.index_by { |b| b[:accountId].to_s }
+
+ eligible_accounts.each do |redbark_account|
+ balance_data = balances_by_id[redbark_account.redbark_account_id]
+ next unless balance_data
+
+ amount = parse_decimal(balance_data[:currentBalance])
+ next if amount.nil?
+
+ redbark_account.update!(
+ current_balance: amount,
+ currency: extract_currency(balance_data, fallback: redbark_account.currency)
+ )
+ stats["balances_updated"] = stats.fetch("balances_updated", 0) + 1
+ end
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue => e
+ capture_failure("Balances fetch failed; keeping previous balances", e)
+ register_error(e, context: "balances")
+ end
+ end
+
+ # The balances endpoint rejects the WHOLE batch when any requested id is
+ # unknown (404) or non-banking (400), so exclude accounts that no longer
+ # exist upstream and accounts on non-banking connections up front.
+ def balance_eligible_accounts(linked_accounts)
+ linked_accounts.select do |redbark_account|
+ next false if redbark_account.redbark_account_id.blank?
+
+ if @upstream_account_ids.present? && !@upstream_account_ids.include?(redbark_account.redbark_account_id)
+ next false
+ end
+
+ connection = connections_by_id[redbark_account.connection_id.to_s]
+ next true if connection.nil? # no connection metadata - let the fallback sort it out
+
+ category = connection[:category].to_s
+ category.blank? || category == "banking"
+ end
+ end
+
+ # If the batch is still rejected (stale id or category we could not see),
+ # fall back to per-account requests so one bad account cannot freeze
+ # balance updates for the rest of the item.
+ def fetch_balances_with_fallback(account_ids)
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+ redbark_provider.get_balances(account_ids: account_ids)
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue Provider::Redbark::Error => e
+ raise unless %i[not_found bad_request].include?(e.error_type)
+ raise if account_ids.size <= 1
+
+ capture_failure("Batched balances call rejected; retrying per account", e)
+
+ account_ids.flat_map do |account_id|
+ begin
+ stats["api_requests"] = stats.fetch("api_requests", 0) + 1
+ redbark_provider.get_balances(account_ids: [ account_id ])
+ rescue Provider::Redbark::AuthenticationError
+ raise
+ rescue Provider::Redbark::Error => account_error
+ capture_failure("Balance fetch failed for account; keeping previous balance", account_error, account_id: account_id)
+ []
+ end
+ end
+ end
+
+ def calculate_transaction_start_date(redbark_account)
+ has_stored_transactions = (redbark_account.raw_transactions_payload || []).any?
+
+ if has_stored_transactions && redbark_item.last_synced_at.present?
+ # Incremental: go back 7 days from last sync to catch late-posting
+ # transactions. The user's sync_start_date governs the initial
+ # backfill only - re-fetching the whole window every sync would blow
+ # through the API's row ceiling on busy accounts.
+ (redbark_item.last_synced_at - 7.days).to_date
+ elsif redbark_account.sync_start_date.present?
+ redbark_account.sync_start_date
+ else
+ # First sync for this account: pull a 90 day history
+ 90.days.ago.to_date
+ end
+ end
+
+ # The snapshot is bounded to the current fetch window - durable history
+ # lives in entries (deduped by external_id), so older rows are dropped
+ # rather than accumulated forever. Rows without a parseable date are kept.
+ # A pending row absent from the refetch has settled (possibly under a new
+ # id) - keeping it would duplicate the posted transaction.
+ def merge_transactions(existing, new_transactions, window_start: nil)
+ new_keys = new_transactions.map { |t| transaction_key(t) }.to_set
+
+ by_id = {}
+ existing.each do |t|
+ next unless within_window?(t, window_start)
+ next if stale_pending?(t, new_keys)
+ by_id[transaction_key(t)] = t
+ end
+ new_transactions.each { |t| by_id[transaction_key(t)] = t }
+ by_id.values
+ end
+
+ def within_window?(transaction, window_start)
+ return true if window_start.nil?
+
+ t = transaction.is_a?(Hash) ? transaction.with_indifferent_access : transaction
+ date = Date.parse(t[:date].to_s) rescue nil
+ date.nil? || date >= window_start
+ end
+
+ def stale_pending?(transaction, new_keys)
+ t = transaction.is_a?(Hash) ? transaction.with_indifferent_access : transaction
+ t[:status].to_s == "pending" && !new_keys.include?(transaction_key(t))
+ end
+
+ def transaction_key(transaction)
+ transaction = transaction.with_indifferent_access if transaction.is_a?(Hash)
+ transaction[:id].presence ||
+ [ transaction[:date], transaction[:amount], transaction[:description] ].join("-")
+ end
+
+ # Removes records that no longer exist upstream and are not linked to any
+ # Account. Guarded to a non-empty upstream list so a transient empty or
+ # failed response can never wipe out all accounts.
+ def prune_removed_accounts(upstream_account_ids)
+ return if upstream_account_ids.empty?
+
+ scope = redbark_item.redbark_accounts.includes(:account_provider)
+ orphaned = scope
+ .where.not(redbark_account_id: upstream_account_ids)
+ .or(scope.where(redbark_account_id: nil))
+
+ orphaned.each do |redbark_account|
+ if redbark_account.account_provider.present?
+ Rails.logger.info "RedbarkItem::Importer - Keeping stale RedbarkAccount #{redbark_account.id} (still linked to an Account)"
+ next
+ end
+
+ begin
+ Rails.logger.info "RedbarkItem::Importer - Pruning orphaned RedbarkAccount #{redbark_account.id} (no longer exists upstream)"
+ redbark_account.destroy
+ stats["accounts_pruned"] = stats.fetch("accounts_pruned", 0) + 1
+ rescue => e
+ capture_failure("Failed to prune orphaned account", e, redbark_account_id: redbark_account.id)
+ end
+ end
+ end
+
+ # Banking and documents connections serve /v1/transactions; anything else
+ # (brokerage) does not. Unknown connections get the benefit of the doubt.
+ def transactable_connection?(connection)
+ return true if connection.nil?
+
+ category = connection[:category].to_s
+ category.blank? || %w[banking documents].include?(category)
+ end
+
+ def register_error(error, **context)
+ stats["errors"] ||= []
+ stats["errors"] << {
+ message: error.message,
+ context: context.to_s,
+ timestamp: Time.current.iso8601
+ }
+ end
+
+ # Surfaces provider failures in the /settings/debug super-admin UI so
+ # support can diagnose without log access
+ def capture_failure(message, error, **metadata)
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: message,
+ source: self.class.name,
+ provider_key: "redbark",
+ family: redbark_item.family,
+ metadata: { error_class: error.class.name, error: error.message }.merge(metadata)
+ )
+ Rails.logger.warn "RedbarkItem::Importer - #{message}: #{error.class}: #{error.message}"
+ end
+end
diff --git a/app/models/redbark_item/provided.rb b/app/models/redbark_item/provided.rb
new file mode 100644
index 0000000000..f23965d7ed
--- /dev/null
+++ b/app/models/redbark_item/provided.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module RedbarkItem::Provided
+ extend ActiveSupport::Concern
+
+ def redbark_provider
+ return nil unless credentials_configured?
+
+ Provider::Redbark.new(
+ api_key: api_key
+ )
+ end
+
+ # Returns credentials hash for API calls that need them passed explicitly
+ def redbark_credentials
+ return nil unless credentials_configured?
+
+ {
+ api_key: api_key
+ }
+ end
+end
diff --git a/app/models/redbark_item/sync_complete_event.rb b/app/models/redbark_item/sync_complete_event.rb
new file mode 100644
index 0000000000..0049f8ffd7
--- /dev/null
+++ b/app/models/redbark_item/sync_complete_event.rb
@@ -0,0 +1,25 @@
+class RedbarkItem::SyncCompleteEvent
+ attr_reader :redbark_item
+
+ def initialize(redbark_item)
+ @redbark_item = redbark_item
+ end
+
+ def broadcast
+ # Update UI with latest account data
+ redbark_item.accounts.each do |account|
+ account.broadcast_sync_complete
+ end
+
+ # Update the Redbark item view
+ redbark_item.broadcast_replace_to(
+ redbark_item.family,
+ target: "redbark_item_#{redbark_item.id}",
+ partial: "redbark_items/redbark_item",
+ locals: { redbark_item: redbark_item }
+ )
+
+ # Let family handle sync notifications
+ redbark_item.family.broadcast_sync_complete
+ end
+end
diff --git a/app/models/redbark_item/syncer.rb b/app/models/redbark_item/syncer.rb
new file mode 100644
index 0000000000..e086f3c2db
--- /dev/null
+++ b/app/models/redbark_item/syncer.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+class RedbarkItem::Syncer
+ include SyncStats::Collector
+
+ attr_reader :redbark_item
+
+ def initialize(redbark_item)
+ @redbark_item = redbark_item
+ end
+
+ def perform_sync(sync)
+ Rails.logger.info "RedbarkItem::Syncer - Starting sync for item #{redbark_item.id}"
+
+ # Phase 1: Import data from provider API
+ sync.update!(status_text: I18n.t("redbark_items.sync.status.importing")) if sync.respond_to?(:status_text)
+ import_stats = redbark_item.import_latest_redbark_data(sync: sync)
+
+ # Phase 2: Collect setup statistics
+ finalize_setup_counts(sync)
+
+ # Phase 3: Process data for linked accounts
+ linked_redbark_accounts = redbark_item.linked_redbark_accounts.includes(account_provider: :account)
+ if linked_redbark_accounts.any?
+ sync.update!(status_text: I18n.t("redbark_items.sync.status.processing")) if sync.respond_to?(:status_text)
+ mark_import_started(sync)
+ redbark_item.process_accounts
+
+ # Phase 4: Schedule balance calculations
+ sync.update!(status_text: I18n.t("redbark_items.sync.status.calculating")) if sync.respond_to?(:status_text)
+ redbark_item.schedule_account_syncs(
+ parent_sync: sync,
+ window_start_date: sync.window_start_date,
+ window_end_date: sync.window_end_date
+ )
+
+ # Phase 5: Collect statistics
+ account_ids = linked_redbark_accounts.filter_map { |pa| pa.current_account&.id }
+ collect_transaction_stats(sync, account_ids: account_ids, source: "redbark")
+ end
+
+ # Mark sync health, surfacing per-account import errors instead of
+ # unconditionally reporting a clean run
+ import_errors = import_stats.is_a?(Hash) ? import_stats["errors"] : nil
+ collect_health_stats(sync, errors: import_errors.presence)
+ rescue Provider::Redbark::AuthenticationError => e
+ redbark_item.update!(status: :requires_update)
+ collect_health_stats(sync, errors: [ { message: e.message, category: "auth_error" } ])
+ raise
+ rescue => e
+ collect_health_stats(sync, errors: [ { message: e.message, category: "sync_error" } ])
+ raise
+ end
+
+ # Public: called by Sync after finalization
+ def perform_post_sync
+ # Override for post-sync cleanup if needed
+ end
+
+ private
+
+ def mark_import_started(sync)
+ # Mark that we're now processing imported data
+ sync.update!(status_text: I18n.t("redbark_items.sync.status.importing_data")) if sync.respond_to?(:status_text)
+ end
+
+ def finalize_setup_counts(sync)
+ sync.update!(status_text: I18n.t("redbark_items.sync.status.checking_setup")) if sync.respond_to?(:status_text)
+
+ unlinked_count = redbark_item.unlinked_accounts_count
+
+ if unlinked_count > 0
+ redbark_item.update!(pending_account_setup: true)
+ sync.update!(status_text: I18n.t("redbark_items.sync.status.needs_setup", count: unlinked_count)) if sync.respond_to?(:status_text)
+ else
+ redbark_item.update!(pending_account_setup: false)
+ end
+
+ # Collect setup stats
+ collect_setup_stats(sync, provider_accounts: redbark_item.redbark_accounts)
+ end
+end
diff --git a/app/models/redbark_item/unlinking.rb b/app/models/redbark_item/unlinking.rb
new file mode 100644
index 0000000000..7fa2b0b368
--- /dev/null
+++ b/app/models/redbark_item/unlinking.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module RedbarkItem::Unlinking
+ # Concern that encapsulates unlinking logic for a Redbark item.
+ extend ActiveSupport::Concern
+
+ # Idempotently remove all connections between this Redbark item and local accounts.
+ # - Detaches any AccountProvider links for each RedbarkAccount
+ # - Detaches Holdings that point at the AccountProvider links
+ # Returns a per-account result payload for observability
+ def unlink_all!(dry_run: false)
+ results = []
+
+ redbark_accounts.find_each do |provider_account|
+ links = AccountProvider.where(provider_type: "RedbarkAccount", provider_id: provider_account.id).to_a
+ link_ids = links.map(&:id)
+ result = {
+ provider_account_id: provider_account.id,
+ name: provider_account.name,
+ provider_link_ids: link_ids
+ }
+ results << result
+
+ next if dry_run
+
+ begin
+ ActiveRecord::Base.transaction do
+ # Detach holdings for any provider links found
+ if link_ids.any?
+ Holding.where(account_provider_id: link_ids).update_all(account_provider_id: nil)
+ end
+
+ # Destroy all provider links
+ links.each do |ap|
+ ap.destroy!
+ end
+ end
+ rescue StandardError => e
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "error",
+ message: "Failed to fully unlink Redbark provider account",
+ source: "RedbarkItem::Unlinking",
+ provider_key: "redbark",
+ family: family,
+ metadata: { redbark_account_id: provider_account.id, provider_link_ids: link_ids, error_class: e.class.name, error: e.message }
+ )
+ # Record error for observability; continue with other accounts
+ result[:error] = e.message
+ end
+ end
+
+ results
+ end
+end
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index ce95308aae..1aec5ef96e 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -95,7 +95,7 @@ class Transaction < ApplicationRecord
INTERNAL_MOVEMENT_LABELS = [ "Transfer", "Sweep In", "Sweep Out", "Exchange" ].freeze
# Providers that support pending transaction flags
- PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up mercury].freeze
+ PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up mercury redbark].freeze
# Pre-computed SQL fragment for subqueries that check if a transaction (aliased as "t") is pending.
# Stored as a constant so static analysis can verify it contains no user input.
diff --git a/app/views/accounts/index.html.erb b/app/views/accounts/index.html.erb
index 85d344024c..ee48dbcd65 100644
--- a/app/views/accounts/index.html.erb
+++ b/app/views/accounts/index.html.erb
@@ -27,7 +27,7 @@
) %>
<% end %>
-<% if @manual_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @akahu_items.empty? && @up_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @questrade_items.empty? && @wise_items.empty? %>
+<% if @manual_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @questrade_items.empty? && @wise_items.empty? %>
<%= render "empty" %>
<% else %>
<div class="space-y-2">
@@ -43,6 +43,10 @@
<%= render @lunchflow_items.sort_by(&:created_at) %>
<% end %>
+ <% if @redbark_items.any? %>
+ <%= render @redbark_items.sort_by(&:created_at) %>
+ <% end %>
+
<% if @akahu_items.any? %>
<%= render @akahu_items.sort_by(&:created_at) %>
<% end %>
diff --git a/app/views/redbark_items/_redbark_item.html.erb b/app/views/redbark_items/_redbark_item.html.erb
new file mode 100644
index 0000000000..3a8a1c44f9
--- /dev/null
+++ b/app/views/redbark_items/_redbark_item.html.erb
@@ -0,0 +1,133 @@
+<%# locals: (redbark_item:) %>
+
+<%= tag.div id: dom_id(redbark_item) do %>
+ <details open class="group bg-container p-4 shadow-border-xs rounded-xl">
+ <summary class="flex items-center justify-between gap-2 focus-visible:outline-hidden">
+ <div class="flex items-center gap-2">
+ <%= icon "chevron-right", class: "group-open:transform group-open:rotate-90" %>
+
+ <div class="flex items-center justify-center h-8 w-8 bg-primary/10 rounded-full">
+ <div class="flex items-center justify-center">
+ <%= tag.p redbark_item.name.first.upcase, class: "text-primary text-xs font-medium" %>
+ </div>
+ </div>
+
+ <div class="pl-1 text-sm">
+ <div class="flex items-center gap-2">
+ <%= tag.p redbark_item.name, class: "font-medium text-primary" %>
+ <% if redbark_item.scheduled_for_deletion? %>
+ <p class="text-destructive text-sm animate-pulse"><%= t(".deletion_in_progress") %></p>
+ <% end %>
+ </div>
+ <p class="text-xs text-secondary"><%= t(".provider_name") %></p>
+ <% if redbark_item.syncing? %>
+ <div class="text-secondary flex items-center gap-1">
+ <%= icon "loader", size: "sm", class: "animate-spin" %>
+ <%= tag.span t(".syncing") %>
+ </div>
+ <% elsif redbark_item.requires_update? %>
+ <div class="text-warning flex items-center gap-1">
+ <%= icon "alert-triangle", size: "sm", color: "warning" %>
+ <%= tag.span t(".requires_update") %>
+ </div>
+ <% else %>
+ <p class="text-secondary">
+ <% if redbark_item.last_synced_at %>
+ <% if redbark_item.sync_status_summary %>
+ <%= t(".status_with_summary", timestamp: time_ago_in_words(redbark_item.last_synced_at), summary: redbark_item.sync_status_summary) %>
+ <% else %>
+ <%= t(".status", timestamp: time_ago_in_words(redbark_item.last_synced_at)) %>
+ <% end %>
+ <% else %>
+ <%= t(".status_never") %>
+ <% end %>
+ </p>
+ <% end %>
+ </div>
+ </div>
+
+ <div class="flex items-center gap-2">
+ <% if redbark_item.requires_update? %>
+ <%= render DS::Link.new(
+ text: t(".update_credentials"),
+ icon: "refresh-cw",
+ variant: "secondary",
+ href: settings_providers_path,
+ frame: "_top"
+ ) %>
+ <% else %>
+ <%= icon(
+ "refresh-cw",
+ as_button: true,
+ href: sync_redbark_item_path(redbark_item),
+ disabled: redbark_item.syncing?
+ ) %>
+ <% end %>
+
+ <%= render DS::Menu.new do |menu| %>
+ <% menu.with_item(
+ variant: "button",
+ text: t(".delete"),
+ icon: "trash-2",
+ href: redbark_item_path(redbark_item),
+ method: :delete,
+ confirm: CustomConfirm.for_resource_deletion(redbark_item.name, high_severity: true)
+ ) %>
+ <% end %>
+ </div>
+ </summary>
+
+ <% unless redbark_item.scheduled_for_deletion? %>
+ <div class="space-y-4 mt-4">
+ <% if redbark_item.accounts.any? %>
+ <%= render "accounts/index/account_groups", accounts: redbark_item.accounts %>
+ <% end %>
+
+ <%# Sync summary (collapsible) - using shared ProviderSyncSummary component %>
+ <% stats = if defined?(@redbark_sync_stats_map) && @redbark_sync_stats_map
+ @redbark_sync_stats_map[redbark_item.id] || {}
+ else
+ redbark_item.syncs.ordered.first&.sync_stats || {}
+ end %>
+ <%= render ProviderSyncSummary.new(
+ stats: stats,
+ provider_item: redbark_item
+ ) %>
+
+ <%# Compute unlinked accounts (no AccountProvider link) %>
+ <% unlinked_count = redbark_item.unlinked_accounts_count %>
+
+ <% if unlinked_count.to_i > 0 && redbark_item.accounts.empty? %>
+ <%# No accounts imported yet - show prominent setup prompt %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".setup_needed") %></p>
+ <p class="text-secondary text-sm"><%= t(".setup_description", linked: redbark_item.linked_accounts_count, total: redbark_item.total_accounts_count) %></p>
+ <%= render DS::Link.new(
+ text: t(".setup_action"),
+ icon: "plus",
+ variant: "primary",
+ href: setup_accounts_redbark_item_path(redbark_item),
+ frame: :modal
+ ) %>
+ </div>
+ <% elsif unlinked_count.to_i > 0 %>
+ <%# Some accounts imported, more available - show subtle link %>
+ <div class="pt-2 border-t border-primary">
+ <%= link_to setup_accounts_redbark_item_path(redbark_item),
+ data: { turbo_frame: :modal },
+ class: "flex items-center gap-2 text-sm text-secondary hover:text-primary transition-colors" do %>
+ <%= icon "plus", size: "sm" %>
+ <span><%= t(".more_accounts_available", count: unlinked_count) %></span>
+ <% end %>
+ </div>
+ <% elsif redbark_item.accounts.empty? && redbark_item.redbark_accounts.none? %>
+ <%# No provider accounts at all - waiting for sync %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".no_accounts_title") %></p>
+ <p class="text-secondary text-sm"><%= t(".no_accounts_description") %></p>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+ </details>
+<% end %>
diff --git a/app/views/redbark_items/_setup_required.html.erb b/app/views/redbark_items/_setup_required.html.erb
new file mode 100644
index 0000000000..b55f42a6f6
--- /dev/null
+++ b/app/views/redbark_items/_setup_required.html.erb
@@ -0,0 +1,23 @@
+<%= turbo_frame_tag "modal" do %>
+ <%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title")) %>
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <%= render DS::Alert.new(
+ title: t(".not_configured_title"),
+ message: t(".not_configured_description"),
+ variant: :warning
+ ) %>
+
+ <div class="flex justify-end">
+ <%= render DS::Link.new(
+ text: t(".go_to_provider_settings"),
+ href: settings_providers_path,
+ variant: :primary,
+ data: { turbo: false }
+ ) %>
+ </div>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/redbark_items/select_existing_account.html.erb b/app/views/redbark_items/select_existing_account.html.erb
new file mode 100644
index 0000000000..f5bd296ff0
--- /dev/null
+++ b/app/views/redbark_items/select_existing_account.html.erb
@@ -0,0 +1,64 @@
+<% content_for :title, t("redbark_items.select_existing_account.title") %>
+
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t("redbark_items.select_existing_account.header")) do %>
+ <div class="flex items-center gap-2">
+ <%= icon "link", class: "text-primary" %>
+ <span class="text-primary"><%= t("redbark_items.select_existing_account.subtitle", account_name: @account.name) %></span>
+ </div>
+ <% end %>
+
+ <% dialog.with_body do %>
+ <% if @redbark_accounts.blank? %>
+ <div class="text-center py-8">
+ <%= icon "alert-circle", class: "text-warning mx-auto mb-4", size: "lg" %>
+ <p class="text-secondary"><%= t("redbark_items.select_existing_account.no_accounts") %></p>
+ <p class="text-sm text-secondary mt-2"><%= t("redbark_items.select_existing_account.connect_hint") %></p>
+ <%= link_to t("redbark_items.select_existing_account.settings_link"), settings_providers_path, class: "btn btn--primary btn--sm mt-4" %>
+ </div>
+ <% else %>
+ <div class="space-y-4">
+ <div class="bg-surface border border-primary p-4 rounded-lg mb-4">
+ <p class="text-sm text-primary">
+ <strong><%= t("redbark_items.select_existing_account.linking_to") %></strong>
+ <%= @account.name %>
+ </p>
+ </div>
+
+ <% @redbark_accounts.each do |redbark_account| %>
+ <%= form_with url: link_existing_account_redbark_items_path,
+ method: :post,
+ local: true,
+ class: "border border-primary rounded-lg p-4 hover:bg-surface transition-colors" do |form| %>
+ <%= hidden_field_tag :account_id, @account.id %>
+ <%= hidden_field_tag :redbark_account_id, redbark_account.id %>
+
+ <div class="flex items-center justify-between">
+ <div>
+ <h4 class="font-medium text-primary"><%= redbark_account.name %></h4>
+ <p class="text-sm text-secondary">
+ <%= t("redbark_items.select_existing_account.balance_label") %>
+ <%= number_to_currency(redbark_account.current_balance || 0, unit: Money::Currency.new(redbark_account.currency || "USD").symbol) %>
+ </p>
+ </div>
+ <%= render DS::Button.new(
+ text: t("redbark_items.select_existing_account.link_button"),
+ variant: "primary",
+ size: "sm",
+ type: "submit"
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+
+ <div class="mt-6">
+ <%= render DS::Link.new(
+ text: t("redbark_items.select_existing_account.cancel_button"),
+ variant: "secondary",
+ href: account_path(@account)
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/redbark_items/setup_accounts.html.erb b/app/views/redbark_items/setup_accounts.html.erb
new file mode 100644
index 0000000000..d2c74faa58
--- /dev/null
+++ b/app/views/redbark_items/setup_accounts.html.erb
@@ -0,0 +1,75 @@
+<% content_for :title, t(".title") %>
+
+<%= render DS::Dialog.new(disable_click_outside: true) do |dialog| %>
+ <% dialog.with_header(title: t(".title")) do %>
+ <div class="flex items-center gap-2">
+ <%= icon "landmark", class: "text-primary" %>
+ <span class="text-primary"><%= t(".subtitle") %></span>
+ </div>
+ <% end %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-6">
+ <% if @api_error.present? %>
+ <%= render DS::Alert.new(
+ title: t(".fetch_failed"),
+ message: @api_error,
+ variant: :error
+ ) %>
+ <% end %>
+
+ <% if @unlinked_accounts.blank? %>
+ <div class="flex flex-col items-center justify-center py-6 space-y-3">
+ <% if @api_error.blank? %>
+ <%= icon "check-circle", size: "lg", class: "text-success" %>
+ <p class="text-primary text-center font-medium"><%= t(".all_accounts_linked") %></p>
+ <% end %>
+ <%= render DS::Link.new(text: t(".done"), variant: "primary", href: accounts_path, frame: "_top") %>
+ </div>
+ <% else %>
+ <%= form_with url: complete_account_setup_redbark_item_path(@redbark_item), method: :post, data: { turbo_frame: "_top" }, class: "space-y-6" do %>
+ <div class="bg-surface border border-primary p-4 rounded-lg">
+ <div class="flex items-start gap-3">
+ <%= icon "info", size: "sm", class: "text-primary mt-0.5 flex-shrink-0" %>
+ <p class="text-sm text-primary"><%= t(".choose_account_type") %></p>
+ </div>
+ </div>
+
+ <div class="space-y-4 max-h-96 overflow-y-auto">
+ <% @unlinked_accounts.each do |redbark_account| %>
+ <div class="border border-primary rounded-lg p-4">
+ <h4 class="font-medium text-primary"><%= redbark_account.name %></h4>
+ <p class="text-xs text-secondary mb-3">
+ <%= [ redbark_account.account_type&.titleize, redbark_account.currency ].compact.join(" · ") %>
+ </p>
+
+ <label class="block text-sm text-secondary mb-1" for="account_type_<%= redbark_account.id %>">
+ <%= t(".account_type_label") %>
+ </label>
+ <select id="account_type_<%= redbark_account.id %>"
+ name="accounts[<%= redbark_account.id %>][account_type]"
+ class="bg-container border border-primary rounded px-2 py-1 text-sm text-primary w-full">
+ <option value="depository" selected><%= t(".account_types.depository") %></option>
+ <option value="credit_card"><%= t(".account_types.credit_card") %></option>
+ <option value="loan"><%= t(".account_types.loan") %></option>
+ <option value="skip"><%= t(".account_types.skip") %></option>
+ </select>
+ </div>
+ <% end %>
+ </div>
+
+ <div class="flex gap-3">
+ <%= render DS::Button.new(
+ text: t(".create_accounts"),
+ variant: "primary",
+ icon: "plus",
+ type: "submit",
+ class: "flex-1"
+ ) %>
+ <%= render DS::Link.new(text: t(".cancel"), variant: "secondary", href: accounts_path, frame: "_top") %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/settings/providers/_redbark_panel.html.erb b/app/views/settings/providers/_redbark_panel.html.erb
new file mode 100644
index 0000000000..a80a2f1693
--- /dev/null
+++ b/app/views/settings/providers/_redbark_panel.html.erb
@@ -0,0 +1,60 @@
+<div id="redbark-providers-panel" class="space-y-4">
+ <div class="prose prose-sm text-secondary">
+ <p class="text-primary font-medium"><%= t("redbark_items.panel.setup_instructions") %></p>
+ <ol>
+ <li><%= t("redbark_items.panel.step_1") %></li>
+ <li><%= t("redbark_items.panel.step_2") %></li>
+ <li><%= t("redbark_items.panel.step_3") %></li>
+ </ol>
+
+ <p class="text-primary font-medium"><%= t("redbark_items.panel.field_descriptions") %></p>
+ <ul>
+ <li><strong><%= t("redbark_items.panel.fields.api_key.label") %>:</strong> <%= t("redbark_items.panel.fields.api_key.description") %> <%= t("redbark_items.panel.required") %></li>
+ </ul>
+ </div>
+
+ <% error_msg = local_assigns[:error_message] || @error_message %>
+ <% if error_msg.present? %>
+ <div class="p-2 rounded-md bg-destructive/10 text-destructive text-sm overflow-hidden">
+ <p class="line-clamp-3" title="<%= error_msg %>"><%= error_msg %></p>
+ </div>
+ <% end %>
+
+ <%
+ # Get or initialize a redbark_item for this family
+ # - If family has an item WITH credentials, use it (for updates)
+ # - If family has an item WITHOUT credentials, use it (to add credentials)
+ # - If family has no items at all, create a new one
+ redbark_item = Current.family.redbark_items.first_or_initialize(name: t("redbark_items.default_name"))
+ is_new_record = redbark_item.new_record?
+ %>
+
+ <%= styled_form_with model: redbark_item,
+ url: is_new_record ? redbark_items_path : redbark_item_path(redbark_item),
+ scope: :redbark_item,
+ method: is_new_record ? :post : :patch,
+ data: { turbo: true },
+ class: "space-y-3" do |form| %>
+ <%= form.text_field :api_key,
+ label: t("redbark_items.panel.fields.api_key.label"),
+ placeholder: is_new_record ? t("redbark_items.panel.fields.api_key.placeholder_new") : t("redbark_items.panel.fields.api_key.placeholder_update"),
+ type: :password,
+ value: nil %>
+
+ <div class="flex justify-end">
+ <%= form.submit is_new_record ? t("redbark_items.panel.save_button") : t("redbark_items.panel.update_button"),
+ class: "inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium btn btn--primary" %>
+ </div>
+ <% end %>
+
+ <% items = local_assigns[:redbark_items] || @redbark_items || Current.family.redbark_items.where.not(api_key: [nil, ""]) %>
+ <div class="flex items-center gap-2">
+ <% if items&.any? %>
+ <div class="w-2 h-2 bg-success rounded-full"></div>
+ <p class="text-sm text-secondary"><%= t("redbark_items.panel.status_configured_html", accounts_path: accounts_path).html_safe %></p>
+ <% else %>
+ <div class="w-2 h-2 bg-surface-inset rounded-full"></div>
+ <p class="text-sm text-secondary"><%= t("redbark_items.panel.status_not_configured") %></p>
+ <% end %>
+ </div>
+</div>
diff --git a/config/initializers/redbark.rb b/config/initializers/redbark.rb
new file mode 100644
index 0000000000..e9a2b30a66
--- /dev/null
+++ b/config/initializers/redbark.rb
@@ -0,0 +1,7 @@
+# Redbark integration runtime configuration
+Rails.application.configure do
+ # Controls whether pending transactions are included in Redbark syncs
+ # When true, adds includePending=true to transaction fetch requests
+ # Default: false (only posted transactions)
+ config.x.redbark.include_pending = ENV["REDBARK_INCLUDE_PENDING"].to_s.strip.downcase.in?(%w[1 true yes])
+end
diff --git a/config/locales/breadcrumbs/en.yml b/config/locales/breadcrumbs/en.yml
index 641c505dcf..400fc31b7c 100644
--- a/config/locales/breadcrumbs/en.yml
+++ b/config/locales/breadcrumbs/en.yml
@@ -64,6 +64,7 @@ en:
properties: Properties
providers: Providers
recurring_transactions: Recurring
+ redbark_items: Redbark
registrations: Sign up
reports: Reports
rules: Rules
diff --git a/config/locales/views/redbark_items/en.yml b/config/locales/views/redbark_items/en.yml
new file mode 100644
index 0000000000..1f7f016e31
--- /dev/null
+++ b/config/locales/views/redbark_items/en.yml
@@ -0,0 +1,212 @@
+---
+en:
+ redbark_items:
+ default_name: "Redbark Connection"
+ # Model method strings (i18n for item_model.rb)
+ sync_status:
+ no_accounts: "No accounts found"
+ synced:
+ one: "%{count} account synced"
+ other: "%{count} accounts synced"
+ synced_with_setup: "%{linked} synced, %{unlinked} need setup"
+ institution_summary:
+ none: "No institutions connected"
+ count:
+ one: "%{count} institution"
+ other: "%{count} institutions"
+ errors:
+ provider_not_configured: "Redbark provider is not configured"
+
+ # Syncer status messages
+ sync:
+ status:
+ importing: "Importing accounts from Redbark..."
+ processing: "Processing transactions..."
+ calculating: "Calculating balances..."
+ importing_data: "Importing account data..."
+ checking_setup: "Checking account configuration..."
+ needs_setup: "%{count} accounts need setup..."
+ success: "Sync started"
+
+ # Panel (settings view)
+ panel:
+ setup_instructions: "Setup instructions:"
+ step_1: "Create an API key at app.redbark.com under Settings"
+ step_2: "Enter your API key below and click the Save button"
+ step_3: "After a successful connection, go to the Accounts tab to set up new accounts"
+ field_descriptions: "Field descriptions:"
+ optional: "(Optional)"
+ required: "(required)"
+ optional_with_default: "(optional, defaults to %{default_value})"
+ save_button: "Save Configuration"
+ update_button: "Update Configuration"
+ status_configured_html: "Configured and ready to use. Visit the <a href=\"%{accounts_path}\" class=\"link\">Accounts</a> tab to manage and set up accounts."
+ status_not_configured: "Not configured"
+ fields:
+ api_key:
+ label: "API Key"
+ description: "Your Redbark API key (starts with rbk_live_)"
+ placeholder_new: "rbk_live_..."
+ placeholder_update: "Enter new API key to update"
+
+ # CRUD success messages
+ create:
+ success: "Redbark connection created successfully"
+ update:
+ success: "Redbark connection updated"
+ destroy:
+ success: "Redbark connection removed"
+ unlink_failed:
+ one: "Could not unlink %{count} account. Please try again."
+ other: "Could not unlink %{count} accounts. Please try again."
+ index:
+ title: "Redbark Connections"
+
+ # Loading states
+ loading:
+ loading_message: "Loading Redbark accounts..."
+ loading_title: "Loading"
+
+ # Provider item display (used in _item partial)
+ redbark_item:
+ accounts_need_setup: "Accounts need setup"
+ delete: "Delete connection"
+ deletion_in_progress: "deletion in progress..."
+ error: "Error"
+ more_accounts_available:
+ one: "%{count} more account available"
+ other: "%{count} more accounts available"
+ no_accounts_description: "This connection has no linked accounts yet."
+ no_accounts_title: "No accounts"
+ provider_name: "Redbark"
+ requires_update: "Connection needs update"
+ setup_action: "Set Up New Accounts"
+ setup_description: "%{linked} of %{total} accounts linked. Choose account types for your newly imported Redbark accounts."
+ setup_needed: "New accounts ready to set up"
+ status: "Synced %{timestamp} ago"
+ status_never: "Never synced"
+ status_with_summary: "Last synced %{timestamp} ago - %{summary}"
+ syncing: "Syncing..."
+ total: "Total"
+ unlinked: "Unlinked"
+ update_credentials: "Update credentials"
+
+ # Select accounts view
+ select_accounts:
+ accounts_selected: "accounts selected"
+ api_error: "API error: %{message}"
+ cancel: "Cancel"
+ configure_name_in_provider: "Cannot import - please configure account name in Redbark"
+ description: "Select the accounts you want to link to your %{product_name} account."
+ link_accounts: "Link selected accounts"
+ no_accounts_found: "No accounts found. Please check your API key configuration."
+ no_api_key: "Redbark API key is not configured. Please configure it in Settings."
+ no_credentials_configured: "Please configure your Redbark credentials first in Provider Settings."
+ no_name_placeholder: "(No name)"
+ title: "Select Redbark Accounts"
+
+ # Select existing account view
+ select_existing_account:
+ account_already_linked: "This account is already linked to a provider"
+ all_accounts_already_linked: "All Redbark accounts are already linked"
+ api_error: "API error: %{message}"
+ balance_label: "Balance:"
+ cancel: "Cancel"
+ cancel_button: "Cancel"
+ configure_name_in_provider: "Cannot import - please configure account name in Redbark"
+ connect_hint: "Connect a Redbark account to enable automatic syncing."
+ description: "Select a Redbark account to link with this account. Transactions will be synced and deduplicated automatically."
+ header: "Link with Redbark"
+ link_account: "Link account"
+ link_button: "Link this account"
+ linking_to: "Linking to:"
+ no_account_specified: "No account specified"
+ no_accounts: "No unlinked Redbark accounts found."
+ no_accounts_found: "No Redbark accounts found. Please check your API key configuration."
+ no_api_key: "Redbark API key is not configured. Please configure it in Settings."
+ no_credentials_configured: "Please configure your Redbark credentials first in Provider Settings."
+ no_name_placeholder: "(No name)"
+ settings_link: "Go to Provider Settings"
+ subtitle: "Choose a Redbark account"
+ title: "Link %{account_name} with Redbark"
+
+ # Link existing account
+ link_existing_account:
+ account_already_linked: "This account is already linked to a provider"
+ api_error: "API error: %{message}"
+ invalid_account_name: "Cannot link account with blank name"
+ provider_account_already_linked: "This Redbark account is already linked to another account"
+ provider_account_not_found: "Redbark account not found"
+ missing_parameters: "Missing required parameters"
+ no_api_key: "Redbark API key not found. Please configure it in Provider Settings."
+ success: "Successfully linked %{account_name} with Redbark"
+
+ # Setup accounts wizard
+ setup_accounts:
+ account_type_label: "Account Type:"
+ accounts_count:
+ one: "%{count} account available"
+ other: "%{count} accounts available"
+ all_accounts_linked: "All your Redbark accounts have already been set up."
+ api_error: "API error: %{message}"
+ creating: "Creating accounts..."
+ fetch_failed: "Failed to Fetch Accounts"
+ import_selected: "Import selected accounts"
+ instructions: "Select the accounts you want to import from Redbark. You can choose multiple accounts."
+ no_accounts: "No unlinked accounts found from this Redbark connection."
+ no_accounts_to_setup: "No Accounts to Set Up"
+ no_api_key: "Redbark API key is not configured. Please check your connection settings."
+ select_all: "Select all"
+ account_types:
+ skip: "Skip this account"
+ depository: "Checking or Savings Account"
+ credit_card: "Credit Card"
+ loan: "Loan or Mortgage"
+ other_asset: "Other Asset"
+ subtype_labels:
+ depository: "Account Subtype:"
+ credit_card: ""
+ loan: "Loan Type:"
+ other_asset: ""
+ subtype_messages:
+ credit_card: "Credit cards will be automatically set up as credit card accounts."
+ other_asset: "No additional options needed for Other Assets."
+ subtypes:
+ depository:
+ checking: "Checking"
+ savings: "Savings"
+ hsa: "Health Savings Account"
+ cd: "Certificate of Deposit"
+ money_market: "Money Market"
+ loan:
+ mortgage: "Mortgage"
+ student: "Student Loan"
+ auto: "Auto Loan"
+ other: "Other Loan"
+ balance: "Balance"
+ cancel: "Cancel"
+ done: "Done"
+ choose_account_type: "Choose the correct account type for each Redbark account:"
+ create_accounts: "Create Accounts"
+ creating_accounts: "Creating Accounts..."
+ historical_data_range: "Historical Data Range:"
+ subtitle: "Choose the correct account types for your imported accounts"
+ sync_start_date_help: "Select how far back you want to sync transaction history."
+ sync_start_date_label: "Start syncing transactions from:"
+ title: "Set Up Your Redbark Accounts"
+
+ setup_required:
+ title: Connect Redbark first
+ not_configured_title: Redbark isn't connected yet
+ not_configured_description: Add your Redbark API key under Provider settings, then come back here to link accounts.
+ go_to_provider_settings: Go to provider settings
+
+ # Complete account setup
+ complete_account_setup:
+ all_skipped: "All accounts were skipped. No accounts were created."
+ creation_failed: "Failed to create accounts: %{error}"
+ creation_failed_generic: "Failed to create accounts."
+ setup_failed: "%{count} account(s) could not be created. Nothing else was changed - fix the issue and try again."
+ no_accounts: "No accounts to set up."
+ success: "Successfully created %{count} account(s)."
+
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 2c2071093c..e4aa695864 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -396,6 +396,7 @@ en:
akahu: Sync New Zealand financial institutions via Akahu.
simplefin: Connect US bank accounts via the open SimpleFIN protocol.
lunchflow: Connect 20k+ banks from 40+ countries (UK, EU, USA and more!)
+ redbark: Sync Australian bank accounts via Redbark open banking.
enable_banking: Sync European bank accounts via PSD2 open banking.
coinstats: Track your entire crypto portfolio across wallets and exchanges.
wise: Sync your Wise multi-currency balances and international transfers automatically.
diff --git a/config/routes.rb b/config/routes.rb
index 5377bcb1d7..2507abceef 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -717,6 +717,20 @@ Rails.application.routes.draw do
end
end
+ resources :redbark_items, only: %i[create update destroy] do
+ collection do
+ get :select_accounts
+ get :select_existing_account
+ post :link_existing_account
+ end
+
+ member do
+ post :sync
+ get :setup_accounts
+ post :complete_account_setup
+ end
+ end
+
resources :akahu_items, only: %i[index new create show edit update destroy] do
collection do
get :preload_accounts
diff --git a/db/migrate/20260725000000_create_redbark_items_and_accounts.rb b/db/migrate/20260725000000_create_redbark_items_and_accounts.rb
new file mode 100644
index 0000000000..28b04b4959
--- /dev/null
+++ b/db/migrate/20260725000000_create_redbark_items_and_accounts.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+class CreateRedbarkItemsAndAccounts < ActiveRecord::Migration[7.2]
+ def change
+ # Create provider items table (stores per-family connection credentials)
+ create_table :redbark_items, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: true, type: :uuid
+ t.string :name, null: false
+
+ # Institution metadata
+ t.string :institution_id
+ t.string :institution_name
+ t.string :institution_domain
+ t.string :institution_url
+ t.string :institution_color
+
+ # Status and lifecycle
+ t.string :status, default: "good", null: false
+ t.boolean :scheduled_for_deletion, default: false, null: false
+ t.boolean :pending_account_setup, default: false, null: false
+
+ # Sync settings
+ t.datetime :sync_start_date
+
+ # Raw data storage
+ t.jsonb :raw_payload
+ t.jsonb :raw_institution_payload
+
+ # Provider-specific credential fields
+ t.text :api_key, null: false
+
+ t.timestamps
+ end
+
+ add_index :redbark_items, :status
+
+ # Create provider accounts table (stores individual account data from provider)
+ create_table :redbark_accounts, id: :uuid do |t|
+ t.references :redbark_item, null: false, foreign_key: true, type: :uuid
+
+ # Account identification
+ t.string :name, null: false
+ t.string :redbark_account_id, null: false
+ t.string :connection_id
+ t.string :account_number
+
+ # Account details
+ t.string :currency, null: false
+ t.decimal :current_balance, precision: 19, scale: 4
+ t.string :account_status
+ t.string :account_type
+ t.string :provider
+
+ # Setup state - accounts the user chose to skip stay hidden from setup prompts
+ t.boolean :ignored, default: false, null: false
+
+ # Metadata and raw data
+ t.jsonb :institution_metadata
+ t.jsonb :raw_payload
+ t.jsonb :raw_transactions_payload
+
+ # Sync settings
+ t.date :sync_start_date
+
+ t.timestamps
+ end
+
+ add_index :redbark_accounts, [ :redbark_item_id, :redbark_account_id ], unique: true, name: "index_redbark_accounts_on_item_and_account_id"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index d2e0872dc8..7e94f1dce2 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[7.2].define(version: 2026_07_19_000002) do
+ActiveRecord::Schema[7.2].define(version: 2026_07_25_000000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pgcrypto"
enable_extension "plpgsql"
@@ -1640,6 +1640,49 @@ ActiveRecord::Schema[7.2].define(version: 2026_07_19_000002) do
t.check_constraint "destination_account_id IS NULL OR destination_account_id <> account_id", name: "chk_recurring_txns_transfer_distinct_accounts"
end
+ create_table "redbark_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "redbark_item_id", null: false
+ t.string "name", null: false
+ t.string "redbark_account_id", null: false
+ t.string "connection_id"
+ t.string "account_number"
+ t.string "currency", null: false
+ t.decimal "current_balance", precision: 19, scale: 4
+ t.string "account_status"
+ t.string "account_type"
+ t.string "provider"
+ t.boolean "ignored", default: false, null: false
+ t.jsonb "institution_metadata"
+ t.jsonb "raw_payload"
+ t.jsonb "raw_transactions_payload"
+ t.date "sync_start_date"
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["redbark_item_id", "redbark_account_id"], name: "index_redbark_accounts_on_item_and_account_id", unique: true
+ t.index ["redbark_item_id"], name: "index_redbark_accounts_on_redbark_item_id"
+ end
+
+ create_table "redbark_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "family_id", null: false
+ t.string "name", null: false
+ t.string "institution_id"
+ t.string "institution_name"
+ t.string "institution_domain"
+ t.string "institution_url"
+ t.string "institution_color"
+ t.string "status", default: "good", null: false
+ t.boolean "scheduled_for_deletion", default: false, null: false
+ t.boolean "pending_account_setup", default: false, null: false
+ t.datetime "sync_start_date"
+ t.jsonb "raw_payload"
+ t.jsonb "raw_institution_payload"
+ t.text "api_key", null: false
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["family_id"], name: "index_redbark_items_on_family_id"
+ t.index ["status"], name: "index_redbark_items_on_status"
+ end
+
create_table "rejected_transfers", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.uuid "inflow_transaction_id", null: false
t.uuid "outflow_transaction_id", null: false
@@ -2370,6 +2413,8 @@ ActiveRecord::Schema[7.2].define(version: 2026_07_19_000002) do
add_foreign_key "recurring_transactions", "accounts", on_delete: :cascade
add_foreign_key "recurring_transactions", "families"
add_foreign_key "recurring_transactions", "merchants"
+ add_foreign_key "redbark_accounts", "redbark_items"
+ add_foreign_key "redbark_items", "families"
add_foreign_key "rejected_transfers", "transactions", column: "inflow_transaction_id", on_delete: :cascade
add_foreign_key "rejected_transfers", "transactions", column: "outflow_transaction_id", on_delete: :cascade
add_foreign_key "rule_actions", "rules"
diff --git a/test/controllers/redbark_items_controller_test.rb b/test/controllers/redbark_items_controller_test.rb
new file mode 100644
index 0000000000..9f94d40dd2
--- /dev/null
+++ b/test/controllers/redbark_items_controller_test.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class RedbarkItemsControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in users(:family_admin)
+ SyncJob.stubs(:perform_later)
+
+ @family = families(:dylan_family)
+ @redbark_item = redbark_items(:one)
+ @redbark_account = redbark_accounts(:savings_account)
+ end
+
+ test "create adds a new redbark connection" do
+ family = users(:empty).family
+ sign_in users(:empty)
+
+ assert_difference "RedbarkItem.count", 1 do
+ post redbark_items_url, params: {
+ redbark_item: { api_key: "rbk_live_new_key" }
+ }
+ end
+
+ item = family.redbark_items.order(:created_at).last
+ assert_equal "rbk_live_new_key", item.api_key
+ end
+
+ test "create with blank api key is rejected" do
+ assert_no_difference "RedbarkItem.count" do
+ post redbark_items_url, params: {
+ redbark_item: { api_key: "" }
+ }
+ end
+ end
+
+ test "update rotates the api key and clears requires_update" do
+ @redbark_item.update!(status: :requires_update)
+
+ patch redbark_item_url(@redbark_item), params: {
+ redbark_item: { api_key: "rbk_live_rotated" }
+ }
+
+ @redbark_item.reload
+ assert_equal "rbk_live_rotated", @redbark_item.api_key
+ assert @redbark_item.good?
+ end
+
+ test "blank api key update is rejected and preserves the stored key" do
+ original_key = @redbark_item.api_key
+
+ patch redbark_item_url(@redbark_item), params: {
+ redbark_item: { api_key: "" }
+ }
+
+ assert_equal original_key, @redbark_item.reload.api_key
+ end
+
+ test "sync enqueues a sync" do
+ RedbarkItem.any_instance.stubs(:syncing?).returns(false)
+ RedbarkItem.any_instance.expects(:sync_later).once
+
+ post sync_redbark_item_url(@redbark_item)
+ assert_response :redirect
+ end
+
+ test "destroy schedules the connection for deletion" do
+ delete redbark_item_url(@redbark_item)
+
+ assert_redirected_to settings_providers_path
+ assert @redbark_item.reload.scheduled_for_deletion?
+ end
+
+ test "complete_account_setup creates and links an account" do
+ assert_difference "Account.count", 1 do
+ post complete_account_setup_redbark_item_url(@redbark_item), params: {
+ accounts: { @redbark_account.id => { account_type: "depository" } }
+ }
+ end
+
+ @redbark_account.reload
+ assert @redbark_account.account_provider.present?
+ assert_equal "Depository", @redbark_account.account.accountable_type
+ assert_not @redbark_account.ignored?
+ end
+
+ test "complete_account_setup skip marks the account ignored" do
+ assert_no_difference "Account.count" do
+ post complete_account_setup_redbark_item_url(@redbark_item), params: {
+ accounts: { @redbark_account.id => { account_type: "skip" } }
+ }
+ end
+
+ assert @redbark_account.reload.ignored?
+ assert_not @redbark_item.reload.unlinked_redbark_accounts.exists?(id: @redbark_account.id)
+ end
+end
diff --git a/test/encryption_verification_test.rb b/test/encryption_verification_test.rb
index 63885a1d0f..c574274372 100644
--- a/test/encryption_verification_test.rb
+++ b/test/encryption_verification_test.rb
@@ -280,6 +280,46 @@ class EncryptionVerificationTest < ActiveSupport::TestCase
account.update!(raw_payload: original_payload)
end
+ test "redbark item credentials and payloads are encrypted" do
+ skip "No redbark items in fixtures" unless RedbarkItem.any?
+
+ item = RedbarkItem.first
+ original_payload = item.raw_payload
+
+ # Should be able to read
+ assert item.api_key.present? || item.raw_payload.present?
+
+ # Update payload
+ item.update!(raw_payload: { test: "data" })
+ item.reload
+
+ assert_equal({ "test" => "data" }, item.raw_payload)
+
+ # Restore
+ item.update!(raw_payload: original_payload)
+ end
+
+ test "redbark account payloads are encrypted" do
+ skip "No redbark accounts in fixtures" unless RedbarkAccount.any?
+
+ account = RedbarkAccount.first
+ original_payload = account.raw_payload
+
+ # Should be able to read encrypted fields without error
+ account.reload
+ assert_nothing_raised { account.raw_payload }
+ assert_nothing_raised { account.raw_transactions_payload }
+
+ # Update and verify
+ account.update!(raw_payload: { account_test: "value" })
+ account.reload
+
+ assert_equal({ "account_test" => "value" }, account.raw_payload)
+
+ # Restore
+ account.update!(raw_payload: original_payload)
+ end
+
# ============================================================================
# DATABASE VERIFICATION TESTS
# ============================================================================
diff --git a/test/fixtures/redbark_accounts.yml b/test/fixtures/redbark_accounts.yml
new file mode 100644
index 0000000000..b3341c976e
--- /dev/null
+++ b/test/fixtures/redbark_accounts.yml
@@ -0,0 +1,7 @@
+savings_account:
+ redbark_item: one
+ redbark_account_id: "rb_acc_savings_1"
+ connection_id: "rb_conn_1"
+ name: "Test Bank - Everyday Saver"
+ currency: AUD
+ current_balance: 2500.00
diff --git a/test/fixtures/redbark_items.yml b/test/fixtures/redbark_items.yml
new file mode 100644
index 0000000000..1110133e7c
--- /dev/null
+++ b/test/fixtures/redbark_items.yml
@@ -0,0 +1,6 @@
+one:
+ family: dylan_family
+
+ name: "Test Redbark Connection"
+ api_key: "rbk_live_test_api_key_123"
+ status: good
diff --git a/test/models/provider/redbark_adapter_test.rb b/test/models/provider/redbark_adapter_test.rb
new file mode 100644
index 0000000000..04a88c1f80
--- /dev/null
+++ b/test/models/provider/redbark_adapter_test.rb
@@ -0,0 +1,33 @@
+require "test_helper"
+
+class Provider::RedbarkAdapterTest < ActiveSupport::TestCase
+ test "supports Depository accounts" do
+ assert_includes Provider::RedbarkAdapter.supported_account_types, "Depository"
+ end
+
+ test "does not support Investment accounts" do
+ assert_not_includes Provider::RedbarkAdapter.supported_account_types, "Investment"
+ end
+
+ test "returns connection config for families" do
+ configs = Provider::RedbarkAdapter.connection_configs(family: families(:empty))
+
+ assert_equal 1, configs.length
+ assert_equal "redbark", configs.first[:key]
+ assert configs.first[:can_connect]
+ end
+
+ test "builds provider with valid credentials" do
+ provider = Provider::RedbarkAdapter.build_provider(family: families(:dylan_family))
+
+ assert_instance_of Provider::Redbark, provider
+ end
+
+ test "returns nil without credentials" do
+ assert_nil Provider::RedbarkAdapter.build_provider(family: families(:empty))
+ end
+
+ test "returns nil without family" do
+ assert_nil Provider::RedbarkAdapter.build_provider(family: nil)
+ end
+end
diff --git a/test/models/provider/redbark_test.rb b/test/models/provider/redbark_test.rb
new file mode 100644
index 0000000000..1e34eba993
--- /dev/null
+++ b/test/models/provider/redbark_test.rb
@@ -0,0 +1,87 @@
+require "test_helper"
+
+class Provider::RedbarkTest < ActiveSupport::TestCase
+ test "initializes with api key" do
+ provider = Provider::Redbark.new(api_key: "rbk_live_test")
+ assert_equal "rbk_live_test", provider.api_key
+ end
+
+ test "raises configuration error when api key blank" do
+ assert_raises(Provider::Redbark::ConfigurationError) do
+ Provider::Redbark.new(api_key: "")
+ end
+ end
+
+ test "error includes error_type" do
+ error = Provider::Redbark::Error.new("Test error", :unauthorized)
+ assert_equal "Test error", error.message
+ assert_equal :unauthorized, error.error_type
+ end
+
+ test "error defaults error_type to unknown" do
+ error = Provider::Redbark::Error.new("Test error")
+ assert_equal :unknown, error.error_type
+ end
+
+ test "rate limit and server errors are typed for retry handling" do
+ assert Provider::Redbark::RateLimitError.new("limited", :rate_limited).is_a?(Provider::Redbark::Error)
+ assert Provider::Redbark::ServerError.new("boom", :server_error).is_a?(Provider::Redbark::Error)
+ end
+
+ test "get_transactions splits the window when the server truncates" do
+ provider = Provider::Redbark.new(api_key: "rbk_live_test")
+
+ stub_request(:get, "https://api.redbark.com/v1/transactions")
+ .with(query: hash_including("from" => "2026-01-01", "to" => "2026-01-31"))
+ .to_return(
+ status: 200,
+ headers: { "Content-Type" => "application/json", "X-Redbark-Truncated" => "true" },
+ body: { data: [ { id: "t1" } ], pagination: { hasMore: true } }.to_json
+ )
+ stub_request(:get, "https://api.redbark.com/v1/transactions")
+ .with(query: hash_including("from" => "2026-01-01", "to" => "2026-01-16"))
+ .to_return(
+ status: 200,
+ headers: { "Content-Type" => "application/json" },
+ body: { data: [ { id: "t1" }, { id: "t2" } ], pagination: { hasMore: false } }.to_json
+ )
+ stub_request(:get, "https://api.redbark.com/v1/transactions")
+ .with(query: hash_including("from" => "2026-01-17", "to" => "2026-01-31"))
+ .to_return(
+ status: 200,
+ headers: { "Content-Type" => "application/json" },
+ body: { data: [ { id: "t3" } ], pagination: { hasMore: false } }.to_json
+ )
+
+ results = provider.get_transactions(
+ connection_id: "conn_1",
+ account_id: "acc_1",
+ start_date: Date.new(2026, 1, 1),
+ end_date: Date.new(2026, 1, 31)
+ )
+
+ assert_equal %w[t1 t2 t3], results.map { |t| t[:id] }
+ end
+
+ test "get_transactions raises when a truncated window cannot be narrowed" do
+ provider = Provider::Redbark.new(api_key: "rbk_live_test")
+
+ stub_request(:get, "https://api.redbark.com/v1/transactions")
+ .with(query: hash_including("connectionId" => "conn_1"))
+ .to_return(
+ status: 200,
+ headers: { "Content-Type" => "application/json", "X-Redbark-Truncated" => "true" },
+ body: { data: [ { id: "t1" } ], pagination: { hasMore: true } }.to_json
+ )
+
+ error = assert_raises(Provider::Redbark::Error) do
+ provider.get_transactions(
+ connection_id: "conn_1",
+ account_id: "acc_1",
+ start_date: Date.new(2026, 1, 5),
+ end_date: Date.new(2026, 1, 5)
+ )
+ end
+ assert_equal :truncated, error.error_type
+ end
+end
diff --git a/test/models/redbark_account/data_helpers_test.rb b/test/models/redbark_account/data_helpers_test.rb
new file mode 100644
index 0000000000..fe523a528f
--- /dev/null
+++ b/test/models/redbark_account/data_helpers_test.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class RedbarkAccount::DataHelpersTest < ActiveSupport::TestCase
+ # Create a test class that includes the concern
+ class TestHelper
+ include RedbarkAccount::DataHelpers
+
+ # Make private methods public for testing
+ public :parse_decimal, :parse_date, :extract_currency
+ end
+
+ setup do
+ @helper = TestHelper.new
+ end
+
+ # ==========================================================================
+ # parse_decimal tests
+ # ==========================================================================
+
+ test "parse_decimal returns nil for nil input" do
+ assert_nil @helper.parse_decimal(nil)
+ end
+
+ test "parse_decimal parses string to BigDecimal" do
+ result = @helper.parse_decimal("123.45")
+ assert_instance_of BigDecimal, result
+ assert_equal BigDecimal("123.45"), result
+ end
+
+ test "parse_decimal handles integer input" do
+ result = @helper.parse_decimal(100)
+ assert_instance_of BigDecimal, result
+ assert_equal BigDecimal("100"), result
+ end
+
+ test "parse_decimal handles float input" do
+ result = @helper.parse_decimal(99.99)
+ assert_instance_of BigDecimal, result
+ assert_in_delta 99.99, result.to_f, 0.001
+ end
+
+ test "parse_decimal returns BigDecimal unchanged" do
+ input = BigDecimal("50.25")
+ result = @helper.parse_decimal(input)
+ assert_equal input, result
+ end
+
+ test "parse_decimal returns nil for invalid string" do
+ assert_nil @helper.parse_decimal("not a number")
+ end
+
+ # ==========================================================================
+ # parse_date tests
+ # ==========================================================================
+
+ test "parse_date returns nil for nil input" do
+ assert_nil @helper.parse_date(nil)
+ end
+
+ test "parse_date returns Date unchanged" do
+ input = Date.new(2024, 6, 15)
+ result = @helper.parse_date(input)
+ assert_equal input, result
+ end
+
+ test "parse_date parses ISO date string" do
+ result = @helper.parse_date("2024-06-15")
+ assert_instance_of Date, result
+ assert_equal Date.new(2024, 6, 15), result
+ end
+
+ test "parse_date parses datetime string to date" do
+ result = @helper.parse_date("2024-06-15T10:30:00Z")
+ assert_instance_of Date, result
+ assert_equal Date.new(2024, 6, 15), result
+ end
+
+ test "parse_date converts Time to Date" do
+ input = Time.zone.parse("2024-06-15 10:30:00")
+ result = @helper.parse_date(input)
+ assert_instance_of Date, result
+ assert_equal Date.new(2024, 6, 15), result
+ end
+
+ test "parse_date returns nil for invalid string" do
+ assert_nil @helper.parse_date("not a date")
+ end
+
+ # ==========================================================================
+ # extract_currency tests
+ # ==========================================================================
+
+ test "extract_currency returns fallback for nil currency" do
+ result = @helper.extract_currency({}, fallback: "USD")
+ assert_equal "USD", result
+ end
+
+ test "extract_currency extracts string currency" do
+ result = @helper.extract_currency({ currency: "cad" })
+ assert_equal "CAD", result
+ end
+
+ test "extract_currency extracts currency from hash with code key" do
+ result = @helper.extract_currency({ currency: { code: "EUR" } })
+ assert_equal "EUR", result
+ end
+
+ test "extract_currency handles indifferent access" do
+ result = @helper.extract_currency({ "currency" => { "code" => "GBP" } })
+ assert_equal "GBP", result
+ end
+end
diff --git a/test/models/redbark_account/processor_test.rb b/test/models/redbark_account/processor_test.rb
new file mode 100644
index 0000000000..4d0a6fd4ae
--- /dev/null
+++ b/test/models/redbark_account/processor_test.rb
@@ -0,0 +1,127 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class RedbarkAccount::ProcessorTest < ActiveSupport::TestCase
+ setup do
+ @redbark_account = redbark_accounts(:savings_account)
+ @family = @redbark_account.redbark_item.family
+
+ @account = @family.accounts.create!(
+ name: "Test Account",
+ balance: 1000,
+ currency: "AUD",
+ accountable: Depository.new
+ )
+
+ @redbark_account.ensure_account_provider!(@account)
+ @redbark_account.reload
+ end
+
+ test "processor initializes with redbark_account" do
+ processor = RedbarkAccount::Processor.new(@redbark_account)
+ assert_not_nil processor
+ end
+
+ test "processor skips processing when no linked account" do
+ @redbark_account.account_provider&.destroy
+ @redbark_account.reload
+
+ processor = RedbarkAccount::Processor.new(@redbark_account)
+ assert_nothing_raised { processor.process }
+ end
+
+ test "processor updates account balance" do
+ @redbark_account.update!(current_balance: 15000)
+
+ RedbarkAccount::Processor.new(@redbark_account).process
+
+ @account.reload
+ assert_equal 15000, @account.balance.to_f
+ end
+
+ test "processor negates balance for credit card accounts" do
+ credit_account = @family.accounts.create!(
+ name: "Test Credit Card",
+ balance: 0,
+ currency: "AUD",
+ accountable: CreditCard.new
+ )
+ @redbark_account.account_provider&.destroy
+ @redbark_account.reload
+ @redbark_account.ensure_account_provider!(credit_account)
+ @redbark_account.update!(current_balance: -250)
+
+ RedbarkAccount::Processor.new(@redbark_account).process
+
+ credit_account.reload
+ assert_equal 250, credit_account.balance.to_f
+ end
+
+ test "transactions processor creates entries from raw payload" do
+ @redbark_account.update!(raw_transactions_payload: [
+ {
+ "id" => "tx_001",
+ "accountId" => @redbark_account.redbark_account_id,
+ "status" => "posted",
+ "date" => Date.current.to_s,
+ "description" => "COFFEE SHOP SYDNEY",
+ "amount" => "-4.50",
+ "direction" => "debit",
+ "merchantName" => "Coffee Shop"
+ }
+ ])
+
+ result = RedbarkAccount::Transactions::Processor.new(@redbark_account).process
+
+ assert result[:success]
+ assert_equal 1, result[:imported]
+
+ entry = @account.entries.find_by(external_id: "redbark_tx_001", source: "redbark")
+ assert_not_nil entry
+ # Redbark amounts are CDR pre-signed (negative = money out); Sure stores the opposite sign
+ assert_equal 4.50, entry.amount.to_f
+ assert_equal "Coffee Shop", entry.name
+ assert_equal "AUD", entry.currency
+ end
+
+ test "transactions processor stores pending flag in extra metadata" do
+ @redbark_account.update!(raw_transactions_payload: [
+ {
+ "id" => "tx_002",
+ "status" => "pending",
+ "date" => Date.current.to_s,
+ "description" => "PENDING PURCHASE",
+ "amount" => "-10.00",
+ "direction" => "debit"
+ }
+ ])
+
+ RedbarkAccount::Transactions::Processor.new(@redbark_account).process
+
+ entry = @account.entries.find_by(external_id: "redbark_tx_002", source: "redbark")
+ assert_not_nil entry
+ assert_equal true, entry.entryable.extra.dig("redbark", "pending")
+ end
+
+ test "transactions processor handles missing transaction id gracefully" do
+ @redbark_account.update!(raw_transactions_payload: [
+ { "id" => nil, "amount" => "-50.00", "date" => Date.current.to_s }
+ ])
+
+ result = RedbarkAccount::Transactions::Processor.new(@redbark_account).process
+
+ assert result[:success]
+ assert_equal 1, result[:skipped]
+ assert_equal 0, result[:failed]
+ end
+
+ test "transactions processor returns empty result when no transactions" do
+ @redbark_account.update!(raw_transactions_payload: [])
+
+ result = RedbarkAccount::Transactions::Processor.new(@redbark_account).process
+
+ assert result[:success]
+ assert_equal 0, result[:total]
+ end
+end
diff --git a/test/models/redbark_item/importer_test.rb b/test/models/redbark_item/importer_test.rb
new file mode 100644
index 0000000000..e740ffa92c
--- /dev/null
+++ b/test/models/redbark_item/importer_test.rb
@@ -0,0 +1,55 @@
+require "test_helper"
+
+class RedbarkItem::ImporterTest < ActiveSupport::TestCase
+ setup do
+ @redbark_item = redbark_items(:one)
+ @importer = RedbarkItem::Importer.new(@redbark_item, redbark_provider: nil)
+ end
+
+ test "merge_transactions keeps posted rows and refreshes by id" do
+ existing = [ { "id" => "t1", "status" => "posted", "date" => "2026-07-01", "amount" => "-10.00" } ]
+ fresh = [ { "id" => "t1", "status" => "posted", "date" => "2026-07-01", "amount" => "-12.00" } ]
+
+ merged = @importer.send(:merge_transactions, existing, fresh, window_start: Date.new(2026, 6, 1))
+
+ assert_equal 1, merged.size
+ assert_equal "-12.00", merged.first["amount"]
+ end
+
+ test "merge_transactions prunes pending rows missing from the refetched window" do
+ existing = [
+ { "id" => "pend_1", "status" => "pending", "date" => "2026-07-10" },
+ { "id" => "kept_posted", "status" => "posted", "date" => "2026-07-05" }
+ ]
+ fresh = [ { "id" => "post_1", "status" => "posted", "date" => "2026-07-10" } ]
+
+ merged = @importer.send(:merge_transactions, existing, fresh, window_start: Date.new(2026, 7, 1))
+ ids = merged.map { |t| t["id"] }
+
+ assert_includes ids, "post_1"
+ assert_includes ids, "kept_posted"
+ assert_not_includes ids, "pend_1"
+ end
+
+ test "merge_transactions drops rows dated before the fetch window" do
+ existing = [
+ { "id" => "old_posted", "status" => "posted", "date" => "2026-05-01" },
+ { "id" => "old_pending", "status" => "pending", "date" => "2026-06-15" },
+ { "id" => "undated", "status" => "posted" }
+ ]
+ fresh = [ { "id" => "post_1", "status" => "posted", "date" => "2026-07-10" } ]
+
+ merged = @importer.send(:merge_transactions, existing, fresh, window_start: Date.new(2026, 7, 1))
+
+ assert_equal %w[post_1 undated], merged.map { |t| t["id"] }.sort
+ end
+
+ test "merge_transactions keeps everything when no window is given" do
+ existing = [ { "id" => "old_posted", "status" => "posted", "date" => "2026-05-01" } ]
+ fresh = [ { "id" => "post_1", "status" => "posted", "date" => "2026-07-10" } ]
+
+ merged = @importer.send(:merge_transactions, existing, fresh, window_start: nil)
+
+ assert_equal %w[old_posted post_1], merged.map { |t| t["id"] }.sort
+ end
+end
diff --git a/test/models/redbark_item_test.rb b/test/models/redbark_item_test.rb
new file mode 100644
index 0000000000..b57b57c021
--- /dev/null
+++ b/test/models/redbark_item_test.rb
@@ -0,0 +1,73 @@
+require "test_helper"
+
+class RedbarkItemTest < ActiveSupport::TestCase
+ def setup
+ @redbark_item = redbark_items(:one)
+ end
+
+ test "fixture is valid" do
+ assert @redbark_item.valid?
+ end
+
+ test "belongs to family" do
+ assert_equal families(:dylan_family), @redbark_item.family
+ end
+
+ test "credentials_configured returns true when api_key present" do
+ assert @redbark_item.credentials_configured?
+ end
+
+ test "credentials_configured returns false when api_key blank" do
+ @redbark_item.api_key = nil
+ assert_not @redbark_item.credentials_configured?
+ end
+
+ test "redbark_provider returns Provider::Redbark instance" do
+ provider = @redbark_item.redbark_provider
+ assert_instance_of Provider::Redbark, provider
+ assert_equal @redbark_item.api_key, provider.api_key
+ end
+
+ test "redbark_provider returns nil when credentials not configured" do
+ @redbark_item.api_key = nil
+ assert_nil @redbark_item.redbark_provider
+ end
+
+ test "syncer returns RedbarkItem::Syncer instance" do
+ assert_instance_of RedbarkItem::Syncer, @redbark_item.syncer
+ end
+
+ test "has_redbark_credentials reflects configured items" do
+ assert families(:dylan_family).has_redbark_credentials?
+ refute families(:empty).has_redbark_credentials?
+ end
+
+ test "ignored accounts are excluded from setup counts" do
+ account = redbark_accounts(:savings_account)
+ assert_equal 1, @redbark_item.unlinked_accounts_count
+
+ account.update!(ignored: true)
+
+ fresh_item = RedbarkItem.find(@redbark_item.id)
+ assert_equal 0, fresh_item.unlinked_accounts_count
+ assert_equal 1, fresh_item.total_accounts_count
+ assert_not RedbarkAccount.needs_setup.exists?(id: account.id)
+ end
+
+ test "encrypted jsonb payloads round-trip nested structures" do
+ payload = {
+ "accounts" => [
+ { "id" => "acc_1", "name" => "Everyday", "balances" => { "current" => "1024.55", "currency" => "AUD" } },
+ { "id" => "acc_2", "name" => "Savings", "meta" => { "tags" => [ "a", "b" ], "nested" => { "deep" => true } } }
+ ],
+ "fetched_at" => "2026-07-25T00:00:00Z"
+ }
+ institution = { "name" => "Test Bank", "logo" => "https://example.com/logo.png" }
+
+ @redbark_item.update!(raw_payload: payload, raw_institution_payload: institution)
+ reloaded = RedbarkItem.find(@redbark_item.id)
+
+ assert_equal payload, reloaded.raw_payload
+ assert_equal institution, reloaded.raw_institution_payload
+ end
+end