Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(fio): add Fio banka (CZ) bank sync (#3523)

Jan Buchar985b51207f96
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index b9fc42c8a7..1208643da1 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -20,6 +20,7 @@ class AccountsController < ApplicationController
@akahu_items = visible_provider_items(family.akahu_items.ordered.with_attached_logo.includes(:akahu_accounts))
@up_items = visible_provider_items(family.up_items.ordered.with_attached_logo.includes(:up_accounts))
@monobank_items = visible_provider_items(family.monobank_items.ordered.with_attached_logo.includes(:monobank_accounts))
+ @fio_items = visible_provider_items(family.fio_items.active.ordered.with_attached_logo.includes(:fio_accounts))
@enable_banking_items = visible_provider_items(family.enable_banking_items.ordered.with_attached_logo)
@coinstats_items = visible_provider_items(family.coinstats_items.ordered.with_attached_logo.includes(:coinstats_accounts, :accounts))
@mercury_items = visible_provider_items(family.mercury_items.ordered.with_attached_logo.includes(:mercury_accounts))
@@ -361,6 +362,7 @@ class AccountsController < ApplicationController
@akahu_items,
@up_items,
@monobank_items,
+ @fio_items,
@enable_banking_items,
@coinstats_items,
@mercury_items,
@@ -639,5 +641,12 @@ class AccountsController < ApplicationController
latest_sync = item.latest_sync_record
@wise_sync_stats_map[item.id] = latest_sync&.sync_stats || {}
end
+
+ # Fio sync stats
+ @fio_sync_stats_map = {}
+ @fio_items.each do |item|
+ latest_sync = item.latest_sync_record
+ @fio_sync_stats_map[item.id] = latest_sync&.sync_stats || {}
+ end
end
end
diff --git a/app/controllers/fio_items_controller.rb b/app/controllers/fio_items_controller.rb
new file mode 100644
index 0000000000..b5f2c46259
--- /dev/null
+++ b/app/controllers/fio_items_controller.rb
@@ -0,0 +1,425 @@
+# frozen_string_literal: true
+
+# Connections are created, updated and removed from the providers settings panel
+# (app/views/settings/providers/_fio_panel.html.erb), and the account is linked through
+# the dialogs in app/views/fio_items. There is deliberately no index/show/new/edit
+# action: nothing links to them and they would have no template.
+#
+# A Fio token reaches exactly one account and Fio has no endpoint that lists accounts, so
+# every screen here works on `fio_item.fio_account` — discovered by the first sync — and
+# never offers a picker.
+class FioItemsController < ApplicationController
+ before_action :set_fio_item, only: [ :update, :destroy, :sync, :setup_accounts, :complete_account_setup ]
+ before_action :require_admin!, only: [
+ :create, :select_accounts, :link_accounts,
+ :select_existing_account, :link_existing_account, :update,
+ :destroy, :sync, :setup_accounts, :complete_account_setup
+ ]
+
+ # Create a Fio connection and kick off its first sync.
+ def create
+ attributes = fio_item_params
+ token = attributes[:token].to_s.strip
+
+ if token.blank?
+ render_provider_panel_error(t(".token_required"))
+ return
+ end
+
+ Current.family.create_fio_item!(
+ token: token,
+ item_name: attributes[:name].presence,
+ sync_start_date: attributes[:sync_start_date].presence
+ )
+
+ render_provider_panel(:notice, t(".success"))
+ rescue ActiveRecord::RecordInvalid => e
+ render_provider_panel_error(e.record.errors.full_messages.join(", "))
+ end
+
+ # Rotate the token and/or rename the connection and/or move its sync start date.
+ def update
+ attributes = update_params
+ # A rotated token is the fix for the failed authorization that set requires_update.
+ attributes[:status] = :good if attributes[:token].present? && @fio_item.requires_update?
+ # A new token or a moved start date is a fresh attempt at the history, so the next
+ # sync may reach for the whole range again. A rename is not: the form resubmits the
+ # stored start date unchanged, and clearing the marker for that would spend the next
+ # sync's single request on a period Fio has already refused.
+ attributes[:history_unlock_required_at] = nil if history_attempt_renewed?(attributes)
+
+ if @fio_item.update(attributes)
+ # Nothing else checks a rotated token: status is set from the form, and only a
+ # sync can find out whether Fio still accepts it. Without this the connection sits
+ # marked healthy until the next scheduled run.
+ @fio_item.sync_later unless @fio_item.syncing?
+ render_provider_panel(:notice, t(".success"))
+ else
+ render_provider_panel_error(@fio_item.errors.full_messages.join(", "))
+ end
+ end
+
+ # Unlink the account then schedule deletion of the connection.
+ def destroy
+ results = @fio_item.unlink_all!(dry_run: false)
+
+ if results.any? { |result| result[:error].present? }
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Fio unlink during destroy failed",
+ source: self.class.name,
+ provider_key: "fio",
+ family: @fio_item.family,
+ metadata: { fio_item_id: @fio_item.id, failures: results.select { |r| r[:error].present? } }
+ )
+ redirect_to settings_providers_path, alert: t(".unlink_failed"), status: :see_other
+ return
+ end
+
+ @fio_item.destroy_later
+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other
+ rescue => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Fio unlink during destroy failed",
+ source: self.class.name,
+ provider_key: "fio",
+ family: @fio_item&.family,
+ metadata: { fio_item_id: @fio_item&.id, error_class: e.class.name, error_message: e.message }
+ )
+ redirect_to settings_providers_path, alert: t(".unlink_failed"), status: :see_other
+ end
+
+ # Trigger a manual sync unless one is already running.
+ #
+ # Pressing Sync is also how a user says "I have just unlocked my full history in
+ # internet banking": the unlock only lasts ten minutes, so the clamp is dropped here
+ # and this sync reaches for the whole range again.
+ def sync
+ @fio_item.update!(history_unlock_required_at: nil) if @fio_item.history_unlock_required_at.present?
+ @fio_item.sync_later unless @fio_item.syncing?
+
+ respond_to do |format|
+ format.html { redirect_back_or_to accounts_path }
+ format.json { head :ok }
+ end
+ end
+
+ # Render the confirmation screen for turning the connection's account into a new Sure
+ # account. Reached from the new-account flow, so there is nothing to choose between.
+ def select_accounts
+ @accountable_type = requested_accountable_type
+ @return_to = safe_return_to_path
+ @fio_item = requested_fio_item
+
+ unless @fio_item.credentials_configured?
+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")
+ return
+ end
+
+ @fio_account = @fio_item.fio_accounts.unlinked.first
+ @discovered_account = @fio_item.fio_account
+ @account_type_options = account_type_options
+
+ render layout: false
+ end
+
+ # Create a new Sure account for the connection's account and link the two.
+ def link_accounts
+ fio_item = requested_fio_item
+ unless fio_item.credentials_configured?
+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")
+ return
+ end
+
+ account_type = requested_accountable_type
+ unless Provider::FioAdapter.supported_account_types.include?(account_type)
+ redirect_to new_account_path, alert: t(".unsupported_account_type")
+ return
+ end
+
+ fio_account = fio_item.fio_accounts.unlinked.first
+ unless fio_account
+ redirect_to select_accounts_fio_items_path(fio_item_id: fio_item.id, accountable_type: account_type, return_to: safe_return_to_path), alert: t(".no_account_found")
+ return
+ end
+
+ account = nil
+ ActiveRecord::Base.transaction do
+ account = create_account_from_fio(fio_account, account_type)
+ AccountProvider.create!(account: account, provider: fio_account)
+ end
+
+ fio_item.sync_later
+
+ redirect_to safe_return_to_path || accounts_path, notice: t(".success", account_name: account.name)
+ rescue ActiveRecord::RecordNotUnique
+ # A concurrent submit linked the account first; the transaction rolled this one back,
+ # so send the user back to the screen rather than a 500.
+ redirect_to select_accounts_fio_items_path(fio_item_id: fio_item.id, accountable_type: params[:accountable_type], return_to: safe_return_to_path), alert: t(".link_failed")
+ end
+
+ # Render the confirmation screen for attaching the connection's account to an existing
+ # Sure account.
+ def select_existing_account
+ @account = Current.family.accounts.find(params[:account_id])
+
+ if @account.account_providers.exists?
+ redirect_to accounts_path, alert: t(".account_already_linked")
+ return
+ end
+
+ @fio_item = requested_fio_item
+ unless @fio_item.credentials_configured?
+ redirect_to settings_providers_path, alert: t(".no_credentials_configured")
+ return
+ end
+
+ @fio_account = @fio_item.fio_accounts.unlinked.first
+ @discovered_account = @fio_item.fio_account
+ @return_to = safe_return_to_path
+
+ render layout: false
+ end
+
+ # Link the connection's account to an existing Sure account and sync.
+ def link_existing_account
+ account = Current.family.accounts.find(params[:account_id])
+ fio_item = requested_fio_item
+
+ unless fio_item.credentials_configured?
+ redirect_to settings_providers_path, alert: t("fio_items.select_existing_account.no_credentials_configured")
+ return
+ end
+
+ fio_account = fio_item.fio_accounts.find_by(id: params[:fio_account_id])
+ unless fio_account
+ redirect_to accounts_path, alert: t(".no_account_selected")
+ return
+ end
+
+ if account.account_providers.exists?
+ redirect_to accounts_path, alert: t(".account_already_linked")
+ return
+ end
+
+ if fio_account.account_provider.present?
+ redirect_to accounts_path, alert: t(".fio_account_already_linked")
+ return
+ end
+
+ # Fio can only describe the account types the adapter claims to support, so linking
+ # its statement to, say, a Crypto account would feed it balances it cannot represent.
+ # link_accounts and complete_account_setup already refuse this for new accounts.
+ unless Provider::FioAdapter.supported_account_types.include?(account.accountable_type)
+ redirect_to accounts_path, alert: t(".unsupported_account_type")
+ return
+ end
+
+ begin
+ AccountProvider.create!(account: account, provider: fio_account)
+ rescue ActiveRecord::RecordNotUnique
+ # The two guards above are reads; a double submit gets both requests past them and
+ # the unique indexes on account_providers are what actually settle it. The request
+ # that loses that race gets the same answer the guard would have given it.
+ redirect_to accounts_path, alert: t(".account_already_linked")
+ return
+ end
+
+ fio_item.sync_later
+
+ redirect_to safe_return_to_path || accounts_path, notice: t(".success", account_name: account.name)
+ end
+
+ # Render the post-sync setup screen while the account still needs a decision.
+ def setup_accounts
+ @fio_account = @fio_item.fio_accounts.needs_setup.first
+ @discovered_account = @fio_item.fio_account
+ @return_to = safe_return_to_path
+ @account_type_options = [ [ t(".account_types.skip"), "skip" ] ] + account_type_options
+ @selected_account_type = @fio_account&.suggested_account_type || "skip"
+ end
+
+ # Apply the user's setup choice: create and link a Sure account, or skip.
+ def complete_account_setup
+ fio_account = @fio_item.fio_accounts.needs_setup.first
+ unless fio_account
+ redirect_to accounts_path, alert: t(".no_account"), status: :see_other
+ return
+ end
+
+ selected_type = params[:account_type].to_s
+ if selected_type.blank? || selected_type == "skip"
+ # Persist the skip so the account stops resurfacing as "needs setup" on every sync.
+ fio_account.update!(ignored: true)
+ redirect_to accounts_path, notice: t(".skipped"), status: :see_other
+ return
+ end
+
+ unless Provider::FioAdapter.supported_account_types.include?(selected_type)
+ redirect_to setup_accounts_fio_item_path(@fio_item), alert: t(".unsupported_account_type"), status: :see_other
+ return
+ end
+
+ account = nil
+ ActiveRecord::Base.transaction do
+ account = create_account_from_fio(fio_account, selected_type)
+ AccountProvider.create!(account: account, provider: fio_account)
+ end
+
+ @fio_item.sync_later
+
+ redirect_to safe_return_to_path || accounts_path, notice: t(".success", account_name: account.name), status: :see_other
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, ActiveRecord::RecordNotUnique => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Fio account setup failed",
+ source: self.class.name,
+ provider_key: "fio",
+ family: @fio_item&.family,
+ metadata: { fio_item_id: @fio_item&.id, error_class: e.class.name, error_message: e.message }
+ )
+ redirect_to accounts_path, alert: t(".creation_failed"), status: :see_other
+ end
+
+ private
+
+ # Load the requested item scoped to the current family.
+ def set_fio_item
+ @fio_item = Current.family.fio_items.find(params[:id])
+ end
+
+ # Strong params for creating/updating a connection.
+ def fio_item_params
+ params.require(:fio_item).permit(:name, :sync_start_date, :token)
+ end
+
+ # Params for update: a stripped token, or none at all so a blank field keeps the
+ # token already on file.
+ def update_params
+ permitted = fio_item_params
+ token = permitted[:token].to_s.strip
+
+ token.present? ? permitted.merge(token: token) : permitted.except(:token)
+ end
+
+ # True when an update is a fresh attempt at the account's history: a replacement
+ # token, or a start date that actually differs from the one on file.
+ def history_attempt_renewed?(attributes)
+ return true if attributes[:token].present?
+
+ attributes.key?(:sync_start_date) &&
+ attributes[:sync_start_date].to_s != @fio_item.sync_start_date.to_s
+ end
+
+ # Load the active item referenced by fio_item_id, scoped to the family.
+ def requested_fio_item
+ Current.family.fio_items.active.find_by!(id: params[:fio_item_id])
+ end
+
+ # The account type the user picked, defaulting to Fio's current-account suggestion.
+ def requested_accountable_type
+ params[:accountable_type].presence || FioAccount::DEFAULT_ACCOUNTABLE_TYPE
+ end
+
+ # Selectable account types for the setup screens.
+ def account_type_options
+ Provider::FioAdapter.supported_account_types.map do |type|
+ [ t("fio_items.account_types.#{type.underscore}"), type ]
+ end
+ end
+
+ # Create and sync a Sure account from the Fio account's statement header.
+ def create_account_from_fio(fio_account, account_type)
+ # Linking clears any prior skip so a future unlink re-prompts for setup.
+ fio_account.update!(ignored: false) if fio_account.ignored?
+
+ # Same normalization FioAccount::Processor applies: Fio reports a drawn loan or
+ # overdraft negative, Sure holds a liability positive. Without it the new account
+ # shows a negative debt until a sync corrects it, and the next sync may well be
+ # throttled — discovery just used the token.
+ balance = fio_account.current_balance || 0
+ balance = balance.abs if account_type == "Loan"
+ subtype = fio_account.suggested_subtype if account_type == fio_account.suggested_account_type
+
+ Account.create_and_sync(
+ {
+ family: Current.family,
+ name: fio_account.name,
+ balance: balance,
+ cash_balance: balance,
+ currency: fio_account.currency,
+ accountable_type: account_type,
+ accountable_attributes: subtype.present? ? { subtype: subtype } : {}
+ },
+ skip_initial_sync: true
+ )
+ end
+
+ # Re-render the providers settings panel (Turbo) or redirect with a flash.
+ def render_provider_panel(flash_type, message)
+ if turbo_frame_request?
+ flash.now[flash_type] = message
+ @fio_items = Current.family.fio_items.active.ordered
+ render turbo_stream: [
+ turbo_stream.replace(
+ "fio-providers-panel",
+ partial: "settings/providers/fio_panel",
+ locals: { fio_items: @fio_items }
+ ),
+ *flash_notification_stream_items
+ ]
+ else
+ redirect_to settings_providers_path, { flash_type => message, status: :see_other }
+ end
+ end
+
+ # Re-render the providers panel with an error (Turbo) or redirect with alert.
+ def render_provider_panel_error(message)
+ @error_message = message
+ if turbo_frame_request?
+ render turbo_stream: turbo_stream.replace(
+ "fio-providers-panel",
+ partial: "settings/providers/fio_panel",
+ locals: { error_message: @error_message }
+ ), status: :unprocessable_entity
+ else
+ redirect_to settings_providers_path, alert: @error_message, status: :see_other
+ end
+ end
+
+ # Validate the return_to param as a safe in-app relative path, or nil.
+ def safe_return_to_path
+ return nil if params[:return_to].blank?
+
+ return_to = params[:return_to].to_s.strip
+ return nil unless return_to.start_with?("/")
+ return nil if return_to[1] == "/" || return_to[1] == "\\"
+ return nil if return_to.include?("\\") || return_to.match?(/[[:cntrl:]]/)
+ return nil if encoded_path_separator?(return_to)
+
+ uri = URI.parse(return_to)
+ return nil unless uri.relative?
+
+ Rails.application.routes.recognize_path(uri.path, method: :get)
+
+ return_to
+ rescue URI::InvalidURIError, ActionController::RoutingError
+ nil
+ end
+
+ # True if the path's second char is a percent-encoded slash/backslash
+ # (used to block protocol-relative redirect bypasses).
+ def encoded_path_separator?(return_to)
+ encoded_second_character = return_to[1, 3]
+ return false unless encoded_second_character&.start_with?("%")
+
+ decoded = URI.decode_www_form_component(encoded_second_character)
+ decoded == "/" || decoded == "\\"
+ rescue ArgumentError
+ true
+ end
+end
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index b694f35527..fe230d89a0 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -191,6 +191,7 @@ class Settings::ProvidersController < ApplicationController
{ key: "akahu", title: "Akahu", turbo_id: "akahu", partial: "akahu_panel" },
{ key: "up", title: "Up", turbo_id: "up", partial: "up_panel" },
{ key: "monobank", title: "Monobank", turbo_id: "monobank", partial: "monobank_panel" },
+ { key: "fio", title: "Fio banka", turbo_id: "fio", partial: "fio_panel" },
{ key: "lunchflow", title: "Lunch Flow", turbo_id: "lunchflow", partial: "lunchflow_panel" },
{ key: "redbark", title: "Redbark", turbo_id: "redbark", partial: "redbark_panel" },
{ key: "simplefin", title: "SimpleFIN", turbo_id: "simplefin", partial: "simplefin_panel" },
@@ -220,6 +221,7 @@ class Settings::ProvidersController < ApplicationController
"akahu" => "AkahuItem",
"up" => "UpItem",
"monobank" => "MonobankItem",
+ "fio" => "FioItem",
"simplefin" => "SimplefinItem",
"lunchflow" => "LunchflowItem",
"redbark" => "RedbarkItem",
@@ -250,6 +252,8 @@ class Settings::ProvidersController < ApplicationController
@up_items = Current.family.up_items.active.ordered
when "monobank"
@monobank_items = Current.family.monobank_items.active.ordered
+ when "fio"
+ @fio_items = Current.family.fio_items.active.ordered
when "simplefin"
@simplefin_items = Current.family.simplefin_items.ordered
when "lunchflow"
@@ -326,6 +330,7 @@ class Settings::ProvidersController < ApplicationController
@coinspot_items = Current.family.coinspot_items.active.ordered
@onchain_wallet_items = Current.family.onchain_wallet_items.active.ordered
@questrade_items = Current.family.questrade_items.active.ordered.select(:id)
+ @fio_items = Current.family.fio_items.active.ordered
@provider_sync_health = compute_provider_sync_health(family_panel_items)
@@ -346,6 +351,7 @@ class Settings::ProvidersController < ApplicationController
"akahu" => @akahu_items,
"up" => @up_items,
"monobank" => @monobank_items,
+ "fio" => @fio_items,
"simplefin" => @simplefin_items,
"lunchflow" => @lunchflow_items,
"redbark" => @redbark_items,
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 16d2e388c9..96aeac4b20 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -66,6 +66,9 @@ module SettingsHelper
when "monobank"
return { status: :off } unless @monobank_items&.any?
sync_based_summary(key)
+ when "fio"
+ return { status: :off } unless @fio_items&.any?
+ sync_based_summary(key)
when "simplefin"
return { status: :off } unless @simplefin_items&.any?
sync_based_summary(key)
diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rb
index 8d9f52d1fb..4c2005b59f 100644
--- a/app/models/data_enrichment.rb
+++ b/app/models/data_enrichment.rb
@@ -21,6 +21,7 @@ class DataEnrichment < ApplicationRecord
questrade: "questrade",
redbark: "redbark",
trade_republic: "trade_republic",
- bayes: "bayes"
+ bayes: "bayes",
+ fio: "fio"
}
end
diff --git a/app/models/family.rb b/app/models/family.rb
index a97f07cfb9..807110c390 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -1,4 +1,5 @@
class Family < ApplicationRecord
+ include FioConnectable
include Syncable, AutoTransferMatchable, Subscribeable, VectorSearchable
include PlaidConnectable, SimplefinConnectable, LunchflowConnectable, AkahuConnectable, EnableBankingConnectable
include CoinbaseConnectable, BinanceConnectable, KrakenConnectable, CoinspotConnectable, CoinstatsConnectable, SnaptradeConnectable, MercuryConnectable, BrexConnectable, SophtronConnectable
diff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rb
index 9ef4d4fbe3..f04f67bb29 100644
--- a/app/models/family/financial_data_reset.rb
+++ b/app/models/family/financial_data_reset.rb
@@ -59,6 +59,7 @@ class Family::FinancialDataReset
sophtron_items
up_items
monobank_items
+ fio_items
].freeze
Result = Struct.new(:user, :family, :dry_run, :before_counts, :deleted_counts, :after_counts, keyword_init: true)
diff --git a/app/models/family/fio_connectable.rb b/app/models/family/fio_connectable.rb
new file mode 100644
index 0000000000..e8183f681d
--- /dev/null
+++ b/app/models/family/fio_connectable.rb
@@ -0,0 +1,30 @@
+module Family::FioConnectable
+ extend ActiveSupport::Concern
+
+ included do
+ has_many :fio_items, dependent: :destroy
+ end
+
+ # Whether this family may connect Fio accounts (always true).
+ def can_connect_fio?
+ true
+ end
+
+ # Create a Fio connection with the given API token and start its first sync. A token
+ # reaches one account, so a family with several Fio accounts creates several items.
+ def create_fio_item!(token:, item_name: nil, sync_start_date: nil)
+ fio_item = fio_items.create!(
+ name: item_name.presence || I18n.t("family.fio.create_fio_item.default_name"),
+ token: token,
+ sync_start_date: sync_start_date
+ )
+
+ fio_item.sync_later
+ fio_item
+ end
+
+ # True when any active Fio item has usable credentials.
+ def has_fio_credentials?
+ fio_items.active.any?(&:credentials_configured?)
+ end
+end
diff --git a/app/models/fio_account.rb b/app/models/fio_account.rb
new file mode 100644
index 0000000000..cc9290ccdf
--- /dev/null
+++ b/app/models/fio_account.rb
@@ -0,0 +1,110 @@
+# frozen_string_literal: true
+
+# The single account a Fio token reaches, as described by the statement header.
+class FioAccount < ApplicationRecord
+ include CurrencyNormalizable, Encryptable
+
+ INSTITUTION_NAME = "Fio banka".freeze
+ INSTITUTION_DOMAIN = "fio.cz".freeze
+
+ # Fio's statement header has no product or type field, so every discovered account is
+ # offered as a current account. The setup screen lets the user pick something else
+ # (Provider::FioAdapter.supported_account_types) for a loan or mortgage token.
+ DEFAULT_ACCOUNTABLE_TYPE = "Depository".freeze
+ DEFAULT_SUBTYPE = "checking".freeze
+
+ if encryption_ready?
+ encrypts :raw_payload
+ encrypts :raw_transactions_payload
+ # Not deterministic: neither is ever looked up by value, and an IBAN is exactly the
+ # kind of field worth keeping opaque at rest.
+ encrypts :iban
+ end
+
+ belongs_to :fio_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 :name, :currency, presence: true
+ validates :fio_account_id, uniqueness: { scope: :fio_item_id, allow_nil: true }
+
+ # Fio accounts with no linked Sure account.
+ scope :unlinked, -> { left_joins(:account_provider).where(account_providers: { id: nil }) }
+ # Unlinked accounts that still need a setup decision (i.e. not explicitly skipped).
+ scope :needs_setup, -> { unlinked.where(ignored: false) }
+ scope :ordered, -> { order(created_at: :desc) }
+ # The linked Sure account, if any.
+ def current_account
+ account
+ end
+
+ def suggested_account_type
+ DEFAULT_ACCOUNTABLE_TYPE
+ end
+
+ def suggested_subtype
+ DEFAULT_SUBTYPE
+ end
+
+ # Idempotently create or update the AccountProvider link.
+ def ensure_account_provider!(linked_account)
+ return nil unless linked_account
+
+ provider = account_provider || build_account_provider
+ provider.account = linked_account
+ provider.save!
+
+ # Reload to clear the cached nil.
+ reload_account_provider
+ account_provider
+ end
+
+ # Persist the statement header. `closingBalance` is the balance at the end of the
+ # requested period, which for a window ending today is the current balance.
+ def upsert_fio_snapshot!(statement_info)
+ info = statement_info.to_h.with_indifferent_access
+ account_number = info[:accountId].presence&.to_s
+
+ update!(
+ fio_account_id: account_number || fio_account_id,
+ name: name.presence || default_name(account_number),
+ bank_id: info[:bankId].presence&.to_s || bank_id,
+ iban: info[:iban].presence || iban,
+ bic: info[:bic].presence || bic,
+ currency: parse_currency(info[:currency]) || currency,
+ current_balance: parse_balance(info[:closingBalance]) || current_balance,
+ institution_metadata: institution_metadata.presence || {
+ "name" => INSTITUTION_NAME,
+ "domain" => INSTITUTION_DOMAIN,
+ "url" => "https://#{INSTITUTION_DOMAIN}"
+ },
+ raw_payload: info
+ )
+ end
+
+ def upsert_fio_transactions_snapshot!(transactions_snapshot)
+ update!(raw_transactions_payload: transactions_snapshot)
+ end
+
+ private
+
+ # Fio names no account, so the account number stands in until the user renames it.
+ def default_name(account_number)
+ [ INSTITUTION_NAME, account_number ].compact_blank.join(" ")
+ end
+
+ def parse_balance(value)
+ return nil if value.nil?
+
+ BigDecimal(value.to_s)
+ rescue ArgumentError
+ Rails.logger.warn("FioAccount - Unparseable balance #{value.inspect} for account #{id}")
+ nil
+ end
+
+ def log_invalid_currency(currency_value)
+ Rails.logger.warn("Invalid currency code #{currency_value.inspect} for Fio account #{id}")
+ end
+end
diff --git a/app/models/fio_account/processor.rb b/app/models/fio_account/processor.rb
new file mode 100644
index 0000000000..d4e142ee5e
--- /dev/null
+++ b/app/models/fio_account/processor.rb
@@ -0,0 +1,92 @@
+# frozen_string_literal: true
+
+class FioAccount::Processor
+ include CurrencyNormalizable
+
+ SanitizedProcessingError = Class.new(StandardError)
+
+ attr_reader :fio_account
+
+ def initialize(fio_account)
+ @fio_account = fio_account
+ end
+
+ # Sync the linked account's balance and process its movements. No-op when the Fio
+ # account isn't linked to a Sure account.
+ def process
+ unless fio_account.current_account.present?
+ Rails.logger.info "FioAccount::Processor - No linked account for fio_account #{fio_account.id}, skipping processing"
+ return
+ end
+
+ process_account!
+ process_transactions
+ rescue StandardError => e
+ Rails.logger.error "FioAccount::Processor - Failed to process account fio_account_id=#{fio_account.id} error_class=#{e.class.name}"
+ report_exception(e, "account")
+ raise
+ end
+
+ private
+
+ # Update the linked Sure account's balance/currency from the statement header.
+ def process_account!
+ account = fio_account.current_account
+ balance = fio_account.current_balance || 0
+ currency = parse_currency(fio_account.currency) || account.currency
+
+ # A drawn overdraft, loan or mortgage is reported negative by Fio; Sure holds a
+ # liability as a positive balance.
+ balance = balance.abs if account.accountable_type == "Loan"
+
+ account.update!(
+ balance: balance,
+ cash_balance: balance,
+ currency: currency
+ )
+ end
+
+ # Delegate to the transactions processor, capturing and logging failures.
+ def process_transactions
+ FioAccount::Transactions::Processor.new(fio_account).process
+ rescue => e
+ report_exception(e, "transactions")
+ Rails.logger.error "FioAccount::Processor - Failed to process transactions fio_account_id=#{fio_account.id} error_class=#{e.class.name}"
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Failed to process transactions",
+ source: self.class.name,
+ provider_key: "fio",
+ family: fio_account.fio_item.family,
+ account_provider: fio_account.account_provider,
+ metadata: { fio_account_id: fio_account.id, error_class: e.class.name, error_message: e.message }
+ )
+ { success: false, failed: 1, errors: [ { error: I18n.t("fio_item.errors.account_processing_failed") } ] }
+ end
+
+ # Report a processing error to Sentry with a sanitized message and tags.
+ def report_exception(error, context)
+ safe_error = SanitizedProcessingError.new("Fio account processing failed")
+
+ Sentry.capture_exception(safe_error) do |scope|
+ scope.set_tags(
+ fio_account_id: fio_account.id,
+ context: context,
+ error_class: error.class.name
+ )
+ scope.set_context(
+ "fio_account_processor",
+ {
+ fio_account_id: fio_account.id,
+ context: context,
+ error_class: error.class.name
+ }
+ )
+ end
+ end
+
+ def log_invalid_currency(currency_value)
+ Rails.logger.warn("Invalid currency code #{currency_value.inspect} for Fio account #{fio_account.id}, falling back to account currency")
+ end
+end
diff --git a/app/models/fio_account/transactions/processor.rb b/app/models/fio_account/transactions/processor.rb
new file mode 100644
index 0000000000..591d3a72f1
--- /dev/null
+++ b/app/models/fio_account/transactions/processor.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+class FioAccount::Transactions::Processor
+ attr_reader :fio_account
+
+ def initialize(fio_account)
+ @fio_account = fio_account
+ end
+
+ # Process each stored movement into a Sure entry and return a stats hash. The whole
+ # stored payload is replayed every sync: entries are matched on Fio's movement id, so
+ # re-processing a movement updates the entry it already produced.
+ def process
+ transactions = fio_account.raw_transactions_payload.to_a
+
+ if transactions.empty?
+ Rails.logger.info "FioAccount::Transactions::Processor - No Fio movements available to process"
+ return { success: true, total: 0, imported: 0, skipped: 0, failed: 0, errors: [] }
+ end
+
+ imported_count = 0
+ skipped_count = 0
+ failed_count = 0
+ errors = []
+
+ transactions.each_with_index do |transaction_data, index|
+ result = FioEntry::Processor.new(transaction_data, fio_account: fio_account).process
+
+ if result.nil?
+ # A movement the entry processor declined: no usable amount or date. Counting it
+ # as a failure would fail every sync from here on, because the stored payload is
+ # replayed in full each time and one unusable movement never becomes usable.
+ skipped_count += 1
+ Rails.logger.warn "FioAccount::Transactions::Processor - Skipped movement #{transaction_id(transaction_data)}"
+ else
+ imported_count += 1
+ end
+ rescue ArgumentError => e
+ failed_count += 1
+ errors << { index: index, transaction_id: transaction_id(transaction_data), error: "Validation error: #{e.message}" }
+ Rails.logger.error "FioAccount::Transactions::Processor - Validation error processing movement #{transaction_id(transaction_data)}: #{e.message}"
+ rescue => e
+ failed_count += 1
+ errors << { index: index, transaction_id: transaction_id(transaction_data), error: "#{e.class}: #{e.message}" }
+ Rails.logger.error "FioAccount::Transactions::Processor - Error processing movement #{transaction_id(transaction_data)}: #{e.class} - #{e.message}"
+ end
+
+ {
+ success: failed_count.zero?,
+ total: transactions.size,
+ imported: imported_count,
+ skipped: skipped_count,
+ failed: failed_count,
+ errors: errors
+ }
+ end
+
+ private
+
+ def transaction_id(transaction_data)
+ FioEntry::Processor.canonical_external_id(transaction_data) || "unknown"
+ end
+end
diff --git a/app/models/fio_entry/processor.rb b/app/models/fio_entry/processor.rb
new file mode 100644
index 0000000000..2902e361fd
--- /dev/null
+++ b/app/models/fio_entry/processor.rb
@@ -0,0 +1,267 @@
+# frozen_string_literal: true
+
+require "digest/md5"
+
+# Maps one Fio movement onto a Sure entry.
+#
+# Fio returns each movement as a bag of numbered columns
+# (`{"column22" => {"value" => 1147608196, "name" => "ID pohybu", "id" => 22}}`), the same
+# ids the CSV and XML exports use. `COLUMNS` is that mapping; `.normalize` flattens a raw
+# movement into named fields, and the raw form is what gets stored so a later change of
+# mapping can be replayed against it.
+class FioEntry::Processor
+ include CurrencyNormalizable
+
+ COLUMNS = {
+ id: "column22", # ID pohybu
+ date: "column0", # Datum
+ amount: "column1", # Objem
+ currency: "column14", # Měna
+ counter_account: "column2", # Protiúčet
+ counter_account_name: "column10", # Název protiúčtu
+ counter_bank_id: "column3", # Kód banky
+ counter_bank_name: "column12", # Název banky
+ constant_symbol: "column4", # KS
+ variable_symbol: "column5", # VS
+ specific_symbol: "column6", # SS
+ user_identification: "column7", # Uživatelská identifikace
+ message: "column16", # Zpráva pro příjemce
+ operation_type: "column8", # Typ
+ executed_by: "column9", # Provedl
+ specification: "column18", # Upřesnění
+ comment: "column25", # Komentář
+ counter_bic: "column26", # BIC
+ instruction_id: "column17", # ID pokynu
+ payer_reference: "column27" # Reference plátce
+ }.freeze
+
+ # Fio books every movement on a Prague banking day and serialises that day as epoch
+ # milliseconds at local midnight. Reading it in the family's timezone would shift a
+ # transaction to the previous day for anyone west of Prague.
+ BANK_TIME_ZONE = "Europe/Prague".freeze
+
+ # A card movement's "Uživatelská identifikace" is the terminal's own receipt line:
+ # "Nákup: MGGA PAPIRNICTVI, BELOHORSKA 197 126, PRAHA 6, 160 00, CZE, dne 26.6.2026, částka 958.00 CZK"
+ # Only the first field is the acceptor; the rest is its address plus a copy of the
+ # date and amount the entry already carries. Keeping any of it would give every branch
+ # of a chain its own merchant.
+ CARD_PURCHASE_PREFIX = /\A(?:nákup|platba|výběr)\s*:\s*/i
+ # Operation types covering card use ("Platba kartou", "Poplatek - platební karta").
+ CARD_OPERATION = /kart/i
+
+ # Original amount and currency of a converted payment, e.g. "15.90 EUR".
+ FOREIGN_AMOUNT = /\A(?<amount>-?[\d\s.,]+)\s*(?<currency>[A-Z]{3})\z/
+
+ # Flattens a raw movement into the fields named by COLUMNS, dropping blanks. Fio pads
+ # empty columns with a single space in some formats, hence the strip.
+ def self.normalize(fio_transaction)
+ raw = fio_transaction.to_h.with_indifferent_access
+
+ COLUMNS.each_with_object({}.with_indifferent_access) do |(field, column), normalized|
+ value = raw.dig(column, :value)
+ value = value.strip if value.is_a?(String)
+ normalized[field] = value unless value.nil? || value == ""
+ end
+ end
+
+ # Stable external id for a movement. Fio guarantees "ID pohybu" is unique per account
+ # and never reused, including for a reversal, which gets its own id.
+ def self.canonical_external_id(fio_transaction)
+ id = normalize(fio_transaction)[:id]
+ return nil if id.blank?
+
+ "fio_#{id}"
+ end
+
+ def initialize(fio_transaction, fio_account:)
+ @fio_transaction = fio_transaction
+ @fio_account = fio_account
+ end
+
+ # Import the movement into the linked Sure account via the import adapter.
+ # Returns nil when the account isn't linked or the movement is unusable.
+ def process
+ unless account.present?
+ Rails.logger.warn "FioEntry::Processor - No linked account for fio_account #{fio_account.id}, skipping movement"
+ return nil
+ end
+
+ return nil if external_id.blank? || amount.nil? || date.nil?
+
+ import_adapter.import_transaction(
+ external_id: external_id,
+ amount: amount,
+ currency: currency,
+ date: date,
+ name: name,
+ source: "fio",
+ merchant: merchant,
+ notes: notes,
+ extra: extra_metadata
+ )
+ rescue ArgumentError => e
+ Rails.logger.error "FioEntry::Processor - Validation error for movement #{external_id}: #{e.message}"
+ raise
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => e
+ Rails.logger.error "FioEntry::Processor - Failed to save movement #{external_id}: #{e.message}"
+ raise StandardError.new("Failed to import transaction: #{e.message}")
+ end
+
+ private
+
+ attr_reader :fio_transaction, :fio_account
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+
+ def account
+ @account ||= fio_account.current_account
+ end
+
+ def data
+ @data ||= self.class.normalize(fio_transaction)
+ end
+
+ def external_id
+ @external_id ||= self.class.canonical_external_id(fio_transaction)
+ end
+
+ # Fio signs outgoing movements negative; Sure stores an expense positive.
+ def amount
+ return @amount if defined?(@amount)
+
+ raw = data[:amount]
+ @amount = raw.nil? ? nil : -BigDecimal(raw.to_s)
+ rescue ArgumentError
+ @amount = nil
+ end
+
+ def currency
+ @currency ||= parse_currency(data[:currency]) || account.currency
+ end
+
+ def date
+ return @date if defined?(@date)
+
+ @date = case (raw = data[:date])
+ when Integer, Float
+ Time.at(raw / 1000.0).in_time_zone(BANK_TIME_ZONE).to_date
+ when String
+ Date.parse(raw)
+ else
+ nil
+ end
+ rescue ArgumentError, TypeError
+ @date = nil
+ end
+
+ # Best available description. A transfer names the counterparty; a card payment has
+ # no counterparty but carries the acceptor in "Uživatelská identifikace"; standing
+ # fees and interest have neither and fall back to the operation type.
+ def name
+ value = data[:counter_account_name].presence ||
+ card_acceptor ||
+ data[:user_identification].presence ||
+ data[:message].presence ||
+ data[:comment].presence ||
+ data[:operation_type].presence ||
+ I18n.t("transactions.unknown_name")
+
+ value.to_s.truncate(255)
+ end
+
+ # Whatever payment detail did not become the name, so the reference the counterparty
+ # sent is not lost. Fio repeats the same text across "Zpráva pro příjemce" and
+ # "Komentář", and on a card movement across "Uživatelská identifikace" too, so any
+ # candidate that is merely the string the name came out of is dropped.
+ def notes
+ candidates = [ data[:message], data[:comment] ]
+ candidates << data[:user_identification] if card_acceptor.blank?
+ echoed = data[:user_identification].to_s if card_acceptor.present?
+
+ candidates
+ .compact_blank
+ .reject { |value| value.to_s == name || value.to_s == echoed }
+ .first&.to_s&.truncate(255)
+ end
+
+ def merchant
+ merchant_name = card_acceptor
+ return nil if merchant_name.blank?
+
+ import_adapter.find_or_create_merchant(
+ provider_merchant_id: "fio_merchant_#{Digest::MD5.hexdigest(merchant_name.downcase)}",
+ name: merchant_name,
+ source: "fio"
+ )
+ end
+
+ # The acceptor is the first field of the receipt line (see CARD_PURCHASE_PREFIX).
+ def card_acceptor
+ return @card_acceptor if defined?(@card_acceptor)
+
+ identification = data[:user_identification]
+ unless identification.present? && data[:operation_type].to_s.match?(CARD_OPERATION)
+ return @card_acceptor = nil
+ end
+
+ @card_acceptor = identification
+ .sub(CARD_PURCHASE_PREFIX, "")
+ .split(",")
+ .first
+ &.strip
+ &.presence
+ end
+
+ def extra_metadata
+ fio = {
+ "id" => data[:id],
+ "instruction_id" => data[:instruction_id],
+ "operation_type" => data[:operation_type],
+ "variable_symbol" => data[:variable_symbol],
+ "constant_symbol" => data[:constant_symbol],
+ "specific_symbol" => data[:specific_symbol],
+ "counter_account" => counter_account_number,
+ "counter_account_name" => data[:counter_account_name],
+ "counter_bic" => data[:counter_bic],
+ "payer_reference" => data[:payer_reference],
+ "executed_by" => data[:executed_by],
+ "specification" => data[:specification],
+ # The acceptor's address survives only here, since the name keeps just the
+ # first field of the receipt line.
+ "user_identification" => data[:user_identification]
+ }.merge(foreign_amount_metadata).compact
+
+ { "fio" => fio }
+ end
+
+ # "Upřesnění" carries the original amount of a converted payment. Recorded under the
+ # cross-provider FX keys so the entry shows what was actually charged abroad.
+ def foreign_amount_metadata
+ specification = data[:specification]
+ return {} if specification.blank?
+
+ match = FOREIGN_AMOUNT.match(specification.to_s.strip)
+ return {} unless match
+
+ foreign_currency = parse_currency(match[:currency])
+ return {} if foreign_currency.blank? || foreign_currency == currency
+
+ foreign_amount = BigDecimal(match[:amount].gsub(/\s/, "").tr(",", "."))
+
+ { "fx_from" => foreign_currency, "fx_amount" => foreign_amount.to_s }
+ rescue ArgumentError
+ {}
+ end
+
+ # Fio writes a counter account as "2212-2000000699" (prefix-number) or bare digits.
+ # Joined with the bank code so the pair is usable without reading two fields.
+ def counter_account_number
+ account_number = data[:counter_account]
+ return nil if account_number.blank?
+
+ bank_id = data[:counter_bank_id]
+ bank_id.present? ? "#{account_number}/#{bank_id}" : account_number.to_s
+ end
+end
diff --git a/app/models/fio_item.rb b/app/models/fio_item.rb
new file mode 100644
index 0000000000..04e81a692d
--- /dev/null
+++ b/app/models/fio_item.rb
@@ -0,0 +1,221 @@
+# frozen_string_literal: true
+
+# One Fio banka API token, and therefore exactly one Fio account.
+#
+# Fio issues a token per account with no way to enumerate accounts, so a family tracking
+# three Fio accounts holds three items. The single `fio_accounts` row is still a
+# collection because the surrounding sync machinery (Family::Syncer, the setup flow,
+# Family::FinancialDataReset) is written against provider items with many accounts.
+class FioItem < ApplicationRecord
+ include Syncable, Provided, Unlinking, Encryptable
+
+ enum :status, { good: "good", requires_update: "requires_update" }, default: :good
+
+ if encryption_ready?
+ encrypts :token, deterministic: true
+ encrypts :raw_payload
+ encrypts :raw_institution_payload
+ end
+
+ belongs_to :family
+ has_one_attached :logo, dependent: :purge_later
+ has_many :fio_accounts, dependent: :destroy
+ has_many :accounts, through: :fio_accounts
+
+ validates :name, presence: true
+ validates :token, presence: true, on: :create
+
+ # Fio is a single institution, so its metadata is known up front rather than discovered
+ # per connection. On the model so both the settings panel and Family#create_fio_item!
+ # get it.
+ before_validation :apply_institution_defaults, on: :create
+
+ scope :active, -> { where(scheduled_for_deletion: false) }
+ # Family::Syncer discovers provider items reflectively and calls `syncable` on every
+ # `*_items` association whose model includes Syncable.
+ scope :syncable, -> { active }
+ scope :ordered, -> { order(created_at: :desc) }
+ scope :needs_update, -> { where(status: :requires_update) }
+
+ # Mark the item for deletion and enqueue the background destroy job.
+ def destroy_later
+ update!(scheduled_for_deletion: true)
+ DestroyJob.perform_later(self)
+ end
+
+ # Run the importer to fetch the latest statement from Fio.
+ def import_latest_fio_data
+ provider = fio_provider
+ unless provider
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Cannot import: Fio provider is not configured",
+ source: self.class.name,
+ provider_key: "fio",
+ family: family,
+ metadata: { fio_item_id: id }
+ )
+ raise StandardError.new("Fio provider is not configured")
+ end
+
+ FioItem::Importer.new(self, fio_provider: provider).import
+ rescue => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Failed to import data",
+ source: self.class.name,
+ provider_key: "fio",
+ family: family,
+ metadata: { fio_item_id: id, error_class: e.class.name, error_message: e.message }
+ )
+ raise
+ end
+
+ # Process each linked, visible Fio account, returning a per-account result array.
+ def process_accounts
+ return [] if fio_accounts.empty?
+
+ fio_accounts.joins(:account).merge(Account.visible).map do |fio_account|
+ result = FioAccount::Processor.new(fio_account).process
+ if result.is_a?(Hash) && result.with_indifferent_access[:success] == false
+ { fio_account_id: fio_account.id, success: false, error: I18n.t("fio_item.errors.account_processing_failed") }
+ else
+ { fio_account_id: fio_account.id, success: true, result: result }
+ end
+ rescue => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Failed to process account",
+ source: self.class.name,
+ provider_key: "fio",
+ family: family,
+ account_provider: fio_account.account_provider,
+ metadata: { fio_item_id: id, fio_account_id: fio_account.id, error_class: e.class.name, error_message: e.message }
+ )
+ { fio_account_id: fio_account.id, success: false, error: I18n.t("fio_item.errors.account_processing_failed") }
+ end
+ end
+
+ # Enqueue a balance sync for each visible linked account, returning per-account results.
+ def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)
+ return [] if accounts.empty?
+
+ accounts.visible.map do |account|
+ account.sync_later(
+ parent_sync: parent_sync,
+ window_start_date: window_start_date,
+ window_end_date: window_end_date
+ )
+ { account_id: account.id, success: true }
+ rescue => e
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Failed to schedule sync for account",
+ source: self.class.name,
+ provider_key: "fio",
+ family: family,
+ account: account,
+ metadata: { fio_item_id: id, account_id: account.id, error_class: e.class.name, error_message: e.message }
+ )
+ { account_id: account.id, success: false, error: I18n.t("fio_item.errors.account_sync_schedule_failed") }
+ end
+ end
+
+ # Persist the latest statement header for this item.
+ #
+ # The header is the only account description Fio offers, so it is kept for support. The
+ # account number is not an institution id, but it is what identifies the connection, and
+ # `raw_payload` is only encrypted at rest when the deployment has ActiveRecord
+ # encryption configured — hence IBAN and balances are dropped here and live on the
+ # account row instead.
+ def upsert_fio_snapshot!(statement_info)
+ snapshot = statement_info.to_h.with_indifferent_access
+
+ assign_attributes(
+ institution_id: snapshot[:bankId].presence || institution_id,
+ raw_payload: snapshot.slice(:accountId, :bankId, :currency, :dateStart, :dateEnd)
+ )
+ save!
+ end
+
+ # The single Fio account reached by this item's token, once discovered.
+ def fio_account
+ fio_accounts.first
+ end
+
+ # True once the Fio account has been linked to a Sure account.
+ def has_completed_initial_setup?
+ accounts.any?
+ end
+
+ # Human-readable summary of linked vs. unlinked account counts.
+ def sync_status_summary
+ if total_accounts_count.zero?
+ I18n.t("fio_item.sync_status.no_accounts")
+ elsif unlinked_accounts_count.zero?
+ I18n.t("fio_item.sync_status.all_synced", count: linked_accounts_count)
+ else
+ I18n.t("fio_item.sync_status.partial", linked: linked_accounts_count, unlinked: unlinked_accounts_count)
+ end
+ end
+
+ # Number of Fio accounts linked to a Sure account.
+ def linked_accounts_count
+ account_counts[:linked]
+ end
+
+ # Number of unlinked Fio accounts still awaiting setup.
+ def unlinked_accounts_count
+ account_counts[:unlinked]
+ end
+
+ # Total number of Fio accounts under this item.
+ def total_accounts_count
+ account_counts[:total]
+ end
+
+ # Best available display name for the connected institution.
+ def institution_display_name
+ institution_name.presence || institution_domain.presence || name
+ end
+
+ # True when a token is present and the item can call the Fio API.
+ def credentials_configured?
+ token.present?
+ end
+
+ # The counts are memoized for the settings partial, which asks for all three while
+ # rendering one connection. A sync links an account midway through and then asks
+ # again, so the memo has to go when the record is reloaded.
+ def reload(*)
+ @account_counts = nil
+ super
+ end
+
+ private
+
+ def apply_institution_defaults
+ self.institution_name ||= FioAccount::INSTITUTION_NAME
+ self.institution_domain ||= FioAccount::INSTITUTION_DOMAIN
+ self.institution_url ||= "https://#{FioAccount::INSTITUTION_DOMAIN}"
+ end
+
+ # Single query for all three account counts, reused across sync_status_summary and
+ # the settings partial.
+ def account_counts
+ @account_counts ||= begin
+ rows = fio_accounts
+ .left_joins(:account_provider)
+ .pluck(Arel.sql("account_providers.id IS NOT NULL"), :ignored)
+
+ linked = rows.count { |has_provider, _ignored| has_provider }
+ unlinked = rows.count { |has_provider, ignored| !has_provider && !ignored }
+
+ { linked: linked, unlinked: unlinked, total: rows.size }
+ end
+ end
+end
diff --git a/app/models/fio_item/importer.rb b/app/models/fio_item/importer.rb
new file mode 100644
index 0000000000..cbb5f1ef2a
--- /dev/null
+++ b/app/models/fio_item/importer.rb
@@ -0,0 +1,303 @@
+# frozen_string_literal: true
+
+# Fetches one statement per sync and persists it raw.
+#
+# A Fio token may be used once per 30 seconds, so the window is chosen to need a single
+# request: from the day the last sync covered (minus an overlap) to today. The statement
+# header doubles as account discovery, so the first sync of a new connection creates the
+# `fio_accounts` row from the same response that brings the movements.
+#
+# Turning stored movements into entries is FioAccount::Processor's job.
+class FioItem::Importer
+ attr_reader :fio_item, :fio_provider
+
+ def initialize(fio_item, fio_provider:)
+ @fio_item = fio_item
+ @fio_provider = fio_provider
+ end
+
+ # Days of history a new connection reaches back on its first sync.
+ def self.initial_history_days
+ Rails.configuration.x.fio.initial_history_days
+ end
+
+ # Days before the last covered day that each subsequent sync re-reads.
+ def self.sync_lookback_days
+ Rails.configuration.x.fio.sync_lookback_days
+ end
+
+ # Returns a result hash with a `success` flag and per-entity counts. A throttled
+ # request (HTTP 409) defers to the next sync and keeps the connection healthy.
+ def import
+ Rails.logger.info "FioItem::Importer - Starting import for item #{fio_item.id}"
+
+ window = statement_window
+ statement = fetch_statement(from: window.first, to: window.last)
+ return @deferred_result if statement.nil?
+
+ info = statement[:info]
+ transactions = extract_transactions(statement)
+
+ if info.blank? && fio_account.nil?
+ # Nothing to describe the account with and nothing stored from a previous sync:
+ # a brand-new connection whose first window happens to be empty. The account is
+ # discovered by the next sync rather than invented here.
+ Rails.logger.info "FioItem::Importer - Statement carried no account header for item #{fio_item.id}"
+ return empty_result
+ end
+
+ return @deferred_result if reject_foreign_account!(info)
+
+ fio_item.upsert_fio_snapshot!(info) if info.present?
+
+ # A quiet range answers with an empty body and no header, so an established
+ # connection keeps the account it already discovered.
+ account = info.present? ? upsert_account!(info) : fio_account
+ created = info.present? && account.previously_new_record?
+
+ store_transactions(account, fresh_transactions: transactions)
+ account.update!(
+ transactions_synced_through: window.last,
+ history_synced_from: [ @served_from, account.history_synced_from ].compact.min
+ )
+
+ dump_raw(window: window, transactions: transactions)
+
+ Rails.logger.info(
+ "FioItem::Importer - Completed import for item #{fio_item.id}: " \
+ "#{transactions.size} movements in #{window.first}..#{window.last}"
+ )
+
+ {
+ success: true,
+ accounts_updated: created ? 0 : 1,
+ accounts_created: created ? 1 : 0,
+ accounts_failed: 0,
+ transactions_imported: transactions.size,
+ transactions_failed: 0
+ }
+ end
+
+ private
+
+ def fio_account
+ @fio_account ||= fio_item.fio_accounts.first
+ end
+
+ # The day the connection reaches back to: the user's start date, or the configured
+ # default when they have not chosen one.
+ #
+ # Once Fio has refused that range for want of a full-history unlock, the target stays
+ # inside the window it serves unauthorized. A sync has exactly one request to spend,
+ # and spending it on a period known to be refused would import nothing at all — the
+ # user unlocks and syncs deliberately, which clears the flag and reaches for the
+ # whole range again.
+ def target_start_date
+ requested = fio_account&.sync_start_date ||
+ fio_item.sync_start_date ||
+ (Date.current - self.class.initial_history_days.days)
+
+ return requested if fio_item.history_unlock_required_at.blank?
+
+ [ requested, Date.current - (Provider::Fio::UNAUTHORIZED_HISTORY_DAYS - 1).days ].max
+ end
+
+ # The window to request, ending today.
+ #
+ # Fio books a movement under its banking date, which can be a day or two behind the
+ # day it becomes visible, so a sync re-reads `sync_lookback_days` before the last
+ # covered day instead of resuming exactly where it stopped. Re-reading costs nothing:
+ # movements carry stable ids and collapse onto the entries they already produced.
+ #
+ # Until the history reaches back to the start date the whole range is requested
+ # instead, so a backfill that Fio refused for want of an unlock is retried on the
+ # next sync rather than being silently abandoned.
+ def statement_window
+ today = Date.current
+ target = target_start_date
+ covered_through = fio_account&.transactions_synced_through
+ history_from = fio_account&.history_synced_from
+
+ # Both cursors are written by the same update, so a missing history marker means
+ # this connection has never fetched anything rather than an unfinished backfill.
+ from =
+ if covered_through.blank? || (history_from.present? && history_from > target)
+ target
+ else
+ [ covered_through - self.class.sync_lookback_days.days, target ].max
+ end
+
+ from = today if from > today
+
+ from..today
+ end
+
+ # Performs the request, classifying the failures Fio documents. Returns nil when the
+ # sync could not fetch anything, having set @deferred_result. `@served_from` records
+ # the start of the window Fio answered, which is what the history cursor is allowed
+ # to claim as covered.
+ def fetch_statement(from:, to:)
+ statement = fio_provider.get_statement(from: from, to: to)
+ @served_from = from
+ statement
+ rescue Provider::Fio::RateLimitError => e
+ # One request per 30 seconds per token. A manual sync landing right after a
+ # scheduled one collides legitimately: nothing was fetched, the connection is
+ # healthy, the next sync picks it up.
+ capture_sync_error("Fio statement request was throttled", e, level: "warn", error_type: e.failure_code)
+ @deferred_result = empty_result
+ nil
+ rescue Provider::Fio::HistoryLockedError => e
+ # The range reaches past the 90 days Fio serves without a temporary full-history
+ # unlock. Retrying clamped right here would be a second use of the same token
+ # inside its 30-second interval, which Fio answers with 409 — so the clamp is
+ # persisted and the next sync spends its request on a window that will be served.
+ fio_item.update!(history_unlock_required_at: Time.current)
+ capture_sync_error(
+ "Fio refused the statement period pending a full-history unlock",
+ e,
+ error_type: e.failure_code,
+ extra_metadata: { requested_from: from.iso8601 }
+ )
+ @deferred_result = failed_result(I18n.t("fio_item.errors.history_locked"))
+ nil
+ rescue Provider::Fio::TooManyItemsError => e
+ capture_sync_error("Fio statement exceeded the per-request movement limit", e, error_type: e.failure_code)
+ @deferred_result = failed_result(I18n.t("fio_item.errors.statement_too_large"))
+ nil
+ rescue Provider::Fio::Error => e
+ mark_requires_update! if e.failure_code == :unauthorized
+ capture_sync_error("Failed to fetch Fio statement", e, error_type: e.failure_code)
+ @deferred_result = failed_result(I18n.t("fio_item.errors.statement_fetch_failed"))
+ nil
+ end
+
+ def extract_transactions(statement)
+ list = statement.dig(:transactionList, :transaction)
+ Array(list).select { |transaction| transaction.is_a?(Hash) }
+ end
+
+ # A connection stands for one token, and a token for one account, so a statement
+ # naming a different account than the one already stored means the token was
+ # replaced with one for another account. Reusing the row would hand the linked Sure
+ # account someone else's balance and movements, so the sync refuses instead; the
+ # user gets a second connection for the second account.
+ def reject_foreign_account!(info)
+ return false if info.blank?
+
+ stored = fio_account&.fio_account_id
+ incoming = info[:accountId].presence&.to_s
+ return false if stored.blank? || incoming.blank? || stored == incoming
+
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Fio token resolves to a different account than this connection",
+ source: self.class.name,
+ provider_key: "fio",
+ family: fio_item.family,
+ account_provider: fio_account&.account_provider,
+ metadata: { fio_item_id: fio_item.id, fio_account_id: fio_account&.id }
+ )
+
+ @deferred_result = failed_result(I18n.t("fio_item.errors.account_mismatch"))
+ true
+ end
+
+ # Creates the account row on first sight, updates the header afterwards. Discovery
+ # never creates a Sure account: linking is the user's decision, made in setup.
+ def upsert_account!(info)
+ account_number = info[:accountId].presence&.to_s
+ account = fio_item.fio_accounts.find_by(fio_account_id: account_number) ||
+ fio_account ||
+ fio_item.fio_accounts.new(currency: info[:currency], name: "")
+
+ account.upsert_fio_snapshot!(info)
+ @fio_account = account
+ end
+
+ # Merges the fetched movements into the stored payload, keyed by movement id, and
+ # saves only when something changed.
+ def store_transactions(account, fresh_transactions:)
+ existing = account.raw_transactions_payload.to_a
+
+ by_id = {}
+ (existing + fresh_transactions).each do |transaction|
+ next unless transaction.is_a?(Hash)
+
+ key = FioEntry::Processor.canonical_external_id(transaction)
+ by_id[key] = transaction if key.present?
+ end
+
+ final_transactions = by_id.values
+ return if final_transactions == existing
+
+ Rails.logger.info(
+ "FioItem::Importer - Storing #{final_transactions.count} movements " \
+ "(#{existing.count} existing) for account #{account.id}"
+ )
+ account.upsert_fio_transactions_snapshot!(final_transactions)
+ end
+
+ # Local-only raw dump. The payload carries counterparty names, account numbers and
+ # payment messages, so it never runs outside development.
+ def dump_raw(window:, transactions:)
+ return unless Rails.configuration.x.fio.debug_raw && Rails.env.local?
+
+ Rails.logger.info(
+ "FioItem::Importer - Raw Fio statement #{window.first}..#{window.last}: #{transactions.inspect}"
+ )
+ end
+
+ def capture_sync_error(message, error, error_type: nil, level: "error", extra_metadata: {})
+ metadata = { fio_item_id: fio_item.id, error_class: error.class.name, error_message: error.message }
+ metadata[:fio_account_id] = fio_account.id if fio_account
+ metadata[:error_type] = error_type if error_type
+ metadata.merge!(extra_metadata)
+
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: level,
+ message: message,
+ source: self.class.name,
+ provider_key: "fio",
+ family: fio_item.family,
+ account_provider: fio_account&.account_provider,
+ metadata: metadata
+ )
+ end
+
+ # Flag the item as needing a new token, swallowing update errors. A failure here
+ # means the connection keeps showing as healthy after its token was rejected, so it
+ # is recorded where support can find it rather than only in the app log.
+ def mark_requires_update!
+ fio_item.update!(status: :requires_update)
+ rescue => e
+ Rails.logger.error "FioItem::Importer - Failed to update item status: #{e.class}"
+ capture_sync_error("Failed to flag connection as requiring a new token", e)
+ end
+
+ # Nothing fetched, nothing broken: the next sync tries again.
+ def empty_result
+ {
+ success: true,
+ accounts_updated: 0,
+ accounts_created: 0,
+ accounts_failed: 0,
+ transactions_imported: 0,
+ transactions_failed: 0
+ }
+ end
+
+ def failed_result(error)
+ {
+ success: false,
+ error: error,
+ accounts_updated: 0,
+ accounts_created: 0,
+ accounts_failed: 1,
+ transactions_imported: 0,
+ transactions_failed: 0
+ }
+ end
+end
diff --git a/app/models/fio_item/provided.rb b/app/models/fio_item/provided.rb
new file mode 100644
index 0000000000..85692bf942
--- /dev/null
+++ b/app/models/fio_item/provided.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module FioItem::Provided
+ extend ActiveSupport::Concern
+
+ def fio_provider
+ return nil unless credentials_configured?
+
+ Provider::Fio.new(token)
+ end
+
+ def syncer
+ FioItem::Syncer.new(self)
+ end
+end
diff --git a/app/models/fio_item/sync_complete_event.rb b/app/models/fio_item/sync_complete_event.rb
new file mode 100644
index 0000000000..509aac343f
--- /dev/null
+++ b/app/models/fio_item/sync_complete_event.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+class FioItem::SyncCompleteEvent
+ attr_reader :fio_item
+
+ def initialize(fio_item)
+ @fio_item = fio_item
+ end
+
+ # Broadcast sync-complete Turbo updates for the item, its accounts, and family.
+ def broadcast
+ fio_item.accounts.each(&:broadcast_sync_complete)
+
+ fio_item.broadcast_replace_to(
+ fio_item.family,
+ target: "fio_item_#{fio_item.id}",
+ partial: "fio_items/fio_item",
+ locals: { fio_item: fio_item }
+ )
+
+ fio_item.family.broadcast_sync_complete
+ end
+end
diff --git a/app/models/fio_item/syncer.rb b/app/models/fio_item/syncer.rb
new file mode 100644
index 0000000000..d40c083013
--- /dev/null
+++ b/app/models/fio_item/syncer.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+class FioItem::Syncer
+ include SyncStats::Collector
+
+ SafeSyncError = Class.new(StandardError)
+
+ # Error carrying the structured per-stage sync errors for health reporting.
+ class SyncError < StandardError
+ attr_reader :sync_errors
+
+ def initialize(message, sync_errors:)
+ super(message)
+ @sync_errors = sync_errors
+ end
+ end
+
+ attr_reader :fio_item
+
+ def initialize(fio_item)
+ @fio_item = fio_item
+ end
+
+ # Run the full sync: import, account setup detection, transaction processing, balance
+ # sync scheduling, and stats/health collection. Raises on failures.
+ def perform_sync(sync)
+ sync.update!(status_text: I18n.t("fio_item.sync.status.importing")) if sync.respond_to?(:status_text)
+ import_result = fio_item.import_latest_fio_data
+ raise_if_failed_result!(import_result, stage: "Fio import")
+
+ sync.update!(status_text: I18n.t("fio_item.sync.status.checking_setup")) if sync.respond_to?(:status_text)
+ collect_setup_stats(sync, provider_accounts: fio_item.fio_accounts)
+ # The collector derives unlinked as total minus linked, which counts an account the
+ # user skipped during setup as outstanding work. FioItem's own counts exclude it, and
+ # the status summary reads these stats in preference to them, so it would otherwise
+ # keep reporting setup the user has already declined.
+ merge_sync_stats(sync, "unlinked_accounts" => fio_item.unlinked_accounts_count)
+
+ linked_accounts = fio_item.fio_accounts.joins(:account_provider)
+ unlinked_accounts = fio_item.fio_accounts.needs_setup
+
+ if unlinked_accounts.any?
+ fio_item.update!(pending_account_setup: true)
+ sync.update!(status_text: I18n.t("fio_item.sync.status.needs_setup", count: unlinked_accounts.count)) if sync.respond_to?(:status_text)
+ else
+ fio_item.update!(pending_account_setup: false)
+ end
+
+ if linked_accounts.any?
+ sync.update!(status_text: I18n.t("fio_item.sync.status.processing")) if sync.respond_to?(:status_text)
+ mark_import_started(sync)
+ process_results = fio_item.process_accounts
+ raise_if_failed_results!(process_results, stage: "Fio account processing")
+
+ sync.update!(status_text: I18n.t("fio_item.sync.status.calculating")) if sync.respond_to?(:status_text)
+ schedule_results = fio_item.schedule_account_syncs(
+ parent_sync: sync,
+ window_start_date: sync.window_start_date,
+ window_end_date: sync.window_end_date
+ )
+ raise_if_failed_results!(schedule_results, stage: "Fio account sync scheduling")
+
+ account_ids = linked_accounts.includes(:account_provider).filter_map { |fa| fa.current_account&.id }
+ collect_transaction_stats(sync, account_ids: account_ids, source: "fio")
+ else
+ Rails.logger.info "FioItem::Syncer - No linked accounts to process"
+ end
+
+ collect_health_stats(sync, errors: nil)
+ rescue SyncError => e
+ collect_health_stats(sync, errors: e.sync_errors)
+ raise
+ rescue => e
+ safe_message = I18n.t("fio_item.errors.sync_failed")
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Unexpected sync error",
+ source: self.class.name,
+ provider_key: "fio",
+ family: fio_item.family,
+ metadata: { fio_item_id: fio_item.id, error_class: e.class.name, error_message: e.message }
+ )
+ collect_health_stats(sync, errors: [ { message: safe_message, category: "sync_error" } ])
+ raise SafeSyncError.new(safe_message), cause: nil
+ end
+
+ # Post-sync hook (no work required for Fio).
+ def perform_post_sync
+ # no-op
+ end
+
+ private
+
+ # Raise a SyncError if a single result hash indicates failure.
+ def raise_if_failed_result!(result, stage:)
+ return unless failed_result?(result)
+
+ errors = errors_from_result(result, stage: stage)
+ raise SyncError.new(error_message(stage, errors), sync_errors: errors)
+ end
+
+ # Raise a SyncError if any result in the collection indicates failure.
+ def raise_if_failed_results!(results, stage:)
+ errors = Array(results).filter_map do |result|
+ next unless failed_result?(result)
+
+ errors_from_result(result, stage: stage).first
+ end
+
+ return if errors.empty?
+
+ raise SyncError.new(error_message(stage, errors), sync_errors: errors)
+ end
+
+ # True when +result+ is a hash explicitly flagged success: false.
+ def failed_result?(result)
+ result.is_a?(Hash) && result.with_indifferent_access[:success] == false
+ end
+
+ # Normalize a failed result into an array of { message:, category: } errors.
+ def errors_from_result(result, stage:)
+ data = result.with_indifferent_access
+ messages = []
+ messages << data[:error] if data[:error].present?
+ messages << "#{data[:accounts_failed]} accounts failed" if data[:accounts_failed].to_i.positive?
+ messages << "#{data[:transactions_failed]} transactions failed" if data[:transactions_failed].to_i.positive?
+ messages.concat(Array(data[:errors]).map { |error| error_message_value(error) }.compact)
+ messages << "#{stage} failed" if messages.empty?
+
+ messages.map { |message| { message: "#{stage}: #{message}", category: "sync_error" } }
+ end
+
+ # Join the error messages into a single stage summary string.
+ def error_message(stage, errors)
+ messages = errors.map { |error| error[:message] || error["message"] }.compact
+ messages.presence&.join(", ") || "#{stage} failed"
+ end
+
+ # Extract a human-readable message from a heterogeneous error value.
+ def error_message_value(error)
+ return error[:message].presence || error["message"].presence || error[:error].presence || error["error"].presence if error.is_a?(Hash)
+
+ error.to_s.presence
+ end
+end
diff --git a/app/models/fio_item/unlinking.rb b/app/models/fio_item/unlinking.rb
new file mode 100644
index 0000000000..ba3e2176fe
--- /dev/null
+++ b/app/models/fio_item/unlinking.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module FioItem::Unlinking
+ # Concern that encapsulates unlinking logic for a Fio item.
+ extend ActiveSupport::Concern
+
+ # Idempotently remove all connections between this Fio item and local accounts.
+ # - Detaches any AccountProvider links for each FioAccount
+ # - Detaches Holdings that point at the AccountProvider links
+ # Returns a per-account result payload for observability
+ def unlink_all!(dry_run: false)
+ results = []
+
+ fio_accounts.find_each do |provider_account|
+ links = AccountProvider.where(provider_type: "FioAccount", provider_id: provider_account.id).to_a
+ link_ids = links.map(&:id)
+ result = {
+ provider_account_id: provider_account.id,
+ name: provider_account.name,
+ provider_link_ids: link_ids
+ }
+ results << result
+
+ next if dry_run
+
+ begin
+ ActiveRecord::Base.transaction do
+ # Detach holdings for any provider links found
+ if link_ids.any?
+ Holding.where(account_provider_id: link_ids).update_all(account_provider_id: nil)
+ end
+
+ # Destroy all provider links
+ links.each do |ap|
+ ap.destroy!
+ end
+ end
+ rescue StandardError => e
+ Rails.logger.warn(
+ "FioItem Unlinker: failed to fully unlink provider account ##{provider_account.id} (links=#{link_ids.inspect}): #{e.class} - #{e.message}"
+ )
+ # Record error for observability; continue with other accounts
+ result[:error] = e.message
+ end
+ end
+
+ results
+ end
+end
diff --git a/app/models/provider/fio.rb b/app/models/provider/fio.rb
new file mode 100644
index 0000000000..6a49808b51
--- /dev/null
+++ b/app/models/provider/fio.rb
@@ -0,0 +1,273 @@
+# frozen_string_literal: true
+
+# Client for Fio banka's "API Bankovnictví" (v1.9, https://www.fio.cz/docs/cz/API_Bankovnictvi.pdf).
+#
+# Two properties of this API shape everything above it:
+#
+# * A token grants access to exactly **one** account, and there is no endpoint that
+# lists accounts. The statement header (`accountStatement.info`) *is* the account
+# description, so a fetch doubles as account discovery.
+# * A token may be used **once per 30 seconds**, for reading or writing, regardless of
+# format. Exceeding that is HTTP 409. One statement request per sync therefore is not
+# an optimisation but the design constraint.
+#
+# The token travels in the URL path, not a header. Nothing here may put a resolved URL
+# into an exception message, a log line or debug metadata.
+class Provider::Fio < Provider
+ include HTTParty
+ extend SslConfigurable
+
+ # Subclass so errors caught in this provider are raised as Provider::Fio::Error
+ Error = Class.new(Provider::Error)
+ # 409: the 30-second interval was not respected. Nothing to do but sync again later.
+ class RateLimitError < Error; end
+ # 422: the requested range reaches further back than 90 days and the account's full
+ # history has not been unlocked in internet banking.
+ class HistoryLockedError < Error; end
+ # 413: more than 50 000 movements in the requested range.
+ class TooManyItemsError < Error; end
+
+ DEFAULT_BASE_URL = "https://fioapi.fio.cz/v1/rest".freeze
+ ALLOWED_HOST = URI.parse(DEFAULT_BASE_URL).host.freeze
+
+ # Days of history reachable without a temporary unlock in internet banking.
+ UNAUTHORIZED_HISTORY_DAYS = 90
+
+ # Documented minimum interval between two uses of one token. Enforced by Fio, not here:
+ # a sleeping client-side timer would have to outlive the job to be of any use, and a
+ # sync only ever spends one request. Callers treat RateLimitError as "try next sync".
+ MIN_REQUEST_INTERVAL = 30.0
+
+ headers "User-Agent" => "Sure Finance Fio Client (https://github.com/we-promise/sure)"
+ default_options.merge!({ timeout: 120 }.merge(httparty_ssl_options))
+
+ RETRYABLE_ERRORS = [
+ SocketError,
+ Net::OpenTimeout,
+ Net::ReadTimeout,
+ Errno::ECONNRESET,
+ Errno::ECONNREFUSED,
+ Errno::ETIMEDOUT,
+ EOFError
+ ].freeze
+
+ MAX_RETRIES = 3
+ INITIAL_RETRY_DELAY = 2 # seconds
+
+ attr_reader :token
+
+ def initialize(token)
+ @token = token.to_s.strip
+
+ if @token.blank?
+ raise Error.new("Fio token is required", failure_code: :configuration_error)
+ end
+ end
+
+ # Movements booked between `from` and `to`, with the statement header describing the
+ # account the token belongs to.
+ #
+ # Both bounds are inclusive banking days. Unlike `/last/`, this endpoint does not touch
+ # the server-side download marker ("zarážka"), so a failed or partial import can simply
+ # be repeated — the caller keeps its own cursor.
+ #
+ # @param from [Date] first booking day to include
+ # @param to [Date] last booking day to include
+ # @return [Hash] the `accountStatement` object: `"info"` plus `"transactionList"`
+ def get_statement(from:, to: Date.current)
+ from_date = to_date(from)
+ to_date_value = to_date(to)
+
+ if from_date > to_date_value
+ raise Error.new("Fio statement range ends before it starts", failure_code: :bad_request)
+ end
+
+ body = get("periods/#{token}/#{path_segment(from_date)}/#{path_segment(to_date_value)}/transactions.json",
+ operation: "GET periods")
+
+ # A range with no movements can answer 200 with an empty body rather than a header
+ # and an empty transactionList.
+ return {}.with_indifferent_access if body.blank?
+
+ statement = body.is_a?(Hash) ? body["accountStatement"] : nil
+
+ unless statement.is_a?(Hash)
+ capture_request_error(
+ level: "error",
+ message: "Fio statement response had no accountStatement object",
+ operation: "GET periods"
+ )
+ raise Error.new("Unexpected Fio statement response", failure_code: :parse_error)
+ end
+
+ statement.with_indifferent_access
+ end
+
+ private
+
+ # Builds the token-bearing URL and performs the request. `operation` is a static
+ # label: it reaches diagnostics, so it must never carry the path.
+ def get(path, operation:)
+ with_retries(operation) do
+ response = self.class.get(resolve_url(path), headers: request_headers)
+ handle_response(response, operation: operation)
+ end
+ end
+
+ # Resolves a relative path against the base URL, refusing to send the token anywhere
+ # but Fio's HTTPS host. The token sits inside `path`: Fio places it after the
+ # endpoint name, not before it (`/v1/rest/periods/{token}/{from}/{to}/…`).
+ def resolve_url(path)
+ "#{DEFAULT_BASE_URL}/#{path}".tap do |url|
+ uri = URI.parse(url)
+ unless uri.scheme == "https" && uri.host == ALLOWED_HOST
+ raise Error.new("Refusing to send credentials to untrusted host", failure_code: :invalid_url)
+ end
+ end
+ rescue URI::InvalidURIError
+ raise Error.new("Invalid Fio API URL", failure_code: :invalid_url)
+ end
+
+ def request_headers
+ { "Accept" => "application/json" }
+ end
+
+ def path_segment(date)
+ date.strftime("%Y-%m-%d")
+ end
+
+ def to_date(value)
+ case value
+ when Date then value
+ when Time, DateTime then value.to_date
+ when String then Date.parse(value)
+ else
+ raise Error.new("Unsupported Fio statement date", failure_code: :bad_request)
+ end
+ rescue ArgumentError, TypeError
+ raise Error.new("Unsupported Fio statement date", failure_code: :bad_request)
+ end
+
+ # Runs the block, retrying transient network errors with exponential backoff.
+ def with_retries(operation_name, max_retries: MAX_RETRIES)
+ retries = 0
+
+ begin
+ yield
+ rescue *RETRYABLE_ERRORS => e
+ retries += 1
+ if retries <= max_retries
+ delay = calculate_retry_delay(retries)
+ capture_request_error(
+ category: "provider_sync",
+ level: "warn",
+ message: "Fio API request will be retried",
+ operation: operation_name,
+ metadata: {
+ error_class: e.class.name,
+ retry_attempt: retries,
+ retry_limit: max_retries,
+ retry_delay: delay.round(2)
+ }
+ )
+ Rails.logger.warn(
+ "Fio API: #{operation_name} failed (attempt #{retries}/#{max_retries}): " \
+ "#{e.class}. Retrying in #{delay.round(2)}s..."
+ )
+ sleep(delay)
+ retry
+ end
+
+ capture_request_error(
+ level: "error",
+ message: "Fio API request failed after retries",
+ operation: operation_name,
+ metadata: { error_class: e.class.name, retry_limit: max_retries }
+ )
+ raise Error.new("Network error after #{max_retries} retries: #{e.message}", failure_code: :network_error)
+ end
+ end
+
+ # Exponential backoff delay (with jitter), capped at 30 seconds.
+ def calculate_retry_delay(retry_count)
+ base_delay = INITIAL_RETRY_DELAY * (2 ** (retry_count - 1))
+ jitter = base_delay * rand * 0.25
+ [ base_delay + jitter, 30 ].min
+ end
+
+ # Maps an HTTP response to parsed data or a typed error. Status codes follow section 8
+ # of the API documentation and are mostly not what their HTTP meaning suggests: 500 is
+ # an unknown or expired token, and 404 is a malformed request rather than a missing
+ # account.
+ def handle_response(response, operation: nil)
+ case response.code
+ when 200, 201
+ parse_response_body(response, operation: operation)
+ when 204
+ {}
+ when 404
+ raise Error.new("Fio rejected the request URL", failure_code: :bad_request)
+ when 409
+ raise RateLimitError.new(
+ "Fio allows one request per 30 seconds per token",
+ failure_code: :rate_limited
+ )
+ when 413
+ raise TooManyItemsError.new(
+ "Fio statement exceeds the 50 000 movement limit for one request",
+ failure_code: :too_many_items
+ )
+ when 422
+ raise HistoryLockedError.new(
+ "Fio movements older than #{UNAUTHORIZED_HISTORY_DAYS} days need the account's " \
+ "full history unlocked in internet banking",
+ failure_code: :history_locked
+ )
+ when 500
+ # Documented as "nonexistent or inactive token", which is an authorization
+ # failure the user has to fix, not a transient server fault.
+ raise Error.new("Fio token is unknown or no longer valid", failure_code: :unauthorized)
+ when 501..599
+ raise Error.new("Fio server error (#{response.code}). Please try again later.", failure_code: :server_error)
+ else
+ capture_request_error(
+ level: "error",
+ message: "Fio API returned an unexpected response status",
+ operation: operation,
+ metadata: { status: response.code }
+ )
+ raise Error.new("Failed to fetch Fio data", failure_code: :fetch_failed)
+ end
+ end
+
+ def parse_response_body(response, operation: nil)
+ # A statement request whose range contains no movements answers 200 with an empty
+ # body rather than an empty transactionList.
+ return {} if response.body.blank?
+
+ JSON.parse(response.body)
+ rescue JSON::ParserError
+ capture_request_error(
+ level: "error",
+ message: "Fio API response could not be parsed",
+ operation: operation,
+ metadata: { status: response.code, body_bytes: response.body.bytesize }
+ )
+ raise Error.new("Failed to parse Fio API response", failure_code: :parse_error)
+ end
+
+ # Transport-level diagnostics for /settings/debug. The client is built from a token
+ # alone, so it has no family or account_provider to attach — FioItem::Importer records
+ # the same failure against the connection. Neither the URL (it contains the token) nor
+ # the body (statement PII) is ever included.
+ def capture_request_error(level:, message:, operation:, category: "provider_sync_error", metadata: {})
+ DebugLogEntry.capture(
+ category: category,
+ level: level,
+ message: message,
+ source: self.class.name,
+ provider_key: "fio",
+ metadata: metadata.merge(operation: operation).compact
+ )
+ end
+end
diff --git a/app/models/provider/fio_adapter.rb b/app/models/provider/fio_adapter.rb
new file mode 100644
index 0000000000..0f3f8d1d44
--- /dev/null
+++ b/app/models/provider/fio_adapter.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+class Provider::FioAdapter < Provider::Base
+ include Provider::Syncable
+ include Provider::InstitutionMetadata
+
+ Provider::Factory.register("FioAccount", self)
+
+ # Fio's statement header carries no account type, so the user picks one during setup.
+ # Current and savings accounts are Depository; a token issued for a mortgage, loan or
+ # overdraft account is a Loan, whose balance Fio reports negative (see
+ # FioAccount::Processor#update_account_balance).
+ def self.supported_account_types
+ %w[Depository Loan]
+ end
+
+ # Connection config hashes for each of the family's configured Fio items. One item per
+ # token, and a token reaches exactly one account, so a family with three Fio accounts
+ # has three items.
+ def self.connection_configs(family:)
+ return [] unless family.can_connect_fio?
+
+ family.fio_items.active.ordered.select(&:credentials_configured?).map do |fio_item|
+ connection_config_for(fio_item)
+ end
+ end
+
+ # Build a Fio API client for the resolved item, or nil if none is usable.
+ def self.build_provider(family: nil, fio_item_id: nil)
+ return nil unless family.present?
+
+ fio_item = resolve_fio_item(family, fio_item_id)
+ return nil unless fio_item&.credentials_configured?
+
+ Provider::Fio.new(fio_item.token)
+ end
+
+ # Build the settings connection-config hash for a single Fio item.
+ def self.connection_config_for(fio_item)
+ path_params = ->(extra = {}) { extra.merge(fio_item_id: fio_item.id) }
+
+ {
+ key: "fio_#{fio_item.id}",
+ name: fio_item.name.presence || I18n.t("providers.fio.name"),
+ description: I18n.t("providers.fio.description"),
+ can_connect: true,
+ new_account_path: ->(accountable_type, return_to) {
+ Rails.application.routes.url_helpers.select_accounts_fio_items_path(
+ path_params.call(accountable_type: accountable_type, return_to: return_to)
+ )
+ },
+ existing_account_path: ->(account_id) {
+ Rails.application.routes.url_helpers.select_existing_account_fio_items_path(
+ path_params.call(account_id: account_id)
+ )
+ }
+ }
+ end
+ private_class_method :connection_config_for
+
+ # Provider key used across the sync/account-provider machinery.
+ def provider_name
+ "fio"
+ end
+
+ # Route to trigger a manual sync for this provider account's item.
+ def sync_path
+ Rails.application.routes.url_helpers.sync_fio_item_path(item)
+ end
+
+ # The FioItem backing this provider account.
+ def item
+ provider_account.fio_item
+ end
+
+ # Fio reports no holdings.
+ def can_delete_holdings?
+ false
+ end
+
+ def institution_domain
+ provider_account.institution_metadata&.dig("domain") || item&.institution_domain
+ end
+
+ def institution_name
+ provider_account.institution_metadata&.dig("name") || item&.institution_name
+ end
+
+ def institution_url
+ provider_account.institution_metadata&.dig("url") || item&.institution_url
+ end
+
+ def institution_color
+ item&.institution_color
+ end
+
+ # Resolve the target Fio item.
+ #
+ # A requested id is authoritative: unlike an aggregator, where one item covers every
+ # account, a Fio item is one token for one account, so a family routinely has several.
+ # Falling back to another connection would silently build a client for the wrong
+ # account. Only an absent id picks the first configured connection.
+ def self.resolve_fio_item(family, fio_item_id)
+ if fio_item_id.present?
+ item = family.fio_items.active.find_by(id: fio_item_id)
+ return item&.credentials_configured? ? item : nil
+ end
+
+ family.fio_items.active.ordered.find(&:credentials_configured?)
+ end
+ private_class_method :resolve_fio_item
+end
diff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rb
index 1e1b586298..e956af53fd 100644
--- a/app/models/provider/metadata.rb
+++ b/app/models/provider/metadata.rb
@@ -6,6 +6,7 @@ class Provider
lunchflow: { region: "Global", kinds: %w[Bank], maturity: :stable, logo_text: "LF", logo_color: "#f97316", domain: "lunchflow.app" },
up: { region: "AU", kinds: %w[Bank], maturity: :beta, logo_text: "UP", logo_color: "#ea580c", domain: "up.com.au" },
monobank: { region: "UA", kinds: %w[Bank], maturity: :alpha, logo_text: "MB", logo_color: "#111827", domain: "monobank.ua" },
+ fio: { region: "CZ", kinds: %w[Bank], maturity: :alpha, logo_text: "FI", logo_color: "#1d4ed8", domain: "fio.cz", name: "Fio banka" },
enable_banking: { region: "EU", kinds: %w[Bank], maturity: :beta, logo_text: "EB", logo_color: "#9333ea", domain: "enablebanking.com" },
coinstats: { region: "Global", kinds: %w[Crypto], maturity: :beta, logo_text: "CS", logo_color: "#db2777", domain: "coinstats.app" },
wise: { region: "Global", kinds: %w[Bank], maturity: :beta, logo_text: "WI", logo_color: "#22c55e", domain: "wise.com" },
diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rb
index cbc6a09292..c562d46386 100644
--- a/app/models/provider_connection_status.rb
+++ b/app/models/provider_connection_status.rb
@@ -5,6 +5,7 @@ class ProviderConnectionStatus
{ key: "akahu", type: "AkahuItem", association: :akahu_items, accounts: :akahu_accounts },
{ key: "up", type: "UpItem", association: :up_items, accounts: :up_accounts },
{ key: "monobank", type: "MonobankItem", association: :monobank_items, accounts: :monobank_accounts },
+ { key: "fio", type: "FioItem", association: :fio_items, accounts: :fio_accounts },
{ key: "plaid", type: "PlaidItem", association: :plaid_items, accounts: :plaid_accounts },
{ key: "simplefin", type: "SimplefinItem", association: :simplefin_items, accounts: :simplefin_accounts },
{ key: "lunchflow", type: "LunchflowItem", association: :lunchflow_items, accounts: :lunchflow_accounts },
diff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rb
index 8e24566129..ce27634eb3 100644
--- a/app/models/provider_merchant.rb
+++ b/app/models/provider_merchant.rb
@@ -1,5 +1,5 @@
class ProviderMerchant < Merchant
- enum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", monobank: "monobank", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade", redbark: "redbark" }
+ enum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", monobank: "monobank", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade", redbark: "redbark", fio: "fio" }
validates :name, uniqueness: { scope: [ :source ] }
validates :source, presence: true
diff --git a/app/views/accounts/index.html.erb b/app/views/accounts/index.html.erb
index 2d8e40b347..3a2b228ba4 100644
--- a/app/views/accounts/index.html.erb
+++ b/app/views/accounts/index.html.erb
@@ -10,7 +10,7 @@
) %>
<% end %>
-<% if @manual_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_items.empty? && @monobank_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @kraken_items.empty? && @coinspot_items.empty? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? && @trading212_items.empty? %>
+<% if @manual_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_items.empty? && @monobank_items.empty? && @fio_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @kraken_items.empty? && @coinspot_items.empty? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? && @trading212_items.empty? %>
<%= render "empty" %>
<% else %>
<div class="space-y-2">
@@ -116,6 +116,10 @@
<%= render @questrade_items.sort_by(&:created_at) %>
<% end %>
+ <% if @fio_items.any? %>
+ <%= render @fio_items.sort_by(&:created_at) %>
+ <% end %>
+
<% if @manual_accounts.any? %>
<div id="manual-accounts">
<%= render "accounts/index/manual_accounts", accounts: @manual_accounts %>
diff --git a/app/views/fio_items/_fio_item.html.erb b/app/views/fio_items/_fio_item.html.erb
new file mode 100644
index 0000000000..c22c9591b7
--- /dev/null
+++ b/app/views/fio_items/_fio_item.html.erb
@@ -0,0 +1,124 @@
+<%# locals: (fio_item:) %>
+
+<%= tag.div id: dom_id(fio_item) do %>
+ <%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center justify-between gap-2 w-full">
+ <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 bg-surface rounded-full">
+ <p class="text-primary text-xs font-medium"><%= fio_item.name.to_s.first.to_s.upcase %></p>
+ </div>
+
+ <div class="pl-1 text-sm">
+ <div class="flex items-center gap-2">
+ <%= tag.p fio_item.name, class: "font-medium text-primary" %>
+ <% if fio_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"><%= fio_item.institution_display_name %></p>
+
+ <% if fio_item.syncing? %>
+ <div class="text-secondary flex items-center gap-1">
+ <%= icon "loader", size: "sm", class: "animate-spin" %>
+ <%= tag.span t(".syncing") %>
+ </div>
+ <% elsif fio_item.requires_update? %>
+ <div class="flex items-center gap-1">
+ <%= icon "alert-triangle", size: "sm", color: "warning" %>
+ <%= tag.span t(".requires_update"), class: "text-warning" %>
+ </div>
+ <% elsif fio_item.sync_error.present? %>
+ <div class="text-secondary flex items-center gap-1">
+ <%= render DS::Tooltip.new(text: fio_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 fio_item.last_synced_at %>
+ <%= t(".status_with_summary", timestamp: time_ago_in_words(fio_item.last_synced_at), summary: fio_item.sync_status_summary) %>
+ <% else %>
+ <%= t(".status_never") %>
+ <% end %>
+ </p>
+ <% end %>
+ </div>
+ </div>
+
+ <% if Current.user&.admin? %>
+ <div class="flex items-center gap-2">
+ <%= render DS::Menu.new do |menu| %>
+ <% menu.with_item(
+ variant: "button",
+ text: t(".delete"),
+ icon: "trash-2",
+ href: fio_item_path(fio_item),
+ method: :delete,
+ confirm: CustomConfirm.for_resource_deletion(fio_item.name, high_severity: true)
+ ) %>
+ <% end %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+
+ <% unless fio_item.scheduled_for_deletion? %>
+ <div class="space-y-4 mt-4">
+ <% if fio_item.accounts.any? %>
+ <%= render "accounts/index/account_groups", accounts: fio_item.accounts %>
+ <% end %>
+
+ <%# The accounts index preloads one stats row per item; a standalone render (the %>
+ <%# sync-complete broadcast) has to look it up itself. %>
+ <% stats = if defined?(@fio_sync_stats_map) && @fio_sync_stats_map
+ @fio_sync_stats_map[fio_item.id] || {}
+ else
+ fio_item.latest_sync_record&.sync_stats || {}
+ end %>
+ <%= render ProviderSyncSummary.new(stats: stats, provider_item: fio_item) %>
+
+ <% if fio_item.requires_update? %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".requires_update_title") %></p>
+ <p class="text-secondary text-sm"><%= t(".requires_update_description") %></p>
+ <%= render DS::Link.new(
+ text: t(".update_token"),
+ icon: "key-round",
+ variant: "primary",
+ href: settings_providers_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% elsif fio_item.unlinked_accounts_count > 0 %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".setup_needed") %></p>
+ <p class="text-secondary text-sm"><%= t(".setup_description") %></p>
+ <%= render DS::Link.new(
+ text: t(".setup_action"),
+ icon: "settings",
+ variant: "primary",
+ href: setup_accounts_fio_item_path(fio_item),
+ frame: :modal
+ ) %>
+ </div>
+ <% elsif fio_item.total_accounts_count.zero? %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".no_accounts_title") %></p>
+ <p class="text-secondary text-sm"><%= t(".no_accounts_description") %></p>
+ <%= render DS::Button.new(
+ text: t(".sync_now"),
+ icon: "refresh-cw",
+ variant: "primary",
+ href: sync_fio_item_path(fio_item),
+ method: :post,
+ disabled: fio_item.syncing?
+ ) %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/fio_items/select_accounts.html.erb b/app/views/fio_items/select_accounts.html.erb
new file mode 100644
index 0000000000..9dfbebf933
--- /dev/null
+++ b/app/views/fio_items/select_accounts.html.erb
@@ -0,0 +1,70 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title")) %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <% if @fio_account.nil? %>
+ <%# A token reaches one account, so there is nothing to pick: either the first %>
+ <%# sync has not reported it yet, or it is already linked. %>
+ <% if @discovered_account %>
+ <p class="text-sm text-secondary"><%= t(".already_linked") %></p>
+ <% else %>
+ <p class="text-sm text-secondary"><%= t(".awaiting_first_sync") %></p>
+ <%= render DS::Button.new(
+ text: t(".sync_now"),
+ icon: "refresh-cw",
+ variant: "primary",
+ href: sync_fio_item_path(@fio_item),
+ method: :post,
+ disabled: @fio_item.syncing?,
+ data: { turbo_frame: "_top" }
+ ) %>
+ <% end %>
+
+ <div class="flex justify-end pt-4">
+ <%= render DS::Link.new(
+ text: t(".cancel"),
+ href: @return_to || new_account_path,
+ variant: :secondary,
+ data: { turbo_frame: "_top", action: "DS--dialog#close" }
+ ) %>
+ </div>
+ <% else %>
+ <p class="text-sm text-secondary"><%= t(".description") %></p>
+
+ <%= form_with url: link_accounts_fio_items_path,
+ method: :post,
+ data: { turbo_frame: "_top" },
+ class: "space-y-4" do %>
+ <%= hidden_field_tag :fio_item_id, @fio_item.id %>
+ <%= hidden_field_tag :return_to, @return_to %>
+
+ <div class="border border-primary rounded-lg p-3">
+ <div class="font-medium text-sm text-primary"><%= @fio_account.name %></div>
+ <div class="text-xs text-secondary mt-1">
+ <%= [ [ @fio_account.fio_account_id, @fio_account.bank_id ].compact_blank.join("/").presence, @fio_account.currency ].compact_blank.join(" · ") %>
+ </div>
+ </div>
+
+ <div>
+ <%= label_tag :accountable_type, t(".account_type_label"),
+ class: "block text-sm font-medium text-primary mb-2" %>
+ <%= select_tag :accountable_type,
+ options_for_select(@account_type_options, @accountable_type),
+ class: "appearance-none bg-container border border-primary rounded-md px-3 py-2 text-sm leading-6 text-primary focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none w-full" %>
+ </div>
+
+ <div class="flex gap-2 justify-end pt-4">
+ <%= render DS::Link.new(
+ text: t(".cancel"),
+ href: @return_to || new_account_path,
+ variant: :secondary,
+ data: { turbo_frame: "_top", action: "DS--dialog#close" }
+ ) %>
+ <%= render DS::Button.new(text: t(".link_account"), type: "submit") %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/fio_items/select_existing_account.html.erb b/app/views/fio_items/select_existing_account.html.erb
new file mode 100644
index 0000000000..6245abc8d7
--- /dev/null
+++ b/app/views/fio_items/select_existing_account.html.erb
@@ -0,0 +1,62 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title", account_name: @account.name)) %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <% if @fio_account.nil? %>
+ <% if @discovered_account %>
+ <p class="text-sm text-secondary"><%= t(".already_linked") %></p>
+ <% else %>
+ <p class="text-sm text-secondary"><%= t(".awaiting_first_sync") %></p>
+ <%= render DS::Button.new(
+ text: t(".sync_now"),
+ icon: "refresh-cw",
+ variant: "primary",
+ href: sync_fio_item_path(@fio_item),
+ method: :post,
+ disabled: @fio_item.syncing?,
+ data: { turbo_frame: "_top" }
+ ) %>
+ <% end %>
+
+ <div class="flex justify-end pt-4">
+ <%= render DS::Link.new(
+ text: t(".cancel"),
+ href: @return_to || accounts_path,
+ variant: :secondary,
+ data: { turbo_frame: "_top", action: "DS--dialog#close" }
+ ) %>
+ </div>
+ <% else %>
+ <p class="text-sm text-secondary"><%= t(".description") %></p>
+
+ <%= form_with url: link_existing_account_fio_items_path,
+ method: :post,
+ data: { turbo_frame: "_top" },
+ class: "space-y-4" do %>
+ <%= hidden_field_tag :fio_item_id, @fio_item.id %>
+ <%= hidden_field_tag :account_id, @account.id %>
+ <%= hidden_field_tag :fio_account_id, @fio_account.id %>
+ <%= hidden_field_tag :return_to, @return_to %>
+
+ <div class="border border-primary rounded-lg p-3">
+ <div class="font-medium text-sm text-primary"><%= @fio_account.name %></div>
+ <div class="text-xs text-secondary mt-1">
+ <%= [ [ @fio_account.fio_account_id, @fio_account.bank_id ].compact_blank.join("/").presence, @fio_account.currency ].compact_blank.join(" · ") %>
+ </div>
+ </div>
+
+ <div class="flex gap-2 justify-end pt-4">
+ <%= render DS::Link.new(
+ text: t(".cancel"),
+ href: @return_to || accounts_path,
+ variant: :secondary,
+ data: { turbo_frame: "_top", action: "DS--dialog#close" }
+ ) %>
+ <%= render DS::Button.new(text: t(".link_account"), type: "submit") %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/fio_items/setup_accounts.html.erb b/app/views/fio_items/setup_accounts.html.erb
new file mode 100644
index 0000000000..4f943c0409
--- /dev/null
+++ b/app/views/fio_items/setup_accounts.html.erb
@@ -0,0 +1,85 @@
+<% content_for :title, t(".title") %>
+
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title")) do %>
+ <div class="flex items-center gap-2">
+ <%= icon "landmark", class: "text-primary" %>
+ <span class="text-primary"><%= t(".subtitle") %></span>
+ </div>
+ <% end %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-4">
+ <% if @fio_account.nil? %>
+ <%# No account to set up: either the first sync has not reported one yet, or the %>
+ <%# one account this token reaches is already linked or skipped. %>
+ <div class="p-8 flex flex-col gap-3 items-center justify-center text-center">
+ <% if @discovered_account %>
+ <%= icon "check-circle", size: "lg", class: "text-success" %>
+ <p class="text-primary font-medium"><%= t(".nothing_to_setup") %></p>
+ <p class="text-secondary text-sm"><%= t(".account_already_handled") %></p>
+ <% else %>
+ <%= icon "landmark", size: "lg", class: "text-secondary" %>
+ <p class="text-primary font-medium"><%= t(".awaiting_first_sync") %></p>
+ <p class="text-secondary text-sm"><%= t(".awaiting_first_sync_description") %></p>
+ <%= render DS::Button.new(
+ text: t(".sync_now"),
+ icon: "refresh-cw",
+ variant: "primary",
+ href: sync_fio_item_path(@fio_item),
+ method: :post,
+ disabled: @fio_item.syncing?,
+ data: { turbo_frame: "_top" }
+ ) %>
+ <% end %>
+ </div>
+
+ <div class="flex justify-end">
+ <%= render DS::Link.new(text: t(".close"), variant: "secondary", href: accounts_path) %>
+ </div>
+ <% else %>
+ <div class="bg-surface border border-primary p-4 rounded-lg">
+ <p class="text-sm text-primary"><strong><%= t(".choose_account_type") %></strong></p>
+ <p class="text-xs text-secondary mt-1"><%= t(".choose_account_type_description") %></p>
+ </div>
+
+ <%= form_with url: complete_account_setup_fio_item_path(@fio_item),
+ method: :post,
+ data: { turbo_frame: "_top" },
+ class: "space-y-6" do %>
+ <%= hidden_field_tag :return_to, @return_to %>
+
+ <div class="border border-primary rounded-lg p-4">
+ <div class="mb-3">
+ <h3 class="font-medium text-primary"><%= @fio_account.name %></h3>
+ <p class="text-xs text-secondary">
+ <%= [ [ @fio_account.fio_account_id, @fio_account.bank_id ].compact_blank.join("/").presence, @fio_account.currency ].compact_blank.join(" · ") %>
+ </p>
+ </div>
+
+ <%= label_tag :account_type, t(".account_type_label"),
+ class: "block text-sm font-medium text-primary mb-2" %>
+ <%= select_tag :account_type,
+ options_for_select(@account_type_options, @selected_account_type),
+ class: "appearance-none bg-container border border-primary rounded-md px-3 py-2 text-sm leading-6 text-primary focus:border-primary focus:ring-1 focus:ring-primary focus:outline-none w-full" %>
+ </div>
+
+ <div class="flex gap-3">
+ <%= render DS::Button.new(
+ text: t(".create_account"),
+ variant: "primary",
+ icon: "plus",
+ type: "submit",
+ class: "flex-1"
+ ) %>
+ <%= render DS::Link.new(
+ text: t(".cancel"),
+ variant: "secondary",
+ href: @return_to || accounts_path
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/app/views/settings/providers/_fio_panel.html.erb b/app/views/settings/providers/_fio_panel.html.erb
new file mode 100644
index 0000000000..add916267d
--- /dev/null
+++ b/app/views/settings/providers/_fio_panel.html.erb
@@ -0,0 +1,169 @@
+<div id="fio-providers-panel" class="space-y-4">
+ <% active_items = local_assigns[:fio_items] || @fio_items || Current.family.fio_items.active.ordered %>
+
+ <%= render "settings/providers/setup_steps",
+ steps: [
+ t("settings.providers.fio_panel.step_1_html", link: link_to(t("providers.fio.name"), "https://ib.fio.cz", target: "_blank", rel: "noopener noreferrer", class: "text-primary font-medium underline")),
+ t("settings.providers.fio_panel.step_2"),
+ t("settings.providers.fio_panel.step_3")
+ ] %>
+
+ <%= render DS::Alert.new(message: t("fio_items.provider_panel.one_account_notice"), variant: :info) %>
+
+ <% error_msg = local_assigns[:error_message] || @error_message %>
+ <% if error_msg.present? %>
+ <%= render DS::Alert.new(message: error_msg, variant: :error) %>
+ <% end %>
+
+ <% if active_items.any? %>
+ <div class="space-y-3">
+ <% active_items.each do |item| %>
+ <%= render DS::Disclosure.new(variant: :card) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center justify-between gap-2 w-full">
+ <div class="flex items-center gap-3">
+ <div class="flex items-center justify-center h-8 w-8 bg-surface rounded-full">
+ <p class="text-primary text-xs font-medium"><%= item.name.to_s.first.to_s.upcase %></p>
+ </div>
+ <div>
+ <p class="font-medium text-primary"><%= item.name %></p>
+ <p class="text-xs text-secondary">
+ <% if item.syncing? %>
+ <%= t("fio_items.provider_panel.syncing") %>
+ <% elsif item.requires_update? %>
+ <%= t("fio_items.provider_panel.requires_update") %>
+ <% elsif item.last_synced_at %>
+ <%= t("fio_items.provider_panel.last_synced", timestamp: time_ago_in_words(item.last_synced_at)) %>
+ <% else %>
+ <%= t("fio_items.provider_panel.never_synced") %>
+ <% end %>
+ · <%= item.sync_status_summary %>
+ </p>
+ </div>
+ </div>
+ </div>
+ <% end %>
+
+ <div class="mt-4 space-y-4">
+ <% if item.requires_update? %>
+ <%= render DS::Alert.new(message: t("fio_items.provider_panel.requires_update_notice"), variant: :warning) %>
+ <% end %>
+
+ <div class="text-sm">
+ <p class="text-secondary text-xs uppercase tracking-wider mb-1"><%= t("fio_items.provider_panel.connected_account") %></p>
+ <% fio_account = item.fio_account %>
+ <% if fio_account.nil? %>
+ <p class="text-secondary"><%= t("fio_items.provider_panel.no_account_yet") %></p>
+ <% else %>
+ <p class="text-primary font-medium">
+ <%= [ fio_account.current_account&.name || fio_account.name,
+ [ fio_account.fio_account_id, fio_account.bank_id ].compact_blank.join("/").presence ].compact_blank.join(" · ") %>
+ </p>
+ <% unless fio_account.current_account %>
+ <p class="text-secondary text-xs"><%= t("fio_items.provider_panel.account_needs_setup") %></p>
+ <% end %>
+ <% end %>
+ </div>
+
+ <div class="flex items-center gap-2">
+ <%= render DS::Button.new(
+ text: t("fio_items.provider_panel.sync"),
+ icon: "refresh-cw",
+ variant: :outline,
+ size: :sm,
+ href: sync_fio_item_path(item),
+ method: :post,
+ disabled: item.syncing?
+ ) %>
+ <%= render DS::Button.new(
+ text: t("fio_items.provider_panel.disconnect"),
+ icon: "trash-2",
+ variant: :outline_destructive,
+ size: :sm,
+ href: fio_item_path(item),
+ method: :delete,
+ data: { turbo_confirm: t("fio_items.provider_panel.disconnect_confirm", name: item.name) }
+ ) %>
+ </div>
+
+ <%= styled_form_with model: item,
+ url: fio_item_path(item),
+ scope: :fio_item,
+ method: :patch,
+ data: { turbo: true },
+ class: "space-y-3" do |form| %>
+ <%= form.text_field :name,
+ label: t("fio_items.provider_panel.connection_name_label"),
+ placeholder: t("fio_items.provider_panel.connection_name_placeholder") %>
+
+ <%= form.text_field :token,
+ label: t("fio_items.provider_panel.token_label"),
+ placeholder: t("fio_items.provider_panel.keep_token_placeholder"),
+ type: :password,
+ value: nil %>
+
+ <%= form.date_field :sync_start_date,
+ label: t("fio_items.provider_panel.sync_start_date_label"),
+ value: item.sync_start_date&.to_date,
+ max: Date.current %>
+
+ <p class="text-xs text-secondary"><%= t("fio_items.provider_panel.sync_start_date_hint") %></p>
+
+ <div class="flex flex-wrap justify-end gap-2">
+ <%= render DS::Link.new(
+ text: t("fio_items.provider_panel.setup_accounts"),
+ icon: "settings",
+ variant: "secondary",
+ href: setup_accounts_fio_item_path(item),
+ frame: :modal
+ ) %>
+ <%= render DS::Button.new(
+ text: t("fio_items.provider_panel.update_connection"),
+ type: "submit"
+ ) %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+
+ <% fio_item = Current.family.fio_items.build(name: t("fio_items.provider_panel.default_connection_name")) %>
+ <% if active_items.any? %>
+ <h3 class="flex items-center gap-2 text-sm font-medium text-primary mt-4">
+ <%= icon "plus", size: "sm" %>
+ <%= t("fio_items.provider_panel.add_connection") %>
+ </h3>
+ <% end %>
+
+ <%= styled_form_with model: fio_item,
+ url: fio_items_path,
+ scope: :fio_item,
+ method: :post,
+ data: { turbo: true },
+ class: "space-y-3" do |form| %>
+ <%= form.text_field :name,
+ label: t("fio_items.provider_panel.connection_name_label"),
+ placeholder: t("fio_items.provider_panel.connection_name_placeholder") %>
+
+ <%= form.text_field :token,
+ label: t("fio_items.provider_panel.token_label"),
+ placeholder: t("fio_items.provider_panel.token_placeholder"),
+ type: :password,
+ value: nil %>
+
+ <%= form.date_field :sync_start_date,
+ label: t("fio_items.provider_panel.sync_start_date_label"),
+ max: Date.current %>
+
+ <p class="text-xs text-secondary"><%= t("fio_items.provider_panel.sync_start_date_hint") %></p>
+
+ <div class="flex justify-end">
+ <%= render DS::Button.new(
+ text: t("fio_items.provider_panel.add_connection"),
+ type: "submit"
+ ) %>
+ </div>
+ <% end %>
+</div>
diff --git a/config/initializers/fio.rb b/config/initializers/fio.rb
new file mode 100644
index 0000000000..ff2c384571
--- /dev/null
+++ b/config/initializers/fio.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+# Fio banka sync tuning. Every value is optional; the defaults suit a personal account.
+Rails.application.configure do
+ # How far back a brand-new connection reaches on its first sync. Fio serves 90 days
+ # without additional authorization; anything older needs the account's full history
+ # unlocked in internet banking for 10 minutes (Provider::Fio::HistoryLockedError).
+ config.x.fio.initial_history_days =
+ ENV.fetch("FIO_INITIAL_HISTORY_DAYS", 90).to_i.clamp(1, 3650)
+
+ # Days before the last covered day that each subsequent sync re-reads. Movements carry
+ # their booking date, which can be a few days behind the day they appear, so the window
+ # overlaps rather than starting where the last one ended. Re-reading is free: entries
+ # are matched on Fio's movement id.
+ config.x.fio.sync_lookback_days =
+ ENV.fetch("FIO_SYNC_LOOKBACK_DAYS", 7).to_i.clamp(1, 90)
+
+ # When truthy, logs the raw statement returned by Fio. PII (counterparty names, account
+ # numbers, payment messages), so the importer additionally requires Rails.env.local?.
+ config.x.fio.debug_raw = ENV["FIO_DEBUG_RAW"].to_s.strip.downcase.in?(%w[1 true yes])
+end
diff --git a/config/locales/views/fio_items/en.yml b/config/locales/views/fio_items/en.yml
new file mode 100644
index 0000000000..a907058df8
--- /dev/null
+++ b/config/locales/views/fio_items/en.yml
@@ -0,0 +1,141 @@
+---
+en:
+ providers:
+ fio:
+ name: Fio banka
+ description: Sync a Fio banka account with a read-only API token
+ family:
+ fio:
+ create_fio_item:
+ default_name: Fio banka Connection
+ fio_item:
+ errors:
+ account_processing_failed: Could not sync Fio account
+ account_mismatch: This token belongs to a different Fio account than the one this connection already syncs. Add it as a separate connection instead.
+ account_sync_schedule_failed: Could not schedule Fio account sync
+ statement_too_large: The statement has more transactions than Fio serves in one request. Move the sync start date forward and sync again.
+ statement_fetch_failed: Could not fetch the statement from Fio
+ history_locked: Fio refused this statement period. Unlock the account's full history in internet banking under Settings → API, then sync again within 10 minutes.
+ sync_failed: Could not sync Fio connection
+ sync:
+ status:
+ importing: Importing the statement from Fio...
+ checking_setup: Checking account configuration...
+ needs_setup:
+ one: 1 account needs setup...
+ other: "%{count} accounts need setup..."
+ processing: Processing transactions...
+ calculating: Calculating balances...
+ sync_status:
+ no_accounts: No account found yet
+ all_synced:
+ one: 1 account synced
+ other: "%{count} accounts synced"
+ partial: "%{linked} synced, %{unlinked} need setup"
+ fio_items:
+ account_types:
+ depository: Current or savings account
+ loan: Loan, mortgage or overdraft
+ provider_panel:
+ default_connection_name: Fio banka Connection
+ add_connection: Add Fio banka connection
+ update_connection: Update connection
+ connection_name_label: Connection name
+ connection_name_placeholder: My Fio account
+ token_label: API token (read-only)
+ token_placeholder: Paste the 64-character token
+ keep_token_placeholder: Leave blank to keep the existing token
+ sync_start_date_label: Import transactions from
+ sync_start_date_hint: Fio serves the last 90 days without extra authorization. For anything older, unlock the account's full history in internet banking under Settings → API (padlock icon) — that opens a 10-minute window — and sync during it.
+ one_account_notice: One token reaches one Fio account, so add a connection for each account you want to track. A token may be used once every 30 seconds; a sync that arrives sooner is picked up by the next one.
+ connected_account: Connected account
+ no_account_yet: No account yet — the first sync discovers the account this token reaches.
+ account_needs_setup: Not linked to a Sure account yet.
+ requires_update: New token needed
+ requires_update_notice: Fio rejected this token. Tokens are valid for up to 180 days unless they are auto-extended on each banking login, so create a new read-only token under Settings → API and paste it below.
+ last_synced: Synced %{timestamp} ago
+ never_synced: Never synced
+ syncing: Syncing...
+ sync: Sync
+ setup_accounts: Setup account
+ disconnect: Disconnect
+ disconnect_confirm: "Are you sure you want to disconnect %{name}?"
+ create:
+ success: Fio banka connection saved.
+ token_required: Paste the API token from Fio internet banking.
+ update:
+ success: Fio banka connection updated.
+ destroy:
+ success: Scheduled Fio banka connection for deletion.
+ unlink_failed: Could not disconnect Fio banka connection
+ select_accounts:
+ title: Link your Fio account
+ description: This token reaches one account. Choose how it should be tracked in Sure.
+ account_type_label: Account type
+ awaiting_first_sync: Fio has not reported the account for this token yet. Run a sync and come back.
+ already_linked: This connection's account is already linked to a Sure account.
+ sync_now: Sync now
+ no_credentials_configured: Configure Fio banka in provider settings first.
+ cancel: Cancel
+ link_account: Link account
+ link_accounts:
+ success: "Linked your Fio account to %{account_name}."
+ no_account_found: No unlinked Fio account was found for this connection.
+ no_credentials_configured: Configure Fio banka in provider settings first.
+ unsupported_account_type: Fio does not support that account type.
+ link_failed: The account could not be linked.
+ select_existing_account:
+ title: "Link Fio account to %{account_name}"
+ description: Connect the account this token reaches to the account you picked.
+ awaiting_first_sync: Fio has not reported the account for this token yet. Run a sync and come back.
+ already_linked: This connection's account is already linked to a Sure account.
+ sync_now: Sync now
+ no_credentials_configured: Configure Fio banka in provider settings first.
+ account_already_linked: This account is already linked to a provider.
+ cancel: Cancel
+ link_account: Link account
+ link_existing_account:
+ success: "Linked your Fio account to %{account_name}."
+ account_already_linked: This account is already linked to a provider.
+ fio_account_already_linked: This Fio account is already linked.
+ no_account_selected: No Fio account was available to link.
+ unsupported_account_type: Fio can only sync cash and loan accounts.
+ setup_accounts:
+ title: Link your Fio account
+ subtitle: Choose how the account this token reaches should appear in Sure.
+ choose_account_type: Choose an account type
+ choose_account_type_description: Skip it if you do not want to track this account.
+ account_type_label: Account type
+ account_types:
+ skip: Skip
+ create_account: Create account
+ awaiting_first_sync: No account found yet
+ awaiting_first_sync_description: Fio reports the account only in a statement, so it appears after the first successful sync.
+ sync_now: Sync now
+ nothing_to_setup: Nothing to set up
+ account_already_handled: This connection's account is already linked or skipped.
+ close: Close
+ cancel: Cancel
+ complete_account_setup:
+ success: "Created %{account_name}."
+ skipped: The Fio account was skipped.
+ no_account: No Fio account needed setting up.
+ unsupported_account_type: Fio does not support that account type.
+ creation_failed: Could not create the Sure account.
+ fio_item:
+ deletion_in_progress: Deletion in progress
+ syncing: Syncing
+ requires_update: New token needed
+ error: Error
+ status_with_summary: "Synced %{timestamp} ago · %{summary}"
+ status_never: Never synced
+ delete: Delete
+ requires_update_title: New token needed
+ requires_update_description: Fio rejected the token for this connection. Create a new read-only token under Settings → API in internet banking.
+ update_token: Update token
+ setup_needed: Account setup needed
+ setup_description: The account this token reaches is not linked to a Sure account yet.
+ setup_action: Setup account
+ no_accounts_title: No account imported yet
+ no_accounts_description: Fio reports the account only in a statement, so it appears after the first successful sync.
+ sync_now: Sync now
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 5a206e3a73..5fe78ba202 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -442,6 +442,7 @@ en:
lunchflow: Connect 20k+ banks from 40+ countries (UK, EU, USA and more!)
redbark: Sync Australian bank accounts via Redbark open banking.
monobank: Sync Ukrainian Monobank cards and jars with a personal API token.
+ fio: Sync a Fio banka account with a read-only API token.
enable_banking: Sync European bank accounts via PSD2 open banking.
coinstats: Track your entire crypto portfolio across wallets and exchanges.
wise: Sync your Wise multi-currency balances and international transfers automatically.
@@ -622,6 +623,10 @@ en:
step_1_html: "Go to %{link}, sign in with the Monobank app and generate a personal token."
step_2: "Copy the token — it is shown only once."
step_3: "Paste the token below, save, then link the cards and jars you want to track."
+ fio_panel:
+ step_1_html: "Sign in to %{link} internet banking and open Settings → API."
+ step_2: 'Create a token with read-only access ("Sledování účtu"). It needs strong authorization and is valid for up to 180 days.'
+ step_3: "Paste the token below and save. One token reaches one account, so add a connection per Fio account."
simplefin_panel:
step_1_html: "Go to %{link} for a one-time setup token."
step_2: "Paste the token below and connect."
diff --git a/config/routes.rb b/config/routes.rb
index 87bbb14f0c..14d59a3e20 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -910,6 +910,21 @@ Rails.application.routes.draw do
end
end
+ resources :fio_items, only: %i[create update destroy] do
+ collection do
+ get :select_accounts
+ post :link_accounts
+ get :select_existing_account
+ post :link_existing_account
+ end
+
+ member do
+ post :sync
+ get :setup_accounts
+ post :complete_account_setup
+ end
+ end
+
resources :sophtron_items, only: %i[index new create show edit update destroy] do
collection do
get :preload_accounts
diff --git a/db/migrate/20260911165424_create_fio_items_and_accounts.rb b/db/migrate/20260911165424_create_fio_items_and_accounts.rb
new file mode 100644
index 0000000000..69b45cef5e
--- /dev/null
+++ b/db/migrate/20260911165424_create_fio_items_and_accounts.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+class CreateFioItemsAndAccounts < ActiveRecord::Migration[8.1]
+ def change
+ create_table :fio_items, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: true, type: :uuid
+ t.string :name
+
+ t.string :institution_id
+ t.string :institution_name
+ t.string :institution_domain
+ t.string :institution_url
+ t.string :institution_color
+
+ t.string :status, default: "good", null: false
+ t.boolean :scheduled_for_deletion, default: false, null: false
+ t.boolean :pending_account_setup, default: false, null: false
+
+ t.date :sync_start_date
+
+ t.jsonb :raw_payload
+ t.jsonb :raw_institution_payload
+
+ t.text :token
+
+ t.timestamps
+ end
+
+ add_index :fio_items, :status
+
+ create_table :fio_accounts, id: :uuid do |t|
+ t.references :fio_item, null: false, foreign_key: true, type: :uuid
+
+ # A Fio token grants access to exactly one account, so these are the statement
+ # header fields rather than anything chosen by the user.
+ t.string :name, null: false
+ t.string :fio_account_id
+ t.string :bank_id
+ t.string :iban
+ t.string :bic
+
+ t.string :currency, null: false
+ t.decimal :current_balance, precision: 19, scale: 4
+
+ t.boolean :ignored, default: false, null: false
+
+ t.jsonb :institution_metadata
+ t.jsonb :raw_payload
+ t.jsonb :raw_transactions_payload
+
+ t.date :sync_start_date
+ # Last day already covered by a statement request. The next sync re-reads a few
+ # days before it (see FIO_SYNC_LOOKBACK_DAYS) because Fio assigns a movement its
+ # booking date, which can land behind the day it becomes visible.
+ t.date :transactions_synced_through
+ # Earliest day a statement request has actually served. While it sits later than
+ # the connection's start date the history is still incomplete, so the next sync
+ # asks for the whole range again instead of resuming at the end — which is how a
+ # backfill survives the 90-day refusal until the user unlocks their full history.
+ t.date :history_synced_from
+
+ t.timestamps
+ end
+
+ add_index :fio_accounts,
+ [ :fio_item_id, :fio_account_id ],
+ unique: true,
+ where: "fio_account_id IS NOT NULL",
+ name: "index_fio_accounts_on_item_and_account_id"
+ end
+end
diff --git a/db/migrate/20260911200000_add_history_unlock_required_at_to_fio_items.rb b/db/migrate/20260911200000_add_history_unlock_required_at_to_fio_items.rb
new file mode 100644
index 0000000000..1dc7067a8b
--- /dev/null
+++ b/db/migrate/20260911200000_add_history_unlock_required_at_to_fio_items.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+class AddHistoryUnlockRequiredAtToFioItems < ActiveRecord::Migration[8.1]
+ def change
+ # Set when Fio refuses a statement period for want of a temporary full-history
+ # unlock. While it is set, syncs stay inside the 90 days Fio serves without one
+ # instead of spending their single request on a certain refusal.
+ add_column :fio_items, :history_unlock_required_at, :datetime
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index c6bca77a16..4fd32a519b 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -881,6 +881,50 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
t.index ["merchant_id"], name: "index_family_merchant_associations_on_merchant_id"
end
+ create_table "fio_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.string "bank_id"
+ t.string "bic"
+ t.datetime "created_at", null: false
+ t.string "currency", null: false
+ t.decimal "current_balance", precision: 19, scale: 4
+ t.string "fio_account_id"
+ t.uuid "fio_item_id", null: false
+ t.date "history_synced_from"
+ t.string "iban"
+ t.boolean "ignored", default: false, null: false
+ t.jsonb "institution_metadata"
+ t.string "name", null: false
+ t.jsonb "raw_payload"
+ t.jsonb "raw_transactions_payload"
+ t.date "sync_start_date"
+ t.date "transactions_synced_through"
+ t.datetime "updated_at", null: false
+ t.index ["fio_item_id", "fio_account_id"], name: "index_fio_accounts_on_item_and_account_id", unique: true, where: "(fio_account_id IS NOT NULL)"
+ t.index ["fio_item_id"], name: "index_fio_accounts_on_fio_item_id"
+ end
+
+ create_table "fio_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "created_at", null: false
+ t.uuid "family_id", null: false
+ t.datetime "history_unlock_required_at"
+ t.string "institution_color"
+ t.string "institution_domain"
+ t.string "institution_id"
+ t.string "institution_name"
+ t.string "institution_url"
+ t.string "name"
+ t.boolean "pending_account_setup", default: false, null: false
+ t.jsonb "raw_institution_payload"
+ t.jsonb "raw_payload"
+ t.boolean "scheduled_for_deletion", default: false, null: false
+ t.string "status", default: "good", null: false
+ t.date "sync_start_date"
+ t.text "token"
+ t.datetime "updated_at", null: false
+ t.index ["family_id"], name: "index_fio_items_on_family_id"
+ t.index ["status"], name: "index_fio_items_on_status"
+ end
+
create_table "goal_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.uuid "account_id", null: false
t.decimal "allocated_amount", precision: 19, scale: 4
@@ -1113,8 +1157,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
t.check_constraint "btrim(source_id::text) <> ''::text", name: "chk_import_source_mappings_source_id_present"
t.check_constraint "btrim(source_type::text) <> ''::text", name: "chk_import_source_mappings_source_type_present"
t.check_constraint "btrim(target_type::text) <> ''::text", name: "chk_import_source_mappings_target_type_present"
- t.check_constraint "source_type::text = ANY (ARRAY['Account'::character varying, 'Category'::character varying, 'Tag'::character varying, 'Merchant'::character varying, 'RecurringTransaction'::character varying, 'RecurringOccurrence'::character varying, 'Transaction'::character varying, 'Budget'::character varying, 'Security'::character varying, 'Rule'::character varying]::text[])", name: "chk_import_source_mappings_source_type"
- t.check_constraint "target_type::text = ANY (ARRAY['Account'::character varying, 'Category'::character varying, 'Tag'::character varying, 'Merchant'::character varying, 'RecurringTransaction'::character varying, 'RecurringOccurrence'::character varying, 'Transaction'::character varying, 'Budget'::character varying, 'Security'::character varying, 'Rule'::character varying]::text[])", name: "chk_import_source_mappings_target_type"
+ t.check_constraint "source_type::text = ANY (ARRAY['Account'::character varying::text, 'Category'::character varying::text, 'Tag'::character varying::text, 'Merchant'::character varying::text, 'RecurringTransaction'::character varying::text, 'RecurringOccurrence'::character varying::text, 'Transaction'::character varying::text, 'Budget'::character varying::text, 'Security'::character varying::text, 'Rule'::character varying::text])", name: "chk_import_source_mappings_source_type"
+ t.check_constraint "target_type::text = ANY (ARRAY['Account'::character varying::text, 'Category'::character varying::text, 'Tag'::character varying::text, 'Merchant'::character varying::text, 'RecurringTransaction'::character varying::text, 'RecurringOccurrence'::character varying::text, 'Transaction'::character varying::text, 'Budget'::character varying::text, 'Security'::character varying::text, 'Rule'::character varying::text])", name: "chk_import_source_mappings_target_type"
end
create_table "imports", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
@@ -1812,7 +1856,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
t.check_constraint "NOT (day_of_month IS NOT NULL AND weekday IS NOT NULL)", name: "chk_recurrence_rules_single_day_spec"
t.check_constraint "\"interval\" > 0", name: "chk_recurrence_rules_interval_positive"
t.check_constraint "day_of_month IS NULL OR day_of_month >= '-1'::integer AND day_of_month <= 31 AND day_of_month <> 0", name: "chk_recurrence_rules_day_of_month_range"
- t.check_constraint "frequency::text = ANY (ARRAY['weekly'::character varying, 'monthly'::character varying, 'yearly'::character varying]::text[])", name: "chk_recurrence_rules_frequency"
+ t.check_constraint "frequency::text = ANY (ARRAY['weekly'::character varying::text, 'monthly'::character varying::text, 'yearly'::character varying::text])", name: "chk_recurrence_rules_frequency"
t.check_constraint "month_of_year IS NULL OR month_of_year >= 1 AND month_of_year <= 12", name: "chk_recurrence_rules_month_of_year_range"
t.check_constraint "weekday IS NULL OR weekday >= 0 AND weekday <= 6", name: "chk_recurrence_rules_weekday_range"
t.check_constraint "weekday_ordinal IS NULL OR weekday IS NOT NULL", name: "chk_recurrence_rules_ordinal_requires_weekday"
@@ -1837,8 +1881,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
t.index ["recurring_occurrence_id", "entry_id"], name: "idx_recurring_allocations_entry_once", unique: true, where: "(entry_id IS NOT NULL)"
t.index ["recurring_occurrence_id"], name: "index_recurring_allocations_on_recurring_occurrence_id"
t.check_constraint "allocated_amount > 0::numeric", name: "chk_recurring_allocations_amount_positive"
- t.check_constraint "source::text = ANY (ARRAY['auto_matched'::character varying, 'user_confirmed'::character varying, 'user_created'::character varying]::text[])", name: "chk_recurring_allocations_source"
- t.check_constraint "state::text = ANY (ARRAY['suggested'::character varying, 'confirmed'::character varying]::text[])", name: "chk_recurring_allocations_state"
+ t.check_constraint "source::text = ANY (ARRAY['auto_matched'::character varying::text, 'user_confirmed'::character varying::text, 'user_created'::character varying::text])", name: "chk_recurring_allocations_source"
+ t.check_constraint "state::text = ANY (ARRAY['suggested'::character varying::text, 'confirmed'::character varying::text])", name: "chk_recurring_allocations_state"
end
create_table "recurring_match_rejections", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
@@ -1869,8 +1913,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
t.index ["id", "currency"], name: "idx_recurring_occurrences_id_currency", unique: true
t.index ["recurring_transaction_id", "original_due_on"], name: "idx_recurring_occurrences_identity", unique: true
t.check_constraint "(status::text = 'scheduled'::text) = (closed_at IS NULL)", name: "chk_recurring_occurrences_closed_state"
- t.check_constraint "closed_source IS NULL OR (closed_source::text = ANY (ARRAY['auto'::character varying, 'user'::character varying]::text[]))", name: "chk_recurring_occurrences_closed_source"
- t.check_constraint "status::text = ANY (ARRAY['scheduled'::character varying, 'paid'::character varying, 'skipped'::character varying, 'missed'::character varying]::text[])", name: "chk_recurring_occurrences_status"
+ t.check_constraint "closed_source IS NULL OR (closed_source::text = ANY (ARRAY['auto'::character varying::text, 'user'::character varying::text]))", name: "chk_recurring_occurrences_closed_source"
+ t.check_constraint "status::text = ANY (ARRAY['scheduled'::character varying::text, 'paid'::character varying::text, 'skipped'::character varying::text, 'missed'::character varying::text])", name: "chk_recurring_occurrences_status"
end
create_table "recurring_price_changes", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
@@ -2727,6 +2771,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
add_foreign_key "family_exports", "families"
add_foreign_key "family_merchant_associations", "families"
add_foreign_key "family_merchant_associations", "merchants"
+ add_foreign_key "fio_accounts", "fio_items"
+ add_foreign_key "fio_items", "families"
add_foreign_key "goal_accounts", "accounts", on_delete: :restrict
add_foreign_key "goal_accounts", "goals", on_delete: :cascade
add_foreign_key "goal_pledges", "accounts", on_delete: :restrict
diff --git a/docs/hosting/fio.md b/docs/hosting/fio.md
new file mode 100644
index 0000000000..cddb8a3ddd
--- /dev/null
+++ b/docs/hosting/fio.md
@@ -0,0 +1,125 @@
+# Setting Up Fio banka (Czechia)
+
+[Fio banka](https://www.fio.cz/) exposes an API for reading movements from your own
+accounts. You bring your own token, so Sure talks to Fio directly on your behalf — no
+third-party aggregator sits in between, and no consent expires every 90 days.
+
+> [!NOTE]
+> A token grants access to **one account**. If you track three Fio accounts in Sure, you
+> generate three tokens and add three connections.
+
+## 1. Get Your Token
+
+1. Sign in to Fio internet banking.
+2. Open **Nastavení** (top right), then the **API** tab.
+3. Create a token with the **Sledování účtu** (account monitoring) right. That is
+ read-only; Sure never initiates payments, and a token without payment rights cannot
+ be abused to move money.
+4. Authorize the request — Fio requires SMS or push confirmation, and every signatory
+ has to sign on jointly held accounts.
+5. Wait five minutes. Fio rejects a brand-new token until then.
+
+Every token must have an expiry, at most **180 days**. Choose automatic renewal if you
+do not want to repeat this twice a year: Fio then extends the token by 180 days on each
+internet or smart banking login.
+
+## 2. Add Fio to Sure
+
+1. In Sure, go to **Settings > Providers** and find the **Fio banka** panel.
+2. Paste the token and save.
+3. The first sync reads the statement header, which is the only account description Fio
+ offers, and the account appears for setup. Link it to an existing Sure account or
+ create a new one from it.
+
+Fio reports no account type, so the account is offered as a current account. Pick a loan
+instead if the token belongs to a mortgage, loan or overdraft account — Fio reports those
+balances negative, and Sure stores a liability as a positive balance.
+
+## 3. Syncing
+
+One property of the API shapes everything: a token may be used **once per 30 seconds**,
+for reading or writing, whatever the format. So a sync spends exactly one request.
+
+- Each sync asks for the movements booked between the day the last sync covered and
+ today, then processes them.
+- The window starts a week before that day rather than after it. Fio books a movement
+ under its banking date, which can trail the day it becomes visible.
+- Re-reading costs nothing: every movement carries a permanent id (`ID pohybu`), and a
+ movement already imported updates its entry rather than duplicating it. A reversal
+ gets its own id and arrives as its own entry.
+
+A manual sync started within 30 seconds of a scheduled one is refused by Fio. That is
+not an error — nothing is fetched, the connection stays healthy, and the next sync
+continues where this one stopped.
+
+Fio has no concept of a pending or held transaction, so nothing is ever badged pending
+and nothing has to be reconciled later.
+
+### History older than 90 days
+
+Fio serves 90 days without further authorization. Older movements need the account's
+full history unlocked: in internet banking under **Nastavení > API**, click the padlock
+on the token and authorize. That opens a **10-minute** window.
+
+Set the connection's start date to how far back you want to go. If that reaches past 90
+days and the history is still locked, Fio refuses the period: the sync reports it and
+every sync from then on stays inside the 90 days Fio does serve, so you keep getting
+recent movements. A sync only ever makes one request — retrying a refused period
+immediately would breach the 30-second rule and get a 409 instead.
+
+To collect the rest: unlock the history in internet banking, then press **Sync** on the
+connection. That is what tells Sure the unlock happened, and the sync reaches for the
+whole range again. Changing the token or the start date does the same.
+
+### What lands in a transaction
+
+Fio returns each movement as numbered columns — the same ids its CSV and XML exports
+use. Values below are shaped as the live API returns them, anonymised.
+
+| Fio column | Becomes | Example in | Example out |
+| --- | --- | --- | --- |
+| `column22` *ID pohybu* | the transaction's provider id | `27707247780` | `fio_27707247780` |
+| `column0` *Datum* | date | `"2026-06-27+0200"` | `2026-06-27` |
+| `column1` *Objem* | amount | `-958.0` | `958.0` spent |
+| `column10` *Název protiúčtu* | name, for transfers | `"Junák - český skaut, z. s."` | same |
+| `column7` *Uživatelská identifikace* | name and merchant, for card payments | `"Nákup: BILLA 1234, NA PRIKOPE 1, PRAHA 1, 11000, CZE, dne 26.6.2026, částka 958.00 CZK"` | `BILLA 1234` |
+| `column16` *Zpráva pro příjemce* | notes | `"Záloha na účet tábora"` | same |
+| `column18` *Upřesnění* | the original amount of a converted payment | `"15.90 EUR"` | `EUR`, `15.9` |
+| `column4` `column5` `column6` *KS/VS/SS*, `column17` *ID pokynu*, `column2`+`column3` | kept on the transaction for rules to match | `"202609"` | `202609` |
+
+Fio does not categorise anything, so nothing arrives with a category. A card payment is
+named after the acceptor — only the first field of the receipt line, so every branch of
+a chain stays one merchant and your rules only have to be written once. A transfer is
+named after the counterparty. Anything with neither, such as a fee or credited interest,
+is named after the operation type.
+
+Fio repeats the same text across *Zpráva pro příjemce*, *Komentář* and, on card
+payments, *Uživatelská identifikace*. Notes only keep it when it says something the name
+does not, so a card payment usually has none. The acceptor's full address stays on the
+transaction's provider data, not in the name.
+
+### Configuration
+
+| Variable | Default | Purpose |
+| --- | --- | --- |
+| `FIO_INITIAL_HISTORY_DAYS` | `90` | History a new connection reaches for when no start date is set. Above 90 needs an unlock. |
+| `FIO_SYNC_LOOKBACK_DAYS` | `7` | Days before the last covered day that every sync re-reads. |
+| `FIO_DEBUG_RAW` | unset | Log raw API payloads. Development only — the dump contains counterparty names and payment messages. |
+
+## Troubleshooting
+
+**Connection requires a new token**
+Fio answers an unknown, expired or deactivated token with HTTP 500, which Sure reports
+as a token problem. Check the token's validity under **Nastavení > API** and paste a new
+one into the provider panel.
+
+**The statement is too large**
+Fio caps one request at 50 000 movements. Set a later start date on the connection.
+
+**Older transactions are missing**
+Either the history was never unlocked (see above), or the connection's start date bounds
+it.
+
+**Sync errors**
+Provider sync failures and notes are captured in Sure's debug log (super admin:
+**Settings > Debug**), filtered by the `fio` provider key. The token is never logged.
diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.md
index 1b5fe566d9..9145120302 100644
--- a/docs/llm-guides/providers.md
+++ b/docs/llm-guides/providers.md
@@ -95,3 +95,10 @@ to Up; the SimpleFIN and Lunchflow flags do not provide the same environment gat
[importer](../../app/models/monobank_item/importer.rb) dumps raw payloads only when
`Rails.env.local?` is also true, because the dump contains PII (merchant and
counterparty names, IBANs, amounts, account ids). Preserve that local-only guard.
+
+`FIO_DEBUG_RAW=1` has the same local-only guard in the
+[importer](../../app/models/fio_item/importer.rb). Fio additionally authenticates by
+putting the token in the **URL path**, so neither [the client](../../app/models/provider/fio.rb)
+nor the importer may put a resolved URL into an exception message, a log line or debug
+metadata; requests are labelled with a static operation name instead. Fio reports no
+pending state, so it is deliberately absent from `Transaction::PENDING_PROVIDERS`.
diff --git a/docs/onboarding/guide.md b/docs/onboarding/guide.md
index 1b2a0077ae..107c137b96 100644
--- a/docs/onboarding/guide.md
+++ b/docs/onboarding/guide.md
@@ -39,6 +39,7 @@ When you arrive at the main dashboard, showing **No accounts yet**, you're all s
> - [**Lunch Flow**](https://www.lunchflow.app/)
> - [**Enable Banking**](https://enablebanking.com/) (beta)
> - [**Monobank**](https://github.com/we-promise/sure/blob/main/docs/hosting/monobank.md) (Ukrainian cards and jars)
+> - [**Fio banka**](https://github.com/we-promise/sure/blob/main/docs/hosting/fio.md) (Czech bank)
> - [**Redbark**](https://github.com/we-promise/sure/blob/main/docs/hosting/redbark.md) (Australian banks)
> - [**Up**](https://up.com.au/) (Australian bank)
> - [**Akahu**](https://www.akahu.nz/) (New Zealand banks)
diff --git a/test/controllers/fio_items_controller_test.rb b/test/controllers/fio_items_controller_test.rb
new file mode 100644
index 0000000000..adce5d0535
--- /dev/null
+++ b/test/controllers/fio_items_controller_test.rb
@@ -0,0 +1,215 @@
+require "test_helper"
+
+class FioItemsControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ ensure_tailwind_build
+ sign_in users(:family_admin)
+ SyncJob.stubs(:perform_later)
+
+ @family = families(:dylan_family)
+ @fio_item = fio_items(:one)
+ @fio_account = fio_accounts(:checking)
+ end
+
+ test "create saves the connection and starts a sync" do
+ # The setup-wide stub allows zero calls, so the enqueue is asserted explicitly here:
+ # a regression that stops kicking off the first sync would otherwise pass.
+ SyncJob.expects(:perform_later).with { |sync| sync.syncable.is_a?(FioItem) }.once
+
+ assert_difference "FioItem.count", 1 do
+ post fio_items_url, params: {
+ fio_item: { name: "Savings", token: " second-token ", sync_start_date: "2026-01-01" }
+ }
+ end
+
+ assert_redirected_to settings_providers_path
+
+ created = FioItem.order(:created_at).last
+ assert_equal "second-token", created.token
+ assert_equal "Savings", created.name
+ assert_equal Date.new(2026, 1, 1), created.sync_start_date
+ assert_equal 1, created.syncs.count
+ end
+
+ test "create rejects a blank token" do
+ assert_no_difference "FioItem.count" do
+ post fio_items_url, params: { fio_item: { name: "No token", token: " " } }
+ end
+
+ assert_redirected_to settings_providers_path
+ assert_equal I18n.t("fio_items.create.token_required"), flash[:alert]
+ end
+
+ # The form sets the status, so only a sync can establish whether Fio accepts the new
+ # token — without one the connection would claim to be healthy on the user's word.
+ test "update rotates the token, clears requires_update and revalidates it" do
+ @fio_item.update!(status: :requires_update)
+ SyncJob.expects(:perform_later).with { |sync| sync.syncable == @fio_item }.once
+
+ patch fio_item_url(@fio_item), params: {
+ fio_item: { name: "Rotated", token: "fresh-token" }
+ }
+
+ @fio_item.reload
+ assert_equal "fresh-token", @fio_item.token
+ assert_equal "Rotated", @fio_item.name
+ assert @fio_item.good?
+ end
+
+ test "update keeps the existing token when the field is left blank" do
+ patch fio_item_url(@fio_item), params: {
+ fio_item: { name: "Renamed", token: "" }
+ }
+
+ @fio_item.reload
+ assert_equal "Renamed", @fio_item.name
+ assert_equal "fio-test-token", @fio_item.token
+ end
+
+ # The edit form resubmits the stored start date, so a rename must not look like a
+ # fresh attempt at the history: the next sync would spend its one request on a period
+ # Fio has already refused.
+ test "update keeps the history lock when only the name changes" do
+ @fio_item.update!(sync_start_date: Date.new(2024, 1, 1), history_unlock_required_at: Time.current)
+
+ patch fio_item_url(@fio_item), params: {
+ fio_item: { name: "Renamed", token: "", sync_start_date: "2024-01-01" }
+ }
+
+ assert @fio_item.reload.history_unlock_required_at.present?
+ end
+
+ test "update drops the history lock when the start date moves" do
+ @fio_item.update!(sync_start_date: Date.new(2024, 1, 1), history_unlock_required_at: Time.current)
+
+ patch fio_item_url(@fio_item), params: {
+ fio_item: { name: @fio_item.name, token: "", sync_start_date: "2023-06-01" }
+ }
+
+ assert_nil @fio_item.reload.history_unlock_required_at
+ end
+
+ test "sync enqueues a sync for the connection" do
+ SyncJob.expects(:perform_later).with { |sync| sync.syncable == @fio_item }.once
+
+ post sync_fio_item_url(@fio_item)
+
+ assert_redirected_to accounts_path
+ end
+
+ test "destroy unlinks the account and schedules the connection for deletion" do
+ @fio_account.ensure_account_provider!(accounts(:depository))
+ DestroyJob.expects(:perform_later).with(@fio_item).once
+
+ delete fio_item_url(@fio_item)
+
+ assert_redirected_to settings_providers_path
+ assert @fio_item.reload.scheduled_for_deletion?
+ assert_nil @fio_account.reload.account_provider
+ end
+
+ test "link_accounts creates a checking account for the connection's single account" do
+ assert_difference [ "Account.count", "AccountProvider.count" ], 1 do
+ post link_accounts_fio_items_url, params: {
+ fio_item_id: @fio_item.id, accountable_type: "Depository"
+ }
+ end
+
+ assert_redirected_to accounts_path
+
+ account = @fio_account.reload.current_account
+ assert_equal "Depository", account.accountable_type
+ assert_equal "checking", account.accountable.subtype
+ assert_equal "CZK", account.currency
+ assert_equal @fio_account.current_balance, account.balance
+ end
+
+ # Fio reports a drawn loan negative; the account must not be born showing a negative
+ # debt and waiting for a sync that Fio may throttle.
+ test "link_accounts honours a user-chosen account type and stores a loan positively" do
+ @fio_account.update!(current_balance: -1_250_000)
+
+ post link_accounts_fio_items_url, params: {
+ fio_item_id: @fio_item.id, accountable_type: "Loan"
+ }
+
+ account = @fio_account.reload.current_account
+ assert_equal "Loan", account.accountable_type
+ assert_equal 1_250_000, account.balance
+ end
+
+ test "link_accounts refuses an unsupported account type" do
+ assert_no_difference "Account.count" do
+ post link_accounts_fio_items_url, params: {
+ fio_item_id: @fio_item.id, accountable_type: "Crypto"
+ }
+ end
+
+ assert_redirected_to new_account_path
+ end
+
+ test "link_existing_account links the Fio account to an account the user already has" do
+ account = accounts(:depository)
+
+ assert_difference "AccountProvider.count", 1 do
+ post link_existing_account_fio_items_url, params: {
+ fio_item_id: @fio_item.id, account_id: account.id, fio_account_id: @fio_account.id
+ }
+ end
+
+ assert_redirected_to accounts_path
+ assert_equal account, @fio_account.reload.current_account
+ end
+
+ test "link_existing_account refuses an account type Fio cannot describe" do
+ account = Account.create!(
+ family: @family, name: "Wallet", accountable: Crypto.new, balance: 1, currency: "CZK"
+ )
+
+ assert_no_difference "AccountProvider.count" do
+ post link_existing_account_fio_items_url, params: {
+ fio_item_id: @fio_item.id, account_id: account.id, fio_account_id: @fio_account.id
+ }
+ end
+
+ assert_redirected_to accounts_path
+ end
+
+ test "complete_account_setup skips the account so it stops asking" do
+ assert_no_difference "Account.count" do
+ post complete_account_setup_fio_item_url(@fio_item), params: { account_type: "skip" }
+ end
+
+ assert_redirected_to accounts_path
+ assert @fio_account.reload.ignored?
+ assert_empty @fio_item.fio_accounts.needs_setup
+ end
+
+ test "complete_account_setup creates the chosen account type" do
+ assert_difference [ "Account.count", "AccountProvider.count" ], 1 do
+ post complete_account_setup_fio_item_url(@fio_item), params: { account_type: "Loan" }
+ end
+
+ assert_redirected_to accounts_path
+ assert_equal "Loan", @fio_account.reload.current_account.accountable_type
+ end
+
+ # Fio only reveals the account a token reaches inside a statement, so the setup screen
+ # has to cope with the first sync not having run (or having run over an empty window).
+ test "setup_accounts offers a sync when no account has been reported yet" do
+ @fio_account.destroy!
+
+ get setup_accounts_fio_item_url(@fio_item)
+
+ assert_response :success
+ assert_select "body", text: /#{Regexp.escape(I18n.t("fio_items.setup_accounts.awaiting_first_sync"))}/
+ end
+
+ test "setup_accounts offers the discovered account with a preselected type" do
+ get setup_accounts_fio_item_url(@fio_item)
+
+ assert_response :success
+ selected_option = css_select("select[name='account_type'] option[selected='selected']").first
+ assert_equal "Depository", selected_option["value"]
+ end
+end
diff --git a/test/fixtures/fio_accounts.yml b/test/fixtures/fio_accounts.yml
new file mode 100644
index 0000000000..5b9fcaad07
--- /dev/null
+++ b/test/fixtures/fio_accounts.yml
@@ -0,0 +1,9 @@
+checking:
+ fio_item: one
+ fio_account_id: "2400222222"
+ name: "Fio banka 2400222222"
+ bank_id: "2010"
+ iban: "CZ7920100000002400222222"
+ bic: "FIOBCZPPXXX"
+ currency: CZK
+ current_balance: 195.01
diff --git a/test/fixtures/fio_items.yml b/test/fixtures/fio_items.yml
new file mode 100644
index 0000000000..16329939fc
--- /dev/null
+++ b/test/fixtures/fio_items.yml
@@ -0,0 +1,10 @@
+one:
+ family: dylan_family
+
+ name: "Test Fio Connection"
+ token: "fio-test-token"
+ institution_id: "2010"
+ institution_name: "Fio banka"
+ institution_domain: "fio.cz"
+ institution_url: "https://fio.cz"
+ status: good
diff --git a/test/models/fio_account/processor_test.rb b/test/models/fio_account/processor_test.rb
new file mode 100644
index 0000000000..b76777acc7
--- /dev/null
+++ b/test/models/fio_account/processor_test.rb
@@ -0,0 +1,89 @@
+require "test_helper"
+
+class FioAccount::ProcessorTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @fio_item = FioItem.create!(family: @family, name: "Test Fio", token: "fio-token")
+ @fio_account = FioAccount.create!(
+ fio_item: @fio_item,
+ name: "Fio banka 2400222222",
+ fio_account_id: "2400222222",
+ currency: "CZK",
+ current_balance: 8_642.5
+ )
+ end
+
+ test "writes the statement balance and currency onto the linked account" do
+ account = link(accountable: Depository.new(subtype: "checking"), currency: "USD", balance: 0)
+
+ FioAccount::Processor.new(@fio_account).process
+
+ account.reload
+ assert_equal 8_642.5, account.balance
+ assert_equal 8_642.5, account.cash_balance
+ assert_equal "CZK", account.currency
+ end
+
+ # Fio reports a drawn overdraft, loan or mortgage as a negative balance; Sure holds a
+ # liability as a positive one, so the same number would otherwise show as a debt of
+ # minus several hundred thousand crowns.
+ test "stores a loan's negative balance as a positive liability" do
+ @fio_account.update!(current_balance: -1_250_000.0)
+ account = link(accountable: Loan.new, currency: "CZK", balance: 0)
+
+ FioAccount::Processor.new(@fio_account).process
+
+ assert_equal 1_250_000.0, account.reload.balance
+ end
+
+ test "does nothing for an account the user has not linked" do
+ assert_nil FioAccount::Processor.new(@fio_account).process
+ end
+
+ test "imports the stored movements into the linked account" do
+ account = link(accountable: Depository.new(subtype: "checking"), currency: "CZK", balance: 0)
+ @fio_account.update!(raw_transactions_payload: [ {
+ "column22" => { "value" => 1_148_734_530, "id" => 22 },
+ "column0" => { "value" => 1_781_474_400_000, "id" => 0 },
+ "column1" => { "value" => -239.0, "id" => 1 },
+ "column14" => { "value" => "CZK", "id" => 14 }
+ } ])
+
+ FioAccount::Processor.new(@fio_account).process
+
+ entry = account.reload.entries.sole
+ assert_equal "fio_1148734530", entry.external_id
+ assert_equal 239.0, entry.amount
+ end
+
+ # The stored payload is replayed in full on every sync, so treating an unusable
+ # movement as a failure would red the connection for good.
+ test "skips an unusable movement without failing the account" do
+ link(accountable: Depository.new(subtype: "checking"), currency: "CZK", balance: 0)
+ @fio_account.update!(raw_transactions_payload: [
+ { "column22" => { "value" => 1, "id" => 22 }, "column0" => { "value" => nil, "id" => 0 } },
+ {
+ "column22" => { "value" => 2, "id" => 22 },
+ "column0" => { "value" => 1_781_474_400_000, "id" => 0 },
+ "column1" => { "value" => -10.0, "id" => 1 }
+ }
+ ])
+
+ result = FioAccount::Transactions::Processor.new(@fio_account).process
+
+ assert result[:success]
+ assert_equal 1, result[:imported]
+ assert_equal 1, result[:skipped]
+ end
+
+ private
+
+ def link(accountable:, currency:, balance:)
+ account = Account.create!(
+ family: @family, name: "Fio", accountable: accountable, balance: balance, currency: currency
+ )
+ AccountProvider.create!(account: account, provider: @fio_account)
+ @fio_account.reload
+ account
+ end
+end
diff --git a/test/models/fio_entry/processor_test.rb b/test/models/fio_entry/processor_test.rb
new file mode 100644
index 0000000000..528400c3b1
--- /dev/null
+++ b/test/models/fio_entry/processor_test.rb
@@ -0,0 +1,221 @@
+require "test_helper"
+
+class FioEntry::ProcessorTest < ActiveSupport::TestCase
+ # 2026-06-15 00:00:00 +02:00 — Prague midnight, the shape Fio serialises a booking day
+ # as. Deliberately not mid-day: a naive reading in a western timezone lands on the 14th.
+ PRAGUE_MIDNIGHT_MS = 1_781_474_400_000
+
+ setup do
+ @family = families(:empty)
+ @family.update!(timezone: "America/New_York")
+ @fio_item = FioItem.create!(family: @family, name: "Test Fio", token: "fio-token")
+ @fio_account = FioAccount.create!(
+ fio_item: @fio_item,
+ name: "Fio banka 2400222222",
+ fio_account_id: "2400222222",
+ currency: "CZK"
+ )
+ @account = Account.create!(
+ family: @family,
+ name: "Fio",
+ accountable: Depository.new(subtype: "checking"),
+ balance: 1000,
+ currency: "CZK"
+ )
+
+ AccountProvider.create!(account: @account, provider: @fio_account)
+ end
+
+ test "imports an outgoing transfer with Fio's sign convention flipped" do
+ entry = process(
+ id: 1_148_734_530,
+ date: PRAGUE_MIDNIGHT_MS,
+ amount: -450.5,
+ currency: "CZK",
+ counter_account_name: "Pavel, Novák",
+ operation_type: "Platba převodem uvnitř banky"
+ )
+
+ assert_equal "fio_1148734530", entry.external_id
+ assert_equal "fio", entry.source
+ assert_equal 450.5, entry.amount
+ assert_equal "Pavel, Novák", entry.name
+ assert_equal Date.new(2026, 6, 15), entry.date
+ end
+
+ test "imports an incoming transfer as a credit" do
+ entry = process(id: 1, date: PRAGUE_MIDNIGHT_MS, amount: 1_200.0, currency: "CZK")
+
+ assert_equal(-1_200.0, entry.amount)
+ end
+
+ # Fio stamps a movement with its Prague banking day at local midnight. Reading it in
+ # the family's zone would file every transaction a day early for anyone west of Prague.
+ test "reads the booking day in Prague regardless of the family timezone" do
+ entry = process(id: 2, date: PRAGUE_MIDNIGHT_MS, amount: -1.0)
+
+ assert_equal Date.new(2026, 6, 15), entry.date
+ end
+
+ # What the live API actually returns for column0 is a string like "2026-08-16+0200"
+ # (no colon in the offset), not the epoch milliseconds the JSON sample in the docs
+ # shows. Both forms are the same banking day and neither may drift by the reader's
+ # timezone, so both are read.
+ test "reads a booking day given as a date with an offset" do
+ entry = process(id: 21, date: "2026-06-15+0200", amount: -1.0)
+
+ assert_equal Date.new(2026, 6, 15), entry.date
+ end
+
+ # Verbatim from the live API: the acceptor is the first field of a receipt line that
+ # then repeats the address, the date and the amount, and Fio echoes the whole thing
+ # into "Zpráva pro příjemce" and "Komentář" as well.
+ RECEIPT_LINE = "Nákup: MGGA PAPIRNICTVI, BELOHORSKA 197 126, PRAHA 6, 160 00, CZE, " \
+ "dne 26.6.2026, částka 958.00 CZK".freeze
+
+ test "names a card payment after the acceptor and records it as a merchant" do
+ entry = process(
+ id: 3,
+ date: PRAGUE_MIDNIGHT_MS,
+ amount: -958.0,
+ user_identification: RECEIPT_LINE,
+ message: RECEIPT_LINE,
+ comment: RECEIPT_LINE,
+ operation_type: "Platba kartou"
+ )
+
+ assert_equal "MGGA PAPIRNICTVI", entry.name
+ assert_equal "MGGA PAPIRNICTVI", entry.entryable.merchant&.name
+ assert_nil entry.notes, "the message and comment only echo the receipt line"
+ assert_equal RECEIPT_LINE, entry.entryable.extra.dig("fio", "user_identification")
+ end
+
+ # Two branches of one chain must not become two merchants.
+ test "gives the same merchant to purchases at different branches" do
+ first = process(id: 31, date: PRAGUE_MIDNIGHT_MS, amount: -100.0, operation_type: "Platba kartou",
+ user_identification: "Nákup: Lidl dekuje za nakup, Fugnerova 1543/10 A, Horovice, 26801, CZE, dne 28.6.2026, částka 100.00 CZK")
+ second = process(id: 32, date: PRAGUE_MIDNIGHT_MS, amount: -200.0, operation_type: "Platba kartou",
+ user_identification: "Nákup: Lidl dekuje za nakup, Tupolevova 736, Praha, 19900, CZE, dne 29.6.2026, částka 200.00 CZK")
+
+ assert_equal "Lidl dekuje za nakup", first.name
+ assert_equal first.entryable.merchant, second.entryable.merchant
+ end
+
+ # The same field on a non-card movement is a free-text reference, not an acceptor, so
+ # it must not be mangled into a merchant.
+ test "does not derive a merchant from a transfer's user identification" do
+ entry = process(
+ id: 4,
+ date: PRAGUE_MIDNIGHT_MS,
+ amount: -100.0,
+ user_identification: "Nákup: something, else, CZ",
+ operation_type: "Bezhotovostní platba"
+ )
+
+ assert_nil entry.entryable.merchant
+ assert_equal "Nákup: something, else, CZ", entry.name
+ end
+
+ # A transfer repeats its message in "Komentář"; the note should appear once.
+ test "keeps a transfer's message once when Fio echoes it into the comment" do
+ entry = process(
+ id: 41,
+ date: PRAGUE_MIDNIGHT_MS,
+ amount: 248_200.0,
+ counter_account_name: "Junák - český skaut, středisko Mořina, z. s.",
+ message: "Záloha na účet tábora Týček",
+ comment: "Záloha na účet tábora Týček",
+ operation_type: "Příjem převodem uvnitř banky"
+ )
+
+ assert_equal "Junák - český skaut, středisko Mořina, z. s.", entry.name
+ assert_equal "Záloha na účet tábora Týček", entry.notes
+ end
+
+ test "falls back to the operation type when a movement has no counterparty or reference" do
+ entry = process(id: 5, date: PRAGUE_MIDNIGHT_MS, amount: 0.02, operation_type: "Připsaný úrok")
+
+ assert_equal "Připsaný úrok", entry.name
+ end
+
+ # "Upřesnění" carries the original amount of a converted card payment.
+ test "records the foreign amount of a converted payment" do
+ entry = process(
+ id: 6,
+ date: PRAGUE_MIDNIGHT_MS,
+ amount: -397.5,
+ currency: "CZK",
+ specification: "15.90 EUR",
+ user_identification: "Nákup: HOTEL WIEN, Wien, AT",
+ operation_type: "Platba kartou"
+ )
+
+ assert_equal "EUR", entry.entryable.extra.dig("fio", "fx_from")
+ assert_equal "15.9", entry.entryable.extra.dig("fio", "fx_amount")
+ end
+
+ test "ignores a specification that is not a foreign amount" do
+ entry = process(id: 7, date: PRAGUE_MIDNIGHT_MS, amount: -1.0, specification: "Poplatek za vedení")
+
+ assert_nil entry.entryable.extra.dig("fio", "fx_from")
+ end
+
+ test "keeps the payment reference in notes when it is not the name" do
+ entry = process(
+ id: 8,
+ date: PRAGUE_MIDNIGHT_MS,
+ amount: -300.0,
+ counter_account_name: "Pavel, Novák",
+ message: "Za obed",
+ variable_symbol: "1234567890"
+ )
+
+ assert_equal "Pavel, Novák", entry.name
+ assert_equal "Za obed", entry.notes
+ assert_equal "1234567890", entry.entryable.extra.dig("fio", "variable_symbol")
+ end
+
+ test "joins the counterparty account with its bank code" do
+ entry = process(
+ id: 9,
+ date: PRAGUE_MIDNIGHT_MS,
+ amount: -50.0,
+ counter_account: "2900233333",
+ counter_bank_id: "2010"
+ )
+
+ assert_equal "2900233333/2010", entry.entryable.extra.dig("fio", "counter_account")
+ end
+
+ # Without an id there is nothing stable to deduplicate on, and a retry would double
+ # the movement.
+ test "skips a movement with no id" do
+ assert_nil FioEntry::Processor.new(raw(date: PRAGUE_MIDNIGHT_MS, amount: -1.0), fio_account: @fio_account).process
+ assert_nil FioEntry::Processor.canonical_external_id(raw(amount: -1.0))
+ end
+
+ test "reprocessing the same movement updates the entry it already produced" do
+ movement = raw(id: 10, date: PRAGUE_MIDNIGHT_MS, amount: -100.0, counter_account_name: "First")
+ first = FioEntry::Processor.new(movement, fio_account: @fio_account).process
+
+ updated = raw(id: 10, date: PRAGUE_MIDNIGHT_MS, amount: -120.0, counter_account_name: "Second")
+ second = FioEntry::Processor.new(updated, fio_account: @fio_account).process
+
+ assert_equal first.id, second.id
+ assert_equal 120.0, second.reload.amount
+ end
+
+ private
+
+ # Builds a raw movement in Fio's numbered-column form.
+ def raw(**fields)
+ fields.each_with_object({}) do |(field, value), payload|
+ column = FioEntry::Processor::COLUMNS.fetch(field)
+ payload[column] = { "value" => value, "id" => column.delete_prefix("column").to_i }
+ end
+ end
+
+ def process(**fields)
+ FioEntry::Processor.new(raw(**fields), fio_account: @fio_account).process
+ end
+end
diff --git a/test/models/fio_item/importer_test.rb b/test/models/fio_item/importer_test.rb
new file mode 100644
index 0000000000..1d4729c126
--- /dev/null
+++ b/test/models/fio_item/importer_test.rb
@@ -0,0 +1,289 @@
+require "test_helper"
+
+class FioItem::ImporterTest < ActiveSupport::TestCase
+ PRAGUE_MIDNIGHT_MS = 1_781_474_400_000
+
+ # Raises on its first N requests, then serves the statement. Enough to model both a
+ # dead token (always raises) and a window Fio refuses until it is clamped.
+ class FakeFioProvider
+ attr_reader :calls
+
+ def initialize(statement: nil, error: nil, failing_calls: Float::INFINITY)
+ @calls = []
+ @statement = statement
+ @error = error
+ @failing_calls = failing_calls
+ end
+
+ def get_statement(from:, to: Date.current)
+ @calls << { from: from, to: to }
+ raise @error if @error && @calls.size <= @failing_calls
+
+ @statement || {}.with_indifferent_access
+ end
+ end
+
+ setup do
+ @family = families(:empty)
+ @fio_item = FioItem.create!(family: @family, name: "Test Fio", token: "fio-token")
+ end
+
+ test "discovers the account from the statement header and stores its movements" do
+ provider = FakeFioProvider.new(statement: statement(movements: [ movement(id: 1), movement(id: 2) ]))
+
+ result = FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert result[:success]
+ assert_equal 1, result[:accounts_created]
+ assert_equal 2, result[:transactions_imported]
+
+ account = @fio_item.fio_accounts.sole
+ assert_equal "2400222222", account.fio_account_id
+ assert_equal "CZK", account.currency
+ assert_equal 195.01, account.current_balance
+ assert_equal "CZ7920100000002400222222", account.iban
+ assert_equal Date.current, account.transactions_synced_through
+ assert_equal 2, account.raw_transactions_payload.size
+ end
+
+ # Discovery must not create a Sure account: which account a connection feeds, and
+ # whether it feeds one at all, is the user's decision in setup.
+ test "does not link the discovered account to a Sure account" do
+ provider = FakeFioProvider.new(statement: statement(movements: [ movement(id: 1) ]))
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert_empty @fio_item.accounts
+ assert_equal 1, @fio_item.fio_accounts.needs_setup.count
+ end
+
+ test "first sync of a new connection reaches back the configured history" do
+ provider = FakeFioProvider.new(statement: statement)
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert_equal Date.current - Rails.configuration.x.fio.initial_history_days.days, provider.calls.sole[:from]
+ assert_equal Date.current, provider.calls.sole[:to]
+ end
+
+ # Fio books a movement under its banking date, which can trail the day it appears, so
+ # the window overlaps what was already covered instead of resuming after it.
+ test "later syncs re-read an overlap before the last covered day" do
+ account = fio_account(
+ transactions_synced_through: Date.current - 2.days,
+ history_synced_from: Date.current - 90.days
+ )
+ provider = FakeFioProvider.new(statement: statement)
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ expected_from = account.transactions_synced_through - Rails.configuration.x.fio.sync_lookback_days.days
+ assert_equal expected_from, provider.calls.sole[:from]
+ end
+
+ test "never requests movements before the connection's start date" do
+ @fio_item.update!(sync_start_date: Date.current - 3.days)
+ provider = FakeFioProvider.new(statement: statement)
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert_equal Date.current - 3.days, provider.calls.sole[:from]
+ end
+
+ # The whole point of the start date is the initial backfill, so it has to be able to
+ # reach further back than the default, not only trim it.
+ test "reaches back to a start date older than the default history" do
+ @fio_item.update!(sync_start_date: Date.current - 2.years)
+ provider = FakeFioProvider.new(statement: statement)
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert_equal Date.current - 2.years, provider.calls.sole[:from]
+ end
+
+ # Once the requested range has actually been served there is nothing left to reach
+ # back for, so the connection settles into small incremental windows.
+ test "stops reaching back once the full range has been served" do
+ @fio_item.update!(sync_start_date: Date.current - 2.years)
+ provider = FakeFioProvider.new(statement: statement)
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+ FioItem::Importer.new(@fio_item.reload, fio_provider: provider).import
+
+ assert_equal Date.current - 2.years, provider.calls.first[:from]
+ assert_equal(
+ Date.current - Rails.configuration.x.fio.sync_lookback_days.days,
+ provider.calls.last[:from]
+ )
+ end
+
+ test "merges fetched movements with the ones already stored" do
+ account = fio_account(raw_transactions_payload: [ movement(id: 1) ])
+ provider = FakeFioProvider.new(statement: statement(movements: [ movement(id: 2) ]))
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ stored_ids = account.reload.raw_transactions_payload.map { |m| FioEntry::Processor.canonical_external_id(m) }
+ assert_equal %w[fio_1 fio_2], stored_ids.sort
+ end
+
+ test "a re-read movement replaces its stored copy instead of duplicating it" do
+ account = fio_account(raw_transactions_payload: [ movement(id: 1, amount: -100.0) ])
+ provider = FakeFioProvider.new(statement: statement(movements: [ movement(id: 1, amount: -120.0) ]))
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ stored = account.reload.raw_transactions_payload.sole
+ assert_equal(-120.0, stored.dig("column1", "value"))
+ end
+
+ # One request per 30 seconds per token: a manual sync landing right after a scheduled
+ # one collides legitimately. Nothing was fetched, so the cursor must not move, but the
+ # connection is healthy and the next sync picks it up.
+ test "a throttled request defers to the next sync without failing it" do
+ account = fio_account(transactions_synced_through: Date.current - 5.days)
+ provider = FakeFioProvider.new(error: Provider::Fio::RateLimitError.new("429", failure_code: :rate_limited))
+
+ result = FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert result[:success]
+ assert_equal 0, result[:transactions_imported]
+ assert_equal Date.current - 5.days, account.reload.transactions_synced_through
+ assert_equal "good", @fio_item.reload.status
+ end
+
+ # Fio serves 90 days without a temporary unlock in internet banking. Retrying clamped
+ # within the same sync would be a second use of the token inside its 30-second
+ # interval, which the real API answers with 409 — so the clamp is persisted and spent
+ # on the next sync instead.
+ test "spends only one request when Fio refuses the period" do
+ @fio_item.update!(sync_start_date: Date.current - 2.years)
+ provider = FakeFioProvider.new(error: Provider::Fio::HistoryLockedError.new("422", failure_code: :history_locked))
+
+ result = FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ refute result[:success]
+ assert_equal 1, provider.calls.size
+ assert @fio_item.reload.history_unlock_required_at.present?
+ end
+
+ test "the next sync after a refusal asks for the window Fio does serve" do
+ @fio_item.update!(sync_start_date: Date.current - 2.years)
+ refusing = FakeFioProvider.new(error: Provider::Fio::HistoryLockedError.new("422", failure_code: :history_locked))
+ FioItem::Importer.new(@fio_item, fio_provider: refusing).import
+
+ serving = FakeFioProvider.new(statement: statement(movements: [ movement(id: 1) ]))
+ result = FioItem::Importer.new(@fio_item.reload, fio_provider: serving).import
+
+ assert result[:success]
+ assert_equal 1, result[:transactions_imported]
+ assert_equal Date.current - (Provider::Fio::UNAUTHORIZED_HISTORY_DAYS - 1).days, serving.calls.sole[:from]
+ end
+
+ # Unlocking the history in internet banking lasts ten minutes, so it is the user's
+ # explicit Sync (which clears the flag) that reaches for the whole range again.
+ test "clearing the unlock flag reaches for the full range again" do
+ @fio_item.update!(sync_start_date: Date.current - 2.years, history_unlock_required_at: Time.current)
+ provider = FakeFioProvider.new(statement: statement)
+
+ @fio_item.update!(history_unlock_required_at: nil)
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert_equal Date.current - 2.years, provider.calls.sole[:from]
+ end
+
+ test "flags the connection for a new token when Fio rejects it" do
+ provider = FakeFioProvider.new(error: Provider::Fio::Error.new("500", failure_code: :unauthorized))
+
+ result = FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ refute result[:success]
+ assert_equal "requires_update", @fio_item.reload.status
+ end
+
+ # Rotating in a token for a *different* Fio account must not quietly repoint the
+ # connection: the linked Sure account would start receiving another account's balance
+ # and movements.
+ test "refuses a statement naming a different account than the connection syncs" do
+ account = fio_account(current_balance: 195.01, raw_transactions_payload: [ movement(id: 1) ])
+ provider = FakeFioProvider.new(
+ statement: statement(movements: [ movement(id: 2) ]).deep_merge(info: { accountId: "9999999999" })
+ )
+
+ result = FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ refute result[:success]
+ account.reload
+ assert_equal "2400222222", account.fio_account_id
+ assert_equal 195.01, account.current_balance
+ assert_equal %w[fio_1], account.raw_transactions_payload.map { |m| FioEntry::Processor.canonical_external_id(m) }
+ end
+
+ test "reports a statement too large to fetch as a failure" do
+ provider = FakeFioProvider.new(error: Provider::Fio::TooManyItemsError.new("413", failure_code: :too_many_items))
+
+ result = FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ refute result[:success]
+ assert result[:error].present?
+ end
+
+ # An empty body is all Fio returns for a quiet range, so a new connection whose first
+ # window has no movements has nothing to describe an account with. Inventing one would
+ # put a nameless, currency-less row in front of the user.
+ test "does not invent an account when the first window comes back empty" do
+ provider = FakeFioProvider.new(statement: {}.with_indifferent_access)
+
+ result = FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert result[:success]
+ assert_empty @fio_item.fio_accounts
+ end
+
+ # A quiet range on an established connection still has to advance the cursor, or every
+ # later sync keeps re-reading from the same day.
+ test "advances the cursor for a known account with no new movements" do
+ account = fio_account(transactions_synced_through: Date.current - 10.days)
+ provider = FakeFioProvider.new(statement: {}.with_indifferent_access)
+
+ FioItem::Importer.new(@fio_item, fio_provider: provider).import
+
+ assert_equal Date.current, account.reload.transactions_synced_through
+ end
+
+ private
+
+ def fio_account(**attributes)
+ FioAccount.create!(
+ {
+ fio_item: @fio_item,
+ name: "Fio banka 2400222222",
+ fio_account_id: "2400222222",
+ currency: "CZK"
+ }.merge(attributes)
+ )
+ end
+
+ def statement(movements: [])
+ {
+ info: {
+ accountId: "2400222222",
+ bankId: "2010",
+ currency: "CZK",
+ iban: "CZ7920100000002400222222",
+ bic: "FIOBCZPPXXX",
+ closingBalance: 195.01
+ },
+ transactionList: { transaction: movements }
+ }.with_indifferent_access
+ end
+
+ def movement(id:, amount: -100.0)
+ {
+ "column22" => { "value" => id, "id" => 22 },
+ "column0" => { "value" => PRAGUE_MIDNIGHT_MS, "id" => 0 },
+ "column1" => { "value" => amount, "id" => 1 },
+ "column14" => { "value" => "CZK", "id" => 14 }
+ }
+ end
+end
diff --git a/test/models/fio_item/syncer_test.rb b/test/models/fio_item/syncer_test.rb
new file mode 100644
index 0000000000..929b8af60c
--- /dev/null
+++ b/test/models/fio_item/syncer_test.rb
@@ -0,0 +1,60 @@
+require "test_helper"
+
+class FioItem::SyncerTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @fio_item = FioItem.create!(family: @family, name: "Test Fio", token: "fio-token")
+ @fio_account = FioAccount.create!(
+ fio_item: @fio_item,
+ name: "Fio banka 2400222222",
+ fio_account_id: "2400222222",
+ currency: "CZK"
+ )
+ @fio_item.stubs(:import_latest_fio_data).returns({ success: true })
+ end
+
+ test "reports an unlinked account as needing setup" do
+ sync = sync_item
+
+ assert_equal 1, sync.sync_stats["unlinked_accounts"]
+ assert @fio_item.reload.pending_account_setup?
+ end
+
+ # Skipping an account in setup is an answer, not an omission. The status summary reads
+ # the persisted stats in preference to the item's own counts, so an account left out of
+ # them here would keep asking to be set up after the user declined.
+ test "stops counting an account the user skipped" do
+ @fio_account.update!(ignored: true)
+
+ sync = sync_item
+
+ assert_equal 1, sync.sync_stats["total_accounts"]
+ assert_equal 0, sync.sync_stats["unlinked_accounts"]
+ refute @fio_item.reload.pending_account_setup?
+ end
+
+ # A connection is linked between its discovery sync and the next one, on the same
+ # in-memory record. Counts memoized during the first sync must not outlive it.
+ test "counts an account linked since the last sync as linked" do
+ sync_item
+
+ account = Account.create!(
+ family: @family, name: "Fio", accountable: Depository.new(subtype: "checking"),
+ balance: 0, currency: "CZK"
+ )
+ AccountProvider.create!(account: account, provider: @fio_account)
+
+ sync = sync_item
+
+ assert_equal 1, sync.sync_stats["linked_accounts"]
+ assert_equal 0, sync.sync_stats["unlinked_accounts"]
+ end
+
+ private
+
+ def sync_item
+ sync = Sync.create!(syncable: @fio_item)
+ FioItem::Syncer.new(@fio_item.reload).perform_sync(sync)
+ sync.reload
+ end
+end
diff --git a/test/models/provider/fio_adapter_test.rb b/test/models/provider/fio_adapter_test.rb
new file mode 100644
index 0000000000..1ce3c4c8f3
--- /dev/null
+++ b/test/models/provider/fio_adapter_test.rb
@@ -0,0 +1,27 @@
+require "test_helper"
+
+class Provider::FioAdapterTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:empty)
+ @first = FioItem.create!(family: @family, name: "Current", token: "token-one")
+ @second = FioItem.create!(family: @family, name: "Savings", token: "token-two")
+ end
+
+ test "builds a client for the requested connection" do
+ provider = Provider::FioAdapter.build_provider(family: @family, fio_item_id: @second.id)
+
+ assert_equal "token-two", provider.token
+ end
+
+ # One token reaches one account, so a family holds a connection per account. Falling
+ # back to another one would hand the caller a client for the wrong account.
+ test "refuses to substitute another connection for an unknown id" do
+ assert_nil Provider::FioAdapter.build_provider(family: @family, fio_item_id: SecureRandom.uuid)
+ end
+
+ test "picks the first configured connection when none is requested" do
+ provider = Provider::FioAdapter.build_provider(family: @family)
+
+ assert_equal @second.token, provider.token, "ordered is newest-first"
+ end
+end
diff --git a/test/models/provider/fio_test.rb b/test/models/provider/fio_test.rb
new file mode 100644
index 0000000000..509825deb4
--- /dev/null
+++ b/test/models/provider/fio_test.rb
@@ -0,0 +1,115 @@
+require "test_helper"
+
+class Provider::FioTest < ActiveSupport::TestCase
+ FakeResponse = Struct.new(:code, :body, :message, keyword_init: true)
+
+ STATEMENT_BODY = {
+ accountStatement: {
+ info: {
+ accountId: "2400222222",
+ bankId: "2010",
+ currency: "CZK",
+ iban: "CZ7920100000002400222222",
+ bic: "FIOBCZPPXXX",
+ closingBalance: 195.01
+ },
+ transactionList: {
+ transaction: [
+ { column22: { value: 1_148_734_530, name: "ID pohybu", id: 22 } }
+ ]
+ }
+ }
+ }.to_json
+
+ test "requests the period endpoint with the token in the path and returns the statement" do
+ requests = []
+
+ Provider::Fio.stub(:get, ->(url, headers:) {
+ requests << { url: url, headers: headers }
+ FakeResponse.new(code: 200, message: "OK", body: STATEMENT_BODY)
+ }) do
+ statement = Provider::Fio.new("fio-token").get_statement(
+ from: Date.new(2026, 6, 1),
+ to: Date.new(2026, 6, 30)
+ )
+
+ assert_equal "2400222222", statement.dig(:info, :accountId)
+ assert_equal [ 1_148_734_530 ], statement.dig(:transactionList, :transaction).map { |tx| tx.dig(:column22, :value) }
+ end
+
+ # Fio puts the token after the endpoint name, not before it. Verified against the
+ # live API: the other order answers 404.
+ assert_equal(
+ "https://fioapi.fio.cz/v1/rest/periods/fio-token/2026-06-01/2026-06-30/transactions.json",
+ requests.sole[:url]
+ )
+ end
+
+ # Fio answers a range with no movements with an empty body. Reading that as a failure
+ # would stall the cursor on a quiet account forever.
+ test "treats an empty response body as a statement with no movements" do
+ Provider::Fio.stub(:get, ->(_url, headers:) { FakeResponse.new(code: 200, message: "OK", body: "") }) do
+ statement = Provider::Fio.new("fio-token").get_statement(from: Date.current, to: Date.current)
+
+ assert_empty statement
+ end
+ end
+
+ # Section 8 of the API documentation. None of these statuses mean what the HTTP status
+ # alone suggests, and each one the caller handles differently: 409 defers, 422 clamps
+ # the window, 413 asks the user for a shorter one, 500 is a dead token.
+ test "maps documented error statuses onto typed errors" do
+ {
+ 409 => [ Provider::Fio::RateLimitError, :rate_limited ],
+ 413 => [ Provider::Fio::TooManyItemsError, :too_many_items ],
+ 422 => [ Provider::Fio::HistoryLockedError, :history_locked ],
+ 500 => [ Provider::Fio::Error, :unauthorized ],
+ 404 => [ Provider::Fio::Error, :bad_request ],
+ 503 => [ Provider::Fio::Error, :server_error ]
+ }.each do |status, (error_class, failure_code)|
+ Provider::Fio.stub(:get, ->(_url, headers:) { FakeResponse.new(code: status, message: "", body: "") }) do
+ error = assert_raises(error_class) do
+ Provider::Fio.new("fio-token").get_statement(from: Date.current, to: Date.current)
+ end
+
+ assert_equal failure_code, error.failure_code, "status #{status}"
+ end
+ end
+ end
+
+ test "rejects a range that ends before it starts without calling the API" do
+ called = false
+
+ Provider::Fio.stub(:get, ->(_url, headers:) { called = true }) do
+ error = assert_raises(Provider::Fio::Error) do
+ Provider::Fio.new("fio-token").get_statement(from: Date.new(2026, 6, 30), to: Date.new(2026, 6, 1))
+ end
+
+ assert_equal :bad_request, error.failure_code
+ end
+
+ refute called
+ end
+
+ test "refuses to build a client without a token" do
+ error = assert_raises(Provider::Fio::Error) { Provider::Fio.new(" ") }
+
+ assert_equal :configuration_error, error.failure_code
+ end
+
+ # The token is a path segment, so an exception message or debug entry that echoed the
+ # URL would leak full account access into logs.
+ test "keeps the token out of error messages and diagnostics" do
+ Provider::Fio.stub(:get, ->(_url, headers:) { FakeResponse.new(code: 418, message: "", body: "teapot") }) do
+ error = assert_raises(Provider::Fio::Error) do
+ Provider::Fio.new("sekret-token").get_statement(from: Date.current, to: Date.current)
+ end
+
+ refute_includes error.message, "sekret-token"
+ end
+
+ entry = DebugLogEntry.where(provider_key: "fio").order(:created_at).last
+ assert_equal "Fio API returned an unexpected response status", entry.message
+ refute_includes entry.metadata.to_json, "sekret-token"
+ end
+end