The personal finance app for everyone (by everyone)
Ruby
class TradeRepublicAccount < ApplicationRecord
include CurrencyNormalizable, Encryptable
include TradeRepublicAccount::DataHelpers
if encryption_ready?
encrypts :raw_positions_payload
encrypts :raw_timeline_payload
end
belongs_to :trade_republic_item
# The provider model can be loaded while Rails is booting before the
# development schema cache has refreshed after a migration. Declaring the
# type explicitly keeps the enum valid in that reload window as well.
attribute :kind, :string, default: "portfolio"
enum :kind, { portfolio: "portfolio", cash: "cash", crypto: "crypto" }, default: :portfolio
# Trade Republic lists crypto under pseudo-ISINs starting with XF000.
CRYPTO_ISIN_PREFIX = "XF000"
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 :currency, presence: true
validates :trade_republic_account_id, uniqueness: { scope: :trade_republic_item_id, allow_nil: true }
# The Sure accounts that settle the trades of the accounts given: the Cash
# account of each connection whose Portfolio or Crypto account is among
# account_ids. ActivitiesProcessor#link_settlement_counterpart! books every
# trade's cash on that account and links it to the securities account as a
# confirmed transfer, so money reaches a split Portfolio or Crypto account
# only through it. Returns a relation of account ids, for use as a subquery.
def self.settlement_account_ids_for(account_ids)
connection_ids = joins(:account_provider)
.where(account_providers: { account_id: account_ids }, kind: %w[portfolio crypto])
.select(:trade_republic_item_id)
AccountProvider
.where(provider_type: name, provider_id: where(kind: "cash", trade_republic_item_id: connection_ids).select(:id))
.select(:account_id)
end
def self.crypto_isin?(isin)
isin.to_s.strip.upcase.start_with?(CRYPTO_ISIN_PREFIX)
end
def self.crypto_position?(position)
return false unless position.is_a?(Hash)
position = position.with_indifferent_access
position[:category].to_s == "crypto_wallet" || crypto_isin?(position[:isin])
end
def current_account
account || linked_account
end
# The linked Sure account, unless it is being deleted or was disabled.
def usable_account
acct = current_account
acct unless acct.nil? || acct.pending_deletion? || acct.disabled?
end
def sibling(kind)
trade_republic_item.trade_republic_accounts.find_by(kind: kind)
end
# Manual accounts this provider account can be linked to. Crypto only
# links to a Crypto exchange account, the Crypto subtype that supports
# trades, or to an Investment account; Portfolio and Cash keep linking to
# Investment and Depository accounts.
def linkable_to?(account)
case account.accountable_type
when "Investment" then true
when "Depository" then !crypto?
when "Crypto" then crypto? && account.accountable&.subtype == "exchange"
else false
end
end
# Portfolio and Crypto accounts hold securities; the Cash account settles
# their trades.
def holds_securities?
portfolio? || crypto?
end
# Crypto moves to its own account once the user linked the Crypto account.
# Until then the portfolio keeps holding it.
def crypto_split?
sibling("crypto")&.usable_account.present?
end
# Trade Republic returns crypto in the portfolio snapshot. The Crypto
# account holds those positions; the portfolio keeps them only while no
# Crypto account is linked.
def positions
case kind
when "crypto"
Array(sibling("portfolio")&.raw_positions_payload).select { |position| self.class.crypto_position?(position) }
when "portfolio"
positions = Array(raw_positions_payload)
crypto_split? ? positions.reject { |position| self.class.crypto_position?(position) } : positions
else
[]
end
end
def positions_snapshot_complete?
crypto? ? sibling("portfolio")&.holdings_snapshot_complete? : holdings_snapshot_complete?
end
# current_balance on the portfolio values the whole snapshot, crypto
# included, so a split portfolio leaves out what the Crypto account holds.
def account_balance
return current_balance unless portfolio? && crypto_split?
(current_balance || 0).to_d - (sibling("crypto").current_balance || 0).to_d
end
def ensure_account_provider!(account = nil)
if account_provider.present?
account_provider.update!(account: account) if account && account_provider.account_id != account.id
return account_provider
end
acct = account || current_account
return nil unless acct
provider = AccountProvider
.find_or_initialize_by(provider_type: "TradeRepublicAccount", provider_id: id)
.tap do |record|
record.account = acct
record.save!
end
reload_account_provider
provider
rescue => e
DebugLogEntry.capture(
category: "sync",
level: "warn",
message: "TradeRepublicAccount##{id}: failed to ensure AccountProvider link: #{e.class} - #{e.message}",
source: "trade_republic",
family: trade_republic_item.family,
provider_key: "trade_republic"
)
nil
end
end