Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add support for trading212 integration in investments sync (#2513)

jdcdp849578a84aa0
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index 14585339e5..a6b05c13f8 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -196,6 +196,7 @@ class Settings::ProvidersController < ApplicationController
{ key: "kraken", title: "Kraken", turbo_id: "kraken", partial: "kraken_panel" },
{ key: "snaptrade", title: "SnapTrade", turbo_id: "snaptrade", partial: "snaptrade_panel", auto_open: "manage" },
{ key: "ibkr", title: "Interactive Brokers", turbo_id: "ibkr", partial: "ibkr_panel" },
+ { key: "trading212", title: "Trading 212", turbo_id: "trading212", partial: "trading212_panel" },
{ key: "indexa_capital", title: "Indexa Capital", turbo_id: "indexa_capital", partial: "indexa_capital_panel" },
{ key: "sophtron", title: "Sophtron", turbo_id: "sophtron", partial: "sophtron_panel" },
{ key: "questrade", title: "Questrade", turbo_id: "questrade", partial: "questrade_panel" }
@@ -220,6 +221,7 @@ class Settings::ProvidersController < ApplicationController
"snaptrade" => "SnaptradeItem",
"questrade" => "QuestradeItem",
"ibkr" => "IbkrItem",
+ "trading212" => "Trading212Item",
"indexa_capital" => "IndexaCapitalItem",
"sophtron" => "SophtronItem"
}.freeze
@@ -254,6 +256,8 @@ class Settings::ProvidersController < ApplicationController
@snaptrade_items = Current.family.snaptrade_items.includes(:snaptrade_accounts).ordered
when "ibkr"
@ibkr_items = Current.family.ibkr_items.ordered
+ when "trading212"
+ @trading212_items = Current.family.trading212_items.ordered
when "indexa_capital"
@indexa_capital_items = Current.family.indexa_capital_items.ordered
when "sophtron"
@@ -286,6 +290,7 @@ class Settings::ProvidersController < ApplicationController
@coinbase_items = Current.family.coinbase_items.ordered # Coinbase panel needs name and sync info for status display
@snaptrade_items = Current.family.snaptrade_items.ordered
@ibkr_items = Current.family.ibkr_items.ordered.select(:id)
+ @trading212_items = Current.family.trading212_items.ordered.select(:id)
@indexa_capital_items = Current.family.indexa_capital_items.ordered.select(:id)
@binance_items = Current.family.binance_items.active.ordered
@kraken_items = Current.family.kraken_items.active.ordered
@@ -322,6 +327,7 @@ class Settings::ProvidersController < ApplicationController
"snaptrade" => @snaptrade_items,
"questrade" => @questrade_items,
"ibkr" => @ibkr_items,
+ "trading212" => @trading212_items,
"indexa_capital" => @indexa_capital_items,
"sophtron" => @sophtron_items
}
diff --git a/app/controllers/trading212_items_controller.rb b/app/controllers/trading212_items_controller.rb
new file mode 100644
index 0000000000..7d5b6ed09e
--- /dev/null
+++ b/app/controllers/trading212_items_controller.rb
@@ -0,0 +1,252 @@
+class Trading212ItemsController < ApplicationController
+ before_action :set_trading212_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
+ @trading212_item = Current.family.trading212_items.build(trading212_item_params)
+ @trading212_item.name ||= t("trading212_items.defaults.name")
+ @trading212_item.currency ||= Current.family.currency
+
+ if @trading212_item.save
+ @trading212_item.sync_later
+
+ if turbo_frame_request?
+ flash.now[:notice] = t(".success")
+ render turbo_stream: [
+ turbo_stream.replace(
+ "trading212-providers-panel",
+ partial: "settings/providers/trading212_panel"
+ ),
+ *flash_notification_stream_items
+ ]
+ else
+ redirect_to accounts_path, notice: t(".success"), status: :see_other
+ end
+ else
+ @error_message = @trading212_item.errors.full_messages.join(", ")
+
+ if turbo_frame_request?
+ render turbo_stream: turbo_stream.replace(
+ "trading212-providers-panel",
+ partial: "settings/providers/trading212_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
+ attrs = trading212_item_params.to_h
+ attrs["api_key"] = @trading212_item.api_key if attrs["api_key"].blank?
+ attrs["api_secret"] = @trading212_item.api_secret if attrs["api_secret"].blank?
+
+ if @trading212_item.update(attrs.merge(status: :good))
+ @trading212_item.sync_later unless @trading212_item.syncing?
+
+ if turbo_frame_request?
+ flash.now[:notice] = t(".success")
+ render turbo_stream: [
+ turbo_stream.replace(
+ "trading212-providers-panel",
+ partial: "settings/providers/trading212_panel"
+ ),
+ *flash_notification_stream_items
+ ]
+ else
+ redirect_to accounts_path, notice: t(".success"), status: :see_other
+ end
+ else
+ @error_message = @trading212_item.errors.full_messages.join(", ")
+
+ if turbo_frame_request?
+ render turbo_stream: turbo_stream.replace(
+ "trading212-providers-panel",
+ partial: "settings/providers/trading212_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
+ @trading212_item.unlink_all!(dry_run: false)
+ @trading212_item.destroy_later
+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other
+ end
+
+ def sync
+ @trading212_item.sync_later unless @trading212_item.syncing?
+
+ respond_to do |format|
+ format.html { redirect_back_or_to accounts_path }
+ format.json { head :ok }
+ end
+ end
+
+ def select_accounts
+ item = current_trading212_item
+ unless item
+ redirect_to settings_providers_path, alert: t(".not_configured")
+ return
+ end
+
+ redirect_to setup_accounts_trading212_item_path(item)
+ end
+
+ def select_existing_account
+ @account = Current.family.accounts.find(params[:account_id])
+ @available_trading212_accounts = Current.family.trading212_items
+ .includes(trading212_accounts: { account_provider: :account })
+ .flat_map(&:trading212_accounts)
+ .select { |t212_account| t212_account.account_provider.nil? }
+ .sort_by { |t212_account| t212_account.updated_at || t212_account.created_at }
+ .reverse
+
+ render :select_existing_account, layout: false
+ end
+
+ def link_existing_account
+ account = Current.family.accounts.find_by(id: params[:account_id])
+ t212_account = Current.family.trading212_items
+ .joins(:trading212_accounts)
+ .where(trading212_accounts: { id: params[:trading212_account_id] })
+ .first
+ &.trading212_accounts
+ &.find_by(id: params[:trading212_account_id])
+
+ if account.blank? || t212_account.blank?
+ redirect_to settings_providers_path, alert: t(".not_found")
+ return
+ end
+
+ if account.accountable_type != "Investment" || account.account_providers.any? || account.plaid_account_id.present? || account.simplefin_account_id.present?
+ redirect_to account_path(account), alert: t(".only_manual_investment")
+ return
+ end
+
+ provider = nil
+
+ t212_account.with_lock do
+ if t212_account.current_account.present?
+ redirect_to account_path(account), alert: t(".already_linked")
+ return
+ end
+
+ provider = t212_account.ensure_account_provider!(account)
+ end
+
+ raise "Failed to create AccountProvider link" unless provider
+
+ begin
+ Trading212Account::Processor.new(t212_account.reload).process
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Failed to process linked Trading 212 account #{t212_account.id}: #{e.class} - #{e.message}",
+ source: "trading212",
+ family: Current.family,
+ provider_key: "trading212"
+ )
+ end
+
+ t212_account.trading212_item.sync_later unless t212_account.trading212_item.syncing?
+ redirect_to account_path(account), notice: t(".success"), status: :see_other
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Failed to link existing Trading 212 account: #{e.class} - #{e.message}",
+ source: "trading212",
+ family: Current.family,
+ provider_key: "trading212"
+ )
+ redirect_to settings_providers_path, alert: t(".failed"), status: :see_other
+ end
+
+ def setup_accounts
+ @trading212_accounts = @trading212_item.trading212_accounts.includes(account_provider: :account)
+ @linked_accounts = @trading212_accounts.select { |a| a.current_account.present? }
+ @unlinked_accounts = @trading212_accounts.reject { |a| a.current_account.present? }
+
+ no_accounts = @linked_accounts.blank? && @unlinked_accounts.blank?
+ latest_sync = @trading212_item.syncs.ordered.first
+ should_sync = latest_sync.nil? || !latest_sync.completed?
+
+ if no_accounts && !@trading212_item.syncing? && should_sync
+ @trading212_item.sync_later
+ end
+
+ @linkable_accounts = Current.family.accounts
+ .visible
+ .where(accountable_type: "Investment")
+ .left_joins(:account_providers)
+ .where(account_providers: { id: nil })
+ .order(:name)
+
+ @syncing = @trading212_item.syncing?
+ @waiting_for_sync = no_accounts && @syncing
+ @no_accounts_found = no_accounts && !@syncing && @trading212_item.last_synced_at.present?
+ end
+
+ def complete_account_setup
+ selected_accounts = Array(params[:account_ids]).reject(&:blank?)
+ created_accounts = []
+
+ selected_accounts.each do |t212_account_id|
+ t212_account = @trading212_item.trading212_accounts.find_by(id: t212_account_id)
+ next unless t212_account
+
+ t212_account.with_lock do
+ next if t212_account.current_account.present?
+
+ account = Account.create_from_trading212_account(t212_account)
+ t212_account.ensure_account_provider!(account)
+ created_accounts << account
+ end
+
+ begin
+ Trading212Account::Processor.new(t212_account.reload).process
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Failed to process Trading 212 account #{t212_account.id} after setup: #{e.class} - #{e.message}",
+ source: "trading212",
+ family: Current.family,
+ provider_key: "trading212"
+ )
+ end
+ end
+
+ @trading212_item.update!(pending_account_setup: @trading212_item.unlinked_accounts_count.positive?)
+ @trading212_item.sync_later if created_accounts.any?
+
+ if created_accounts.any?
+ redirect_to accounts_path, notice: t(".success", count: created_accounts.count), status: :see_other
+ elsif selected_accounts.empty?
+ redirect_to setup_accounts_trading212_item_path(@trading212_item), alert: t(".none_selected"), status: :see_other
+ else
+ redirect_to setup_accounts_trading212_item_path(@trading212_item), alert: t(".none_created"), status: :see_other
+ end
+ end
+
+ private
+
+ def set_trading212_item
+ @trading212_item = Current.family.trading212_items.find(params[:id])
+ end
+
+ def current_trading212_item
+ active_items = Current.family.trading212_items.active
+ active_items.syncable.ordered.first || active_items.ordered.first
+ end
+
+ def trading212_item_params
+ params.require(:trading212_item).permit(:api_key, :api_secret, :environment, :currency)
+ end
+end
diff --git a/app/models/account.rb b/app/models/account.rb
index 008bb56462..e2bb0c0bb5 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -352,6 +352,24 @@ class Account < ApplicationRecord
create_and_sync(attributes, skip_initial_sync: true)
end
+ def create_from_trading212_account(trading212_account)
+ family = trading212_account.trading212_item.family
+
+ attributes = {
+ family: family,
+ name: trading212_account.name.presence || "Trading 212",
+ balance: 0,
+ cash_balance: 0,
+ currency: trading212_account.currency.presence || family.currency,
+ accountable_type: "Investment",
+ accountable_attributes: {
+ subtype: "brokerage"
+ }
+ }
+
+ create_and_sync(attributes, skip_initial_sync: true)
+ end
+
def create_from_kraken_account(kraken_account)
create_from_crypto_exchange_account(kraken_account, family: kraken_account.kraken_item.family)
end
diff --git a/app/models/family.rb b/app/models/family.rb
index a352d72d2c..ddd11c4d69 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -4,6 +4,7 @@ class Family < ApplicationRecord
include CoinbaseConnectable, BinanceConnectable, KrakenConnectable, CoinstatsConnectable, SnaptradeConnectable, MercuryConnectable, BrexConnectable, SophtronConnectable
include IndexaCapitalConnectable, IbkrConnectable, WiseConnectable
include UpConnectable
+ include Trading212Connectable
include QuestradeConnectable
DATE_FORMATS = [
diff --git a/app/models/family/trading212_connectable.rb b/app/models/family/trading212_connectable.rb
new file mode 100644
index 0000000000..5b3147e270
--- /dev/null
+++ b/app/models/family/trading212_connectable.rb
@@ -0,0 +1,11 @@
+module Family::Trading212Connectable
+ extend ActiveSupport::Concern
+
+ included do
+ has_many :trading212_items, dependent: :destroy
+ end
+
+ def can_connect_trading212?
+ true
+ end
+end
diff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rb
index 91014fc2f7..132d8eed07 100644
--- a/app/models/provider/metadata.rb
+++ b/app/models/provider/metadata.rb
@@ -17,6 +17,7 @@ class Provider
ibkr: { region: "Global", kinds: %w[Investment], maturity: :beta, logo_text: "IB", logo_bg: "bg-red-600" },
indexa_capital: { region: "ES", kinds: %w[Investment], maturity: :alpha, logo_text: "IC", logo_bg: "bg-red-600" },
sophtron: { region: "US", kinds: %w[Bank Investment], maturity: :alpha, logo_text: "SO", logo_bg: "bg-teal-600" },
+ 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" }
diff --git a/app/models/provider/trading212.rb b/app/models/provider/trading212.rb
new file mode 100644
index 0000000000..5a62cf10ad
--- /dev/null
+++ b/app/models/provider/trading212.rb
@@ -0,0 +1,166 @@
+class Provider::Trading212
+ include HTTParty
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class AuthenticationError < Error; end
+ class ConfigurationError < Error; end
+ class RateLimitError < Error; end
+ class ApiError < Error
+ attr_reader :status_code, :response_body
+
+ def initialize(message, status_code: nil, response_body: nil)
+ super(message)
+ @status_code = status_code
+ @response_body = response_body
+ end
+ end
+
+ LIVE_BASE_URI = "https://live.trading212.com/api/v0".freeze
+ DEMO_BASE_URI = "https://demo.trading212.com/api/v0".freeze
+
+ MAX_PAGES = 200
+ PAGE_LIMIT = 50
+
+ RETRYABLE_ERRORS = [
+ SocketError,
+ Net::OpenTimeout,
+ Net::ReadTimeout,
+ Errno::ECONNRESET,
+ Errno::ECONNREFUSED,
+ Errno::ETIMEDOUT,
+ EOFError
+ ].freeze
+
+ default_options.merge!({ timeout: 60 }.merge(httparty_ssl_options))
+
+ attr_reader :api_key, :api_secret, :environment
+
+ def initialize(api_key:, api_secret:, environment: "live")
+ raise ConfigurationError, "api_key is required" if api_key.blank?
+ raise ConfigurationError, "api_secret is required" if api_secret.blank?
+ raise ConfigurationError, "Invalid environment: #{environment}" unless %w[live demo].include?(environment.to_s)
+
+ @api_key = api_key.to_s.strip
+ @api_secret = api_secret.to_s.strip
+ @environment = environment.to_s
+ end
+
+ def fetch_account_summary
+ get("/equity/account/summary")
+ end
+
+ def fetch_positions
+ get("/equity/positions")
+ end
+
+ def fetch_instruments
+ get("/equity/metadata/instruments")
+ end
+
+ def fetch_all_orders
+ fetch_all_pages("/equity/history/orders")
+ end
+
+ def fetch_all_dividends
+ fetch_all_pages("/equity/history/dividends")
+ end
+
+ def fetch_all_transactions
+ fetch_all_pages("/equity/history/transactions")
+ end
+
+ private
+
+ def base_uri
+ environment == "demo" ? DEMO_BASE_URI : LIVE_BASE_URI
+ end
+
+ def auth_headers
+ encoded = Base64.strict_encode64("#{api_key}:#{api_secret}")
+ {
+ "Authorization" => "Basic #{encoded}",
+ "Content-Type" => "application/json",
+ "User-Agent" => "Sure Finance Trading 212 Client"
+ }
+ end
+
+ def get(path, query: {})
+ url = "#{base_uri}#{path}"
+ response = with_retries(path) do
+ self.class.get(url, headers: auth_headers, query: query.compact)
+ end
+ handle_response(response)
+ end
+
+ def fetch_all_pages(path)
+ items = []
+ cursor = nil
+ pages_fetched = 0
+
+ loop do
+ query = { limit: PAGE_LIMIT }
+ query[:cursor] = cursor if cursor
+
+ data = get(path, query: query)
+ items.concat(Array(data["items"]))
+
+ next_page = data["nextPagePath"]
+ pages_fetched += 1
+
+ break if next_page.nil? || pages_fetched >= MAX_PAGES
+
+ cursor = extract_cursor(next_page)
+ break if cursor.nil?
+
+ sleep(10) # 6 req/min limit on history endpoint
+ end
+
+ items
+ end
+
+ def extract_cursor(next_page_path)
+ uri = URI.parse("https://placeholder#{next_page_path}")
+ params = URI.decode_www_form(uri.query.to_s).to_h
+ params["cursor"]
+ rescue URI::InvalidURIError
+ nil
+ end
+
+ def handle_response(response)
+ case response.code
+ when 200, 201
+ response.parsed_response
+ when 401, 403
+ raise AuthenticationError, "Trading 212 authentication failed (#{response.code}). Check your API key."
+ when 429
+ raise RateLimitError, "Trading 212 rate limit exceeded. Please wait before retrying."
+ else
+ raise ApiError.new(
+ "Trading 212 API error (status #{response.code})",
+ status_code: response.code,
+ response_body: response.body
+ )
+ end
+ end
+
+ def with_retries(label, max_retries: 3)
+ attempt = 0
+ begin
+ attempt += 1
+ yield
+ rescue *RETRYABLE_ERRORS => e
+ raise if attempt >= max_retries
+ delay = [ 2**attempt, 30 ].min
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "Provider::Trading212 #{label} attempt #{attempt} failed: #{e.message}. Retrying in #{delay}s",
+ source: "trading212",
+ provider_key: "trading212"
+ )
+ sleep(delay)
+ retry
+ end
+ end
+end
diff --git a/app/models/provider/trading212_adapter.rb b/app/models/provider/trading212_adapter.rb
new file mode 100644
index 0000000000..145c60cc51
--- /dev/null
+++ b/app/models/provider/trading212_adapter.rb
@@ -0,0 +1,59 @@
+class Provider::Trading212Adapter < Provider::Base
+ include Provider::Syncable
+ include Provider::InstitutionMetadata
+
+ Provider::Factory.register("Trading212Account", self)
+
+ def self.supported_account_types
+ %w[Investment]
+ end
+
+ def self.connection_configs(family:)
+ return [] unless family.can_connect_trading212?
+
+ [ {
+ key: "trading212",
+ name: I18n.t("providers.trading212.name"),
+ description: I18n.t("providers.trading212.connection_description"),
+ can_connect: true,
+ new_account_path: ->(_accountable_type, _return_to) {
+ Rails.application.routes.url_helpers.select_accounts_trading212_items_path
+ },
+ existing_account_path: ->(account_id) {
+ Rails.application.routes.url_helpers.select_existing_account_trading212_items_path(account_id: account_id)
+ }
+ } ]
+ end
+
+ def provider_name
+ "trading212"
+ end
+
+ def sync_path
+ Rails.application.routes.url_helpers.sync_trading212_item_path(item)
+ end
+
+ def item
+ provider_account.trading212_item
+ end
+
+ def can_delete_holdings?
+ false
+ end
+
+ def institution_domain
+ "trading212.com"
+ end
+
+ def institution_name
+ I18n.t("providers.trading212.institution_name")
+ end
+
+ def institution_url
+ "https://www.trading212.com"
+ end
+
+ def institution_color
+ "#2A9D8F"
+ end
+end
diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rb
index cf026629ac..0bb684e18c 100644
--- a/app/models/provider_connection_status.rb
+++ b/app/models/provider_connection_status.rb
@@ -18,6 +18,7 @@ class ProviderConnectionStatus
{ key: "brex", type: "BrexItem", association: :brex_items, accounts: :brex_accounts },
{ key: "sophtron", type: "SophtronItem", association: :sophtron_items, accounts: :sophtron_accounts },
{ 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: "wise", type: "WiseItem", association: :wise_items, accounts: :wise_accounts }
].freeze
diff --git a/app/models/trading212_account.rb b/app/models/trading212_account.rb
new file mode 100644
index 0000000000..1af578f275
--- /dev/null
+++ b/app/models/trading212_account.rb
@@ -0,0 +1,58 @@
+class Trading212Account < ApplicationRecord
+ include CurrencyNormalizable, Encryptable
+ include Trading212Account::DataHelpers
+
+ if encryption_ready?
+ encrypts :raw_positions_payload
+ encrypts :raw_orders_payload
+ encrypts :raw_dividends_payload
+ encrypts :raw_transactions_payload
+ end
+
+ belongs_to :trading212_item
+
+ 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 :trading212_account_id, uniqueness: { scope: :trading212_item_id, allow_nil: true }
+
+ def current_account
+ account || linked_account
+ 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: "Trading212Account", 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: "Trading212Account##{id}: failed to ensure AccountProvider link: #{e.class} - #{e.message}",
+ source: "trading212",
+ family: trading212_item.family,
+ provider_key: "trading212"
+ )
+ nil
+ end
+
+ def instruments_map
+ trading212_item.instruments_map
+ end
+end
diff --git a/app/models/trading212_account/activities_processor.rb b/app/models/trading212_account/activities_processor.rb
new file mode 100644
index 0000000000..75647e9b0d
--- /dev/null
+++ b/app/models/trading212_account/activities_processor.rb
@@ -0,0 +1,221 @@
+class Trading212Account::ActivitiesProcessor
+ include Trading212Account::DataHelpers
+
+ # T212 transaction types that map to cash flows
+ DEPOSIT_TYPE = "DEPOSIT".freeze
+ WITHDRAW_TYPE = "WITHDRAW".freeze
+ INTEREST_TYPE = "INTEREST".freeze
+ FEE_TYPE = "FEE".freeze
+
+ def initialize(trading212_account)
+ @trading212_account = trading212_account
+ end
+
+ def process
+ return { trades: 0, dividends: 0, transactions: 0 } unless account.present?
+
+ trade_count = Array(@trading212_account.raw_orders_payload).sum do |order|
+ process_order(order.with_indifferent_access) ? 1 : 0
+ end
+
+ dividend_count = Array(@trading212_account.raw_dividends_payload).sum do |dividend|
+ process_dividend(dividend.with_indifferent_access) ? 1 : 0
+ end
+
+ transaction_count = Array(@trading212_account.raw_transactions_payload).sum do |transaction|
+ process_cash_transaction(transaction.with_indifferent_access) ? 1 : 0
+ end
+
+ { trades: trade_count, dividends: dividend_count, transactions: transaction_count }
+ end
+
+ private
+
+ def account
+ @trading212_account.current_account
+ end
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+
+ def currency
+ @trading212_account.currency
+ end
+
+ def process_order(raw)
+ # T212 orders response is {order: {...}, fill: {...}}
+ order = (raw[:order] || {}).with_indifferent_access
+ fill = (raw[:fill] || {}).with_indifferent_access
+
+ return false unless order[:status].to_s.upcase == "FILLED"
+
+ instrument = (order[:instrument] || {}).with_indifferent_access
+ t212_ticker = instrument[:ticker].presence || order[:ticker].to_s
+ return false if t212_ticker.blank?
+
+ filled_quantity = parse_decimal(fill[:quantity])
+ fill_price = parse_decimal(fill[:price])
+ net_value = parse_decimal(fill.dig(:walletImpact, :netValue)) ||
+ parse_decimal(order[:filledValue])
+
+ return false unless filled_quantity && fill_price
+ return false if filled_quantity.zero?
+
+ isin = instrument[:isin].presence
+ ticker = standard_ticker(t212_ticker)
+ name = instrument[:name].presence || ticker
+ security = resolve_security_direct(isin, ticker, name)
+ return false unless security
+
+ is_buy = order[:side].to_s.upcase == "BUY"
+ activity_label = is_buy ? "Buy" : "Sell"
+ signed_quantity = is_buy ? filled_quantity : -filled_quantity
+ amount = net_value ? net_value.abs : (fill_price * filled_quantity.abs)
+ amount = is_buy ? amount : -amount
+
+ instrument_ccy = instrument[:currency].presence || currency
+ date = parse_date(fill[:filledAt] || order[:createdAt]) || Date.current
+ order_id = (fill[:id] || order[:id]).to_s
+ external_id = "trading212_order_#{order_id}"
+
+ import_adapter.import_trade(
+ external_id: external_id,
+ security: security,
+ quantity: signed_quantity,
+ price: fill_price,
+ amount: amount,
+ currency: instrument_ccy,
+ date: date,
+ name: build_order_name(security.ticker, signed_quantity),
+ source: "trading212",
+ activity_label: activity_label
+ )
+
+ true
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Trading212Account::ActivitiesProcessor - Failed to process order #{raw.dig(:order, :id)}: #{e.message}",
+ source: "trading212",
+ family: @trading212_account.trading212_item.family,
+ provider_key: "trading212",
+ metadata: { order_id: raw.dig(:order, :id), trading212_account_id: @trading212_account.id }
+ )
+ false
+ end
+
+ def process_dividend(dividend)
+ reference = dividend[:reference].to_s
+ return false if reference.blank?
+
+ amount = parse_decimal(dividend[:amount])
+ return false unless amount && amount > 0
+
+ t212_ticker = dividend[:ticker].to_s
+ security = t212_ticker.present? ? resolve_security_for_ticker(t212_ticker) : nil
+
+ date = parse_date(dividend[:paidOn]) || Date.current
+
+
+ import_adapter.import_transaction(
+ external_id: "trading212_dividend_#{reference}",
+ amount: -amount.abs,
+ currency: currency,
+ date: date,
+ name: build_dividend_name(security),
+ source: "trading212",
+ investment_activity_label: "Dividend",
+ extra: {
+ security_id: security&.id,
+ trading212: {
+ reference: reference,
+ ticker: t212_ticker,
+ quantity: dividend[:quantity],
+ gross_amount_per_share: dividend[:grossAmountPerShare],
+ type: dividend[:type]
+ }.compact
+ }
+ )
+
+ true
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Trading212Account::ActivitiesProcessor - Failed to process dividend #{dividend[:reference]}: #{e.message}",
+ source: "trading212",
+ family: @trading212_account.trading212_item.family,
+ provider_key: "trading212",
+ metadata: { reference: dividend[:reference], trading212_account_id: @trading212_account.id }
+ )
+ false
+ end
+
+ def process_cash_transaction(transaction)
+ reference = transaction[:reference].to_s
+ return false if reference.blank?
+
+ type = transaction[:type].to_s.upcase
+ amount = parse_decimal(transaction[:amount])
+ return false unless amount && !amount.zero?
+
+ label, signed_amount = classify_transaction(type, amount)
+ return false unless label
+
+ date = parse_date(transaction[:dateTime]) || Date.current
+
+ import_adapter.import_transaction(
+ external_id: "trading212_transaction_#{reference}",
+ amount: signed_amount,
+ currency: currency,
+ date: date,
+ name: label,
+ source: "trading212",
+ investment_activity_label: label,
+ extra: {
+ trading212: {
+ reference: reference,
+ type: type,
+ amount: transaction[:amount]
+ }.compact
+ }
+ )
+
+ true
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Trading212Account::ActivitiesProcessor - Failed to process transaction #{transaction[:reference]}: #{e.message}",
+ source: "trading212",
+ family: @trading212_account.trading212_item.family,
+ provider_key: "trading212",
+ metadata: { reference: transaction[:reference], trading212_account_id: @trading212_account.id }
+ )
+ false
+ end
+
+ def classify_transaction(type, amount)
+ case type
+ when DEPOSIT_TYPE
+ [ "Contribution", -amount.abs ]
+ when WITHDRAW_TYPE
+ [ "Withdrawal", amount.abs ]
+ when INTEREST_TYPE
+ [ "Interest", -amount.abs ]
+ when FEE_TYPE
+ [ "Fee", amount.abs ]
+ end
+ end
+
+ def build_order_name(ticker, signed_quantity)
+ action = signed_quantity.negative? ? "Sell" : "Buy"
+ "#{action} #{signed_quantity.abs} shares of #{ticker}"
+ end
+
+ def build_dividend_name(security)
+ security ? "Dividend from #{security.ticker}" : "Dividend"
+ end
+end
diff --git a/app/models/trading212_account/data_helpers.rb b/app/models/trading212_account/data_helpers.rb
new file mode 100644
index 0000000000..18b60d0491
--- /dev/null
+++ b/app/models/trading212_account/data_helpers.rb
@@ -0,0 +1,80 @@
+module Trading212Account::DataHelpers
+ extend ActiveSupport::Concern
+
+ private
+
+ def instruments_map
+ @trading212_account&.instruments_map || {}
+ end
+
+ def parse_decimal(value)
+ return nil if value.nil?
+
+ normalized = value.is_a?(String) ? value.strip : value.to_s
+ return nil if normalized.blank?
+
+ BigDecimal(normalized)
+ rescue ArgumentError
+ nil
+ end
+
+ def parse_date(value)
+ return nil if value.blank?
+
+ case value
+ when DateTime, Time, ActiveSupport::TimeWithZone
+ value.to_date
+ when Date
+ value
+ else
+ Time.zone.parse(value.to_s)&.to_date || Date.parse(value.to_s)
+ end
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ # T212 tickers look like "AAPL_US_EQ". Derive a standard ticker by taking
+ # the first segment, which is the instrument symbol on its primary exchange.
+ def standard_ticker(t212_ticker)
+ t212_ticker.to_s.split("_").first&.upcase || ""
+ end
+
+ def resolve_security_for_ticker(t212_ticker)
+ instrument = instruments_map[t212_ticker]
+
+ if instrument
+ resolve_security_from_instrument(instrument, t212_ticker)
+ else
+ ticker = standard_ticker(t212_ticker)
+ Security.find_by(ticker: ticker) || Security.create!(ticker: ticker, name: ticker)
+ end
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
+ ticker = standard_ticker(t212_ticker)
+ Security.find_by(ticker: ticker)
+ end
+
+ def resolve_security_from_instrument(instrument, t212_ticker)
+ ticker = standard_ticker(t212_ticker)
+ name = instrument["shortName"].presence || ticker
+
+ Security.find_by(ticker: ticker) ||
+ Security.create!(ticker: ticker, name: name)
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
+ Security.find_by(ticker: ticker)
+ end
+
+ # Resolve (or create) a Security when we already have isin/ticker/name in hand,
+ # e.g. from the nested instrument object in positions and orders responses.
+ # Note: the securities table has no isin column; isin is accepted but unused.
+ def resolve_security_direct(isin, ticker, name)
+ Security.find_by(ticker: ticker) ||
+ Security.create!(ticker: ticker, name: name)
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotUnique
+ Security.find_by(ticker: ticker)
+ end
+
+ def instrument_currency(t212_ticker)
+ instrument = instruments_map[t212_ticker]
+ instrument&.dig("currencyCode").presence || currency
+ end
+end
diff --git a/app/models/trading212_account/holdings_processor.rb b/app/models/trading212_account/holdings_processor.rb
new file mode 100644
index 0000000000..6e020f24bc
--- /dev/null
+++ b/app/models/trading212_account/holdings_processor.rb
@@ -0,0 +1,76 @@
+class Trading212Account::HoldingsProcessor
+ include Trading212Account::DataHelpers
+
+ def initialize(trading212_account)
+ @trading212_account = trading212_account
+ end
+
+ def process
+ return unless account.present?
+
+ Array(@trading212_account.raw_positions_payload).each do |position|
+ process_position(position.with_indifferent_access)
+ end
+ end
+
+ private
+
+ def account
+ @trading212_account.current_account
+ end
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+
+ def currency
+ @trading212_account.currency
+ end
+
+ def process_position(position)
+ instrument = (position[:instrument] || {}).with_indifferent_access
+ t212_ticker = instrument[:ticker].to_s
+ return if t212_ticker.blank?
+
+ isin = instrument[:isin].presence
+ ticker = standard_ticker(t212_ticker)
+ name = instrument[:name].presence || ticker
+ position_ccy = instrument[:currency].presence || currency
+
+ security = resolve_security_direct(isin, ticker, name)
+ return unless security
+
+ quantity = parse_decimal(position[:quantity])
+ price = parse_decimal(position[:currentPrice])
+ return unless quantity && price && quantity > 0
+
+ amount = quantity * price
+ date = Date.current
+
+ external_id = "trading212_position_#{@trading212_account.trading212_account_id}_#{t212_ticker}_#{date}"
+
+ import_adapter.import_holding(
+ security: security,
+ quantity: quantity,
+ amount: amount,
+ currency: position_ccy,
+ date: date,
+ price: price,
+ cost_basis: parse_decimal(position[:averagePricePaid]),
+ external_id: external_id,
+ source: "trading212",
+ account_provider_id: @trading212_account.account_provider&.id,
+ delete_future_holdings: false
+ )
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Trading212Account::HoldingsProcessor - Failed to process position #{t212_ticker}: #{e.message}",
+ source: "trading212",
+ family: @trading212_account.trading212_item.family,
+ provider_key: "trading212",
+ metadata: { ticker: t212_ticker, trading212_account_id: @trading212_account.id }
+ )
+ end
+end
diff --git a/app/models/trading212_account/processor.rb b/app/models/trading212_account/processor.rb
new file mode 100644
index 0000000000..54f8c6a5e8
--- /dev/null
+++ b/app/models/trading212_account/processor.rb
@@ -0,0 +1,36 @@
+class Trading212Account::Processor
+ attr_reader :trading212_account
+
+ def initialize(trading212_account)
+ @trading212_account = trading212_account
+ end
+
+ def process
+ return unless account.present?
+
+ update_account_balance!
+ Trading212Account::HoldingsProcessor.new(trading212_account).process
+ Trading212Account::ActivitiesProcessor.new(trading212_account).process
+
+ account.broadcast_sync_complete
+ end
+
+ private
+
+ def account
+ @account ||= trading212_account.current_account
+ end
+
+ def update_account_balance!
+ total_balance = trading212_account.current_balance || 0
+ cash_balance = trading212_account.cash_balance || 0
+
+ account.assign_attributes(
+ balance: total_balance,
+ cash_balance: cash_balance,
+ currency: trading212_account.currency
+ )
+ account.save!
+ account.set_current_balance(total_balance)
+ end
+end
diff --git a/app/models/trading212_item.rb b/app/models/trading212_item.rb
new file mode 100644
index 0000000000..e02f17d5ce
--- /dev/null
+++ b/app/models/trading212_item.rb
@@ -0,0 +1,147 @@
+class Trading212Item < ApplicationRecord
+ include Syncable, Provided, Unlinking, Encryptable
+
+ enum :status, { good: "good", requires_update: "requires_update" }, default: :good
+ enum :environment, { live: "live", demo: "demo" }, default: :live
+
+ if encryption_ready?
+ encrypts :api_key, deterministic: true
+ encrypts :api_secret
+ encrypts :raw_instruments_payload
+ end
+
+ belongs_to :family
+ has_many :trading212_accounts, dependent: :destroy
+
+ validates :api_key, presence: true, on: :create
+ validates :api_secret, presence: true, on: :create
+
+ scope :active, -> { where(scheduled_for_deletion: false) }
+ scope :syncable, -> { active.where.not(api_key: [ nil, "" ]) }
+ scope :ordered, -> { order(created_at: :desc) }
+ scope :needs_update, -> { where(status: :requires_update) }
+
+ def destroy_later
+ update!(scheduled_for_deletion: true)
+ DestroyJob.perform_later(self)
+ end
+
+ def credentials_configured?
+ api_key.present? && api_secret.present?
+ end
+
+ def import_latest_data
+ provider = trading212_provider
+ raise StandardError, "Trading 212 provider is not configured" unless provider
+
+ Trading212Item::Importer.new(self, provider: provider).import
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Trading212Item #{id} - Failed to import data: #{e.message}",
+ source: "trading212",
+ family: family,
+ provider_key: "trading212"
+ )
+ raise
+ end
+
+ def process_accounts
+ return [] if trading212_accounts.empty?
+
+ linked_trading212_accounts.includes(account_provider: :account).each_with_object([]) do |t212_account, results|
+ account = t212_account.current_account
+ next unless account
+ next if account.pending_deletion? || account.disabled?
+
+ begin
+ result = Trading212Account::Processor.new(t212_account).process
+ results << { trading212_account_id: t212_account.id, success: true, result: result }
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Trading212Item #{id} - Failed to process account #{t212_account.id}: #{e.message}",
+ source: "trading212",
+ family: family,
+ provider_key: "trading212",
+ account_provider_id: t212_account.account_provider&.id
+ )
+ results << { trading212_account_id: t212_account.id, success: false, error: e.message }
+ end
+ end
+ end
+
+ def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)
+ accounts.reject { |account| account.pending_deletion? || account.disabled? }.each_with_object([]) do |account, results|
+ 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: "sync",
+ level: "error",
+ message: "Trading212Item #{id} - Failed to schedule sync for account #{account.id}: #{e.message}",
+ source: "trading212",
+ family: family,
+ provider_key: "trading212",
+ account_id: account.id
+ )
+ results << { account_id: account.id, success: false, error: e.message }
+ end
+ end
+ end
+
+ def accounts
+ trading212_accounts.includes(account_provider: :account).filter_map(&:current_account).uniq
+ end
+
+ def linked_trading212_accounts
+ trading212_accounts.joins(:account_provider)
+ end
+
+ def linked_accounts_count
+ trading212_accounts.joins(:account_provider).count
+ end
+
+ def unlinked_accounts_count
+ trading212_accounts.left_joins(:account_provider).where(account_providers: { id: nil }).count
+ end
+
+ def total_accounts_count
+ trading212_accounts.count
+ end
+
+ def has_completed_initial_setup?
+ accounts.any?
+ end
+
+ def sync_status_summary
+ total = total_accounts_count
+ linked = linked_accounts_count
+ unlinked = unlinked_accounts_count
+
+ if total.zero?
+ I18n.t("trading212_items.sync_status.no_accounts")
+ elsif unlinked.zero?
+ I18n.t("trading212_items.sync_status.all_linked", count: linked)
+ else
+ I18n.t("trading212_items.sync_status.partial", linked: linked, unlinked: unlinked)
+ end
+ end
+
+ def institution_display_name
+ I18n.t("trading212_items.defaults.name")
+ end
+
+ def instruments_map
+ @instruments_map ||= Array(raw_instruments_payload).each_with_object({}) do |instrument, map|
+ map[instrument["ticker"]] = instrument
+ end
+ end
+end
diff --git a/app/models/trading212_item/importer.rb b/app/models/trading212_item/importer.rb
new file mode 100644
index 0000000000..32539f6508
--- /dev/null
+++ b/app/models/trading212_item/importer.rb
@@ -0,0 +1,74 @@
+class Trading212Item::Importer
+ attr_reader :trading212_item, :provider
+
+ def initialize(trading212_item, provider:)
+ @trading212_item = trading212_item
+ @provider = provider
+ end
+
+ def import
+ ActiveRecord::Base.transaction do
+ instruments = fetch_instruments
+ trading212_item.update!(raw_instruments_payload: instruments, status: :good)
+
+ summary = provider.fetch_account_summary
+ account_id = summary["id"]&.to_s
+ cash_data = (summary["cash"] || {}).with_indifferent_access
+
+ # T212 account summary structure:
+ # totalValue – total portfolio value (cash + investments)
+ # cash.availableToTrade – free cash
+ # cash.reservedForOrders – cash locked in pending orders
+ # investments.currentValue – current market value of open positions
+ cash_balance = parse_decimal(cash_data[:availableToTrade])
+ current_balance = parse_decimal(summary["totalValue"]) || BigDecimal("0")
+
+ currency = trading212_item.currency.presence || trading212_item.family.currency
+
+ t212_account = trading212_item.trading212_accounts.find_or_initialize_by(trading212_account_id: account_id)
+ t212_account.assign_attributes(
+ name: build_account_name(account_id),
+ currency: currency,
+ current_balance: current_balance,
+ cash_balance: cash_balance,
+ raw_positions_payload: provider.fetch_positions,
+ raw_orders_payload: provider.fetch_all_orders,
+ raw_dividends_payload: provider.fetch_all_dividends,
+ raw_transactions_payload: provider.fetch_all_transactions,
+ last_positions_sync: Time.current,
+ last_orders_sync: Time.current
+ )
+ t212_account.save!
+ end
+
+ { success: true }
+ end
+
+ private
+
+ def fetch_instruments
+ provider.fetch_instruments
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "Trading212Item::Importer - Failed to fetch instruments: #{e.message}. Using cached payload.",
+ source: "trading212",
+ family: trading212_item.family,
+ provider_key: "trading212"
+ )
+ Array(trading212_item.raw_instruments_payload)
+ end
+
+ def build_account_name(account_id)
+ base = I18n.t("trading212_items.defaults.name")
+ account_id.present? ? "#{base} (#{account_id})" : base
+ end
+
+ def parse_decimal(value)
+ return BigDecimal("0") if value.nil?
+ BigDecimal(value.to_s)
+ rescue ArgumentError
+ BigDecimal("0")
+ end
+end
diff --git a/app/models/trading212_item/provided.rb b/app/models/trading212_item/provided.rb
new file mode 100644
index 0000000000..01950f8308
--- /dev/null
+++ b/app/models/trading212_item/provided.rb
@@ -0,0 +1,9 @@
+module Trading212Item::Provided
+ extend ActiveSupport::Concern
+
+ def trading212_provider
+ return nil unless credentials_configured?
+
+ Provider::Trading212.new(api_key: api_key, api_secret: api_secret, environment: environment)
+ end
+end
diff --git a/app/models/trading212_item/sync_complete_event.rb b/app/models/trading212_item/sync_complete_event.rb
new file mode 100644
index 0000000000..6221997084
--- /dev/null
+++ b/app/models/trading212_item/sync_complete_event.rb
@@ -0,0 +1,22 @@
+class Trading212Item::SyncCompleteEvent
+ attr_reader :trading212_item
+
+ def initialize(trading212_item)
+ @trading212_item = trading212_item
+ end
+
+ def broadcast
+ trading212_item.accounts.each do |account|
+ account.broadcast_sync_complete
+ end
+
+ trading212_item.broadcast_replace_to(
+ trading212_item.family,
+ target: "trading212_item_#{trading212_item.id}",
+ partial: "trading212_items/trading212_item",
+ locals: { trading212_item: trading212_item }
+ )
+
+ trading212_item.family.broadcast_sync_complete
+ end
+end
diff --git a/app/models/trading212_item/syncer.rb b/app/models/trading212_item/syncer.rb
new file mode 100644
index 0000000000..75c6e5c679
--- /dev/null
+++ b/app/models/trading212_item/syncer.rb
@@ -0,0 +1,68 @@
+class Trading212Item::Syncer
+ include SyncStats::Collector
+
+ attr_reader :trading212_item
+
+ def initialize(trading212_item)
+ @trading212_item = trading212_item
+ end
+
+ def perform_sync(sync)
+ sync.update!(status_text: I18n.t("trading212_items.sync.status.checking_credentials")) if sync.respond_to?(:status_text)
+ unless trading212_item.credentials_configured?
+ trading212_item.update!(status: :requires_update)
+ raise Provider::Trading212::ConfigurationError, "Trading 212 API key is missing."
+ end
+
+ sync.update!(status_text: I18n.t("trading212_items.sync.status.importing_account")) if sync.respond_to?(:status_text)
+ trading212_item.import_latest_data
+
+ sync.update!(status_text: I18n.t("trading212_items.sync.status.checking_configuration")) if sync.respond_to?(:status_text)
+ collect_setup_stats(sync, provider_accounts: trading212_item.trading212_accounts.to_a)
+
+ unlinked_accounts = trading212_item.trading212_accounts.left_joins(:account_provider).where(account_providers: { id: nil })
+ linked_accounts = trading212_item.trading212_accounts.joins(:account).merge(Account.visible)
+
+ if unlinked_accounts.any?
+ trading212_item.update!(pending_account_setup: true)
+ sync.update!(status_text: I18n.t("trading212_items.sync.status.accounts_need_setup", count: unlinked_accounts.count)) if sync.respond_to?(:status_text)
+ else
+ trading212_item.update!(pending_account_setup: false)
+ end
+
+ if linked_accounts.any?
+ sync.update!(status_text: I18n.t("trading212_items.sync.status.processing_activity")) if sync.respond_to?(:status_text)
+ trading212_item.process_accounts
+
+ sync.update!(status_text: I18n.t("trading212_items.sync.status.calculating_balances")) if sync.respond_to?(:status_text)
+ trading212_item.schedule_account_syncs(
+ parent_sync: sync,
+ window_start_date: sync.window_start_date,
+ window_end_date: sync.window_end_date
+ )
+
+ account_ids = linked_accounts.includes(:account).filter_map { |pa| pa.account&.id }
+ collect_transaction_stats(sync, account_ids: account_ids, source: "trading212") if account_ids.any?
+ collect_trades_stats(sync, account_ids: account_ids, source: "trading212") if account_ids.any?
+ collect_holdings_stats(sync, holdings_count: count_holdings, label: "processed")
+ end
+
+ collect_health_stats(sync, errors: nil)
+ rescue Provider::Trading212::AuthenticationError, Provider::Trading212::ConfigurationError => e
+ trading212_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
+
+ def perform_post_sync
+ end
+
+ private
+
+ def count_holdings
+ trading212_item.trading212_accounts.sum { |acct| Array(acct.raw_positions_payload).size }
+ end
+end
diff --git a/app/models/trading212_item/unlinking.rb b/app/models/trading212_item/unlinking.rb
new file mode 100644
index 0000000000..cae88e0b62
--- /dev/null
+++ b/app/models/trading212_item/unlinking.rb
@@ -0,0 +1,40 @@
+module Trading212Item::Unlinking
+ extend ActiveSupport::Concern
+
+ def unlink_all!(dry_run: false)
+ results = []
+
+ trading212_accounts.find_each do |provider_account|
+ links = AccountProvider.where(provider_type: "Trading212Account", 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
+ Holding.where(account_provider_id: link_ids).update_all(account_provider_id: nil) if link_ids.any?
+ links.each(&:destroy!)
+ end
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Trading212Item Unlinker: failed to fully unlink provider account ##{provider_account.id} " \
+ "(links=#{link_ids.inspect}): #{e.class} - #{e.message}",
+ source: "trading212",
+ family: family,
+ provider_key: "trading212"
+ )
+ result[:error] = e.message
+ end
+ end
+
+ results
+ end
+end
diff --git a/app/views/settings/providers/_trading212_panel.html.erb b/app/views/settings/providers/_trading212_panel.html.erb
new file mode 100644
index 0000000000..0d0a5eae5f
--- /dev/null
+++ b/app/views/settings/providers/_trading212_panel.html.erb
@@ -0,0 +1,82 @@
+<div id="trading212-providers-panel" class="space-y-4">
+ <% error_msg = local_assigns[:error_message] || @error_message %>
+ <% if error_msg.present? %>
+ <%= render DS::Alert.new(message: error_msg, variant: :error) %>
+ <% end %>
+
+ <%= render "settings/providers/setup_steps",
+ steps: [
+ t(".steps.step_1"),
+ t(".steps.step_2"),
+ t(".steps.step_3")
+ ] %>
+
+ <%
+ trading212_item = Current.family.trading212_items.first_or_initialize
+ is_new_record = trading212_item.new_record?
+ %>
+
+ <% if trading212_item.persisted? %>
+ <div class="flex flex-wrap justify-end gap-2">
+ <%= button_to sync_trading212_item_path(trading212_item),
+ method: :post,
+ class: "inline-flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-secondary hover:text-primary border border-secondary rounded-lg hover:border-primary",
+ disabled: trading212_item.syncing? do %>
+ <%= icon "refresh-cw", size: "sm" %>
+ <%= t(".sync") %>
+ <% end %>
+
+ <%= button_to trading212_item_path(trading212_item),
+ method: :delete,
+ class: "inline-flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-destructive hover:bg-destructive/10 rounded-lg",
+ data: { turbo_confirm: t(".disconnect_confirm") } do %>
+ <%= icon "trash-2", size: "sm" %>
+ <% end %>
+ </div>
+ <% end %>
+
+ <%= styled_form_with model: trading212_item,
+ url: is_new_record ? trading212_items_path : trading212_item_path(trading212_item),
+ scope: :trading212_item,
+ method: is_new_record ? :post : :patch,
+ data: { turbo: true },
+ class: "space-y-3" do |form| %>
+ <%= form.text_field :api_key,
+ label: t(".api_key_label"),
+ placeholder: is_new_record ? t(".api_key_placeholder_new") : t(".api_key_placeholder_existing"),
+ type: :password,
+ value: nil %>
+
+ <%= form.text_field :api_secret,
+ label: t(".api_secret_label"),
+ placeholder: is_new_record ? t(".api_secret_placeholder_new") : t(".api_secret_placeholder_existing"),
+ type: :password,
+ value: nil %>
+
+ <%= form.select :environment,
+ [ [ t(".environment_live"), "live" ], [ t(".environment_demo"), "demo" ] ],
+ { label: t(".environment_label"), selected: trading212_item.environment || "live" } %>
+
+ <%= form.select :currency,
+ Money::Currency.as_options.map { |c| [ "#{c.name} (#{c.iso_code})", c.iso_code ] },
+ { label: t(".currency_label"), selected: trading212_item.currency.presence || Current.family.currency } %>
+
+ <div class="flex flex-wrap justify-end gap-2">
+ <%= form.submit(is_new_record ? t(".save_configuration") : t(".update_configuration")) %>
+ </div>
+ <% end %>
+
+ <div class="flex items-center gap-2">
+ <% if trading212_item.persisted? && trading212_item.credentials_configured? %>
+ <div class="w-2 h-2 bg-success rounded-full"></div>
+ <p class="text-sm text-secondary">
+ <%= t(".status_configured_prefix", summary: trading212_item.sync_status_summary) %>
+ <%= link_to t(".accounts_tab"), accounts_path, class: "link" %>
+ <%= t(".status_configured_suffix") %>
+ </p>
+ <% else %>
+ <div class="w-2 h-2 bg-surface-inset rounded-full"></div>
+ <p class="text-sm text-secondary"><%= t(".not_configured") %></p>
+ <% end %>
+ </div>
+</div>
diff --git a/app/views/trading212_items/_trading212_item.html.erb b/app/views/trading212_items/_trading212_item.html.erb
new file mode 100644
index 0000000000..70888978ae
--- /dev/null
+++ b/app/views/trading212_items/_trading212_item.html.erb
@@ -0,0 +1,116 @@
+<%# locals: (trading212_item:) %>
+
+<%= tag.div id: dom_id(trading212_item) do %>
+ <% unlinked_count = trading212_item.unlinked_accounts_count %>
+
+ <%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center justify-between gap-2">
+ <div class="flex items-center gap-2">
+ <%= icon "chevron-right", class: "group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>
+
+ <div class="flex items-center justify-center h-8 w-8 rounded-full bg-teal-600/10">
+ <span class="text-teal-600 text-xs font-medium">T2</span>
+ </div>
+
+ <div class="pl-1 text-sm">
+ <div class="flex items-center gap-2">
+ <%= tag.p trading212_item.institution_display_name, class: "font-medium text-primary" %>
+ <% if trading212_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(".environment_label_#{trading212_item.environment}") %></p>
+ <% if trading212_item.syncing? %>
+ <div class="text-secondary flex items-center gap-1">
+ <%= icon "loader", size: "sm", class: "animate-spin" %>
+ <%= tag.span t(".syncing") %>
+ </div>
+ <% elsif trading212_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>
+ <% elsif trading212_item.sync_error.present? %>
+ <div class="text-secondary flex items-center gap-1">
+ <%= render DS::Tooltip.new(text: trading212_item.sync_error, icon: "alert-circle", size: "sm", color: "destructive", as: :span) %>
+ <%= tag.span t(".error"), class: "text-destructive" %>
+ </div>
+ <% else %>
+ <p class="text-secondary">
+ <% if trading212_item.last_synced_at %>
+ <%= t(".synced", time: time_ago_in_words(trading212_item.last_synced_at), summary: trading212_item.sync_status_summary) %>
+ <% else %>
+ <%= t(".never_synced") %>
+ <% end %>
+ </p>
+ <% end %>
+ </div>
+ </div>
+
+ <% if Current.user&.admin? %>
+ <div class="flex items-center gap-2">
+ <%= icon(
+ "refresh-cw",
+ as_button: true,
+ href: sync_trading212_item_path(trading212_item),
+ disabled: trading212_item.syncing?
+ ) %>
+
+ <%= render DS::Menu.new do |menu| %>
+ <% if unlinked_count > 0 %>
+ <% menu.with_item(
+ variant: "link",
+ text: t(".setup_accounts"),
+ icon: "settings",
+ href: setup_accounts_trading212_item_path(trading212_item),
+ frame: :modal
+ ) %>
+ <% end %>
+ <% menu.with_item(
+ variant: "button",
+ text: t(".delete"),
+ icon: "trash-2",
+ href: trading212_item_path(trading212_item),
+ method: :delete,
+ confirm: CustomConfirm.for_resource_deletion(trading212_item.institution_display_name, high_severity: true)
+ ) %>
+ <% end %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+
+ <% unless trading212_item.scheduled_for_deletion? %>
+ <div class="space-y-4 mt-4">
+ <% if trading212_item.accounts.any? %>
+ <%= render "accounts/index/account_groups", accounts: trading212_item.accounts %>
+ <% end %>
+
+ <% stats = trading212_item.syncs.ordered.first&.sync_stats || {} %>
+ <%= render ProviderSyncSummary.new(stats: stats, provider_item: trading212_item) %>
+
+ <% if Current.user&.admin? %>
+ <% if unlinked_count > 0 && trading212_item.accounts.empty? %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".accounts_need_setup") %></p>
+ <p class="text-secondary text-sm"><%= t(".accounts_need_setup_description") %></p>
+ <%= render DS::Link.new(
+ text: t(".setup_accounts"),
+ icon: "settings",
+ variant: "primary",
+ href: setup_accounts_trading212_item_path(trading212_item),
+ frame: :modal
+ ) %>
+ </div>
+ <% elsif trading212_item.trading212_accounts.none? %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".no_accounts_discovered") %></p>
+ <p class="text-secondary text-sm"><%= t(".no_accounts_discovered_description") %></p>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/trading212_items/select_existing_account.html.erb b/app/views/trading212_items/select_existing_account.html.erb
new file mode 100644
index 0000000000..8180dbb1ae
--- /dev/null
+++ b/app/views/trading212_items/select_existing_account.html.erb
@@ -0,0 +1,39 @@
+<%= turbo_frame_tag "modal" do %>
+ <%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title")) %>
+
+ <% dialog.with_body do %>
+ <% if @available_trading212_accounts.blank? %>
+ <div class="p-4 text-sm text-secondary">
+ <p class="mb-2"><%= t(".no_accounts_available") %></p>
+ <ul class="list-disc list-inside space-y-1">
+ <li><%= t(".run_sync_hint") %></li>
+ <li><%= t(".wait_for_sync") %></li>
+ </ul>
+ </div>
+ <% else %>
+ <%= form_with url: link_existing_account_trading212_items_path, method: :post, data: { turbo_frame: "_top" }, class: "space-y-4" do %>
+ <%= hidden_field_tag :account_id, @account.id %>
+ <div class="space-y-2 max-h-64 overflow-auto">
+ <% @available_trading212_accounts.each do |t212_account| %>
+ <label class="flex items-center gap-3 p-2 rounded border border-secondary hover:border-primary cursor-pointer">
+ <%= radio_button_tag :trading212_account_id, t212_account.id, false %>
+ <div class="flex flex-col">
+ <span class="text-sm text-primary font-medium"><%= t212_account.name.presence || t212_account.trading212_account_id %></span>
+ <span class="text-xs text-secondary">
+ <%= t212_account.currency %> • <%= t(".balance") %>: <%= number_to_currency((t212_account.current_balance || 0), unit: Money::Currency.new(t212_account.currency.presence || Current.family.currency).symbol) %>
+ </span>
+ </div>
+ </label>
+ <% end %>
+ </div>
+
+ <div class="flex items-center justify-end gap-2">
+ <%= render DS::Button.new(text: t(".link"), variant: :primary, icon: "link-2", type: :submit) %>
+ <%= render DS::Link.new(text: t(".cancel"), variant: :secondary, href: accounts_path, data: { turbo_frame: "_top" }) %>
+ </div>
+ <% end %>
+ <% end %>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/trading212_items/setup_accounts.html.erb b/app/views/trading212_items/setup_accounts.html.erb
new file mode 100644
index 0000000000..2db6088e28
--- /dev/null
+++ b/app/views/trading212_items/setup_accounts.html.erb
@@ -0,0 +1,170 @@
+<% content_for :title, t(".page_title") %>
+
+<%= render DS::Dialog.new(disable_click_outside: true) do |dialog| %>
+ <% dialog.with_header(title: t(".dialog_title")) do %>
+ <div class="flex items-center gap-2">
+ <%= icon "chart-line", class: "text-primary" %>
+ <span class="text-primary"><%= t(".subtitle") %></span>
+ </div>
+ <% end %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-6">
+ <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" %>
+ <div>
+ <p class="text-sm text-primary mb-2"><strong><%= t(".info_box.title") %></strong></p>
+ <ul class="text-xs text-secondary space-y-1 list-disc list-inside">
+ <li><%= t(".info_box.items.item_1") %></li>
+ <li><%= t(".info_box.items.item_2") %></li>
+ <li><%= t(".info_box.items.item_3") %></li>
+ </ul>
+ </div>
+ </div>
+ </div>
+
+ <% if @waiting_for_sync %>
+ <div class="flex flex-col items-center justify-center py-6 space-y-3">
+ <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
+ <p class="text-secondary text-center"><%= t(".status.fetching_accounts") %></p>
+ </div>
+ <div class="flex gap-3 justify-center">
+ <%= render DS::Link.new(
+ text: t(".buttons.refresh"),
+ variant: "secondary",
+ icon: "refresh-cw",
+ href: setup_accounts_trading212_item_path(@trading212_item),
+ frame: "_top"
+ ) %>
+ <%= render DS::Link.new(
+ text: t(".buttons.cancel"),
+ variant: "ghost",
+ href: accounts_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% elsif @no_accounts_found %>
+ <div class="flex flex-col items-center justify-center py-6 space-y-3">
+ <%= icon "alert-circle", size: "lg", class: "text-warning" %>
+ <p class="text-primary text-center font-medium"><%= t(".status.no_accounts_found_title") %></p>
+ <p class="text-secondary text-center text-sm"><%= t(".status.no_accounts_found_description") %></p>
+ </div>
+ <div class="flex gap-3 justify-center">
+ <%= render DS::Link.new(
+ text: t(".buttons.back_to_settings"),
+ variant: "secondary",
+ href: settings_providers_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% else %>
+ <%= form_with url: complete_account_setup_trading212_item_path(@trading212_item), method: :post, data: { turbo_frame: "_top" } do %>
+ <% if @unlinked_accounts.any? %>
+ <div class="space-y-4">
+ <h3 class="font-medium text-primary"><%= t(".available_accounts.title") %></h3>
+
+ <% @unlinked_accounts.each do |t212_account| %>
+ <div class="border border-primary rounded-lg p-4 hover:bg-surface transition-colors">
+ <div class="flex items-center gap-3">
+ <input type="checkbox"
+ id="account_<%= t212_account.id %>"
+ name="account_ids[]"
+ value="<%= t212_account.id %>"
+ checked
+ class="cursor-pointer">
+ <label for="account_<%= t212_account.id %>" class="flex-1 cursor-pointer">
+ <h4 class="font-medium text-primary"><%= t212_account.name %></h4>
+ <p class="text-sm text-secondary">
+ <%= t(
+ ".available_accounts.account_summary",
+ account_type: t(".available_accounts.account_type_investment"),
+ balance: number_to_currency(t212_account.current_balance || 0, unit: Money::Currency.new(t212_account.currency.presence || Current.family.currency).symbol)
+ ) %>
+ </p>
+ <% if t212_account.trading212_account_id.present? %>
+ <p class="text-xs text-secondary"><%= t(".available_accounts.account_id", account_id: t212_account.trading212_account_id) %></p>
+ <% end %>
+ </label>
+ </div>
+ </div>
+ <% end %>
+ </div>
+
+ <div class="flex gap-3 mt-6">
+ <%= render DS::Button.new(
+ text: t(".buttons.create_selected_accounts"),
+ variant: "primary",
+ icon: "plus",
+ type: "submit",
+ class: "flex-1"
+ ) %>
+ <%= render DS::Link.new(
+ text: t(".buttons.cancel"),
+ variant: "secondary",
+ href: accounts_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+
+ <% if @unlinked_accounts.any? && @linkable_accounts.any? %>
+ <div class="border-t border-secondary pt-4 mt-2">
+ <p class="text-xs text-secondary mb-3"><%= t(".link_existing.description") %></p>
+ <div class="space-y-2">
+ <% @unlinked_accounts.each do |t212_account| %>
+ <%= form_with url: link_existing_account_trading212_items_path, method: :post, data: { turbo_frame: "_top" } do |link_form| %>
+ <%= link_form.hidden_field :trading212_account_id, value: t212_account.id %>
+ <p class="text-xs text-primary mb-1"><%= t212_account.name %></p>
+ <div class="flex items-center gap-2">
+ <%= link_form.select :account_id,
+ options_for_select(@linkable_accounts.map { |a| [ t(".link_existing.manual_account_option", name: a.name, balance: number_to_currency(a.balance, unit: Money::Currency.new(a.currency.presence || Current.family.currency).symbol)), a.id ] }),
+ { prompt: t(".link_existing.select_prompt") },
+ class: "bg-container border border-primary rounded px-2 py-1 text-sm text-primary flex-1 min-w-0" %>
+ <%= render DS::Button.new(
+ text: t(".buttons.link"),
+ variant: "secondary",
+ size: "sm",
+ type: "submit"
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ </div>
+ <% end %>
+
+ <% if @linked_accounts.any? %>
+ <div class="<%= 'border-t border-primary pt-6 mt-4' if @unlinked_accounts.any? %>">
+ <h3 class="font-medium text-primary mb-4"><%= t(".linked_accounts.title") %></h3>
+ <% @linked_accounts.each do |t212_account| %>
+ <div class="border border-success/20 bg-success/5 rounded-lg p-4 mb-2">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-3">
+ <%= icon "check-circle", class: "text-success" %>
+ <div>
+ <h4 class="font-medium text-primary"><%= t212_account.name %></h4>
+ <p class="text-sm text-secondary"><%= t(".linked_accounts.linked_to_html", account: link_to(t212_account.current_account.name, account_path(t212_account.current_account), class: "link")) %></p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <% end %>
+
+ <% if @unlinked_accounts.blank? %>
+ <div class="flex justify-end mt-4">
+ <%= render DS::Link.new(
+ text: t(".buttons.done"),
+ variant: "primary",
+ href: accounts_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/config/initializers/trading212.rb b/config/initializers/trading212.rb
new file mode 100644
index 0000000000..d287e9dd79
--- /dev/null
+++ b/config/initializers/trading212.rb
@@ -0,0 +1,9 @@
+Rails.application.configure do
+ truthy = %w[1 true yes on]
+
+ config.x.trading212 ||= ActiveSupport::OrderedOptions.new
+ # Enable raw payload debug logging for Trading 212 API responses.
+ # DEV-ONLY: the dump may contain PII and is gated to local environments,
+ # so it never logs in managed/production.
+ config.x.trading212.debug_raw = Rails.env.local? && truthy.include?(ENV["TRADING212_DEBUG_RAW"].to_s.strip.downcase)
+end
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 03b150ac1c..2c2071093c 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -405,6 +405,7 @@ en:
binance: Sync your Binance spot balances using a read-only API key.
kraken: Sync Kraken balances and spot trade fills using a read-only API key.
snaptrade: Connect brokerage accounts via the SnapTrade aggregation network.
+ trading212: Sync your Trading 212 investment portfolio using a read-only API key.
ibkr: Sync Interactive Brokers investment accounts via Flex Query imports.
questrade: Sync your Questrade investment accounts directly via the Questrade API.
indexa_capital: Track your Indexa Capital automated investment portfolio.
@@ -601,3 +602,26 @@ en:
accounts_tab: Accounts
status_configured_suffix: tab to manage discovered accounts.
not_configured: Not configured.
+ trading212_panel:
+ steps:
+ step_1: Go to Trading 212 → Settings → API (web or mobile app).
+ step_2: Generate a new API key — Trading 212 will show you an API ID and a Secret Key.
+ step_3: Paste both below, select your environment and account currency, then save.
+ api_key_label: API ID
+ api_key_placeholder_new: Paste your Trading 212 API ID
+ api_key_placeholder_existing: Leave blank to keep the current API ID
+ api_secret_label: Secret Key
+ api_secret_placeholder_new: Paste your Trading 212 Secret Key
+ api_secret_placeholder_existing: Leave blank to keep the current Secret Key
+ environment_label: Environment
+ environment_live: Live account
+ environment_demo: Demo account
+ currency_label: Account currency
+ save_configuration: Save Configuration
+ update_configuration: Update Configuration
+ sync: Sync
+ disconnect_confirm: Disconnect Trading 212?
+ status_configured_prefix: "Configured. Visit the"
+ accounts_tab: Accounts
+ status_configured_suffix: tab to manage discovered accounts.
+ not_configured: Not configured.
diff --git a/config/locales/views/trading212_items/en.yml b/config/locales/views/trading212_items/en.yml
new file mode 100644
index 0000000000..a45fa0a55c
--- /dev/null
+++ b/config/locales/views/trading212_items/en.yml
@@ -0,0 +1,102 @@
+---
+en:
+ providers:
+ trading212:
+ name: Trading 212
+ connection_description: Connect a Trading 212 investment account via API key
+ institution_name: Trading 212
+ trading212_items:
+ defaults:
+ name: Trading 212
+ trading212_item:
+ deletion_in_progress: Deletion in progress
+ environment_label_live: Live account
+ environment_label_demo: Demo account
+ syncing: Syncing
+ requires_update: API key needs attention
+ error: Error
+ synced: Synced %{time} ago. %{summary}.
+ never_synced: Never synced.
+ setup_accounts: Set up accounts
+ delete: Delete
+ accounts_need_setup: Account needs setup
+ accounts_need_setup_description: Your Trading 212 account needs to be linked to a Sure account.
+ no_accounts_discovered: No Trading 212 account discovered yet.
+ no_accounts_discovered_description: Run a sync after saving your API key to discover your account.
+ setup_accounts:
+ page_title: Set Up Trading 212 Account
+ dialog_title: Set Up Your Trading 212 Account
+ subtitle: Link your Trading 212 investment account.
+ info_box:
+ title: Trading 212 API Import
+ items:
+ item_1: Current positions with prices and quantities
+ item_2: Full order history (buys and sells)
+ item_3: Dividends and cash transactions
+ status:
+ fetching_accounts: Fetching account from Trading 212...
+ no_accounts_found_title: No account found.
+ no_accounts_found_description: Sure could not find a Trading 212 account. Check that your API key is valid.
+ available_accounts:
+ title: Available account
+ account_type_investment: Investment
+ account_summary: "%{account_type} • Balance: %{balance}"
+ account_id: "Account ID: %{account_id}"
+ link_existing:
+ description: Or link the discovered Trading 212 account to an existing manual investment account.
+ manual_account_option: "%{name} (%{balance})"
+ select_prompt: Select an account...
+ linked_accounts:
+ title: Already linked
+ linked_to_html: "Linked to: %{account}"
+ buttons:
+ refresh: Refresh
+ cancel: Cancel
+ back_to_settings: Back to Settings
+ create_selected_accounts: Create selected accounts
+ link: Link
+ done: Done
+ sync:
+ status:
+ checking_credentials: Checking Trading 212 credentials...
+ importing_account: Importing Trading 212 account...
+ checking_configuration: Checking account configuration...
+ accounts_need_setup:
+ one: 1 Trading 212 account needs setup...
+ other: "%{count} Trading 212 accounts need setup..."
+ processing_activity: Processing positions and activity...
+ calculating_balances: Calculating balances...
+ sync_status:
+ no_accounts: No Trading 212 account discovered yet
+ all_linked:
+ one: 1 account linked
+ other: "%{count} accounts linked"
+ partial: "%{linked} linked, %{unlinked} need setup"
+ select_existing_account:
+ title: Link Trading 212 account
+ no_accounts_available: No unlinked Trading 212 accounts are available yet.
+ run_sync_hint: "Run a sync from Settings > Providers after saving your API key."
+ wait_for_sync: Wait for the account discovery sync to finish.
+ balance: Balance
+ link: Link
+ cancel: Cancel
+ create:
+ success: Successfully configured Trading 212.
+ update:
+ success: Successfully updated Trading 212 configuration.
+ destroy:
+ success: Scheduled Trading 212 connection for deletion.
+ select_accounts:
+ not_configured: Trading 212 is not configured.
+ link_existing_account:
+ not_found: Account or Trading 212 configuration not found.
+ only_manual_investment: Only manual investment accounts can be linked to Trading 212.
+ already_linked: This Trading 212 account is already linked.
+ success: Successfully linked to Trading 212 account.
+ failed: Failed to link Trading 212 account.
+ complete_account_setup:
+ success:
+ one: Successfully created %{count} Trading 212 account.
+ other: Successfully created %{count} Trading 212 accounts.
+ none_selected: No accounts were selected.
+ none_created: No accounts were created.
diff --git a/config/routes.rb b/config/routes.rb
index b44bc74092..5377bcb1d7 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -162,6 +162,20 @@ Rails.application.routes.draw do
end
end
+ resources :trading212_items, only: [ :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
+
# CoinStats routes
resources :coinstats_items, only: [ :index, :new, :create, :update, :destroy ] do
collection do
diff --git a/db/migrate/20260622212404_create_trading212_items_and_accounts.rb b/db/migrate/20260622212404_create_trading212_items_and_accounts.rb
new file mode 100644
index 0000000000..d932cadc43
--- /dev/null
+++ b/db/migrate/20260622212404_create_trading212_items_and_accounts.rb
@@ -0,0 +1,42 @@
+class CreateTrading212ItemsAndAccounts < ActiveRecord::Migration[7.2]
+ def change
+ create_table :trading212_items, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: true, type: :uuid
+ t.string :name
+ t.string :status, default: "good", null: false
+ t.string :environment, default: "live", null: false
+ t.string :currency
+ t.boolean :scheduled_for_deletion, default: false, null: false
+ t.boolean :pending_account_setup, default: false, null: false
+ t.string :api_key
+ t.jsonb :raw_instruments_payload, default: [], null: false
+
+ t.timestamps
+ end
+
+ add_index :trading212_items, :status
+
+ create_table :trading212_accounts, id: :uuid do |t|
+ t.references :trading212_item, null: false, foreign_key: true, type: :uuid
+ t.string :name
+ t.string :trading212_account_id
+ t.string :account_type
+ t.string :currency
+ t.decimal :current_balance, precision: 19, scale: 4
+ t.decimal :cash_balance, precision: 19, scale: 4
+ t.jsonb :raw_positions_payload, default: [], null: false
+ t.jsonb :raw_orders_payload, default: [], null: false
+ t.jsonb :raw_dividends_payload, default: [], null: false
+ t.jsonb :raw_transactions_payload, default: [], null: false
+ t.datetime :last_positions_sync
+ t.datetime :last_orders_sync
+
+ t.timestamps
+ end
+
+ add_index :trading212_accounts, [ :trading212_item_id, :trading212_account_id ],
+ unique: true,
+ where: "(trading212_account_id IS NOT NULL)",
+ name: "index_trading212_accounts_on_item_and_account_id"
+ end
+end
diff --git a/db/migrate/20260622224653_add_api_secret_to_trading212_items.rb b/db/migrate/20260622224653_add_api_secret_to_trading212_items.rb
new file mode 100644
index 0000000000..c353fb1abf
--- /dev/null
+++ b/db/migrate/20260622224653_add_api_secret_to_trading212_items.rb
@@ -0,0 +1,5 @@
+class AddApiSecretToTrading212Items < ActiveRecord::Migration[7.2]
+ def change
+ add_column :trading212_items, :api_secret, :string
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index d743bd3448..d2e0872dc8 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2048,6 +2048,43 @@ ActiveRecord::Schema[7.2].define(version: 2026_07_19_000002) do
t.index ["security_id"], name: "index_trades_on_security_id"
end
+ create_table "trading212_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.string "account_type"
+ t.decimal "cash_balance", precision: 19, scale: 4
+ t.datetime "created_at", null: false
+ t.string "currency"
+ t.decimal "current_balance", precision: 19, scale: 4
+ t.datetime "last_orders_sync"
+ t.datetime "last_positions_sync"
+ t.string "name"
+ t.jsonb "raw_dividends_payload", default: [], null: false
+ t.jsonb "raw_orders_payload", default: [], null: false
+ t.jsonb "raw_positions_payload", default: [], null: false
+ t.jsonb "raw_transactions_payload", default: [], null: false
+ t.string "trading212_account_id"
+ t.uuid "trading212_item_id", null: false
+ t.datetime "updated_at", null: false
+ t.index ["trading212_item_id", "trading212_account_id"], name: "index_trading212_accounts_on_item_and_account_id", unique: true, where: "(trading212_account_id IS NOT NULL)"
+ t.index ["trading212_item_id"], name: "index_trading212_accounts_on_trading212_item_id"
+ end
+
+ create_table "trading212_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.string "api_key"
+ t.string "api_secret"
+ t.datetime "created_at", null: false
+ t.string "currency"
+ t.string "environment", default: "live", null: false
+ t.uuid "family_id", null: false
+ t.string "name"
+ t.boolean "pending_account_setup", default: false, null: false
+ t.jsonb "raw_instruments_payload", default: [], null: false
+ t.boolean "scheduled_for_deletion", default: false, null: false
+ t.string "status", default: "good", null: false
+ t.datetime "updated_at", null: false
+ t.index ["family_id"], name: "index_trading212_items_on_family_id"
+ t.index ["status"], name: "index_trading212_items_on_status"
+ end
+
create_table "transactions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
@@ -2356,6 +2393,8 @@ ActiveRecord::Schema[7.2].define(version: 2026_07_19_000002) do
add_foreign_key "tags", "families"
add_foreign_key "tool_calls", "messages"
add_foreign_key "trades", "securities"
+ add_foreign_key "trading212_accounts", "trading212_items"
+ add_foreign_key "trading212_items", "families"
add_foreign_key "transactions", "categories", on_delete: :nullify
add_foreign_key "transactions", "merchants"
add_foreign_key "transactions", "transfers", column: "transfer_id"
diff --git a/test/controllers/trading212_controller_test.rb b/test/controllers/trading212_controller_test.rb
new file mode 100644
index 0000000000..2308f0d36f
--- /dev/null
+++ b/test/controllers/trading212_controller_test.rb
@@ -0,0 +1,145 @@
+require "test_helper"
+
+class Trading212ItemsControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in @user = users(:family_admin)
+ @item = trading212_items(:configured_item)
+ end
+
+ # === create ===
+
+ test "create redirects to accounts on success" do
+ assert_difference "Trading212Item.count", 1 do
+ post trading212_items_url, params: {
+ trading212_item: {
+ api_key: "new_api_key",
+ api_secret: "new_api_secret",
+ environment: "live",
+ currency: "USD"
+ }
+ }
+ end
+
+ assert_redirected_to accounts_path
+ end
+
+ test "create renders error on invalid params" do
+ assert_no_difference "Trading212Item.count" do
+ post trading212_items_url, params: {
+ trading212_item: {
+ api_key: "",
+ api_secret: "",
+ environment: "live"
+ }
+ }, headers: { "Turbo-Frame" => "modal" }
+ end
+
+ assert_response :unprocessable_entity
+ end
+
+ # === update ===
+
+ test "update redirects to accounts on success" do
+ patch trading212_item_url(@item), params: {
+ trading212_item: {
+ api_key: "",
+ api_secret: "",
+ environment: "demo"
+ }
+ }
+
+ assert_redirected_to accounts_path
+ assert_equal "demo", @item.reload.environment
+ end
+
+ # === destroy ===
+
+ test "destroy schedules item for deletion" do
+ delete trading212_item_url(@item)
+
+ assert_redirected_to settings_providers_path
+ assert @item.reload.scheduled_for_deletion?
+ end
+
+ # === sync ===
+
+ test "sync triggers sync job" do
+ @item.update!(status: :good)
+ assert_enqueued_with(job: SyncJob) do
+ post sync_trading212_item_url(@item)
+ end
+
+ assert_response :redirect
+ end
+
+ # === complete_account_setup ===
+
+ test "complete_account_setup creates investment account and provider link" do
+ t212_account = trading212_accounts(:main_account)
+
+ assert_difference "Account.count", 1 do
+ assert_difference "AccountProvider.count", 1 do
+ post complete_account_setup_trading212_item_url(@item), params: {
+ account_ids: [ t212_account.id ]
+ }
+ end
+ end
+
+ created_account = Account.order(created_at: :desc).first
+ assert_equal "Investment", created_account.accountable_type
+ assert_redirected_to accounts_path
+
+ t212_account.reload
+ assert_equal created_account, t212_account.current_account
+ end
+
+ test "complete_account_setup returns alert when no accounts selected" do
+ post complete_account_setup_trading212_item_url(@item), params: {
+ account_ids: []
+ }
+
+ assert_redirected_to setup_accounts_trading212_item_path(@item)
+ assert_not_nil flash[:alert]
+ end
+
+ # === link_existing_account ===
+
+ test "link_existing_account links manual investment account" do
+ account = accounts(:investment)
+
+ assert_difference "AccountProvider.count", 1 do
+ post link_existing_account_trading212_items_url, params: {
+ account_id: account.id,
+ trading212_account_id: trading212_accounts(:main_account).id
+ }
+ end
+
+ assert_redirected_to account_path(account)
+ trading212_accounts(:main_account).reload
+ assert_equal account, trading212_accounts(:main_account).current_account
+ end
+
+ test "link_existing_account rejects already linked trading212 account" do
+ original_account = accounts(:investment)
+ t212_account = trading212_accounts(:main_account)
+ AccountProvider.create!(account: original_account, provider: t212_account)
+
+ assert_no_difference "AccountProvider.count" do
+ post link_existing_account_trading212_items_url, params: {
+ account_id: original_account.id,
+ trading212_account_id: t212_account.id
+ }
+ end
+
+ assert_redirected_to account_path(original_account)
+ end
+
+ # === select_existing_account ===
+
+ test "select_existing_account renders available trading212 accounts" do
+ get select_existing_account_trading212_items_url, params: { account_id: accounts(:investment).id }
+
+ assert_response :success
+ assert_includes response.body, trading212_accounts(:main_account).name
+ end
+end
diff --git a/test/fixtures/trading212_accounts.yml b/test/fixtures/trading212_accounts.yml
new file mode 100644
index 0000000000..781192aaa4
--- /dev/null
+++ b/test/fixtures/trading212_accounts.yml
@@ -0,0 +1,26 @@
+# Minimal fixtures for Trading212 accounts
+# Per CLAUDE.md: Keep fixtures minimal (2-3 per model for base cases)
+
+main_account:
+ trading212_item: configured_item
+ name: "Trading 212 Invest"
+ trading212_account_id: "t212_acc_123"
+ currency: USD
+ current_balance: 50000.0000
+ cash_balance: 2500.0000
+ raw_positions_payload: []
+ raw_orders_payload: []
+ raw_dividends_payload: []
+ raw_transactions_payload: []
+
+pending_setup_account:
+ trading212_item: pending_setup_item
+ name: "Trading 212 ISA"
+ trading212_account_id: "t212_acc_456"
+ currency: GBP
+ current_balance: 20000.0000
+ cash_balance: 1000.0000
+ raw_positions_payload: []
+ raw_orders_payload: []
+ raw_dividends_payload: []
+ raw_transactions_payload: []
diff --git a/test/fixtures/trading212_items.yml b/test/fixtures/trading212_items.yml
new file mode 100644
index 0000000000..765c040b83
--- /dev/null
+++ b/test/fixtures/trading212_items.yml
@@ -0,0 +1,49 @@
+# Minimal fixtures for Trading212 items
+# Per CLAUDE.md: Keep fixtures minimal (2-3 per model for base cases)
+
+configured_item:
+ family: dylan_family
+ name: "Trading 212 Connection"
+ status: good
+ environment: live
+ currency: USD
+ scheduled_for_deletion: false
+ pending_account_setup: false
+ api_key: "test_api_key"
+ api_secret: "test_api_secret"
+ raw_instruments_payload: []
+
+pending_setup_item:
+ family: dylan_family
+ name: "Trading 212 Setup Pending"
+ status: good
+ environment: live
+ currency: USD
+ scheduled_for_deletion: false
+ pending_account_setup: true
+ api_key: "test_api_key_pending"
+ api_secret: "test_api_secret_pending"
+ raw_instruments_payload: []
+
+requires_update_item:
+ family: dylan_family
+ name: "Trading 212 Needs Update"
+ status: requires_update
+ environment: live
+ currency: USD
+ scheduled_for_deletion: false
+ pending_account_setup: false
+ api_key: "bad_key"
+ api_secret: "bad_secret"
+ raw_instruments_payload: []
+
+no_credentials_item:
+ family: dylan_family
+ name: "Trading 212 No Credentials"
+ status: good
+ environment: demo
+ currency: USD
+ scheduled_for_deletion: false
+ pending_account_setup: true
+ # api_key and api_secret intentionally blank
+ raw_instruments_payload: []
diff --git a/test/models/trading212_account_test.rb b/test/models/trading212_account_test.rb
new file mode 100644
index 0000000000..28e3d819c6
--- /dev/null
+++ b/test/models/trading212_account_test.rb
@@ -0,0 +1,132 @@
+require "test_helper"
+
+class Trading212AccountTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @trading212_item = trading212_items(:configured_item)
+ @trading212_account = trading212_accounts(:main_account)
+ end
+
+ # === Validations ===
+
+ test "validates presence of currency" do
+ account = Trading212Account.new(
+ trading212_item: @trading212_item,
+ name: "Test Account",
+ trading212_account_id: "t212_test_1"
+ # currency intentionally blank
+ )
+ assert_not account.valid?
+ assert_includes account.errors[:currency], "can't be blank"
+ end
+
+ test "validates uniqueness of trading212_account_id within item scope" do
+ existing = @trading212_item.trading212_accounts.create!(
+ name: "Duplicate",
+ trading212_account_id: "t212_duplicate",
+ currency: "USD"
+ )
+
+ duplicate = @trading212_item.trading212_accounts.build(
+ name: "Another Duplicate",
+ trading212_account_id: "t212_duplicate",
+ currency: "USD"
+ )
+
+ assert_not duplicate.valid?
+ assert_includes duplicate.errors[:trading212_account_id], "has already been taken"
+ end
+
+ test "allows nil trading212_account_id across items" do
+ second_item = trading212_items(:pending_setup_item)
+
+ account1 = @trading212_item.trading212_accounts.create!(
+ name: "Account 1",
+ currency: "USD"
+ )
+
+ account2 = second_item.trading212_accounts.create!(
+ name: "Account 2",
+ currency: "USD"
+ )
+
+ # Both nil IDs are allowed across different items (unique index has WHERE clause)
+ assert account1.valid?
+ assert account2.valid?
+ end
+
+ # === current_account ===
+
+ test "current_account returns account through account_provider" do
+ investment = accounts(:investment)
+ @trading212_account.ensure_account_provider!(investment)
+
+ assert_equal investment, @trading212_account.current_account
+ end
+
+ test "current_account returns nil when no provider link" do
+ assert_nil @trading212_account.current_account
+ end
+
+ # === ensure_account_provider! ===
+
+ test "ensure_account_provider! creates AccountProvider for the given account" do
+ investment = accounts(:investment)
+
+ assert_difference "AccountProvider.count", 1 do
+ @trading212_account.ensure_account_provider!(investment)
+ end
+
+ assert_equal investment, @trading212_account.reload.current_account
+ end
+
+ test "ensure_account_provider! is idempotent" do
+ investment = accounts(:investment)
+
+ assert_difference "AccountProvider.count", 1 do
+ @trading212_account.ensure_account_provider!(investment)
+ end
+
+ assert_no_difference "AccountProvider.count" do
+ @trading212_account.ensure_account_provider!(investment)
+ end
+
+ assert_equal investment, @trading212_account.reload.current_account
+ end
+
+ test "ensure_account_provider! updates account if different" do
+ investment = accounts(:investment)
+ @trading212_account.ensure_account_provider!(investment)
+
+ crypto = accounts(:crypto)
+ @trading212_account.ensure_account_provider!(crypto)
+
+ assert_equal crypto, @trading212_account.reload.current_account
+ end
+
+ # === instruments_map ===
+
+ test "instruments_map delegates to trading212_item" do
+ instruments = [
+ { "ticker" => "AAPL_US_EQ", "shortName" => "Apple Inc.", "currencyCode" => "USD" }
+ ]
+ @trading212_item.update!(raw_instruments_payload: instruments)
+
+ result = @trading212_account.instruments_map
+ assert_equal "Apple Inc.", result["AAPL_US_EQ"]["shortName"]
+ end
+
+ # === belongs_to relationships ===
+
+ test "belongs to trading212_item" do
+ assert_equal @trading212_item, @trading212_account.trading212_item
+ end
+
+ test "destroyed when trading212_item is destroyed" do
+ t212_account_id = @trading212_account.id
+
+ @trading212_item.destroy
+
+ assert_nil Trading212Account.find_by(id: t212_account_id)
+ end
+end
diff --git a/test/models/trading212_activities_processor_test.rb b/test/models/trading212_activities_processor_test.rb
new file mode 100644
index 0000000000..c56834171a
--- /dev/null
+++ b/test/models/trading212_activities_processor_test.rb
@@ -0,0 +1,419 @@
+require "test_helper"
+
+class Trading212ActivitiesProcessorTest < ActiveSupport::TestCase
+ fixtures :families, :trading212_items, :trading212_accounts, :accounts, :securities
+ setup do
+ @family = families(:dylan_family)
+ @trading212_item = trading212_items(:configured_item)
+ @trading212_account = trading212_accounts(:main_account)
+
+ # Link to an investment account
+ @account = @family.accounts.create!(
+ name: "Test T212 Investment",
+ balance: 0,
+ cash_balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ @trading212_account.ensure_account_provider!(@account)
+ @trading212_account.reload
+ end
+
+ # === process orders (BUY) ===
+
+ test "processes a filled buy order as a Buy trade" do
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => "order_001",
+ "status" => "FILLED",
+ "side" => "BUY",
+ "instrument" => {
+ "ticker" => "AAPL_US_EQ",
+ "isin" => "US0378331005",
+ "name" => "Apple Inc."
+ },
+ "filledValue" => "1750.00",
+ "createdAt" => "2024-06-15T10:30:00Z"
+ },
+ "fill" => {
+ "id" => "fill_001",
+ "quantity" => "10",
+ "price" => "175.00",
+ "filledAt" => "2024-06-15T10:30:00Z"
+ }
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:trades]
+ entry = @account.entries.find_by(external_id: "trading212_order_fill_001")
+ assert_not_nil entry
+ assert_equal "Trade", entry.entryable_type
+ assert_equal "Buy", entry.entryable.investment_activity_label
+ assert entry.entryable.qty.positive?
+ end
+
+ test "processes a filled sell order as a Sell trade" do
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => "order_002",
+ "status" => "FILLED",
+ "side" => "SELL",
+ "instrument" => {
+ "ticker" => "TSLA_US_EQ",
+ "name" => "Tesla Inc."
+ },
+ "filledValue" => "2500.00",
+ "createdAt" => "2024-06-15T10:30:00Z"
+ },
+ "fill" => {
+ "id" => "fill_002",
+ "quantity" => "10",
+ "price" => "250.00",
+ "filledAt" => "2024-06-15T10:30:00Z"
+ }
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:trades]
+ entry = @account.entries.find_by(external_id: "trading212_order_fill_002")
+ assert_equal "Sell", entry.entryable.investment_activity_label
+ assert entry.entryable.qty.negative?
+ end
+
+ test "skips non-filled orders" do
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => "order_003",
+ "status" => "PENDING",
+ "side" => "BUY",
+ "instrument" => { "ticker" => "MSFT_US_EQ", "name" => "Microsoft" },
+ "filledValue" => "400.00",
+ "createdAt" => "2024-06-15T10:30:00Z"
+ },
+ "fill" => {
+ "id" => "fill_003",
+ "quantity" => "1",
+ "price" => "400.00"
+ }
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 0, result[:trades]
+ end
+
+ test "uses order id as external_id when fill id is absent" do
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => "order_005",
+ "status" => "FILLED",
+ "side" => "BUY",
+ "instrument" => { "ticker" => "MSFT_US_EQ", "name" => "Microsoft" },
+ "filledValue" => "400.00",
+ "createdAt" => "2024-06-15T10:30:00Z"
+ },
+ "fill" => {
+ "quantity" => "1",
+ "price" => "400.00",
+ "filledAt" => "2024-06-15T10:30:00Z"
+ }
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:trades]
+ entry = @account.entries.find_by(external_id: "trading212_order_order_005")
+ assert_not_nil entry
+ end
+
+ # === process dividends ===
+
+ test "processes dividend as a cash transaction" do
+ @trading212_account.update!(
+ raw_dividends_payload: [
+ {
+ "reference" => "div_001",
+ "ticker" => "AAPL_US_EQ",
+ "amount" => "25.00",
+ "paidOn" => "2024-06-15",
+ "quantity" => "50",
+ "grossAmountPerShare" => "0.50",
+ "type" => "ORDINARY"
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:dividends]
+ entry = @account.entries.find_by(external_id: "trading212_dividend_div_001")
+ assert_not_nil entry
+ assert_equal "Transaction", entry.entryable_type
+ assert_equal "Dividend", entry.entryable.investment_activity_label
+ # Dividends are negative in Sure (inflow)
+ assert entry.amount.negative?
+ end
+
+ test "skips dividend with blank reference" do
+ @trading212_account.update!(
+ raw_dividends_payload: [
+ {
+ "ticker" => "AAPL_US_EQ",
+ "amount" => "25.00",
+ "paidOn" => "2024-06-15"
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 0, result[:dividends]
+ end
+
+ test "skips dividend with zero or nil amount" do
+ @trading212_account.update!(
+ raw_dividends_payload: [
+ { "reference" => "div_zero", "amount" => "0", "paidOn" => "2024-06-15" },
+ { "reference" => "div_nil", "amount" => nil, "paidOn" => "2024-06-15" }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 0, result[:dividends]
+ end
+
+ # === process cash transactions ===
+
+ test "processes DEPOSIT as Contribution" do
+ @trading212_account.update!(
+ raw_transactions_payload: [
+ {
+ "reference" => "txn_001",
+ "type" => "DEPOSIT",
+ "amount" => "1000.00",
+ "dateTime" => "2024-06-15T10:00:00Z"
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:transactions]
+ entry = @account.entries.find_by(external_id: "trading212_transaction_txn_001")
+ assert_not_nil entry
+ assert_equal "Contribution", entry.entryable.investment_activity_label
+ # Deposits are negative in Sure (inflow)
+ assert entry.amount.negative?
+ end
+
+ test "processes WITHDRAW as Withdrawal" do
+ @trading212_account.update!(
+ raw_transactions_payload: [
+ {
+ "reference" => "txn_002",
+ "type" => "WITHDRAW",
+ "amount" => "500.00",
+ "dateTime" => "2024-06-15T10:00:00Z"
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:transactions]
+ entry = @account.entries.find_by(external_id: "trading212_transaction_txn_002")
+ assert_equal "Withdrawal", entry.entryable.investment_activity_label
+ assert entry.amount.positive?
+ end
+
+ test "processes INTEREST as Interest" do
+ @trading212_account.update!(
+ raw_transactions_payload: [
+ {
+ "reference" => "txn_003",
+ "type" => "INTEREST",
+ "amount" => "5.00",
+ "dateTime" => "2024-06-15T10:00:00Z"
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:transactions]
+ entry = @account.entries.find_by(external_id: "trading212_transaction_txn_003")
+ assert_equal "Interest", entry.entryable.investment_activity_label
+ end
+
+ test "processes FEE as Fee" do
+ @trading212_account.update!(
+ raw_transactions_payload: [
+ {
+ "reference" => "txn_004",
+ "type" => "FEE",
+ "amount" => "2.50",
+ "dateTime" => "2024-06-15T10:00:00Z"
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 1, result[:transactions]
+ entry = @account.entries.find_by(external_id: "trading212_transaction_txn_004")
+ assert_equal "Fee", entry.entryable.investment_activity_label
+ end
+
+ test "skips transaction with blank reference" do
+ @trading212_account.update!(
+ raw_transactions_payload: [
+ {
+ "type" => "DEPOSIT",
+ "amount" => "100.00",
+ "dateTime" => "2024-06-15T10:00:00Z"
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 0, result[:transactions]
+ end
+
+ test "skips transaction with zero amount" do
+ @trading212_account.update!(
+ raw_transactions_payload: [
+ { "reference" => "txn_zero", "type" => "DEPOSIT", "amount" => "0", "dateTime" => "2024-06-15T10:00:00Z" }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 0, result[:transactions]
+ end
+
+ # === idempotency ===
+
+ test "processor is idempotent - does not duplicate entries" do
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => {
+ "id" => "order_idempotent",
+ "status" => "FILLED",
+ "side" => "BUY",
+ "instrument" => { "ticker" => "AAPL_US_EQ", "name" => "Apple" },
+ "filledValue" => "1750.00",
+ "createdAt" => "2024-06-15T10:30:00Z"
+ },
+ "fill" => {
+ "id" => "fill_idempotent",
+ "quantity" => "10",
+ "price" => "175.00"
+ }
+ }
+ ],
+ raw_dividends_payload: [
+ { "reference" => "div_idempotent", "amount" => "10.00", "paidOn" => "2024-06-15" }
+ ],
+ raw_transactions_payload: [
+ { "reference" => "txn_idempotent", "type" => "DEPOSIT", "amount" => "100.00", "dateTime" => "2024-06-15T10:00:00Z" }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ first_result = processor.process
+ second_result = processor.process
+
+ assert_equal first_result, second_result
+ assert_equal 1, @account.entries.where(external_id: "trading212_order_fill_idempotent").count
+ assert_equal 1, @account.entries.where(external_id: "trading212_dividend_div_idempotent").count
+ assert_equal 1, @account.entries.where(external_id: "trading212_transaction_txn_idempotent").count
+ end
+
+ # === process returns early without account ===
+
+ test "returns zero counts when no account linked" do
+ @trading212_account.account_provider.destroy!
+
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => { "id" => "o1", "status" => "FILLED", "side" => "BUY",
+ "instrument" => { "ticker" => "AAPL_US_EQ", "name" => "Apple" } },
+ "fill" => { "quantity" => "10", "price" => "175.00" }
+ }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal({ trades: 0, dividends: 0, transactions: 0 }, result)
+ end
+
+ # === combined results ===
+
+ test "returns combined stats for all activity types" do
+ @trading212_account.update!(
+ raw_orders_payload: [
+ {
+ "order" => { "id" => "o1", "status" => "FILLED", "side" => "BUY",
+ "instrument" => { "ticker" => "AAPL_US_EQ", "name" => "Apple" } },
+ "fill" => { "id" => "f1", "quantity" => "10", "price" => "175.00", "filledAt" => "2024-06-15T10:30:00Z" }
+ },
+ {
+ "order" => { "id" => "o2", "status" => "FILLED", "side" => "SELL",
+ "instrument" => { "ticker" => "TSLA_US_EQ", "name" => "Tesla" } },
+ "fill" => { "id" => "f2", "quantity" => "5", "price" => "250.00", "filledAt" => "2024-06-15T11:00:00Z" }
+ }
+ ],
+ raw_dividends_payload: [
+ { "reference" => "d1", "amount" => "10.00", "paidOn" => "2024-06-15" }
+ ],
+ raw_transactions_payload: [
+ { "reference" => "t1", "type" => "DEPOSIT", "amount" => "1000.00", "dateTime" => "2024-06-15T10:00:00Z" },
+ { "reference" => "t2", "type" => "FEE", "amount" => "2.00", "dateTime" => "2024-06-15T10:00:00Z" }
+ ]
+ )
+
+ processor = Trading212Account::ActivitiesProcessor.new(@trading212_account)
+ result = processor.process
+
+ assert_equal 2, result[:trades]
+ assert_equal 1, result[:dividends]
+ assert_equal 2, result[:transactions]
+ end
+end
diff --git a/test/models/trading212_data_helpers_test.rb b/test/models/trading212_data_helpers_test.rb
new file mode 100644
index 0000000000..5e29d9b88d
--- /dev/null
+++ b/test/models/trading212_data_helpers_test.rb
@@ -0,0 +1,209 @@
+require "test_helper"
+
+class Trading212DataHelpersTest < ActiveSupport::TestCase
+ # Test class that includes the DataHelpers concern and exposes private methods
+ class TestHelper
+ include Trading212Account::DataHelpers
+
+ attr_accessor :currency, :instruments_map
+
+ def initialize(currency: "USD", instruments_map: {})
+ @currency = currency
+ @instruments_map = instruments_map
+ end
+
+ def test_parse_decimal(value) = parse_decimal(value)
+ def test_parse_date(value) = parse_date(value)
+ def test_standard_ticker(v) = standard_ticker(v)
+ def test_resolve_security_for_ticker(v) = resolve_security_for_ticker(v)
+ def test_resolve_security_direct(isin, ticker, name) = resolve_security_direct(isin, ticker, name)
+ def test_instrument_currency(v) = instrument_currency(v)
+ end
+
+ setup do
+ @helper = TestHelper.new
+ end
+
+ # === parse_decimal ===
+
+ test "parse_decimal handles BigDecimal" do
+ result = @helper.test_parse_decimal(BigDecimal("123.45"))
+ assert_equal BigDecimal("123.45"), result
+ end
+
+ test "parse_decimal handles String" do
+ result = @helper.test_parse_decimal("456.78")
+ assert_equal BigDecimal("456.78"), result
+ end
+
+ test "parse_decimal handles Integer" do
+ result = @helper.test_parse_decimal(100)
+ assert_equal BigDecimal("100"), result
+ end
+
+ test "parse_decimal handles Float" do
+ result = @helper.test_parse_decimal(99.99)
+ assert_equal BigDecimal("99.99"), result
+ end
+
+ test "parse_decimal handles negative values" do
+ result = @helper.test_parse_decimal("-50.25")
+ assert_equal BigDecimal("-50.25"), result
+ end
+
+ test "parse_decimal strips whitespace" do
+ result = @helper.test_parse_decimal(" 42.0 ")
+ assert_equal BigDecimal("42.0"), result
+ end
+
+ test "parse_decimal returns nil for nil input" do
+ assert_nil @helper.test_parse_decimal(nil)
+ end
+
+ test "parse_decimal returns nil for blank string" do
+ assert_nil @helper.test_parse_decimal("")
+ end
+
+ test "parse_decimal returns nil for invalid string" do
+ assert_nil @helper.test_parse_decimal("not_a_number")
+ end
+
+ # === parse_date ===
+
+ test "parse_date handles Date object" do
+ date = Date.new(2024, 6, 15)
+ result = @helper.test_parse_date(date)
+ assert_equal date, result
+ end
+
+ test "parse_date handles ISO string" do
+ result = @helper.test_parse_date("2024-06-15")
+ assert_equal Date.new(2024, 6, 15), result
+ end
+
+ test "parse_date handles Time object" do
+ time = Time.zone.parse("2024-06-15 10:30:00")
+ result = @helper.test_parse_date(time)
+ assert_equal Date.new(2024, 6, 15), result
+ end
+
+ test "parse_date handles DateTime" do
+ dt = DateTime.new(2024, 6, 15, 10, 30)
+ result = @helper.test_parse_date(dt)
+ assert_equal Date.new(2024, 6, 15), result
+ end
+
+ test "parse_date returns nil for nil input" do
+ assert_nil @helper.test_parse_date(nil)
+ end
+
+ test "parse_date returns nil for blank input" do
+ assert_nil @helper.test_parse_date("")
+ end
+
+ test "parse_date returns nil for invalid string" do
+ assert_nil @helper.test_parse_date("invalid_date")
+ end
+
+ # === standard_ticker ===
+
+ test "standard_ticker extracts first segment of T212 ticker" do
+ assert_equal "AAPL", @helper.test_standard_ticker("AAPL_US_EQ")
+ end
+
+ test "standard_ticker handles single segment" do
+ assert_equal "TSLA", @helper.test_standard_ticker("TSLA")
+ end
+
+ test "standard_ticker uppercases the ticker" do
+ assert_equal "AAPL", @helper.test_standard_ticker("aapl_us_eq")
+ end
+
+ test "standard_ticker handles empty string" do
+ assert_equal "", @helper.test_standard_ticker("")
+ end
+
+ # === resolve_security_for_ticker ===
+
+ test "resolve_security_for_ticker finds via instruments_map" do
+ Security.create!(ticker: "TSLA", name: "Tesla Inc.")
+ helper = TestHelper.new(
+ instruments_map: {
+ "TSLA_US_EQ" => { "shortName" => "Tesla Inc.", "currencyCode" => "USD" }
+ }
+ )
+
+ security = helper.test_resolve_security_for_ticker("TSLA_US_EQ")
+ assert_equal "TSLA", security.ticker
+ assert_equal "Tesla Inc.", security.name
+ end
+
+ test "resolve_security_for_ticker creates security if not found" do
+ helper = TestHelper.new(instruments_map: {})
+
+ security = helper.test_resolve_security_for_ticker("MSFT_US_EQ")
+ assert_equal "MSFT", security.ticker
+ end
+
+ test "resolve_security_for_ticker returns nil for nil input" do
+ security = @helper.test_resolve_security_for_ticker(nil)
+ assert_nil security
+ end
+
+ test "resolve_security_for_ticker returns nil for empty ticker" do
+ security = @helper.test_resolve_security_for_ticker("")
+ assert_nil security
+ end
+
+ # === resolve_security_direct ===
+
+ test "resolve_security_direct finds existing by ticker" do
+ existing = Security.create!(ticker: "GOOGL", name: "Alphabet Inc.")
+
+ result = @helper.test_resolve_security_direct("ISIN123", "GOOGL", "Alphabet Inc.")
+ assert_equal existing, result
+ end
+
+ test "resolve_security_direct creates new when not found" do
+ result = @helper.test_resolve_security_direct("ISIN456", "NVDA", "Nvidia Corp")
+ assert_equal "NVDA", result.ticker
+ assert_equal "Nvidia Corp", result.name
+ end
+
+ test "resolve_security_direct handles race condition on create" do
+ Security.create!(ticker: "RACE", name: "Already Exists")
+
+ result = @helper.test_resolve_security_direct(nil, "RACE", "New Name")
+ assert_equal "RACE", result.ticker
+ assert_equal "Already Exists", result.name
+ end
+
+ # === instrument_currency ===
+
+ test "instrument_currency returns currency from instruments_map" do
+ helper = TestHelper.new(
+ currency: "USD",
+ instruments_map: { "AAPL_US_EQ" => { "currencyCode" => "EUR" } }
+ )
+
+ assert_equal "EUR", helper.test_instrument_currency("AAPL_US_EQ")
+ end
+
+ test "instrument_currency falls back to account currency" do
+ helper = TestHelper.new(
+ currency: "USD",
+ instruments_map: {}
+ )
+
+ assert_equal "USD", helper.test_instrument_currency("UNKNOWN_TICKER")
+ end
+
+ test "instrument_currency falls back when instrument has no currencyCode" do
+ helper = TestHelper.new(
+ currency: "GBP",
+ instruments_map: { "TSLA_US_EQ" => { "shortName" => "Tesla" } }
+ )
+
+ assert_equal "GBP", helper.test_instrument_currency("TSLA_US_EQ")
+ end
+end
diff --git a/test/models/trading212_holdings_processor_test.rb b/test/models/trading212_holdings_processor_test.rb
new file mode 100644
index 0000000000..8ab047b2ca
--- /dev/null
+++ b/test/models/trading212_holdings_processor_test.rb
@@ -0,0 +1,208 @@
+require "test_helper"
+
+class Trading212HoldingsProcessorTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @trading212_item = trading212_items(:configured_item)
+ @trading212_account = trading212_accounts(:main_account)
+
+ # Link to an investment account
+ @account = @family.accounts.create!(
+ name: "Test T212 Investment",
+ balance: 0,
+ cash_balance: 0,
+ currency: "USD",
+ accountable: Investment.new
+ )
+ @trading212_account.ensure_account_provider!(@account)
+ @trading212_account.reload
+ end
+
+ # === process ===
+
+ test "processor creates holdings from raw positions payload" do
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => {
+ "ticker" => "AAPL_US_EQ",
+ "isin" => "US0378331005",
+ "name" => "Apple Inc.",
+ "currency" => "USD"
+ },
+ "quantity" => "50",
+ "currentPrice" => "175.00",
+ "averagePricePaid" => "150.00"
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+ processor.process
+
+ security = Security.find_by(ticker: "AAPL")
+ assert_not_nil security
+
+ holding = @account.holdings.find_by(security: security)
+ assert_not_nil holding
+ assert_equal BigDecimal("50"), holding.qty
+ assert_equal BigDecimal("175.00"), holding.price
+ end
+
+ test "processor stores cost basis when available" do
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => {
+ "ticker" => "TSLA_US_EQ",
+ "name" => "Tesla Inc."
+ },
+ "quantity" => "25",
+ "currentPrice" => "250.00",
+ "averagePricePaid" => "200.00"
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+ processor.process
+
+ security = Security.find_by(ticker: "TSLA")
+ holding = @account.holdings.find_by(security: security)
+ assert_not_nil holding
+ assert_equal BigDecimal("200.00"), holding.cost_basis
+ assert_equal "provider", holding.cost_basis_source
+ end
+
+ test "processor skips position with blank ticker" do
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => {
+ "ticker" => "",
+ "name" => "No Ticker"
+ },
+ "quantity" => "100",
+ "currentPrice" => "50.00"
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+
+ assert_nothing_raised do
+ processor.process
+ end
+
+ assert_equal 0, @account.holdings.count
+ end
+
+ test "processor skips position with zero quantity" do
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => {
+ "ticker" => "MSFT_US_EQ",
+ "name" => "Microsoft"
+ },
+ "quantity" => "0",
+ "currentPrice" => "400.00"
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+ processor.process
+
+ assert_equal 0, @account.holdings.count
+ end
+
+ test "processor skips position with nil price" do
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => {
+ "ticker" => "GOOGL_US_EQ",
+ "name" => "Alphabet"
+ },
+ "quantity" => "10",
+ "currentPrice" => nil
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+ processor.process
+
+ assert_equal 0, @account.holdings.count
+ end
+
+ test "processor is idempotent - does not duplicate holdings" do
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => {
+ "ticker" => "NVDA_US_EQ",
+ "name" => "Nvidia"
+ },
+ "quantity" => "30",
+ "currentPrice" => "800.00",
+ "averagePricePaid" => "600.00"
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+ 2.times { processor.process }
+
+ security = Security.find_by(ticker: "NVDA")
+ assert_equal 1, @account.holdings.where(security: security).count
+ end
+
+ test "processor handles empty positions payload" do
+ @trading212_account.update!(raw_positions_payload: [])
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+ processor.process
+
+ assert_equal 0, @account.holdings.count
+ end
+
+ test "processor returns early when no account linked" do
+ @trading212_account.account_provider.destroy!
+
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ "instrument" => { "ticker" => "AAPL_US_EQ", "name" => "Apple" },
+ "quantity" => "10",
+ "currentPrice" => "150.00"
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+ processor.process
+
+ assert_equal 0, @account.holdings.count
+ end
+
+ test "processor gracefully handles individual position errors" do
+ # Position without instrument at all
+ @trading212_account.update!(
+ raw_positions_payload: [
+ {
+ # Missing instrument key entirely
+ "quantity" => "10",
+ "currentPrice" => "150.00"
+ }
+ ]
+ )
+
+ processor = Trading212Account::HoldingsProcessor.new(@trading212_account)
+
+ assert_nothing_raised do
+ processor.process
+ end
+ end
+end
diff --git a/test/models/trading212_item_importer_test.rb b/test/models/trading212_item_importer_test.rb
new file mode 100644
index 0000000000..3de757903e
--- /dev/null
+++ b/test/models/trading212_item_importer_test.rb
@@ -0,0 +1,121 @@
+require "test_helper"
+
+class Trading212ItemImporterTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @item = trading212_items(:configured_item)
+ end
+
+ test "import creates trading212_account with fetched data" do
+ provider = mock("trading212_provider")
+ provider.expects(:fetch_instruments).returns([
+ { "ticker" => "AAPL_US_EQ", "shortName" => "Apple Inc.", "currencyCode" => "USD" }
+ ])
+ provider.expects(:fetch_account_summary).returns({
+ "id" => "t212_acc_new",
+ "totalValue" => "15000.00",
+ "cash" => { "availableToTrade" => "2000.00" }
+ })
+ provider.expects(:fetch_positions).returns([
+ { "instrument" => { "ticker" => "AAPL_US_EQ" }, "quantity" => "10", "currentPrice" => "175.00" }
+ ])
+ provider.expects(:fetch_all_orders).returns([
+ { "order" => { "id" => "o1", "status" => "FILLED", "side" => "BUY" } }
+ ])
+ provider.expects(:fetch_all_dividends).returns([
+ { "reference" => "d1", "amount" => "10.00" }
+ ])
+ provider.expects(:fetch_all_transactions).returns([
+ { "reference" => "t1", "type" => "DEPOSIT", "amount" => "1000.00" }
+ ])
+
+ importer = Trading212Item::Importer.new(@item, provider: provider)
+ result = importer.import
+
+ assert_equal({ success: true }, result)
+
+ account = @item.trading212_accounts.find_by(trading212_account_id: "t212_acc_new")
+ assert_not_nil account
+ assert_equal BigDecimal("15000.00"), account.current_balance
+ assert_equal BigDecimal("2000.00"), account.cash_balance
+ assert account.raw_positions_payload.present?
+ assert account.raw_orders_payload.present?
+ assert account.raw_dividends_payload.present?
+ assert account.raw_transactions_payload.present?
+ end
+
+ test "import updates existing account on subsequent sync" do
+ existing = @item.trading212_accounts.create!(
+ name: "Existing Account",
+ trading212_account_id: "t212_acc_existing",
+ currency: "USD",
+ current_balance: BigDecimal("1000.00"),
+ cash_balance: BigDecimal("100.00")
+ )
+
+ provider = mock("trading212_provider")
+ provider.expects(:fetch_instruments).returns([])
+ provider.expects(:fetch_account_summary).returns({
+ "id" => "t212_acc_existing",
+ "totalValue" => "12000.00",
+ "cash" => { "availableToTrade" => "1500.00" }
+ })
+ provider.expects(:fetch_positions).returns([])
+ provider.expects(:fetch_all_orders).returns([])
+ provider.expects(:fetch_all_dividends).returns([])
+ provider.expects(:fetch_all_transactions).returns([])
+
+ assert_no_difference "Trading212Account.count" do
+ Trading212Item::Importer.new(@item, provider: provider).import
+ end
+
+ existing.reload
+ assert_equal BigDecimal("12000.00"), existing.current_balance
+ assert_equal BigDecimal("1500.00"), existing.cash_balance
+ end
+
+ test "import stores instruments payload on item" do
+ instruments = [
+ { "ticker" => "AAPL_US_EQ", "shortName" => "Apple Inc." },
+ { "ticker" => "TSLA_US_EQ", "shortName" => "Tesla Inc." }
+ ]
+
+ provider = mock("trading212_provider")
+ provider.expects(:fetch_instruments).returns(instruments)
+ provider.expects(:fetch_account_summary).returns({
+ "id" => "t212_acc_inst",
+ "totalValue" => "5000.00",
+ "cash" => { "availableToTrade" => "500.00" }
+ })
+ provider.expects(:fetch_positions).returns([])
+ provider.expects(:fetch_all_orders).returns([])
+ provider.expects(:fetch_all_dividends).returns([])
+ provider.expects(:fetch_all_transactions).returns([])
+
+ Trading212Item::Importer.new(@item, provider: provider).import
+
+ assert_equal 2, @item.reload.raw_instruments_payload.size
+ end
+
+ test "import falls back to cached instruments on fetch failure" do
+ @item.update!(raw_instruments_payload: [
+ { "ticker" => "CACHED_US_EQ", "shortName" => "Cached Inc." }
+ ])
+
+ provider = mock("trading212_provider")
+ provider.expects(:fetch_instruments).raises(StandardError.new("Network error"))
+ provider.expects(:fetch_account_summary).returns({
+ "id" => "t212_acc_cache",
+ "totalValue" => "5000.00",
+ "cash" => { "availableToTrade" => "500.00" }
+ })
+ provider.expects(:fetch_positions).returns([])
+ provider.expects(:fetch_all_orders).returns([])
+ provider.expects(:fetch_all_dividends).returns([])
+ provider.expects(:fetch_all_transactions).returns([])
+
+ # Should not raise
+ result = Trading212Item::Importer.new(@item, provider: provider).import
+ assert_equal({ success: true }, result)
+ end
+end
diff --git a/test/models/trading212_item_syncer_test.rb b/test/models/trading212_item_syncer_test.rb
new file mode 100644
index 0000000000..1a592d4d55
--- /dev/null
+++ b/test/models/trading212_item_syncer_test.rb
@@ -0,0 +1,87 @@
+require "test_helper"
+
+class Trading212ItemSyncerTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @item = trading212_items(:configured_item)
+ @syncer = Trading212Item::Syncer.new(@item)
+ end
+
+ # === perform_sync (missing credentials) ===
+
+ test "perform_sync raises ConfigurationError when credentials are missing" do
+ @item.update!(api_key: nil, api_secret: nil)
+ sync = @item.syncs.create!
+
+ error = assert_raises(Provider::Trading212::ConfigurationError) do
+ @syncer.perform_sync(sync)
+ end
+
+ assert_equal "Trading 212 API key is missing.", error.message
+ assert_equal "requires_update", @item.reload.status
+ end
+
+ test "perform_sync sets requires_update status on auth error" do
+ sync = @item.syncs.create!
+ Provider::Trading212.any_instance.expects(:fetch_account_summary)
+ .raises(Provider::Trading212::AuthenticationError.new("Trading 212 authentication failed (401)."))
+
+ assert_raises(Provider::Trading212::AuthenticationError) do
+ @syncer.perform_sync(sync)
+ end
+
+ assert_equal "requires_update", @item.reload.status
+ end
+
+ # === perform_sync (happy path) ===
+
+ test "perform_sync imports data and processes accounts when linked" do
+ # Link an account
+ t212_account = trading212_accounts(:main_account)
+ investment = accounts(:investment)
+ t212_account.ensure_account_provider!(investment)
+
+ sync = @item.syncs.create!
+ @item.update!(status: :good)
+
+ # Stub the importer to avoid HTTP calls
+ Trading212Item::Importer.any_instance.stubs(:import).returns({ success: true })
+
+ # Run sync without raising
+ @syncer.perform_sync(sync)
+
+ # Sync ran without raising; verify stats were collected
+ stats = sync.reload.sync_stats
+ assert stats.present?
+ end
+
+ test "perform_sync sets pending_account_setup when accounts are unlinked" do
+ sync = @item.syncs.create!
+
+ Trading212Item::Importer.any_instance.expects(:import).returns({ success: true })
+
+ @syncer.perform_sync(sync)
+
+ assert @item.reload.pending_account_setup?
+ end
+
+ # === perform_sync (error handling) ===
+
+ test "perform_sync records error stats on generic failure" do
+ sync = @item.syncs.create!
+ Trading212Item::Importer.any_instance.expects(:import).raises(StandardError.new("Boom"))
+
+ assert_raises(StandardError) do
+ @syncer.perform_sync(sync)
+ end
+
+ stats = sync.reload.sync_stats
+ assert stats["total_errors"] >= 1
+ end
+
+ # === perform_post_sync ===
+
+ test "perform_post_sync is a no-op" do
+ assert_nil @syncer.perform_post_sync
+ end
+end
diff --git a/test/models/trading212_item_test.rb b/test/models/trading212_item_test.rb
new file mode 100644
index 0000000000..a47887e7f4
--- /dev/null
+++ b/test/models/trading212_item_test.rb
@@ -0,0 +1,204 @@
+require "test_helper"
+
+class Trading212ItemTest < ActiveSupport::TestCase
+ include SyncableInterfaceTest
+
+ setup do
+ @family = families(:dylan_family)
+ @trading212_item = @syncable = trading212_items(:configured_item)
+ end
+
+ # === Validations ===
+
+ test "validates presence of api_key on create" do
+ item = Trading212Item.new(family: @family, api_secret: "secret", environment: "live")
+ assert_not item.valid?
+ assert_includes item.errors[:api_key], "can't be blank"
+ end
+
+ test "validates presence of api_secret on create" do
+ item = Trading212Item.new(family: @family, api_key: "key", environment: "live")
+ assert_not item.valid?
+ assert_includes item.errors[:api_secret], "can't be blank"
+ end
+
+ test "validates api_key and api_secret on create" do
+ item = Trading212Item.new(family: @family, api_key: "key", api_secret: "secret")
+ assert item.valid?
+ end
+
+ # === Status enum ===
+
+ test "default status is good" do
+ item = Trading212Item.new(family: @family, api_key: "key", api_secret: "secret")
+ assert_equal "good", item.status
+ end
+
+ test "can query good items" do
+ items = Trading212Item.good
+ assert_includes items, @trading212_item
+ assert_not_includes items, trading212_items(:requires_update_item)
+ end
+
+ test "can query requires_update items" do
+ items = Trading212Item.needs_update
+ assert_includes items, trading212_items(:requires_update_item)
+ assert_not_includes items, @trading212_item
+ end
+
+ # === Environment enum ===
+
+ test "default environment is live" do
+ item = Trading212Item.new(family: @family, api_key: "key", api_secret: "secret")
+ assert_equal "live", item.environment
+ end
+
+ test "accepts demo environment" do
+ item = Trading212Item.new(family: @family, api_key: "key", api_secret: "secret", environment: "demo")
+ assert item.valid?
+ assert_equal "demo", item.environment
+ end
+
+ # === credentials_configured? ===
+
+ test "credentials_configured? returns true when api_key and api_secret are present" do
+ assert @trading212_item.credentials_configured?
+ end
+
+ test "credentials_configured? returns false when api_key is blank" do
+ item = trading212_items(:no_credentials_item)
+ assert_not item.credentials_configured?
+ end
+
+ # === trading212_provider ===
+
+ test "trading212_provider returns a Provider::Trading212 instance when configured" do
+ provider = @trading212_item.trading212_provider
+ assert_instance_of Provider::Trading212, provider
+ end
+
+ test "trading212_provider returns nil when credentials not configured" do
+ item = trading212_items(:no_credentials_item)
+ assert_nil item.trading212_provider
+ end
+
+ test "Provider::Trading212 raises ConfigurationError with blank credentials" do
+ assert_raises(Provider::Trading212::ConfigurationError) do
+ Provider::Trading212.new(api_key: "", api_secret: "secret")
+ end
+ end
+
+ # === Scopes ===
+
+ test "active scope excludes items scheduled for deletion" do
+ item = trading212_items(:configured_item)
+ item.update!(scheduled_for_deletion: true)
+
+ assert_not_includes Trading212Item.active, item
+ end
+
+ test "syncable scope excludes items without api_key" do
+ assert_not_includes Trading212Item.syncable, trading212_items(:no_credentials_item)
+ end
+
+ test "syncable scope includes items with credentials" do
+ assert_includes Trading212Item.syncable, @trading212_item
+ end
+
+ # === destroy_later ===
+
+ test "destroy_later marks item for deletion and enqueues DestroyJob" do
+ assert_enqueued_with(job: DestroyJob) do
+ @trading212_item.destroy_later
+ end
+
+ assert_predicate @trading212_item.reload, :scheduled_for_deletion?
+ end
+
+ # === accounts ===
+
+ test "accounts returns linked investment accounts" do
+ trading212_account = trading212_accounts(:main_account)
+ investment = accounts(:investment)
+
+ trading212_account.ensure_account_provider!(investment)
+
+ account_list = @trading212_item.accounts
+ assert_includes account_list, investment
+ end
+
+ test "accounts returns empty when no accounts are linked" do
+ assert_empty @trading212_item.accounts
+ end
+
+ # === has_completed_initial_setup? ===
+
+ test "has_completed_initial_setup? returns false when no accounts exist" do
+ assert_not @trading212_item.has_completed_initial_setup?
+ end
+
+ test "has_completed_initial_setup? returns true when accounts exist" do
+ trading212_account = trading212_accounts(:main_account)
+ investment = accounts(:investment)
+ trading212_account.ensure_account_provider!(investment)
+
+ assert @trading212_item.has_completed_initial_setup?
+ end
+
+ # === sync_status_summary ===
+
+ test "sync_status_summary reports no_accounts when no trading212 accounts" do
+ # Delete fixture account to test empty state
+ @trading212_item.trading212_accounts.delete_all
+ summary = @trading212_item.reload.sync_status_summary
+ assert_match(/No Trading 212 account discovered yet/, summary)
+ end
+
+ test "sync_status_summary reports all_linked when all accounts have providers" do
+ trading212_account = trading212_accounts(:main_account)
+ investment = accounts(:investment)
+ trading212_account.ensure_account_provider!(investment)
+
+ summary = @trading212_item.reload.sync_status_summary
+ assert_match(/account linked/, summary)
+ end
+
+ test "sync_status_summary reports partial when some accounts are unlinked" do
+ # main_account is linked
+ trading212_account = trading212_accounts(:main_account)
+ investment = accounts(:investment)
+ trading212_account.ensure_account_provider!(investment)
+
+ # Create a second, unlinked account
+ @trading212_item.trading212_accounts.create!(
+ name: "Unlinked Account",
+ trading212_account_id: "t212_acc_789",
+ currency: "USD"
+ )
+
+ summary = @trading212_item.reload.sync_status_summary
+ assert_match(/need setup/, summary)
+ end
+
+ # === unlink_all! ===
+
+ test "unlink_all! removes account providers from all trading212 accounts" do
+ trading212_account = trading212_accounts(:main_account)
+ investment = accounts(:investment)
+ trading212_account.ensure_account_provider!(investment)
+
+ assert_difference -> { AccountProvider.where(provider_type: "Trading212Account").count }, -1 do
+ @trading212_item.unlink_all!(dry_run: false)
+ end
+ end
+
+ test "unlink_all! dry_run does not remove providers" do
+ trading212_account = trading212_accounts(:main_account)
+ investment = accounts(:investment)
+ trading212_account.ensure_account_provider!(investment)
+
+ assert_no_difference -> { AccountProvider.where(provider_type: "Trading212Account").count } do
+ @trading212_item.unlink_all!(dry_run: true)
+ end
+ end
+end