Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Support multiple Trade Republic connections per family (#3754)

GFR7ba16d642066
diff --git a/app/components/trade_republic/account_editor_component.html.erb b/app/components/trade_republic/account_editor_component.html.erb
new file mode 100644
index 0000000000..a04a6263e3
--- /dev/null
+++ b/app/components/trade_republic/account_editor_component.html.erb
@@ -0,0 +1,47 @@
+<% items.each do |item| %>
+ <%= render TradeRepublic::ConnectionCardComponent.new(
+ item: item,
+ open: open?(item),
+ qr_active: qr_login_active?(item),
+ qr_code_svg: qr_code_svg_for(item)
+ ) %>
+<% end %>
+
+<% if items.any? %>
+ <h3 class="flex items-center gap-2 text-sm font-medium text-primary mt-4">
+ <%= helpers.icon "plus", size: "sm" %>
+ <%= translation("add_account") %>
+ </h3>
+<% end %>
+
+<%= helpers.styled_form_with model: new_item,
+ url: helpers.trade_republic_items_path,
+ scope: :trade_republic_item,
+ method: :post,
+ data: { turbo: true },
+ class: "space-y-3" do |form| %>
+ <%= form.text_field :phone_number,
+ label: translation("phone_number_label"),
+ placeholder: translation("phone_number_placeholder_new"),
+ type: :tel,
+ value: new_item.phone_number %>
+
+ <%= form.text_field :pin,
+ label: translation("pin_label"),
+ placeholder: translation("pin_placeholder_new"),
+ type: :password,
+ value: nil %>
+
+ <div class="flex flex-wrap justify-end gap-2">
+ <%= form.submit(translation("save_configuration")) %>
+ <%= render DS::Button.new(
+ text: translation("qr_login"),
+ variant: :outline,
+ size: :sm,
+ icon: "qr-code",
+ type: "submit",
+ name: "login_method",
+ value: "qr"
+ ) %>
+ </div>
+<% end %>
diff --git a/app/components/trade_republic/account_editor_component.rb b/app/components/trade_republic/account_editor_component.rb
new file mode 100644
index 0000000000..aeacc623c2
--- /dev/null
+++ b/app/components/trade_republic/account_editor_component.rb
@@ -0,0 +1,40 @@
+class TradeRepublic::AccountEditorComponent < ApplicationComponent
+ include TradeRepublic::PanelTranslatable
+
+ def initialize(items: nil, family:, qr_code_svg: nil, qr_login_auto_poll_item: nil, new_item: nil)
+ @items = items || family.trade_republic_items.active.ordered.includes(:trade_republic_accounts)
+ @family = family
+ @qr_code_svg = qr_code_svg
+ @qr_login_auto_poll_item = qr_login_auto_poll_item
+ @new_item = new_item
+ end
+
+ attr_reader :items, :family
+
+ def new_item
+ @new_item ||= family.trade_republic_items.build
+ end
+
+ # A collapsed card would hide the QR code, the push notice, the
+ # authenticator form or the "accounts discovered" setup CTA, so only
+ # healthy, fully linked connections among several start closed.
+ def open?(item)
+ items.size == 1 || qr_login_active?(item) || item.pending_login_state.present? ||
+ !item.good? || setup_cta_visible?(item)
+ end
+
+ # Mirrors the card template's condition for the "X accounts discovered —
+ # Set up accounts" link: without a configured session the CTA never
+ # renders, so unlinked accounts alone are no reason to expand.
+ def setup_cta_visible?(item)
+ item.session_configured? && item.unlinked_accounts_count.positive?
+ end
+
+ def qr_login_active?(item)
+ item == @qr_login_auto_poll_item || item.login_stage == "qr_pending"
+ end
+
+ def qr_code_svg_for(item)
+ @qr_code_svg if item == @qr_login_auto_poll_item
+ end
+end
diff --git a/app/components/trade_republic/connection_card_component.html.erb b/app/components/trade_republic/connection_card_component.html.erb
new file mode 100644
index 0000000000..283c6b0c5b
--- /dev/null
+++ b/app/components/trade_republic/connection_card_component.html.erb
@@ -0,0 +1,200 @@
+<div id="<%= dom_id %>">
+ <%= render DS::Disclosure.new(variant: :card, open: open) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center justify-between gap-3 w-full">
+ <div class="min-w-0">
+ <p class="font-medium text-primary truncate">
+ <%= item.name %>
+ <% if identifier_last4 %>
+ <span class="font-normal text-secondary">&middot; <%= identifier_label %> &bull;&bull;&bull;&bull; <%= identifier_last4 %></span>
+ <% end %>
+ </p>
+ <p class="text-xs text-secondary">
+ <% if item.syncing? %>
+ <%= translation("syncing") %>
+ <% else %>
+ <%= item.sync_status_summary %>
+ <% end %>
+ </p>
+ </div>
+ </div>
+ <% end %>
+
+ <div class="mt-4 space-y-4"
+ <% if item.persisted? && login_stage == "waiting_for_approval" %>
+ data-controller="trade-republic-login"
+ data-trade-republic-login-url-value="<%= helpers.poll_login_trade_republic_item_path(item) %>"
+ <% end %>>
+ <div class="flex flex-wrap justify-end gap-2">
+ <% if item.pending_login_state.blank? && item.session_configured? %>
+ <%= render DS::Button.new(
+ text: translation("connect"),
+ variant: :outline,
+ size: :sm,
+ icon: "log-in",
+ href: helpers.initiate_login_trade_republic_item_path(item),
+ method: :post
+ ) %>
+
+ <%= render DS::Button.new(
+ text: translation("sync"),
+ variant: :outline,
+ size: :sm,
+ icon: "refresh-cw",
+ href: helpers.sync_trade_republic_item_path(item),
+ method: :post,
+ disabled: item.syncing?
+ ) %>
+ <% end %>
+
+ <%= render DS::Button.new(
+ variant: :outline_destructive,
+ size: :sm,
+ icon: "trash-2",
+ aria_label: translation("disconnect"),
+ title: translation("disconnect"),
+ href: helpers.trade_republic_item_path(item),
+ method: :delete,
+ confirm: identifier_last4 ? translation("disconnect_confirm_with_identifier", last4: identifier_last4) : translation("disconnect_confirm")
+ ) %>
+ </div>
+
+ <% if item.pending_login_state.blank? || login_stage == "qr_pending" %>
+ <div class="space-y-3" data-controller="trade-republic-qr"
+ data-trade-republic-qr-auto-poll-value="<%= qr_active %>"
+ data-trade-republic-qr-initiate-url-value="<%= helpers.initiate_qr_login_trade_republic_item_path(item) %>"
+ data-trade-republic-qr-poll-url-value="<%= helpers.poll_qr_login_trade_republic_item_path(item) %>"
+ data-trade-republic-qr-cancel-url-value="<%= helpers.cancel_qr_login_trade_republic_item_path(item) %>"
+ data-trade-republic-qr-return-url-value="<%= helpers.settings_providers_path(anchor: "trade-republic") %>"
+ data-trade-republic-qr-loading-text-value="<%= translation("qr_loading") %>"
+ data-trade-republic-qr-instruction-text-value="<%= translation("qr_instruction") %>"
+ data-trade-republic-qr-success-text-value="<%= translation("qr_success") %>"
+ data-trade-republic-qr-error-text-value="<%= translation("qr_error") %>"
+ data-trade-republic-qr-login-text-value="<%= translation("qr_login") %>"
+ data-trade-republic-qr-cancel-text-value="<%= translation("qr_cancel") %>">
+ <%= render DS::Button.new(
+ text: qr_active ? translation("qr_cancel") : translation("qr_login"),
+ variant: :outline,
+ size: :sm,
+ icon: "qr-code",
+ type: "button",
+ data: {
+ action: "trade-republic-qr#toggle",
+ trade_republic_qr_target: "button"
+ }
+ ) %>
+
+ <div data-trade-republic-qr-target="panel" <%= "hidden" unless qr_active %> class="rounded-lg border border-secondary bg-container-inset p-4 space-y-3">
+ <p data-trade-republic-qr-target="status" class="text-sm text-secondary"></p>
+ <div data-trade-republic-qr-target="code" class="qrcode flex justify-center min-h-48"><%= qr_code_svg %></div>
+ </div>
+ </div>
+ <% end %>
+
+ <% if login_stage == "authenticator_code" %>
+ <%= render DS::Alert.new(
+ message: translation("authenticator_code_notice"),
+ variant: :info
+ ) %>
+
+ <%= helpers.styled_form_with url: helpers.complete_login_trade_republic_item_path(item),
+ method: :post,
+ scope: :trade_republic_login,
+ class: "space-y-3" do |form| %>
+ <%= form.text_field :code,
+ label: translation("authenticator_code_label"),
+ placeholder: translation("authenticator_code_placeholder"),
+ value: nil,
+ required: true %>
+ <div class="flex flex-wrap justify-end gap-2">
+ <%= form.submit(translation("complete_login")) %>
+ </div>
+ <% end %>
+ <% elsif login_stage == "waiting_for_approval" %>
+ <%= render DS::Alert.new(message: translation("push_login_notice"), variant: :info) %>
+ <div class="flex flex-wrap justify-end gap-2">
+ <%= render DS::Button.new(
+ text: translation("check_login_status"),
+ variant: :outline,
+ size: :sm,
+ icon: "refresh-cw",
+ href: helpers.poll_login_trade_republic_item_path(item),
+ method: :post
+ ) %>
+ </div>
+ <% end %>
+
+ <% if item.pending_login_state.blank? %>
+ <%= helpers.styled_form_with model: item,
+ url: helpers.trade_republic_item_path(item),
+ scope: :trade_republic_item,
+ method: :patch,
+ data: { turbo: true },
+ class: "space-y-3" do |form| %>
+ <%= form.text_field :phone_number,
+ label: translation("phone_number_label"),
+ placeholder: translation("phone_number_placeholder_existing"),
+ type: :tel,
+ value: nil %>
+
+ <%= form.text_field :pin,
+ label: translation("pin_label"),
+ placeholder: translation("pin_placeholder_existing"),
+ type: :password,
+ value: nil %>
+
+ <div class="flex flex-wrap justify-end gap-2">
+ <%= form.submit(item.session_configured? ? translation("update_configuration") : translation("save_configuration")) %>
+ </div>
+ <% end %>
+ <% end %>
+
+ <div class="flex items-center gap-2">
+ <% if item.pending_login_state.present? %>
+ <% if login_stage == "expired" %>
+ <div class="w-2 h-2 bg-destructive rounded-full"></div>
+ <p class="text-sm text-secondary"><%= translation("login_expired") %></p>
+ <%= render DS::Button.new(
+ text: translation("restart_login"),
+ variant: :outline,
+ size: :sm,
+ icon: "rotate-cw",
+ href: helpers.initiate_login_trade_republic_item_path(item),
+ method: :post,
+ form: { class: "ml-auto" }
+ ) %>
+ <% else %>
+ <div class="w-2 h-2 bg-warning rounded-full"></div>
+ <p class="text-sm text-secondary">
+ <%= login_stage == "authenticator_code" ? translation("awaiting_authenticator_code") : translation("awaiting_confirmation") %>
+ </p>
+ <% end %>
+ <% elsif item.status == "good" && item.session_configured? %>
+ <div class="w-2 h-2 bg-success rounded-full"></div>
+ <p class="text-sm text-secondary">
+ <% if item.unlinked_accounts_count.positive? %>
+ <%= translation("accounts_discovered", count: item.unlinked_accounts_count) %>
+ <%= render DS::Link.new(
+ text: translation("setup_accounts"),
+ icon: "plus",
+ variant: "primary",
+ href: helpers.setup_accounts_trade_republic_item_path(item),
+ frame: :modal
+ ) %>
+ <% else %>
+ <%= translation("status_configured_prefix", summary: item.sync_status_summary) %>
+ <%= helpers.link_to translation("accounts_tab"), helpers.accounts_path, class: "link" %>
+ <%= translation("status_configured_suffix") %>
+ <% end %>
+ </p>
+ <% elsif item.status == "requires_update" %>
+ <div class="w-2 h-2 bg-warning rounded-full"></div>
+ <p class="text-sm text-secondary"><%= translation("requires_update") %></p>
+ <% else %>
+ <div class="w-2 h-2 bg-surface-inset rounded-full"></div>
+ <p class="text-sm text-secondary"><%= translation("not_configured") %></p>
+ <% end %>
+ </div>
+ </div>
+ <% end %>
+</div>
diff --git a/app/components/trade_republic/connection_card_component.rb b/app/components/trade_republic/connection_card_component.rb
new file mode 100644
index 0000000000..f5d9f96392
--- /dev/null
+++ b/app/components/trade_republic/connection_card_component.rb
@@ -0,0 +1,62 @@
+class TradeRepublic::ConnectionCardComponent < ApplicationComponent
+ include TradeRepublic::PanelTranslatable
+
+ def self.dom_id_for(item)
+ ActionView::RecordIdentifier.dom_id(item, :trade_republic_card)
+ end
+
+ def initialize(item:, open: true, qr_active: false, qr_code_svg: nil)
+ @item = item
+ @open = open
+ @qr_active = qr_active
+ @qr_code_svg = qr_code_svg
+ end
+
+ attr_reader :item, :open, :qr_active, :qr_code_svg
+
+ def dom_id
+ self.class.dom_id_for(item)
+ end
+
+ # Every connection defaults to the same name, and QR logins have no phone
+ # number, so the last 4 characters of whichever identifier is available
+ # help tell cards apart when disconnecting one of several.
+ def identifier_last4
+ identifier&.last
+ end
+
+ def identifier_label
+ translation("identifier_#{identifier.first}") if identifier
+ end
+
+ # TradeRepublicItem#login_stage decodes the pending login payload on every
+ # call, and the template checks the stage several times per card, so cache
+ # it for the duration of the render.
+ def login_stage
+ return @login_stage if defined?(@login_stage)
+
+ @login_stage = item.login_stage
+ end
+
+ private
+
+ def identifier
+ return @identifier if defined?(@identifier)
+
+ @identifier =
+ if (digits = last4(item.phone_number))
+ [ :phone, digits ]
+ elsif (digits = last4(item.brokerage_account_id.presence || portfolio_account_id))
+ [ :account, digits ]
+ end
+ end
+
+ def portfolio_account_id
+ item.trade_republic_accounts.detect { |account| account.kind == "portfolio" }&.trade_republic_account_id
+ end
+
+ def last4(value)
+ cleaned = value.to_s.delete(" ")
+ cleaned.last(4) if cleaned.size >= 4
+ end
+end
diff --git a/app/components/trade_republic/panel_translatable.rb b/app/components/trade_republic/panel_translatable.rb
new file mode 100644
index 0000000000..468dcfce29
--- /dev/null
+++ b/app/components/trade_republic/panel_translatable.rb
@@ -0,0 +1,7 @@
+# Shared i18n scope for the Trade Republic settings panel components so the
+# prefix can't drift between the editor and the per-connection cards.
+module TradeRepublic::PanelTranslatable
+ def translation(key, **options)
+ helpers.t("settings.providers.trade_republic_panel.#{key}", **options)
+ end
+end
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index 27ae95912e..a0d1fbb48e 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -287,7 +287,7 @@ class Settings::ProvidersController < ApplicationController
when "trading212"
@trading212_items = Current.family.trading212_items.ordered
when "trade_republic"
- @trade_republic_items = Current.family.trade_republic_items.ordered
+ @trade_republic_items = Current.family.trade_republic_items.active.ordered.includes(:trade_republic_accounts)
when "indexa_capital"
@indexa_capital_items = Current.family.indexa_capital_items.ordered
when "sophtron"
@@ -323,7 +323,7 @@ class Settings::ProvidersController < ApplicationController
@snaptrade_items = Current.family.snaptrade_items.ordered
@ibkr_items = Current.family.ibkr_items.ordered.select(:id)
@trading212_items = Current.family.trading212_items.ordered
- @trade_republic_items = Current.family.trade_republic_items.ordered.select(:id)
+ @trade_republic_items = Current.family.trade_republic_items.active.ordered.includes(:trade_republic_accounts)
@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
diff --git a/app/controllers/trade_republic_items_controller.rb b/app/controllers/trade_republic_items_controller.rb
index 114d9418bd..3ca574399f 100644
--- a/app/controllers/trade_republic_items_controller.rb
+++ b/app/controllers/trade_republic_items_controller.rb
@@ -37,9 +37,8 @@ class TradeRepublicItemsController < ApplicationController
"trade-republic-providers-panel",
partial: "settings/providers/trade_republic_panel",
locals: {
- trade_republic_item: @trade_republic_item,
qr_code_svg: @qr_code_svg,
- qr_login_auto_poll: qr_login_requested && @error_message.blank?
+ qr_login_auto_poll_item: (@trade_republic_item if qr_login_requested && @error_message.blank?)
}
),
*flash_notification_stream_items
@@ -113,13 +112,31 @@ class TradeRepublicItemsController < ApplicationController
else
redirect_to settings_providers_path(anchor: "trade-republic"), notice: t(".approval_pending")
end
+ elsif duplicate_connection?(result)
+ discard_duplicate_connection!
+ if turbo_panel_request?
+ render_login_panel(alert: t("trade_republic_items.duplicate_connection"), whole_panel: true)
+ else
+ redirect_to settings_providers_path(anchor: "trade-republic"), alert: t("trade_republic_items.duplicate_connection"), status: :see_other
+ end
else
- ActiveRecord::Base.transaction do
- @trade_republic_item.update!(
- session_blob: result.data.fetch("session_txt"),
- pending_login_state: nil,
- status: :good
- )
+ begin
+ ActiveRecord::Base.transaction do
+ @trade_republic_item.update!(
+ session_blob: result.data.fetch("session_txt"),
+ pending_login_state: nil,
+ status: :good,
+ brokerage_account_id: account_id_from(result)
+ )
+ end
+ rescue ActiveRecord::RecordNotUnique
+ discard_duplicate_connection!
+ if turbo_panel_request?
+ render_login_panel(alert: t("trade_republic_items.duplicate_connection"), whole_panel: true)
+ else
+ redirect_to settings_providers_path(anchor: "trade-republic"), alert: t("trade_republic_items.duplicate_connection"), status: :see_other
+ end
+ return
end
@trade_republic_item.sync_later unless @trade_republic_item.syncing?
if turbo_panel_request?
@@ -149,8 +166,16 @@ class TradeRepublicItemsController < ApplicationController
if result.data["status"] == "pending"
@trade_republic_item.update!(pending_login_state: result.data.fetch("pending_login_b64")) if result.data["pending_login_b64"].present?
render_login_panel
+ elsif duplicate_connection?(result)
+ discard_duplicate_connection!
+ render_login_panel(alert: t("trade_republic_items.duplicate_connection"), whole_panel: true)
else
- @trade_republic_item.update!(session_blob: result.data.fetch("session_txt"), pending_login_state: nil, status: :good)
+ begin
+ @trade_republic_item.update!(session_blob: result.data.fetch("session_txt"), pending_login_state: nil, status: :good, brokerage_account_id: account_id_from(result))
+ rescue ActiveRecord::RecordNotUnique
+ discard_duplicate_connection!
+ return render_login_panel(alert: t("trade_republic_items.duplicate_connection"), whole_panel: true)
+ end
@trade_republic_item.sync_later unless @trade_republic_item.syncing?
render_login_panel(success: true)
end
@@ -189,9 +214,23 @@ class TradeRepublicItemsController < ApplicationController
response_data = result.data.except("pending_login_b64")
response_data["qr_code_svg"] = view_context.generate_mfa_qr_code(result.data["qr_code_payload"]) if result.data["qr_code_payload"].present?
render json: response_data
+ elsif duplicate_connection?(result)
+ return render_superseded_qr_login unless update_if_pending_login_current!(pending, pending_login_state: nil, status: :requires_update)
+
+ discard_duplicate_connection!
+ # The QR controller reloads the providers page for any non-pending
+ # status, where this alert is shown.
+ flash[:alert] = t("trade_republic_items.duplicate_connection")
+ render json: { status: "duplicate_connection" }
else
- unless update_if_pending_login_current!(pending, session_blob: result.data.fetch("session_txt"), pending_login_state: nil, status: :good)
- return render_superseded_qr_login
+ begin
+ unless update_if_pending_login_current!(pending, session_blob: result.data.fetch("session_txt"), pending_login_state: nil, status: :good, brokerage_account_id: account_id_from(result))
+ return render_superseded_qr_login
+ end
+ rescue ActiveRecord::RecordNotUnique
+ discard_duplicate_connection!
+ flash[:alert] = t("trade_republic_items.duplicate_connection")
+ return render json: { status: "duplicate_connection" }
end
@trade_republic_item.sync_later unless @trade_republic_item.syncing?
@@ -214,13 +253,7 @@ class TradeRepublicItemsController < ApplicationController
def cancel_qr_login
@trade_republic_item.update!(pending_login_state: nil, status: :requires_update)
respond_to do |format|
- format.turbo_stream do
- render turbo_stream: turbo_stream.replace(
- "trade-republic-providers-panel",
- partial: "settings/providers/trade_republic_panel",
- locals: { trade_republic_item: @trade_republic_item }
- )
- end
+ format.turbo_stream { render turbo_stream: replace_card_stream }
format.json { render json: { status: "cancelled" } }
end
end
@@ -245,11 +278,7 @@ class TradeRepublicItemsController < ApplicationController
flash.now[:notice] = t(".success")
end
render turbo_stream: [
- turbo_stream.replace(
- "trade-republic-providers-panel",
- partial: "settings/providers/trade_republic_panel",
- locals: { trade_republic_item: @trade_republic_item }
- ),
+ replace_card_stream,
*flash_notification_stream_items
]
elsif @error_message.present?
@@ -524,7 +553,7 @@ class TradeRepublicItemsController < ApplicationController
params.fetch(:trade_republic_login, {}).permit(:code)
end
- def render_login_panel(alert: nil, notice: nil, success: false)
+ def render_login_panel(alert: nil, notice: nil, success: false, whole_panel: false)
if success
return render turbo_stream: [
turbo_stream.replace("drawer", view_context.turbo_frame_tag("drawer")),
@@ -538,15 +567,61 @@ class TradeRepublicItemsController < ApplicationController
flash.now[:alert] = alert if alert
flash.now[:notice] = notice if notice
render turbo_stream: [
- turbo_stream.replace(
- "trade-republic-providers-panel",
- partial: "settings/providers/trade_republic_panel",
- locals: { trade_republic_item: @trade_republic_item }
- ),
+ whole_panel ? replace_panel_stream : replace_card_stream,
*flash_notification_stream_items
]
end
+ # Push-login polling re-renders about once per second; replacing only this
+ # item's card keeps other cards (open state, typed credentials, running QR
+ # logins) intact.
+ def replace_card_stream(item = @trade_republic_item)
+ turbo_stream.replace(
+ TradeRepublic::ConnectionCardComponent.dom_id_for(item),
+ TradeRepublic::ConnectionCardComponent.new(item: item, qr_active: item.login_stage == "qr_pending")
+ )
+ end
+
+ def replace_panel_stream
+ turbo_stream.replace("trade-republic-providers-panel", partial: "settings/providers/trade_republic_panel")
+ end
+
+ # Connecting the same Trade Republic account through a second item would
+ # import its accounts twice.
+ def account_id_from(result)
+ result.data.dig("account", "brokerage_account_id").presence
+ end
+
+ def other_active_trade_republic_items
+ Current.family.trade_republic_items.active.where.not(id: @trade_republic_item.id)
+ end
+
+ # trade_republic_accounts rows only exist once the importer's first sync
+ # runs, so checking only those would let a second item finish login for
+ # the same account in the gap before that job runs (or truly
+ # concurrently). brokerage_account_id is written on the item itself the
+ # moment login succeeds and is backed by a unique index, so this is an
+ # early, user-facing check; the index (see discard_duplicate_connection!
+ # callers) is what actually closes the race.
+ def duplicate_connection?(result)
+ account_id = account_id_from(result)
+ return false if account_id.blank?
+
+ other_active_trade_republic_items.exists?(brokerage_account_id: account_id) ||
+ other_active_trade_republic_items
+ .joins(:trade_republic_accounts)
+ .where(trade_republic_accounts: { trade_republic_account_id: [ account_id, "cash:#{account_id}" ] })
+ .exists?
+ end
+
+ def discard_duplicate_connection!
+ # A failed unique-index write from the losing update! left brokerage_account_id
+ # dirty on the in-memory record with the other item's value; clear it
+ # explicitly or this update! would collide with the same index again.
+ @trade_republic_item.update!(session_blob: nil, pending_login_state: nil, status: :requires_update, brokerage_account_id: nil)
+ @trade_republic_item.destroy_later if @trade_republic_item.trade_republic_accounts.none?
+ end
+
def turbo_panel_request?
turbo_frame_request? || request.format.turbo_stream?
end
@@ -558,7 +633,13 @@ class TradeRepublicItemsController < ApplicationController
render turbo_stream: turbo_stream.replace(
"trade-republic-providers-panel",
partial: "settings/providers/trade_republic_panel",
- locals: { error_message: @error_message, trade_republic_item: @trade_republic_item }
+ locals: {
+ error_message: @error_message,
+ # Only the add-connection form's own unsaved item should replace
+ # its blank default; an existing item failing update/login keeps
+ # the add form blank.
+ new_item: (@trade_republic_item if @trade_republic_item&.new_record?)
+ }
), status: :unprocessable_entity
else
redirect_to settings_providers_path(anchor: "trade-republic"), alert: @error_message, status: :see_other
diff --git a/app/views/settings/providers/_trade_republic_panel.html.erb b/app/views/settings/providers/_trade_republic_panel.html.erb
index 480f161566..407ab67001 100644
--- a/app/views/settings/providers/_trade_republic_panel.html.erb
+++ b/app/views/settings/providers/_trade_republic_panel.html.erb
@@ -1,16 +1,4 @@
-<%
- trade_republic_item = local_assigns.fetch(:trade_republic_item) { Current.family.trade_republic_items.first_or_initialize }
- is_new_record = trade_republic_item.new_record?
- session_configured = trade_republic_item.persisted? && trade_republic_item.session_configured?
- qr_login_pending = trade_republic_item.persisted? && trade_republic_item.login_stage == "qr_pending"
- qr_login_active = local_assigns[:qr_login_auto_poll] || qr_login_pending
-%>
-
-<div id="trade-republic-providers-panel" class="space-y-4"
- <% if trade_republic_item.persisted? && trade_republic_item.login_stage == "waiting_for_approval" %>
- data-controller="trade-republic-login"
- data-trade-republic-login-url-value="<%= poll_login_trade_republic_item_path(trade_republic_item) %>"
- <% end %>>
+<div id="trade-republic-providers-panel" class="space-y-4">
<% unless TradeRepublicItem.encryption_ready? %>
<div class="p-3 rounded-md bg-warning/10 text-warning text-sm">
<div class="flex items-start gap-2">
@@ -34,190 +22,11 @@
t(".steps.step_3")
] %>
- <% if trade_republic_item.persisted? %>
- <% if trade_republic_item.pending_login_state.blank? %>
- <% if session_configured %>
- <div class="flex flex-wrap justify-end gap-2">
- <%= render DS::Button.new(
- text: t(".connect"),
- variant: :outline,
- size: :sm,
- icon: "log-in",
- href: initiate_login_trade_republic_item_path(trade_republic_item),
- method: :post
- ) %>
-
- <%= render DS::Button.new(
- text: t(".sync"),
- variant: :outline,
- size: :sm,
- icon: "refresh-cw",
- href: sync_trade_republic_item_path(trade_republic_item),
- method: :post,
- disabled: trade_republic_item.syncing?
- ) %>
-
- <%= render DS::Button.new(
- variant: :outline_destructive,
- size: :sm,
- icon: "trash-2",
- aria_label: t(".disconnect"),
- title: t(".disconnect"),
- href: trade_republic_item_path(trade_republic_item),
- method: :delete,
- confirm: t(".disconnect_confirm")
- ) %>
- </div>
- <% end %>
-
- <% end %>
-
- <% if trade_republic_item.pending_login_state.blank? || qr_login_pending %>
- <div class="space-y-3" data-controller="trade-republic-qr"
- data-trade-republic-qr-auto-poll-value="<%= qr_login_active %>"
- data-trade-republic-qr-initiate-url-value="<%= initiate_qr_login_trade_republic_item_path(trade_republic_item) %>"
- data-trade-republic-qr-poll-url-value="<%= poll_qr_login_trade_republic_item_path(trade_republic_item) %>"
- data-trade-republic-qr-cancel-url-value="<%= cancel_qr_login_trade_republic_item_path(trade_republic_item) %>"
- data-trade-republic-qr-return-url-value="<%= settings_providers_path(anchor: "trade-republic") %>"
- data-trade-republic-qr-loading-text-value="<%= t(".qr_loading") %>"
- data-trade-republic-qr-instruction-text-value="<%= t(".qr_instruction") %>"
- data-trade-republic-qr-success-text-value="<%= t(".qr_success") %>"
- data-trade-republic-qr-error-text-value="<%= t(".qr_error") %>"
- data-trade-republic-qr-login-text-value="<%= t(".qr_login") %>"
- data-trade-republic-qr-cancel-text-value="<%= t(".qr_cancel") %>">
- <%= render DS::Button.new(
- text: qr_login_active ? t(".qr_cancel") : t(".qr_login"),
- variant: :outline,
- size: :sm,
- icon: "qr-code",
- type: "button",
- data: {
- action: "trade-republic-qr#toggle",
- trade_republic_qr_target: "button"
- }
- ) %>
-
- <div data-trade-republic-qr-target="panel" <%= "hidden" unless qr_login_active %> class="rounded-lg border border-secondary bg-container-inset p-4 space-y-3">
- <p data-trade-republic-qr-target="status" class="text-sm text-secondary"></p>
- <div data-trade-republic-qr-target="code" class="qrcode flex justify-center min-h-48"><%= local_assigns[:qr_code_svg] %></div>
- </div>
- </div>
- <% end %>
-
- <% if trade_republic_item.login_stage == "authenticator_code" %>
- <%= render DS::Alert.new(
- message: t(".authenticator_code_notice"),
- variant: :info
- ) %>
-
- <%= styled_form_with url: complete_login_trade_republic_item_path(trade_republic_item),
- method: :post,
- scope: :trade_republic_login,
- class: "space-y-3" do |form| %>
- <%= form.text_field :code,
- label: t(".authenticator_code_label"),
- placeholder: t(".authenticator_code_placeholder"),
- value: nil,
- required: true %>
- <div class="flex flex-wrap justify-end gap-2">
- <%= form.submit(t(".complete_login")) %>
- </div>
- <% end %>
- <% elsif trade_republic_item.login_stage == "waiting_for_approval" %>
- <%= render DS::Alert.new(message: t(".push_login_notice"), variant: :info) %>
- <div class="flex flex-wrap justify-end gap-2">
- <%= render DS::Button.new(
- text: t(".check_login_status"),
- variant: :outline,
- size: :sm,
- icon: "refresh-cw",
- href: poll_login_trade_republic_item_path(trade_republic_item),
- method: :post
- ) %>
- </div>
- <% end %>
- <% end %>
-
- <% if trade_republic_item.new_record? || trade_republic_item.pending_login_state.blank? %>
- <%= styled_form_with model: trade_republic_item,
- url: is_new_record ? trade_republic_items_path : trade_republic_item_path(trade_republic_item),
- scope: :trade_republic_item,
- method: is_new_record ? :post : :patch,
- data: { turbo: true },
- class: "space-y-3" do |form| %>
- <%= form.text_field :phone_number,
- label: t(".phone_number_label"),
- placeholder: is_new_record ? t(".phone_number_placeholder_new") : t(".phone_number_placeholder_existing"),
- type: :tel,
- value: nil %>
-
- <%= form.text_field :pin,
- label: t(".pin_label"),
- placeholder: is_new_record ? t(".pin_placeholder_new") : t(".pin_placeholder_existing"),
- type: :password,
- value: nil %>
-
- <div class="flex flex-wrap justify-end gap-2">
- <%= form.submit(trade_republic_item.session_configured? ? t(".update_configuration") : t(".save_configuration")) %>
- <% if is_new_record %>
- <%= render DS::Button.new(
- text: t(".qr_login"),
- variant: :outline,
- size: :sm,
- icon: "qr-code",
- type: "submit",
- name: "login_method",
- value: "qr"
- ) %>
- <% end %>
- </div>
- <% end %>
- <% end %>
-
- <div class="flex items-center gap-2">
- <% if trade_republic_item.persisted? && trade_republic_item.pending_login_state.present? %>
- <% if trade_republic_item.login_stage == "expired" %>
- <div class="w-2 h-2 bg-destructive rounded-full"></div>
- <p class="text-sm text-secondary"><%= t(".login_expired") %></p>
- <%= render DS::Button.new(
- text: t(".restart_login"),
- variant: :outline,
- size: :sm,
- icon: "rotate-cw",
- href: initiate_login_trade_republic_item_path(trade_republic_item),
- method: :post,
- form: { class: "ml-auto" }
- ) %>
- <% else %>
- <div class="w-2 h-2 bg-warning rounded-full"></div>
- <p class="text-sm text-secondary">
- <%= trade_republic_item.login_stage == "authenticator_code" ? t(".awaiting_authenticator_code") : t(".awaiting_confirmation") %>
- </p>
- <% end %>
- <% elsif trade_republic_item.persisted? && trade_republic_item.status == "good" && trade_republic_item.session_configured? %>
- <div class="w-2 h-2 bg-success rounded-full"></div>
- <p class="text-sm text-secondary">
- <% if trade_republic_item.unlinked_accounts_count.positive? %>
- <%= t(".accounts_discovered", count: trade_republic_item.unlinked_accounts_count) %>
- <%= render DS::Link.new(
- text: t(".setup_accounts"),
- icon: "plus",
- variant: "primary",
- href: setup_accounts_trade_republic_item_path(trade_republic_item),
- frame: :modal
- ) %>
- <% else %>
- <%= t(".status_configured_prefix", summary: trade_republic_item.sync_status_summary) %>
- <%= link_to t(".accounts_tab"), accounts_path, class: "link" %>
- <%= t(".status_configured_suffix") %>
- <% end %>
- </p>
- <% elsif trade_republic_item.persisted? && trade_republic_item.status == "requires_update" %>
- <div class="w-2 h-2 bg-warning rounded-full"></div>
- <p class="text-sm text-secondary"><%= t(".requires_update") %></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>
+ <%= render TradeRepublic::AccountEditorComponent.new(
+ items: local_assigns[:trade_republic_items] || @trade_republic_items,
+ family: Current.family,
+ qr_code_svg: local_assigns[:qr_code_svg],
+ qr_login_auto_poll_item: local_assigns[:qr_login_auto_poll_item],
+ new_item: local_assigns[:new_item]
+ ) %>
</div>
diff --git a/config/locales/views/settings/ca.yml b/config/locales/views/settings/ca.yml
index 1cd44e59f0..fd32b24095 100644
--- a/config/locales/views/settings/ca.yml
+++ b/config/locales/views/settings/ca.yml
@@ -667,11 +667,16 @@ ca:
qr_instruction: Escaneja el codi QR amb l'aplicació de Trade Republic i aprova l'inici de sessió.
qr_success: Inici de sessió aprovat. Sure està actualitzant la pàgina del proveïdor.
qr_error: No s'ha pogut iniciar la sessió amb QR. Torna-ho a provar.
+ add_account: "Afegeix una altra connexió"
save_configuration: Desa i inicia sessió
update_configuration: Actualitza la configuració
sync: Sincronitza
+ syncing: "Sincronitzant..."
disconnect: Desconnecta Trade Republic
disconnect_confirm: Vols desconnectar Trade Republic? Els comptes sincronitzats passaran a ser comptes manuals.
+ disconnect_confirm_with_identifier: "Vols desconnectar la connexió de Trade Republic acabada en %{last4}? Els comptes sincronitzats passaran a ser comptes manuals."
+ identifier_phone: Telèfon
+ identifier_account: Compte
status_configured_prefix: Connectat. Ves a la pestanya
accounts_tab: Comptes
setup_accounts: Configura els comptes
diff --git a/config/locales/views/settings/de.yml b/config/locales/views/settings/de.yml
index 13380deaca..879adabf2d 100644
--- a/config/locales/views/settings/de.yml
+++ b/config/locales/views/settings/de.yml
@@ -548,11 +548,16 @@ de:
qr_instruction: Scanne den QR-Code mit deiner Trade-Republic-App und bestätige die Anmeldung.
qr_success: Anmeldung bestätigt. Sure lädt die Provider-Übersicht neu.
qr_error: Der QR-Login konnte nicht gestartet werden. Bitte versuche es erneut.
+ add_account: Weitere Verbindung hinzufügen
save_configuration: Speichern und Login starten
update_configuration: Konfiguration aktualisieren
sync: Sync
+ syncing: Wird synchronisiert...
disconnect: Trade Republic trennen
disconnect_confirm: Trade Republic trennen? Deine synchronisierten Konten werden zu manuellen Konten.
+ disconnect_confirm_with_identifier: "Die Trade-Republic-Verbindung mit den Endziffern %{last4} trennen? Deine synchronisierten Konten werden zu manuellen Konten."
+ identifier_phone: Telefon
+ identifier_account: Konto
status_configured_prefix: "Verbunden. Im Reiter"
accounts_tab: Konten
setup_accounts: Konten einrichten
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 431a06a638..785e7b38be 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -753,11 +753,16 @@ en:
qr_instruction: Scan the QR code with your Trade Republic app and approve the login.
qr_success: Login approved. Sure is refreshing the provider page.
qr_error: QR login could not be started. Please try again.
+ add_account: Add another connection
save_configuration: Save & Start Login
update_configuration: Update Configuration
sync: Sync
+ syncing: Syncing...
disconnect: Disconnect Trade Republic
disconnect_confirm: Disconnect Trade Republic? Your synced accounts will become manual accounts.
+ disconnect_confirm_with_identifier: "Disconnect the Trade Republic connection ending in %{last4}? Your synced accounts will become manual accounts."
+ identifier_phone: Phone
+ identifier_account: Account
status_configured_prefix: "Connected. Visit the"
accounts_tab: Accounts
setup_accounts: Set up accounts
diff --git a/config/locales/views/settings/fr.yml b/config/locales/views/settings/fr.yml
index ecdb6a4ea1..233865f38f 100644
--- a/config/locales/views/settings/fr.yml
+++ b/config/locales/views/settings/fr.yml
@@ -583,6 +583,9 @@ fr:
currency_label: Devise du compte
disconnect: Déconnecter Trade Republic
disconnect_confirm: Déconnecter Trade Republic ? Vos comptes synchronisés deviendront des comptes manuels.
+ disconnect_confirm_with_identifier: "Déconnecter la connexion Trade Republic se terminant par %{last4} ? Vos comptes synchronisés deviendront des comptes manuels."
+ identifier_phone: Téléphone
+ identifier_account: Compte
encryption_warning:
message: Les identifiants et les données de session Trade Republic ne peuvent pas être stockés de façon sécurisée tant que le chiffrement Active Record n'est pas configuré.
title: Le chiffrement n'est pas configuré
@@ -603,6 +606,7 @@ fr:
qr_login: Se connecter avec un QR code
qr_success: Connexion approuvée. Sure actualise la page du fournisseur.
restart_login: Relancer la connexion
+ add_account: "Ajouter une autre connexion"
save_configuration: Enregistrer et lancer la connexion
setup_accounts: Configurer les comptes
status_configured_prefix: Connecté. Ouvrez l'onglet
@@ -612,6 +616,7 @@ fr:
step_2: Saisissez le code de votre application d'authentification lorsqu'il vous est demandé.
step_3: Approuvez la connexion dans votre application Trade Republic lorsque vous y êtes invité.
sync: Synchroniser
+ syncing: "Synchronisation..."
update_configuration: Mettre à jour la configuration
trading212_panel:
accounts_tab: Comptes
diff --git a/config/locales/views/settings/pl.yml b/config/locales/views/settings/pl.yml
index 803064f8ba..0df8b1ddee 100644
--- a/config/locales/views/settings/pl.yml
+++ b/config/locales/views/settings/pl.yml
@@ -734,6 +734,9 @@ pl:
disconnect: Odłącz Trade Republic
disconnect_confirm: Odłączyć Trade Republic? Twoje zsynchronizowane konta
staną się kontami ręcznymi.
+ disconnect_confirm_with_identifier: "Odłączyć połączenie Trade Republic kończące się na %{last4}? Twoje zsynchronizowane konta staną się kontami ręcznymi."
+ identifier_phone: Telefon
+ identifier_account: Konto
encryption_warning:
message: Danych logowania i sesji Trade Republic nie można bezpiecznie przechowywać,
dopóki nie skonfigurowano Active Record Encryption.
@@ -757,6 +760,7 @@ pl:
qr_login: Zaloguj się kodem QR
qr_success: Logowanie zatwierdzone. Sure odświeża stronę dostawcy.
restart_login: Rozpocznij logowanie ponownie
+ add_account: "Dodaj kolejne połączenie"
save_configuration: Zapisz i rozpocznij logowanie
setup_accounts: Skonfiguruj konta
status_configured_prefix: Połączono. Przejdź do zakładki
@@ -768,6 +772,7 @@ pl:
step_3: Gdy zostaniesz o to poproszony, zatwierdź logowanie w aplikacji
Trade Republic.
sync: Synchronizuj
+ syncing: "Synchronizowanie..."
update_configuration: Zaktualizuj konfigurację
trading212_panel:
accounts_tab: Konta
diff --git a/config/locales/views/settings/ru.yml b/config/locales/views/settings/ru.yml
index c66b3b52cc..933c544361 100644
--- a/config/locales/views/settings/ru.yml
+++ b/config/locales/views/settings/ru.yml
@@ -701,11 +701,16 @@ ru:
qr_instruction: Отсканируйте QR-код в приложении Trade Republic и подтвердите вход.
qr_success: Вход подтверждён. Sure обновляет страницу провайдера.
qr_error: Не удалось начать вход по QR-коду. Пожалуйста, попробуйте снова.
+ add_account: "Добавить ещё одно подключение"
save_configuration: Сохранить и войти
update_configuration: Обновить конфигурацию
sync: Синхронизировать
+ syncing: "Синхронизация..."
disconnect: Отключить Trade Republic
disconnect_confirm: Отключить Trade Republic? Ваши синхронизированные счета станут ручными.
+ disconnect_confirm_with_identifier: "Отключить подключение Trade Republic, оканчивающееся на %{last4}? Ваши синхронизированные счета станут ручными."
+ identifier_phone: Телефон
+ identifier_account: Счёт
status_configured_prefix: Подключено. Перейдите на
accounts_tab: Счета
setup_accounts: Настроить счета
diff --git a/config/locales/views/settings/tr.yml b/config/locales/views/settings/tr.yml
index 0bc069548c..457faca270 100644
--- a/config/locales/views/settings/tr.yml
+++ b/config/locales/views/settings/tr.yml
@@ -714,11 +714,16 @@ tr:
qr_instruction: QR kodu Trade Republic uygulamanızla tarayın ve girişi onaylayın.
qr_success: Giriş onaylandı. Sure sağlayıcı sayfasını yeniliyor.
qr_error: QR girişi başlatılamadı. Lütfen tekrar deneyin.
+ add_account: "Başka bir bağlantı ekle"
save_configuration: Kaydet ve Girişi Başlat
update_configuration: Yapılandırmayı Güncelle
sync: Senkronize et
+ syncing: "Senkronize ediliyor..."
disconnect: Trade Republic bağlantısını kes
disconnect_confirm: Trade Republic bağlantısı kesilsin mi? Senkronize hesaplarınız manuel hesaplara dönüşecektir.
+ disconnect_confirm_with_identifier: "%{last4} ile biten Trade Republic bağlantısı kesilsin mi? Senkronize hesaplarınız manuel hesaplara dönüşecektir."
+ identifier_phone: Telefon
+ identifier_account: Hesap
status_configured_prefix: Bağlandı. Keşfedilen hesapları yönetmek için
accounts_tab: Hesaplar
setup_accounts: Hesapları kur
diff --git a/config/locales/views/settings/uk.yml b/config/locales/views/settings/uk.yml
index ae8e3e692a..9f0d27578a 100644
--- a/config/locales/views/settings/uk.yml
+++ b/config/locales/views/settings/uk.yml
@@ -742,11 +742,16 @@ uk:
qr_instruction: Відскануйте QR-код у застосунку Trade Republic і підтвердьте вхід.
qr_success: Вхід підтверджено. Sure оновлює сторінку постачальника.
qr_error: Не вдалося розпочати вхід за QR-кодом. Спробуйте ще раз.
+ add_account: "Додати ще одне підключення"
save_configuration: Зберегти й увійти
update_configuration: Оновити конфігурацію
sync: Синхронізувати
+ syncing: "Синхронізація..."
disconnect: Відключити Trade Republic
disconnect_confirm: Відключити Trade Republic? Ваші синхронізовані рахунки стануть ручними.
+ disconnect_confirm_with_identifier: "Відключити підключення Trade Republic, що закінчується на %{last4}? Ваші синхронізовані рахунки стануть ручними."
+ identifier_phone: Телефон
+ identifier_account: Рахунок
status_configured_prefix: Підключено. Перейдіть на вкладку
accounts_tab: Рахунки
setup_accounts: Налаштувати рахунки
diff --git a/config/locales/views/trade_republic_items/ca.yml b/config/locales/views/trade_republic_items/ca.yml
index 33ae0df5f2..b7eb6d6fbb 100644
--- a/config/locales/views/trade_republic_items/ca.yml
+++ b/config/locales/views/trade_republic_items/ca.yml
@@ -6,6 +6,7 @@ ca:
connection_description: "Connecta un compte d'inversió de Trade Republic mitjançant un inici de sessió web segur"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Aquest compte de Trade Republic ja està connectat. S'ha eliminat la connexió nova."
portfolio_categories:
brokerage: "Compte de corretatge"
private_markets: "Mercats privats"
diff --git a/config/locales/views/trade_republic_items/de.yml b/config/locales/views/trade_republic_items/de.yml
index e996b28513..db993a9bf8 100644
--- a/config/locales/views/trade_republic_items/de.yml
+++ b/config/locales/views/trade_republic_items/de.yml
@@ -6,6 +6,7 @@ de:
connection_description: "Verbinde ein Trade-Republic-Investmentkonto über eine sichere Web-Anmeldung"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Dieses Trade-Republic-Konto ist bereits verbunden. Die neue Verbindung wurde entfernt."
defaults:
name: Trade Republic
portfolio_categories:
diff --git a/config/locales/views/trade_republic_items/en.yml b/config/locales/views/trade_republic_items/en.yml
index 943939f5ec..f7561a72d2 100644
--- a/config/locales/views/trade_republic_items/en.yml
+++ b/config/locales/views/trade_republic_items/en.yml
@@ -11,6 +11,7 @@ en:
private_markets: Private Markets
interest_products: Interest Products
crypto_wallet: Crypto Wallet
+ duplicate_connection: "This Trade Republic account is already connected. The new connection was removed."
defaults:
name: Trade Republic
trade_republic_item:
diff --git a/config/locales/views/trade_republic_items/es.yml b/config/locales/views/trade_republic_items/es.yml
index 9523cacfb0..01dab56c03 100644
--- a/config/locales/views/trade_republic_items/es.yml
+++ b/config/locales/views/trade_republic_items/es.yml
@@ -6,6 +6,7 @@ es:
connection_description: "Conecta una cuenta de inversión de Trade Republic mediante un inicio de sesión web seguro"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Esta cuenta de Trade Republic ya está conectada. Se ha eliminado la nueva conexión."
portfolio_categories:
brokerage: "Cuenta de corretaje"
private_markets: "Mercados privados"
diff --git a/config/locales/views/trade_republic_items/fr.yml b/config/locales/views/trade_republic_items/fr.yml
index 9c9626d20b..0a99bcae88 100644
--- a/config/locales/views/trade_republic_items/fr.yml
+++ b/config/locales/views/trade_republic_items/fr.yml
@@ -8,6 +8,7 @@ fr:
trade_republic_items:
create:
success: Trade Republic enregistré. Confirmez la connexion dans l'application Trade Republic pour la finaliser.
+ duplicate_connection: "Ce compte Trade Republic est déjà connecté. La nouvelle connexion a été supprimée."
defaults:
name: Trade Republic
destroy:
diff --git a/config/locales/views/trade_republic_items/hu.yml b/config/locales/views/trade_republic_items/hu.yml
index eb07779417..d52df263d9 100644
--- a/config/locales/views/trade_republic_items/hu.yml
+++ b/config/locales/views/trade_republic_items/hu.yml
@@ -6,6 +6,7 @@ hu:
connection_description: "Trade Republic befektetési számla összekapcsolása biztonságos webes bejelentkezéssel"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Ez a Trade Republic-fiók már csatlakoztatva van. Az új kapcsolat törölve lett."
portfolio_categories:
brokerage: "Brókerszámla"
private_markets: "Privát piacok"
diff --git a/config/locales/views/trade_republic_items/it.yml b/config/locales/views/trade_republic_items/it.yml
index c10375b92a..1c092ed8f4 100644
--- a/config/locales/views/trade_republic_items/it.yml
+++ b/config/locales/views/trade_republic_items/it.yml
@@ -6,6 +6,7 @@ it:
connection_description: "Collega un conto d’investimento Trade Republic tramite accesso web sicuro"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Questo conto Trade Republic è già collegato. La nuova connessione è stata rimossa."
portfolio_categories:
brokerage: "Conto di intermediazione"
private_markets: "Mercati privati"
diff --git a/config/locales/views/trade_republic_items/nb.yml b/config/locales/views/trade_republic_items/nb.yml
index e06e69ba9b..433cb80f0c 100644
--- a/config/locales/views/trade_republic_items/nb.yml
+++ b/config/locales/views/trade_republic_items/nb.yml
@@ -6,6 +6,7 @@ nb:
connection_description: "Koble til en Trade Republic-investeringskonto via sikker nettpålogging"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Denne Trade Republic-kontoen er allerede koblet til. Den nye tilkoblingen ble fjernet."
portfolio_categories:
brokerage: "Meglerkonto"
private_markets: "Private markeder"
diff --git a/config/locales/views/trade_republic_items/nl.yml b/config/locales/views/trade_republic_items/nl.yml
index 4090179de1..b3d8491326 100644
--- a/config/locales/views/trade_republic_items/nl.yml
+++ b/config/locales/views/trade_republic_items/nl.yml
@@ -6,6 +6,7 @@ nl:
connection_description: "Verbind een Trade Republic-beleggingsrekening via een veilige webaanmelding"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Deze Trade Republic-rekening is al gekoppeld. De nieuwe koppeling is verwijderd."
portfolio_categories:
brokerage: "Brokeragerekening"
private_markets: "Privémarkten"
diff --git a/config/locales/views/trade_republic_items/pl.yml b/config/locales/views/trade_republic_items/pl.yml
index 7cd95ded64..b54bcb3c15 100644
--- a/config/locales/views/trade_republic_items/pl.yml
+++ b/config/locales/views/trade_republic_items/pl.yml
@@ -48,6 +48,7 @@ pl:
create:
success: Trade Republic zapisano. Potwierdź logowanie w aplikacji Trade Republic,
aby zakończyć łączenie.
+ duplicate_connection: "To konto Trade Republic jest już połączone. Nowe połączenie zostało usunięte."
defaults:
name: Trade Republic
destroy:
diff --git a/config/locales/views/trade_republic_items/pt-BR.yml b/config/locales/views/trade_republic_items/pt-BR.yml
index dde32772b1..195eca70b1 100644
--- a/config/locales/views/trade_republic_items/pt-BR.yml
+++ b/config/locales/views/trade_republic_items/pt-BR.yml
@@ -6,6 +6,7 @@ pt-BR:
connection_description: "Conecte uma conta de investimentos da Trade Republic por meio de login web seguro"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Esta conta da Trade Republic já está conectada. A nova conexão foi removida."
portfolio_categories:
brokerage: "Conta de corretora"
private_markets: "Mercados privados"
diff --git a/config/locales/views/trade_republic_items/ro.yml b/config/locales/views/trade_republic_items/ro.yml
index efa9dd44af..a2c4e0ec5e 100644
--- a/config/locales/views/trade_republic_items/ro.yml
+++ b/config/locales/views/trade_republic_items/ro.yml
@@ -6,6 +6,7 @@ ro:
connection_description: "Conectează un cont de investiții Trade Republic prin autentificare web securizată"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Acest cont Trade Republic este deja conectat. Noua conexiune a fost eliminată."
portfolio_categories:
brokerage: "Cont de brokeraj"
private_markets: "Piețe private"
diff --git a/config/locales/views/trade_republic_items/ru.yml b/config/locales/views/trade_republic_items/ru.yml
index fa0661e932..8c50486cca 100644
--- a/config/locales/views/trade_republic_items/ru.yml
+++ b/config/locales/views/trade_republic_items/ru.yml
@@ -166,6 +166,7 @@ ru:
card_refund: Возврат на карту
tax_refund: Налоговый возврат
round_up: Round up
+ duplicate_connection: "Этот счёт Trade Republic уже подключён. Новое подключение удалено."
defaults:
name: Trade Republic
sync_status:
diff --git a/config/locales/views/trade_republic_items/tr.yml b/config/locales/views/trade_republic_items/tr.yml
index 6dcfb430af..2da28b148c 100644
--- a/config/locales/views/trade_republic_items/tr.yml
+++ b/config/locales/views/trade_republic_items/tr.yml
@@ -148,6 +148,7 @@ tr:
card_refund: Kart iadesi
tax_refund: Vergi iadesi
round_up: Round up
+ duplicate_connection: "Bu Trade Republic hesabı zaten bağlı. Yeni bağlantı kaldırıldı."
defaults:
name: Trade Republic
sync_status:
diff --git a/config/locales/views/trade_republic_items/uk.yml b/config/locales/views/trade_republic_items/uk.yml
index fc5ce3d0c6..f517ae7651 100644
--- a/config/locales/views/trade_republic_items/uk.yml
+++ b/config/locales/views/trade_republic_items/uk.yml
@@ -166,6 +166,7 @@ uk:
card_refund: Повернення на картку
tax_refund: Повернення податку
round_up: Round up
+ duplicate_connection: "Цей рахунок Trade Republic уже підключено. Нове підключення видалено."
defaults:
name: Trade Republic
sync_status:
diff --git a/config/locales/views/trade_republic_items/vi.yml b/config/locales/views/trade_republic_items/vi.yml
index 42ea9a73f3..fea32f34bb 100644
--- a/config/locales/views/trade_republic_items/vi.yml
+++ b/config/locales/views/trade_republic_items/vi.yml
@@ -6,6 +6,7 @@ vi:
connection_description: "Kết nối tài khoản đầu tư Trade Republic bằng đăng nhập web an toàn"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "Tài khoản Trade Republic này đã được kết nối. Kết nối mới đã bị xóa."
portfolio_categories:
brokerage: "Tài khoản môi giới"
private_markets: "Thị trường tư nhân"
diff --git a/config/locales/views/trade_republic_items/zh-CN.yml b/config/locales/views/trade_republic_items/zh-CN.yml
index 64b8ad8481..c38f1b0796 100644
--- a/config/locales/views/trade_republic_items/zh-CN.yml
+++ b/config/locales/views/trade_republic_items/zh-CN.yml
@@ -6,6 +6,7 @@ zh-CN:
connection_description: "通过安全的网页登录连接 Trade Republic 投资账户"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "此 Trade Republic 账户已连接。新的连接已被移除。"
portfolio_categories:
brokerage: "券商账户"
private_markets: "私募市场"
diff --git a/config/locales/views/trade_republic_items/zh-TW.yml b/config/locales/views/trade_republic_items/zh-TW.yml
index b8cd3d88c1..1cd10851cc 100644
--- a/config/locales/views/trade_republic_items/zh-TW.yml
+++ b/config/locales/views/trade_republic_items/zh-TW.yml
@@ -6,6 +6,7 @@ zh-TW:
connection_description: "透過安全的網頁登入連結 Trade Republic 投資帳戶"
institution_name: Trade Republic
trade_republic_items:
+ duplicate_connection: "此 Trade Republic 帳戶已連結。新的連結已被移除。"
portfolio_categories:
brokerage: "經紀帳戶"
private_markets: "私人市場"
diff --git a/db/migrate/20260927160000_add_brokerage_account_id_to_trade_republic_items.rb b/db/migrate/20260927160000_add_brokerage_account_id_to_trade_republic_items.rb
new file mode 100644
index 0000000000..10bc6b78ce
--- /dev/null
+++ b/db/migrate/20260927160000_add_brokerage_account_id_to_trade_republic_items.rb
@@ -0,0 +1,12 @@
+# trade_republic_accounts only exist after the first sync, so the account id is
+# stored on the item at login; this index makes a second active login for the
+# same account raise RecordNotUnique.
+class AddBrokerageAccountIdToTradeRepublicItems < ActiveRecord::Migration[8.1]
+ def change
+ add_column :trade_republic_items, :brokerage_account_id, :string
+ add_index :trade_republic_items, [ :family_id, :brokerage_account_id ],
+ unique: true,
+ where: "(brokerage_account_id IS NOT NULL) AND (scheduled_for_deletion = false)",
+ name: "index_trade_republic_items_on_family_id_and_brokerage_account"
+ end
+end
diff --git a/db/migrate/20260927161700_backfill_brokerage_account_id_on_trade_republic_items.rb b/db/migrate/20260927161700_backfill_brokerage_account_id_on_trade_republic_items.rb
new file mode 100644
index 0000000000..c21953e9ee
--- /dev/null
+++ b/db/migrate/20260927161700_backfill_brokerage_account_id_on_trade_republic_items.rb
@@ -0,0 +1,37 @@
+# Items connected before brokerage_account_id existed claim it from their
+# synced portfolio account; items that never synced are covered by their next
+# sync instead. Families can already hold several active items for the same
+# account, and the unique index allows only one claim per account, so the
+# oldest item wins and ids another active item already holds are skipped.
+class BackfillBrokerageAccountIdOnTradeRepublicItems < ActiveRecord::Migration[8.1]
+ def up
+ execute <<~SQL.squish
+ UPDATE trade_republic_items
+ SET brokerage_account_id = claims.account_id
+ FROM (
+ SELECT DISTINCT ON (items.family_id, portfolio.trade_republic_account_id)
+ items.id AS item_id,
+ portfolio.trade_republic_account_id AS account_id
+ FROM trade_republic_items AS items
+ JOIN trade_republic_accounts AS portfolio
+ ON portfolio.trade_republic_item_id = items.id
+ AND portfolio.kind = 'portfolio'
+ AND portfolio.trade_republic_account_id IS NOT NULL
+ WHERE items.brokerage_account_id IS NULL
+ AND items.scheduled_for_deletion = false
+ ORDER BY items.family_id, portfolio.trade_republic_account_id, items.created_at, items.id
+ ) AS claims
+ WHERE trade_republic_items.id = claims.item_id
+ AND NOT EXISTS (
+ SELECT 1
+ FROM trade_republic_items AS claimed
+ WHERE claimed.family_id = trade_republic_items.family_id
+ AND claimed.brokerage_account_id = claims.account_id
+ AND claimed.scheduled_for_deletion = false
+ )
+ SQL
+ end
+
+ def down
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 47eb7613d4..7f96682ac5 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_09_25_220151) do
+ActiveRecord::Schema[8.1].define(version: 2026_09_27_161700) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -2655,6 +2655,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_25_220151) do
end
create_table "trade_republic_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.string "brokerage_account_id"
t.datetime "created_at", null: false
t.string "currency"
t.uuid "family_id", null: false
@@ -2667,6 +2668,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_25_220151) do
t.text "session_blob"
t.string "status", default: "good", null: false
t.datetime "updated_at", null: false
+ t.index ["family_id", "brokerage_account_id"], name: "index_trade_republic_items_on_family_id_and_brokerage_account", unique: true, where: "((brokerage_account_id IS NOT NULL) AND (scheduled_for_deletion = false))"
t.index ["family_id"], name: "index_trade_republic_items_on_family_id"
t.index ["status"], name: "index_trade_republic_items_on_status"
end
diff --git a/test/components/trade_republic/account_editor_component_test.rb b/test/components/trade_republic/account_editor_component_test.rb
new file mode 100644
index 0000000000..2a0c51bc0e
--- /dev/null
+++ b/test/components/trade_republic/account_editor_component_test.rb
@@ -0,0 +1,174 @@
+require "test_helper"
+
+class TradeRepublic::AccountEditorComponentTest < ViewComponent::TestCase
+ # The account fixtures ship unlinked (no account_providers rows); pairing
+ # each with a Sure account puts an item into the fully set up state.
+ def link_all_accounts(item)
+ sure_accounts = accounts(:investment, :depository, :credit_card)
+ item.trade_republic_accounts.each_with_index do |provider_account, index|
+ AccountProvider.create!(account: sure_accounts.fetch(index), provider: provider_account)
+ end
+ end
+
+ test "renders a card per item and an add-connection form" do
+ family = families(:dylan_family)
+ items = [ trade_republic_items(:configured_item), trade_republic_items(:requires_update_item) ]
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: items, family: family))
+
+ items.each do |item|
+ assert_text item.name
+ end
+ assert_selector "form[action='#{Rails.application.routes.url_helpers.trade_republic_items_path}']"
+ end
+
+ test "wraps each card in its own target for per-connection turbo streams" do
+ item = trade_republic_items(:configured_item)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ item ], family: families(:dylan_family)))
+
+ assert_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(item)} details"
+ end
+
+ test "a single connection renders expanded" do
+ item = trade_republic_items(:configured_item)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ item ], family: families(:dylan_family)))
+
+ assert_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(item)} details[open]"
+ end
+
+ test "with several connections only those needing attention render expanded" do
+ healthy = trade_republic_items(:configured_item)
+ needs_update = trade_republic_items(:requires_update_item)
+ link_all_accounts(healthy)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ healthy, needs_update ], family: families(:dylan_family)))
+
+ assert_no_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(healthy)} details[open]"
+ assert_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(needs_update)} details[open]"
+ end
+
+ test "a healthy connection with unlinked accounts renders expanded so the setup CTA stays visible" do
+ with_unlinked = trade_republic_items(:configured_item)
+ fully_linked = trade_republic_items(:no_session_item)
+ fully_linked.update!(session_blob: "session")
+ link_all_accounts(fully_linked)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ with_unlinked, fully_linked ], family: families(:dylan_family)))
+
+ assert_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(with_unlinked)} details[open]",
+ text: I18n.t("settings.providers.trade_republic_panel.setup_accounts")
+ assert_no_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(fully_linked)} details[open]"
+ end
+
+ test "the connection whose QR login just started renders expanded with its QR code" do
+ healthy = trade_republic_items(:configured_item)
+ other = trade_republic_items(:no_session_item)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(
+ items: [ healthy, other ],
+ family: families(:dylan_family),
+ qr_code_svg: "<svg id='fresh-qr'></svg>".html_safe,
+ qr_login_auto_poll_item: healthy
+ ))
+
+ assert_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(healthy)} details[open] svg#fresh-qr"
+ assert_no_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(other)} details[open]"
+ end
+
+ test "connections scheduled for deletion are not rendered" do
+ family = families(:dylan_family)
+ deleted = trade_republic_items(:requires_update_item)
+ deleted.update_column(:scheduled_for_deletion, true)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(family: family))
+
+ assert_text trade_republic_items(:configured_item).name
+ assert_no_text deleted.name
+ end
+
+ test "renders only the add-connection form when the family has no items" do
+ family = families(:empty)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [], family: family))
+
+ assert_selector "form[action='#{Rails.application.routes.url_helpers.trade_republic_items_path}']"
+ end
+
+ test "card summary shows the last 4 digits of the phone number" do
+ item = trade_republic_items(:configured_item)
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ item ], family: families(:dylan_family)))
+
+ assert_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(item)}",
+ text: "#{I18n.t("settings.providers.trade_republic_panel.identifier_phone")} •••• 4567"
+ end
+
+ test "card summary shows the account number stored at login before the first sync" do
+ family = families(:dylan_family)
+ item = family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "session", brokerage_account_id: "DE1122334455"
+ )
+
+ render_inline(TradeRepublic::ConnectionCardComponent.new(item: item))
+
+ assert_text "#{I18n.t("settings.providers.trade_republic_panel.identifier_account")} •••• 4455"
+ end
+
+ test "card summary falls back to the account number when there is no phone number" do
+ family = families(:dylan_family)
+ item = family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :requires_update, session_blob: "session"
+ )
+ item.trade_republic_accounts.create!(
+ kind: "portfolio", trade_republic_account_id: "DE9876543210", currency: "EUR", raw_positions_payload: [], raw_timeline_payload: []
+ )
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [ item ], family: family))
+
+ assert_selector "##{TradeRepublic::ConnectionCardComponent.dom_id_for(item)}",
+ text: "#{I18n.t("settings.providers.trade_republic_panel.identifier_account")} •••• 3210"
+ end
+
+ test "disconnect confirmation names the connection by its last 4 digits" do
+ item = trade_republic_items(:configured_item)
+
+ render_inline(TradeRepublic::ConnectionCardComponent.new(item: item))
+
+ assert_selector "button[data-turbo-confirm*='4567']"
+ end
+
+ test "card summary shows no identifier for a connection with neither a phone number nor an account yet" do
+ item = families(:dylan_family).trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :requires_update, session_blob: "session"
+ )
+
+ render_inline(TradeRepublic::ConnectionCardComponent.new(item: item))
+
+ assert_no_text "••••"
+ end
+
+ test "an item with a configured session offers to update its configuration" do
+ render_inline(TradeRepublic::ConnectionCardComponent.new(item: trade_republic_items(:configured_item)))
+
+ assert_selector "button[type=submit]", text: I18n.t("settings.providers.trade_republic_panel.update_configuration")
+ assert_no_text I18n.t("settings.providers.trade_republic_panel.save_configuration")
+ end
+
+ test "an item without a configured session offers to save and start login instead" do
+ render_inline(TradeRepublic::ConnectionCardComponent.new(item: trade_republic_items(:requires_update_item)))
+
+ assert_selector "button[type=submit]", text: I18n.t("settings.providers.trade_republic_panel.save_configuration")
+ assert_no_text I18n.t("settings.providers.trade_republic_panel.update_configuration")
+ end
+
+ test "a failed connection attempt is redisplayed with its phone number" do
+ family = families(:dylan_family)
+ failed_item = family.trade_republic_items.build(phone_number: "+491701234567")
+
+ render_inline(TradeRepublic::AccountEditorComponent.new(items: [], family: family, new_item: failed_item))
+
+ assert_selector "input[name='trade_republic_item[phone_number]'][value='+491701234567']"
+ end
+end
diff --git a/test/controllers/trade_republic_items_controller_test.rb b/test/controllers/trade_republic_items_controller_test.rb
index 41873af002..2b551755b6 100644
--- a/test/controllers/trade_republic_items_controller_test.rb
+++ b/test/controllers/trade_republic_items_controller_test.rb
@@ -19,6 +19,47 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTest
assert_equal I18n.t("trade_republic_items.initiate_login.pin_required"), flash[:alert]
end
+ test "create redisplays the entered phone number after a validation failure" do
+ assert_no_difference "TradeRepublicItem.count" do
+ post trade_republic_items_url, params: {
+ trade_republic_item: {
+ phone_number: "+491701234567",
+ pin: ""
+ }
+ }, headers: { "ACCEPT" => "text/vnd.turbo-stream.html" }
+ end
+
+ assert_response :unprocessable_entity
+ assert_includes response.body, I18n.t("trade_republic_items.initiate_login.pin_required")
+ assert_select "input[name='trade_republic_item[phone_number]'][value='+491701234567']"
+ end
+
+ test "create adds a second connection without touching the first" do
+ existing_item = trade_republic_items(:configured_item)
+ provider = mock
+ provider.expects(:initiate_qr_login).returns(
+ Provider::TradeRepublicClient::Result.new(
+ data: { "status" => "qr_pending", "pending_login_b64" => "qr-second-pending" }
+ )
+ )
+ provider.stubs(:login_stage).returns("qr_pending")
+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)
+
+ assert_difference "TradeRepublicItem.count", 1 do
+ post trade_republic_items_url, params: {
+ login_method: "qr",
+ trade_republic_item: { currency: "EUR" }
+ }, headers: { "ACCEPT" => "text/vnd.turbo-stream.html" }
+ end
+
+ assert_response :success
+ new_item = families(:dylan_family).trade_republic_items.order(:created_at).last
+ assert_equal "qr-second-pending", new_item.pending_login_state
+ assert_includes response.body, existing_item.name
+ assert_includes response.body, new_item.name
+ assert_equal existing_item.session_blob, existing_item.reload.session_blob
+ end
+
test "Trade Republic PIN is filtered from logs" do
parameter_filter = ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters)
filtered_params = parameter_filter.filter(
@@ -327,4 +368,145 @@ class TradeRepublicItemsControllerTest < ActionDispatch::IntegrationTest
assert_includes response.body, 'data-action="DS--dialog#close"'
assert_includes response.body, I18n.t("settings.providers.trade_republic_panel.connection_success.close")
end
+
+ test "pending push login poll replaces only that connection's card" do
+ item = trade_republic_items(:requires_update_item)
+ item.update!(pending_login_state: "pending-login")
+ provider = mock
+ provider.expects(:complete_login).with(pending_login_b64: "pending-login").returns(
+ Provider::TradeRepublicClient::Result.new(data: { "status" => "pending" })
+ )
+ provider.stubs(:login_stage).returns("waiting_for_approval")
+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)
+
+ post poll_login_trade_republic_item_url(item), headers: { "ACCEPT" => "text/vnd.turbo-stream.html" }
+
+ assert_response :success
+ card_id = TradeRepublic::ConnectionCardComponent.dom_id_for(item)
+ assert_includes response.body, %(target="#{card_id}")
+ assert_not_includes response.body, %(target="trade-republic-providers-panel")
+ assert_not_includes response.body, trade_republic_items(:configured_item).name
+ end
+
+ test "push login for an account already connected by another item is discarded" do
+ item = families(:dylan_family).trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :requires_update, pending_login_state: "pending-login"
+ )
+ provider = mock
+ provider.expects(:complete_login).with(pending_login_b64: "pending-login").returns(
+ Provider::TradeRepublicClient::Result.new(
+ data: { "status" => "ok", "session_txt" => "duplicate-session", "account" => { "brokerage_account_id" => "DE1234" } }
+ )
+ )
+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)
+
+ post poll_login_trade_republic_item_url(item), headers: { "ACCEPT" => "text/vnd.turbo-stream.html" }
+
+ assert_response :success
+ assert_includes response.body, %(target="trade-republic-providers-panel")
+ assert_includes response.body, I18n.t("trade_republic_items.duplicate_connection")
+ item.reload
+ assert_predicate item, :scheduled_for_deletion?
+ assert_not item.session_configured?
+ assert_nil item.pending_login_state
+ end
+
+ test "QR login for an account already connected by another item is discarded" do
+ item = families(:dylan_family).trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :requires_update, pending_login_state: "qr-pending"
+ )
+ provider = mock
+ provider.expects(:poll_qr_login).with(pending_login_b64: "qr-pending").returns(
+ Provider::TradeRepublicClient::Result.new(
+ data: { "status" => "ok", "session_txt" => "duplicate-session", "account" => { "brokerage_account_id" => "DE1234" } }
+ )
+ )
+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)
+
+ post poll_qr_login_trade_republic_item_url(item), headers: { "ACCEPT" => "application/json" }
+
+ assert_response :success
+ assert_equal "duplicate_connection", JSON.parse(response.body).fetch("status")
+ assert_equal I18n.t("trade_republic_items.duplicate_connection"), flash[:alert]
+ item.reload
+ assert_predicate item, :scheduled_for_deletion?
+ assert_not item.session_configured?
+ assert_predicate trade_republic_items(:configured_item).reload, :session_configured?
+ end
+
+ test "a login for an account another item already claimed before its first sync is treated as a duplicate" do
+ other_item = families(:dylan_family).trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "not-yet-synced", brokerage_account_id: "DE9999"
+ )
+ item = families(:dylan_family).trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :requires_update, pending_login_state: "pending-login"
+ )
+ provider = mock
+ provider.expects(:complete_login).with(pending_login_b64: "pending-login").returns(
+ Provider::TradeRepublicClient::Result.new(
+ data: { "status" => "ok", "session_txt" => "duplicate-session", "account" => { "brokerage_account_id" => "DE9999" } }
+ )
+ )
+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)
+
+ post poll_login_trade_republic_item_url(item), headers: { "ACCEPT" => "text/vnd.turbo-stream.html" }
+
+ assert_response :success
+ assert_includes response.body, I18n.t("trade_republic_items.duplicate_connection")
+ item.reload
+ assert_predicate item, :scheduled_for_deletion?
+ assert_nil item.brokerage_account_id
+ assert_equal "DE9999", other_item.reload.brokerage_account_id
+ end
+
+ test "a race lost against a concurrent login for the same account is handled as a duplicate, not a server error" do
+ # A real row for the account the concurrent winner just claimed, so the
+ # unique index -- not a stub -- is what rejects this item's write below.
+ families(:dylan_family).trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "winner", brokerage_account_id: "DE1234"
+ )
+ item = families(:dylan_family).trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :requires_update, pending_login_state: "pending-login"
+ )
+ provider = mock
+ provider.expects(:complete_login).with(pending_login_b64: "pending-login").returns(
+ Provider::TradeRepublicClient::Result.new(
+ data: { "status" => "ok", "session_txt" => "session", "account" => { "brokerage_account_id" => "DE1234" } }
+ )
+ )
+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)
+ # Force the early check to miss it, as a genuinely concurrent request
+ # would (the winner's row exists, but not yet at the moment this request
+ # checked) -- only the unique index catches it from here.
+ TradeRepublicItemsController.any_instance.stubs(:duplicate_connection?).returns(false)
+
+ post poll_login_trade_republic_item_url(item), headers: { "ACCEPT" => "text/vnd.turbo-stream.html" }
+
+ assert_response :success
+ assert_includes response.body, I18n.t("trade_republic_items.duplicate_connection")
+ item.reload
+ assert_predicate item, :scheduled_for_deletion?
+ assert_nil item.brokerage_account_id
+ end
+
+ test "reconnecting an item to its own account is not treated as a duplicate" do
+ item = trade_republic_items(:configured_item)
+ item.update!(pending_login_state: "qr-pending", status: :requires_update)
+ provider = mock
+ provider.expects(:poll_qr_login).with(pending_login_b64: "qr-pending").returns(
+ Provider::TradeRepublicClient::Result.new(
+ data: { "status" => "ok", "session_txt" => "fresh-session", "account" => { "brokerage_account_id" => "DE1234" } }
+ )
+ )
+ TradeRepublicItem.any_instance.stubs(:trade_republic_provider).returns(provider)
+ TradeRepublicItem.any_instance.stubs(:syncing?).returns(true)
+
+ post poll_qr_login_trade_republic_item_url(item), headers: { "ACCEPT" => "application/json" }
+
+ assert_response :success
+ item.reload
+ assert_predicate item, :good?
+ assert_equal "fresh-session", item.session_blob
+ assert_not item.scheduled_for_deletion?
+ end
end
diff --git a/test/controllers/trade_republic_panel_render_test.rb b/test/controllers/trade_republic_panel_render_test.rb
index 7475b83bc8..6aaca8f153 100644
--- a/test/controllers/trade_republic_panel_render_test.rb
+++ b/test/controllers/trade_republic_panel_render_test.rb
@@ -6,8 +6,8 @@ class TradeRepublicPanelRenderTest < ActionDispatch::IntegrationTest
end
test "expired login state renders restart login via DS::Button" do
+ trade_republic_items(:configured_item).update!(pending_login_state: "some-state")
TradeRepublicItem.any_instance.stubs(:login_stage).returns("expired")
- TradeRepublicItem.any_instance.stubs(:pending_login_state).returns("some-state")
get connect_form_settings_providers_path(provider_key: "trade_republic")
assert_response :success
@@ -17,6 +17,29 @@ class TradeRepublicPanelRenderTest < ActionDispatch::IntegrationTest
refute_includes response.body, "hover:border-primary"
end
+ test "item stuck in a pending login state still renders disconnect" do
+ item = trade_republic_items(:configured_item)
+ item.update!(pending_login_state: "some-state")
+
+ get connect_form_settings_providers_path(provider_key: "trade_republic")
+ assert_response :success
+
+ disconnect_label = I18n.t("settings.providers.trade_republic_panel.disconnect")
+ assert_includes response.body, %(aria-label="#{disconnect_label}")
+ assert_includes response.body, trade_republic_item_path(item)
+ end
+
+ test "item without a configured session still renders disconnect" do
+ item = trade_republic_items(:no_session_item)
+
+ get connect_form_settings_providers_path(provider_key: "trade_republic")
+ assert_response :success
+
+ disconnect_label = I18n.t("settings.providers.trade_republic_panel.disconnect")
+ assert_includes response.body, %(aria-label="#{disconnect_label}")
+ assert_includes response.body, trade_republic_item_path(item)
+ end
+
test "new record form renders QR submit via DS::Button" do
sign_in users(:empty)
@@ -29,7 +52,7 @@ class TradeRepublicPanelRenderTest < ActionDispatch::IntegrationTest
end
test "configured connection renders an accessible disconnect button" do
- TradeRepublicItem.any_instance.stubs(:session_configured?).returns(true)
+ item = trade_republic_items(:configured_item)
get connect_form_settings_providers_path(provider_key: "trade_republic")
assert_response :success
@@ -37,5 +60,19 @@ class TradeRepublicPanelRenderTest < ActionDispatch::IntegrationTest
disconnect_label = I18n.t("settings.providers.trade_republic_panel.disconnect")
assert_includes response.body, %(aria-label="#{disconnect_label}")
assert_includes response.body, %(title="#{disconnect_label}")
+ assert_includes response.body, trade_republic_item_path(item)
+ end
+
+ test "multiple connections render as separate cards with independent action URLs" do
+ first_item = trade_republic_items(:configured_item)
+ second_item = trade_republic_items(:requires_update_item)
+
+ get connect_form_settings_providers_path(provider_key: "trade_republic")
+ assert_response :success
+
+ assert_includes response.body, first_item.name
+ assert_includes response.body, second_item.name
+ assert_includes response.body, sync_trade_republic_item_path(first_item)
+ assert_includes response.body, trade_republic_item_path(second_item)
end
end
diff --git a/test/migrations/backfill_brokerage_account_id_on_trade_republic_items_migration_test.rb b/test/migrations/backfill_brokerage_account_id_on_trade_republic_items_migration_test.rb
new file mode 100644
index 0000000000..17e8c21202
--- /dev/null
+++ b/test/migrations/backfill_brokerage_account_id_on_trade_republic_items_migration_test.rb
@@ -0,0 +1,84 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20260927161700_backfill_brokerage_account_id_on_trade_republic_items")
+
+class BackfillBrokerageAccountIdOnTradeRepublicItemsMigrationTest < ActiveSupport::TestCase
+ test "claims the brokerage account id from an already-synced legacy item" do
+ item = trade_republic_items(:configured_item)
+ assert_nil item.brokerage_account_id
+
+ run_migration
+
+ assert_equal "DE1234", item.reload.brokerage_account_id
+ end
+
+ test "leaves an item with no synced accounts unclaimed" do
+ item = trade_republic_items(:no_session_item).family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "never-synced"
+ )
+
+ run_migration
+
+ assert_nil item.reload.brokerage_account_id
+ end
+
+ test "does not overwrite an id already claimed by a fresh connection" do
+ item = trade_republic_items(:configured_item)
+ item.update_column(:brokerage_account_id, "DE9999")
+
+ run_migration
+
+ assert_equal "DE9999", item.reload.brokerage_account_id
+ end
+
+ test "gives a shared account to the oldest active item only" do
+ oldest = trade_republic_items(:configured_item)
+ duplicate = oldest.family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "session"
+ )
+ duplicate.trade_republic_accounts.create!(
+ kind: "portfolio", trade_republic_account_id: "DE1234", currency: "EUR", raw_positions_payload: [], raw_timeline_payload: []
+ )
+
+ run_migration
+
+ assert_equal "DE1234", oldest.reload.brokerage_account_id
+ assert_nil duplicate.reload.brokerage_account_id
+ end
+
+ test "skips an account another active item already claimed" do
+ claimed = trade_republic_items(:requires_update_item)
+ claimed.update_column(:brokerage_account_id, "DE1234")
+
+ run_migration
+
+ assert_nil trade_republic_items(:configured_item).reload.brokerage_account_id
+ assert_equal "DE1234", claimed.reload.brokerage_account_id
+ end
+
+ test "leaves items scheduled for deletion unclaimed" do
+ item = trade_republic_items(:configured_item)
+ item.update_column(:scheduled_for_deletion, true)
+
+ run_migration
+
+ assert_nil item.reload.brokerage_account_id
+ end
+
+ test "can be run again" do
+ item = trade_republic_items(:configured_item)
+
+ 2.times { run_migration }
+
+ assert_equal "DE1234", item.reload.brokerage_account_id
+ end
+
+ private
+
+ def run_migration
+ ActiveRecord::Migration.suppress_messages do
+ BackfillBrokerageAccountIdOnTradeRepublicItems.new.up
+ end
+ end
+end
diff --git a/test/models/trade_republic_item_test.rb b/test/models/trade_republic_item_test.rb
index c3d2a94bf4..fdb7a8c004 100644
--- a/test/models/trade_republic_item_test.rb
+++ b/test/models/trade_republic_item_test.rb
@@ -13,6 +13,33 @@ class TradeRepublicItemTest < ActiveSupport::TestCase
end
end
+ test "database enforces one active connection per family per brokerage account" do
+ family = trade_republic_items(:configured_item).family
+ family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "a", brokerage_account_id: "DE1234"
+ )
+
+ assert_raises ActiveRecord::RecordNotUnique do
+ family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "b", brokerage_account_id: "DE1234"
+ )
+ end
+ end
+
+ test "a connection scheduled for deletion does not block reconnecting the same brokerage account" do
+ family = trade_republic_items(:configured_item).family
+ deleted = family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "a", brokerage_account_id: "DE1234",
+ scheduled_for_deletion: true
+ )
+
+ reconnected = family.trade_republic_items.create!(
+ name: "Trade Republic", currency: "EUR", status: :good, session_blob: "b", brokerage_account_id: "DE1234"
+ )
+
+ assert_not_equal deleted.id, reconnected.id
+ end
+
test "syncable scope requires a stored session" do
items = TradeRepublicItem.syncable