The personal finance app for everyone (by everyone)
Ruby
Add CoinSpot exchange support (#3453)
jaysbeekay629bf2aca630
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex 0bc1359fa8..b9fc42c8a7 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -34,6 +34,7 @@ class AccountsController < ApplicationController)@binance_items = visible_provider_items(family.binance_items.ordered.with_attached_logo.includes(:binance_accounts, :accounts))@kraken_items = visible_provider_items(family.kraken_items.ordered.with_attached_logo.includes(:kraken_accounts, :accounts))+ @coinspot_items = visible_provider_items(family.coinspot_items.ordered.with_attached_logo.includes(:coinspot_accounts, :accounts))@trading212_items = visible_provider_items(family.trading212_items.ordered.with_attached_logo.includes(:trading212_accounts)).sort_by(&:created_at)@questrade_items = visible_provider_items(family.questrade_items.ordered.with_attached_logo.includes(:accounts, questrade_accounts: :account_provider))@wise_items = visible_provider_items(family.wise_items.ordered.includes(:wise_accounts, :accounts))@@ -371,6 +372,7 @@ class AccountsController < ApplicationController@sophtron_items,@binance_items,@kraken_items,+ @coinspot_items,@trading212_items,@questrade_items,@wise_items,diff --git a/app/controllers/coinspot_items_controller.rb b/app/controllers/coinspot_items_controller.rbnew file mode 100644index 0000000000..f833d8481a--- /dev/null+++ b/app/controllers/coinspot_items_controller.rb@@ -0,0 +1,363 @@+# frozen_string_literal: true++class CoinspotItemsController < ApplicationController+ before_action :set_coinspot_item, only: %i[update destroy sync setup_accounts complete_account_setup]+ before_action :require_admin!, only: %i[+ create select_accounts link_accounts select_existing_account link_existing_account+ update destroy sync setup_accounts complete_account_setup+ ]++ # Creates a new CoinSpot connection from the settings panel form, sets its+ # institution branding, and queues the first sync.+ def create+ @coinspot_item = Current.family.coinspot_items.build(coinspot_item_params)+ @coinspot_item.name ||= t(".default_name")++ if @coinspot_item.save+ @coinspot_item.set_coinspot_institution_defaults!+ @coinspot_item.sync_later+ render_panel_success(t(".success"))+ else+ render_panel_error(@coinspot_item.errors.full_messages.join(", "))+ end+ end++ # Updates a connection's editable fields (name, sync start date, and+ # optionally new credentials).+ def update+ if @coinspot_item.update(coinspot_item_params)+ render_panel_success(t(".success"))+ else+ render_panel_error(@coinspot_item.errors.full_messages.join(", "))+ end+ end++ # Unlinks every account from this connection, then schedules the+ # connection itself for asynchronous deletion.+ def destroy+ # unlink_all! captures a per-account failure on the result rather than+ # raising, so discarding the results scheduled the connection for deletion+ # even when accounts were still linked to it -- taking their provider+ # links down with it.+ unlink_results = @coinspot_item.unlink_all!(dry_run: false)+ if unlink_results.any? { |result| result[:error].present? }+ redirect_to settings_providers_path, alert: t(".unlink_failed")+ return+ end++ @coinspot_item.destroy_later+ redirect_to settings_providers_path, notice: t(".success")+ end++ # Queues a manual sync, unless one is already running.+ def sync+ @coinspot_item.sync_later unless @coinspot_item.syncing?++ respond_to do |format|+ format.html { redirect_back_or_to settings_providers_path }+ format.json { head :ok }+ end+ end++ # Entry point for adding a new CoinSpot-backed account: resolves which+ # connection to use (from the param, or the family's only credentialed+ # one) and redirects into account setup, or back with a selection prompt+ # when the connection is ambiguous or missing.+ def select_accounts+ account_flow = coinspot_item_account_flow_context+ coinspot_item = account_flow[:coinspot_item]++ unless coinspot_item+ redirect_to settings_providers_path, alert: coinspot_item_selection_message(account_flow[:credentialed_items])+ return+ end++ redirect_to setup_accounts_coinspot_item_path(coinspot_item, return_to: safe_return_to_path), status: :see_other+ end++ # Entry point for linking an already-existing manual account to a CoinSpot+ # connection: resolves the connection and redirects into account setup.+ def link_accounts+ coinspot_item = coinspot_item_account_flow_context[:coinspot_item]+ unless coinspot_item+ redirect_to settings_providers_path, alert: t(".select_connection")+ return+ end++ redirect_to setup_accounts_coinspot_item_path(coinspot_item), status: :see_other+ end++ # Renders the dialog for picking which unlinked CoinSpot account to attach+ # to an existing manual Crypto exchange account.+ def select_existing_account+ @account = Current.family.accounts.find(params[:account_id])+ # require_admin! is a family-role check, not an account one: an admin who+ # neither owns this account nor holds full_control on it still reaches+ # here. auto_share_with_family! only grants members read_write, so without+ # this the dialog exposes a co-member's account to be linked.+ return unless require_account_permission!(@account, :write, redirect_path: accounts_path)++ account_flow = coinspot_item_account_flow_context+ @coinspot_item = account_flow[:coinspot_item]++ unless manual_crypto_exchange_account?(@account)+ redirect_to accounts_path, alert: t("coinspot_items.link_existing_account.errors.only_manual")+ return+ end++ unless @coinspot_item+ redirect_to settings_providers_path, alert: coinspot_item_selection_message(account_flow[:credentialed_items])+ return+ end++ @available_coinspot_accounts = @coinspot_item.coinspot_accounts+ .left_joins(:account_provider)+ .where(account_providers: { id: nil })+ .order(:name)++ render :select_existing_account, layout: false+ end++ # Links a chosen unlinked CoinSpot account to an existing manual account+ # and queues a sync so its history imports immediately.+ def link_existing_account+ @account = Current.family.accounts.find(params[:account_id])+ # Must precede the AccountProvider.create! below: family scoping alone+ # would let an admin attach a provider to a co-member's account they only+ # hold read_write on. Same guard as select_existing_account.+ return unless require_account_permission!(@account, :write, redirect_path: accounts_path)++ coinspot_item = coinspot_item_account_flow_context[:coinspot_item]++ unless manual_crypto_exchange_account?(@account)+ return redirect_or_flash_error(t(".errors.only_manual"), account_path(@account))+ end++ unless coinspot_item+ redirect_to settings_providers_path, alert: t(".select_connection")+ return+ end++ coinspot_account = coinspot_item.coinspot_accounts.find_by(id: params[:coinspot_account_id])+ unless coinspot_account+ return redirect_or_flash_error(t(".errors.invalid_coinspot_account"), account_path(@account))+ end+ # Two locks, outer on @account, because the unique index is on+ # (account_id, provider_type): locking only the coinspot row lets two+ # requests pick DIFFERENT coinspot accounts for the SAME @account, both+ # pass their own check, and the second create! raise RecordNotUnique as an+ # unrescued 500. The eligibility check is repeated inside the lock, since+ # manual_crypto_exchange_account? read account_providers before it.+ already_linked = false+ @account.with_lock do+ if @account.reload.account_providers.any?+ already_linked = true+ else+ coinspot_account.with_lock do+ if coinspot_account.reload.account_provider.present?+ already_linked = true+ else+ AccountProvider.create!(account: @account, provider: coinspot_account)+ end+ end+ end+ end++ if already_linked+ return redirect_or_flash_error(t(".errors.coinspot_account_already_linked"), account_path(@account))+ end++ coinspot_item.sync_later++ redirect_to accounts_path, notice: t(".success")+ end++ # Renders the dialog listing this connection's not-yet-imported accounts+ # for the user to select from.+ def setup_accounts+ @coinspot_accounts = unlinked_accounts_for(@coinspot_item)+ end++ # Creates a Sure account for each selected, still-unlinked CoinSpot+ # account and processes its initial activity. A single account's failure+ # is logged and skipped rather than aborting the rest of the selection;+ # a created account whose provider link fails to save is torn back down+ # instead of left half-set-up.+ def complete_account_setup+ selected_accounts = Array(params[:selected_accounts]).reject(&:blank?)+ return_to = safe_return_to_path(params[:return_to])+ created_accounts = []+ failed_accounts = 0++ selected_accounts.each do |coinspot_account_id|+ coinspot_account = @coinspot_item.coinspot_accounts.find_by(id: coinspot_account_id)+ next unless coinspot_account++ coinspot_account.with_lock do+ if coinspot_account.account_provider.blank?+ account = Account.create_from_coinspot_account(coinspot_account)+ provider_link = coinspot_account.ensure_account_provider!(account)+ provider_link ? created_accounts << account : account.destroy!+ end+ end++ CoinspotAccount::Processor.new(coinspot_account.reload).process+ rescue StandardError => e+ failed_accounts += 1+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to setup account for CoinspotAccount: #{e.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: @coinspot_item.family,+ metadata: { coinspot_account_id: coinspot_account_id, error_class: e.class.name }+ )+ end++ @coinspot_item.update!(pending_account_setup: unlinked_accounts_for(@coinspot_item).exists?)+ @coinspot_item.sync_later if created_accounts.any?++ notice = if created_accounts.any?+ t(".success", count: created_accounts.count)+ elsif selected_accounts.empty?+ t(".none_selected")+ elsif failed_accounts == selected_accounts.count+ t(".setup_failed", count: failed_accounts)+ else+ t(".no_accounts")+ end++ redirect_to return_to || accounts_path, notice: notice, status: :see_other+ end++ private++ # Loads the connection scoped to the current family, 404ing if it+ # doesn't belong to them.+ def set_coinspot_item+ @coinspot_item = Current.family.coinspot_items.find(params[:id])+ end++ # Permitted connection attributes. Blank credential fields are dropped+ # on update so re-submitting the edit form without touching them doesn't+ # overwrite already-stored credentials with blanks.+ def coinspot_item_params+ permitted = params.require(:coinspot_item).permit(:name, :sync_start_date, :api_key, :api_secret)+ if @coinspot_item&.persisted?+ permitted.delete(:api_key) if permitted[:api_key].blank?+ permitted.delete(:api_secret) if permitted[:api_secret].blank?+ end+ permitted+ end++ # Reports a settings-panel action's success: a Turbo Stream update for a+ # frame request, or a full-page redirect otherwise.+ def render_panel_success(message)+ if turbo_frame_request?+ flash.now[:notice] = message+ @coinspot_items = Current.family.coinspot_items.active.ordered+ stream = turbo_stream.update(+ "coinspot-providers-panel",+ partial: "settings/providers/coinspot_panel",+ locals: { coinspot_items: @coinspot_items }+ )+ render turbo_stream: [ stream, *flash_notification_stream_items ]+ else+ redirect_to settings_providers_path, notice: message, status: :see_other+ end+ end++ # Reports a settings-panel action's failure: a Turbo Stream replace for a+ # frame request, or a full-page redirect with an alert otherwise.+ def render_panel_error(message)+ if turbo_frame_request?+ @coinspot_items = Current.family.coinspot_items.active.ordered+ render turbo_stream: turbo_stream.replace(+ "coinspot-providers-panel",+ partial: "settings/providers/coinspot_panel",+ locals: { error_message: message }+ ), status: :unprocessable_entity+ else+ redirect_to settings_providers_path, alert: message, status: :see_other+ end+ end++ # Resolves which connection an account-linking flow should act on: the+ # one named by params[:coinspot_item_id], or the family's only+ # credentialed connection when there's exactly one and no id was given.+ # Also returns every credentialed connection, for the selection prompt+ # when the target is ambiguous.+ def coinspot_item_account_flow_context+ credentialed_items = Current.family.coinspot_items+ .active.credentials_configured.ordered+ .select(&:credentials_configured?)+ item = if params[:coinspot_item_id].present?+ credentialed_items.find { |candidate| candidate.id.to_s == params[:coinspot_item_id].to_s }+ elsif credentialed_items.one?+ credentialed_items.first+ end++ { coinspot_item: item, credentialed_items: credentialed_items }+ end++ # A connection's CoinSpot accounts not yet linked to a Sure account.+ def unlinked_accounts_for(coinspot_item)+ coinspot_item.coinspot_accounts.left_joins(:account_provider).where(account_providers: { id: nil }).order(:name)+ end++ # Explains why no connection could be resolved: ambiguous (multiple+ # connections, none specified) versus none configured at all.+ def coinspot_item_selection_message(credentialed_items)+ if credentialed_items.count > 1 && params[:coinspot_item_id].blank?+ t("coinspot_items.select_accounts.select_connection")+ else+ t("coinspot_items.select_accounts.no_credentials_configured")+ end+ end++ # Only a manual Crypto exchange account with no existing provider link+ # is eligible to be linked to a CoinSpot account.+ def manual_crypto_exchange_account?(account)+ account.manual_crypto_exchange?+ end++ # Reports an error from a linking action: a flash Turbo Stream for a+ # frame request, or a redirect with an alert otherwise.+ def redirect_or_flash_error(message, fallback_path)+ if turbo_frame_request?+ flash.now[:alert] = message+ render turbo_stream: Array(flash_notification_stream_items)+ else+ redirect_to fallback_path, alert: message+ end+ end++ # Validates params[:return_to] is a same-origin relative path before+ # using it as a redirect target, rejecting anything with a scheme, host,+ # backslashes, control characters, or encoded separators (open-redirect protection).+ def safe_return_to_path(value = nil)+ return_value = value || params[:return_to]+ return nil if return_value.blank?++ return_to = return_value.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++ def encoded_path_separator?(return_to)+ encoded_second_character = return_to[1, 3]+ %w[%2F %5C].include?(encoded_second_character)+ end+enddiff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rbindex ca7174bed0..b694f35527 100644--- a/app/controllers/settings/providers_controller.rb+++ b/app/controllers/settings/providers_controller.rb@@ -202,6 +202,7 @@ class Settings::ProvidersController < ApplicationController{ key: "coinbase", title: "Coinbase", turbo_id: "coinbase", partial: "coinbase_panel" },{ key: "binance", title: "Binance", turbo_id: "binance", partial: "binance_panel" },{ key: "kraken", title: "Kraken", turbo_id: "kraken", partial: "kraken_panel" },+ { key: "coinspot", title: "CoinSpot", turbo_id: "coinspot", partial: "coinspot_panel" },{ key: "onchain_wallet", title: "On-chain wallets", turbo_id: "onchain_wallet", partial: "onchain_wallet_panel" },{ key: "snaptrade", title: "SnapTrade", turbo_id: "snaptrade", partial: "snaptrade_panel", auto_open: "manage" },{ key: "ibkr", title: "Interactive Brokers", turbo_id: "ibkr", partial: "ibkr_panel" },@@ -230,6 +231,7 @@ class Settings::ProvidersController < ApplicationController"coinbase" => "CoinbaseItem","binance" => "BinanceItem","kraken" => "KrakenItem",+ "coinspot" => "CoinspotItem","onchain_wallet" => "OnchainWalletItem","snaptrade" => "SnaptradeItem","questrade" => "QuestradeItem",@@ -270,6 +272,8 @@ class Settings::ProvidersController < ApplicationController@binance_items = Current.family.binance_items.active.orderedwhen "kraken"@kraken_items = Current.family.kraken_items.active.ordered+ when "coinspot"+ @coinspot_items = Current.family.coinspot_items.active.orderedwhen "onchain_wallet"@onchain_wallet_items = Current.family.onchain_wallet_items.active.orderedwhen "snaptrade"@@ -319,6 +323,7 @@ class Settings::ProvidersController < ApplicationController@indexa_capital_items = Current.family.indexa_capital_items.ordered.select(:id)@binance_items = Current.family.binance_items.active.ordered@kraken_items = Current.family.kraken_items.active.ordered+ @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)@@ -352,6 +357,7 @@ class Settings::ProvidersController < ApplicationController"coinbase" => @coinbase_items,"binance" => @binance_items,"kraken" => @kraken_items,+ "coinspot" => @coinspot_items,"onchain_wallet" => @onchain_wallet_items,"snaptrade" => @snaptrade_items,"questrade" => @questrade_items,diff --git a/app/models/account.rb b/app/models/account.rbindex b70858d20f..dc7932d5b9 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -419,6 +419,12 @@ class Account < ApplicationRecordcreate_from_crypto_exchange_account(kraken_account, family: kraken_account.kraken_item.family)end+ # Creates a manual Crypto account for a newly-selected CoinSpot account,+ # owned by the connection's family.+ def create_from_coinspot_account(coinspot_account)+ create_from_crypto_exchange_account(coinspot_account, family: coinspot_account.coinspot_item.family)+ end+# Self-custody assets are wallets, not exchanges: no trade entry by hand,# and no cash side. The balance is written by the provider sync, which is# the only thing that knows what the chain says.diff --git a/app/models/coinspot_account.rb b/app/models/coinspot_account.rbnew file mode 100644index 0000000000..6e1c55dd35--- /dev/null+++ b/app/models/coinspot_account.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++class CoinspotAccount < ApplicationRecord+ include Encryptable++ FIAT_CURRENCIES = %w[AUD USD EUR GBP CAD CHF JPY NZD SGD HKD].freeze++ if encryption_ready?+ encrypts :raw_payload+ encrypts :raw_transactions_payload+ end++ belongs_to :coinspot_item++ has_one :account_provider, as: :provider, dependent: :destroy+ has_one :account, through: :account_provider, source: :account++ validates :name, :account_id, :account_type, :currency, presence: true++ # The linked Sure account this CoinSpot account is imported into, if any.+ def current_account+ account+ end++ # Links this CoinSpot account to a Sure account via an AccountProvider,+ # creating or updating the join record. Defaults to the already-linked+ # account when no target is given. Returns nil (rather than raising) on+ # failure so a single bad link doesn't abort a broader sync/import loop.+ def ensure_account_provider!(target_account = nil)+ acct = target_account || current_account+ return nil unless acct++ AccountProvider+ .find_or_initialize_by(provider_type: "CoinspotAccount", provider_id: id)+ .tap do |ap|+ ap.account = acct+ ap.save!+ end+ rescue StandardError => e+ Rails.logger.warn("CoinspotAccount #{id}: failed to link account provider - #{e.class}: #{e.message}")+ nil+ end+enddiff --git a/app/models/coinspot_account/aud_converter.rb b/app/models/coinspot_account/aud_converter.rbnew file mode 100644index 0000000000..53d8b41c1f--- /dev/null+++ b/app/models/coinspot_account/aud_converter.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++module CoinspotAccount::AudConverter+ class ConversionUnavailableError < StandardError; end++ private++ # Converts an AUD amount (all CoinSpot activity is reported in AUD) into+ # the account's target currency using the exchange rate for `date`.+ # Returns [converted_amount, approximate?, rate_date]: approximate? is+ # true when the nearest available rate came from a different date than+ # requested. Raises when a non-AUD amount cannot be converted. Persisting the raw AUD+ # number with a different currency would corrupt the account valuation.+ def convert_from_aud(amount, date:)+ amount = amount.to_d+ target = target_currency.presence || "AUD"+ return [ amount, false, date ] if target == "AUD"++ rate = ExchangeRate.find_or_fetch_rate(from: "AUD", to: target, date: date)+ raise ConversionUnavailableError, "No AUD-#{target} exchange rate for #{date}" unless rate++ # ExchangeRate validates presence but not numericality, so a zero,+ # negative or non-finite rate is storable -- and multiplying by one+ # silently writes a zeroed or sign-flipped valuation rather than failing.+ numeric_rate = rate.rate.to_d+ unless numeric_rate.finite? && numeric_rate.positive?+ raise ConversionUnavailableError, "AUD-#{target} exchange rate for #{date} is not usable: #{rate.rate.inspect}"+ end++ [ amount * numeric_rate, rate.date != date, rate.date ]+ rescue ConversionUnavailableError => e+ capture_conversion_failure(amount, date, target, e)+ raise+ rescue StandardError => e+ capture_conversion_failure(amount, date, target, e)+ raise ConversionUnavailableError, "AUD conversion failed: #{e.message}"+ end++ def capture_conversion_failure(amount, date, target, error)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "AUD conversion unavailable for #{target}: #{error.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_account.coinspot_item&.family,+ account_provider: coinspot_account.account_provider,+ metadata: {+ amount: amount.to_s("F"),+ date: date.to_s,+ target_currency: target,+ error_class: error.class.name+ }+ )+ end+enddiff --git a/app/models/coinspot_account/holdings_processor.rb b/app/models/coinspot_account/holdings_processor.rbnew file mode 100644index 0000000000..0e51456290--- /dev/null+++ b/app/models/coinspot_account/holdings_processor.rb@@ -0,0 +1,183 @@+# frozen_string_literal: true++class CoinspotAccount::HoldingsProcessor+ include CoinspotAccount::AudConverter++ class SnapshotUnavailableError < StandardError; end++ # Initializes with the CoinspotAccount whose latest balance snapshot+ # (raw_payload) will be turned into holdings.+ def initialize(coinspot_account)+ @coinspot_account = coinspot_account+ end++ # Imports every non-AUD asset in the account's latest balance snapshot as a+ # holding, then zeroes out any previously-imported holding whose security+ # is absent from that snapshot (sold/transferred away entirely). No-op for+ # accounts not yet linked to a Crypto Sure account. Returns structured+ # failures so the parent sync cannot report a partial import as successful.+ def process+ return unless account&.accountable_type == "Crypto"++ # An unavailable snapshot is NOT an empty portfolio. raw_payload["assets"]+ # missing (a failed or never-completed fetch) used to read as [], and+ # mark_absent_provider_holdings_zero! then zeroed every holding the+ # account had. A genuinely empty array still zeroes, which is how a+ # wallet emptied down to nothing is represented.+ assets = snapshot_assets+ unless assets+ failure = log_failure(nil, SnapshotUnavailableError.new("CoinSpot balance snapshot has no assets array"))+ return { success: false, failures: [ failure ] }+ end++ failures = assets.filter_map { |asset| process_asset(asset) }+ mark_absent_provider_holdings_zero!+ { success: failures.empty?, failures: failures }+ rescue StandardError => e+ failure = log_failure(nil, e)+ { success: false, failures: [ failure ] }+ end++ private++ attr_reader :coinspot_account++ # The family's base currency -- holdings are always imported in it.+ def target_currency+ coinspot_account.coinspot_item&.family&.currency+ end++ # The linked Sure account holdings are imported into.+ def account+ coinspot_account.current_account+ end++ # The `assets` array from the account's last-synced balance snapshot, or+ # nil when the snapshot doesn't carry one. Callers must treat nil as+ # "unknown" rather than "empty" -- see #process.+ def snapshot_assets+ assets = coinspot_account.raw_payload&.dig("assets")+ assets.is_a?(Array) ? assets : nil+ end++ # The assets actually present in the snapshot; [] when unavailable, for+ # the read-only callers that only ask what is currently held.+ def raw_assets+ snapshot_assets || []+ end++ # Resolves one raw balance-snapshot asset to a Security and imports it as+ # a holding for today. Skips AUD (cash, not a holding) and anything+ # missing a symbol, balance, or AUD amount. A single asset's failure is+ # logged and returned while the rest of the snapshot is still attempted.+ def process_asset(asset)+ symbol = asset["symbol"] || asset[:symbol]+ return if symbol.to_s.upcase == "AUD"++ total = (asset["balance"] || asset[:balance] || 0).to_d+ amount_aud = asset["amount_aud"] || asset[:amount_aud]+ price_aud = asset["price_aud"] || asset[:price_aud]+ source = asset["source"] || asset[:source] || "spot"++ return if symbol.blank? || total.zero? || amount_aud.blank?++ security = CoinspotAccount::SecurityResolver.resolve(symbol)+ return unless security++ amount, amount_stale, amount_rate_date = convert_from_aud(amount_aud.to_d, date: Date.current)+ price = if price_aud.present?+ converted_price, price_stale, price_rate_date = convert_from_aud(price_aud.to_d, date: Date.current)+ log_stale_rate(symbol, "price", price_rate_date) if price_stale+ converted_price+ end+ log_stale_rate(symbol, "amount", amount_rate_date) if amount_stale++ import_adapter.import_holding(+ security: security,+ quantity: total,+ amount: amount,+ currency: target_currency,+ date: Date.current,+ price: price,+ cost_basis: nil,+ external_id: "coinspot_#{symbol}_#{source}_#{Date.current}",+ account_provider_id: coinspot_account.account_provider&.id,+ source: "coinspot",+ delete_future_holdings: false+ )+ nil+ rescue StandardError => e+ log_failure(symbol, e, asset)+ end++ def log_failure(symbol, error, asset = nil)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to process CoinSpot holding#{" #{symbol}" if symbol.present?}: #{error.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_account.coinspot_item&.family,+ account_provider: coinspot_account.account_provider,+ metadata: { symbol: symbol, asset: asset, error_class: error.class.name }+ )+ { kind: "holding", symbol: symbol, error: error.message, error_class: error.class.name }+ end++ def import_adapter+ @import_adapter ||= Account::ProviderImportAdapter.new(account)+ end++ # Zeroes out every previously-imported CoinSpot-owned holding whose+ # security is no longer present in the latest balance snapshot -- the+ # snapshot omits zero balances entirely, so without this a sold or+ # transferred-away position would keep showing its last nonzero value+ # (and latest_provider_holdings_snapshot_date would keep resolving to+ # that stale snapshot indefinitely).+ def mark_absent_provider_holdings_zero!+ provider_link = coinspot_account.account_provider+ return unless provider_link++ present_security_ids = raw_assets.filter_map do |asset|+ symbol = asset["symbol"] || asset[:symbol]+ next if symbol.to_s.upcase == "AUD"+ next if symbol.blank?++ balance = (asset["balance"] || asset[:balance] || 0).to_d+ next if balance.zero?++ CoinspotAccount::SecurityResolver.resolve(symbol)&.id+ end.to_set++ previously_seen = account.holdings+ .where(account_provider_id: provider_link.id)+ .where.not(security_id: present_security_ids.to_a)+ .includes(:security)+ .to_a+ .uniq(&:security_id)++ previously_seen.each do |holding|+ import_adapter.import_holding(+ security: holding.security,+ quantity: 0,+ amount: 0,+ currency: target_currency,+ date: Date.current,+ price: 0,+ cost_basis: nil,+ external_id: "coinspot_absent_#{holding.security_id}_#{Date.current}",+ account_provider_id: provider_link.id,+ source: "coinspot",+ delete_future_holdings: false+ )+ end+ end++ # Logs when a holding's amount/price was converted from AUD using a rate+ # that wasn't for the exact requested date (or no rate at all).+ def log_stale_rate(symbol, field, rate_date)+ Rails.logger.warn(+ "CoinspotAccount::HoldingsProcessor - stale FX rate for #{field} symbol=#{symbol} rate_date=#{rate_date || "unknown"}"+ )+ end+enddiff --git a/app/models/coinspot_account/processor.rb b/app/models/coinspot_account/processor.rbnew file mode 100644index 0000000000..9dec080105--- /dev/null+++ b/app/models/coinspot_account/processor.rb@@ -0,0 +1,399 @@+# frozen_string_literal: true++class CoinspotAccount::Processor+ include CoinspotAccount::AudConverter++ class NativeFeeConversionUnavailableError < StandardError; end+ class UnknownOrderTypeError < StandardError; end+ class UnparseableTimestampError < StandardError; end++ ORDER_TYPES = %w[buy sell].freeze++ # Serializes a record with hash keys sorted recursively (array order is+ # preserved, since it carries meaning) so a content hash identifies the+ # record itself rather than the key order the provider happened to send.+ def self.canonical_json(record)+ deep_sort_keys(record).to_json+ end++ def self.deep_sort_keys(value)+ case value+ when Hash then value.sort_by { |key, _| key.to_s }.to_h { |key, nested| [ key, deep_sort_keys(nested) ] }+ when Array then value.map { |element| deep_sort_keys(element) }+ else value+ end+ end++ attr_reader :coinspot_account++ # Initializes with the CoinspotAccount whose latest synced snapshot+ # (balances + transaction history) will be turned into a Sure account's+ # balance, holdings, and activity.+ def initialize(coinspot_account)+ @coinspot_account = coinspot_account+ end++ # Updates the linked Sure account's balance and imports every kind of+ # activity CoinSpot reports for it: holdings, orders, sends/receives, and+ # AUD deposits/withdrawals. No-op until the account is actually linked.+ def process+ return unless coinspot_account.current_account.present?++ holdings_result = CoinspotAccount::HoldingsProcessor.new(coinspot_account).process+ failures = Array(holdings_result&.dig(:failures))+ process_account!+ failures.concat(process_orders)+ failures.concat(process_send_receive)+ failures.concat(process_fiat_deposits)+ failures.concat(process_fiat_withdrawals)++ { success: failures.empty?, failures: failures }+ end++ private++ # The family's base currency -- all imported amounts are converted into it.+ def target_currency+ coinspot_account.coinspot_item&.family&.currency+ end++ # The linked Sure account activity is imported into.+ def account+ coinspot_account.current_account+ end++ def import_adapter+ @import_adapter ||= Account::ProviderImportAdapter.new(account)+ end++ # Updates the linked account's balance from CoinSpot's reported total,+ # converted to the family currency, and records whether that conversion+ # used a stale (non-exact-date) FX rate.+ def process_account!+ amount, stale, rate_date = convert_from_aud((coinspot_account.current_balance || 0).to_d, date: Date.current)++ account.update!(+ balance: amount,+ cash_balance: 0,+ currency: target_currency+ )++ coinspot_account.update!(extra: coinspot_account.extra.to_h.deep_merge(build_stale_extra(stale, rate_date)))+ end++ # Imports every buy/sell order from the three shapes CoinSpot's history+ # endpoints can return them in: the primary buy/sell-order history, and+ # the market-order fallback (a flat "orders" list whose type is inferred+ # per order rather than split by endpoint).+ def process_orders+ failures = []+ Array(raw_transactions.dig("orders", "buyorders")).each { |order| failures << process_order(order, "buy") }+ Array(raw_transactions.dig("orders", "sellorders")).each { |order| failures << process_order(order, "sell") }+ Array(raw_transactions.dig("orders", "orders")).each { |order| failures << process_order(order, infer_order_type(order)) }+ failures.compact+ end++ # Imports one buy/sell order as a trade, plus its fee as a separate+ # transaction when CoinSpot reports one. A single order's failure is+ # captured to DebugLogEntry and skipped rather than aborting the batch.+ def process_order(order, type)+ symbol = CoinspotAccount::SecurityResolver.normalize_symbol(order["coin"].presence || market_base(order["market"]))+ security = CoinspotAccount::SecurityResolver.resolve(symbol)+ return unless security++ quantity = order["amount"].to_d+ return if quantity.zero?++ rate = order["rate"].to_d+ total_aud = order["audtotal"].presence&.to_d || order["total"].to_d+ fee_aud = order["audfeeExGst"].to_d + order["audGst"].to_d+ order_type = validate_order_type!(type)+ date = parse_date!(order["solddate"] || order["created"], "order")+ type = order_type+ signed_quantity = type == "sell" ? -quantity.abs : quantity.abs+ amount_aud = type == "sell" ? total_aud.abs : -total_aud.abs++ amount, = convert_from_aud(amount_aud, date: date)+ price = trade_price(amount: amount, quantity: quantity, fallback_rate: rate, date: date)+ external_id = order_external_id(order, type, symbol, date)++ Entry.transaction do+ import_adapter.import_trade(+ external_id: external_id,+ security: security,+ quantity: signed_quantity,+ price: price,+ amount: amount,+ currency: target_currency,+ date: date,+ name: "#{type.capitalize} #{quantity.round(8)} #{symbol}",+ source: "coinspot",+ activity_label: type == "sell" ? "Sell" : "Buy"+ )++ import_fee(order, fee_aud, date, symbol) if fee_aud.positive?+ end+ nil+ rescue StandardError => e+ log_record_failure("order", order, e)+ end++ # Imports every on-chain send and receive as account activity.+ def process_send_receive+ failures = []+ Array(raw_transactions.dig("send_receive", "sendtransactions")).each do |transaction|+ failures << process_coin_movement(transaction, "send")+ end+ Array(raw_transactions.dig("send_receive", "receivetransactions")).each do |transaction|+ failures << process_coin_movement(transaction, "receive")+ end+ failures.compact+ end++ # Imports one on-chain send/receive as a contribution (receive) or+ # withdrawal (send) transaction, plus its network fee (converted from the+ # native asset to AUD) as a separate transaction when CoinSpot reports one.+ def process_coin_movement(transaction, type)+ symbol = CoinspotAccount::SecurityResolver.normalize_symbol(transaction["coin"])+ date = parse_date!(transaction["timestamp"], "send_receive")+ aud_amount = transaction["aud"].to_d+ signed_amount = type == "receive" ? -aud_amount.abs : aud_amount.abs+ amount, = convert_from_aud(signed_amount, date: date)+ label = type == "receive" ? "Contribution" : "Withdrawal"+ external_id = coin_movement_external_id(transaction, type, symbol, date)++ Entry.transaction do+ import_adapter.import_transaction(+ external_id: external_id,+ amount: amount,+ currency: target_currency,+ date: date,+ name: "#{label} #{transaction["amount"]} #{symbol}",+ source: "coinspot",+ investment_activity_label: label,+ extra: { "coinspot" => transaction.merge("type" => type) }+ )++ send_fee_aud = native_fee_to_aud(transaction["sendfee"], transaction)+ import_fee(transaction, send_fee_aud, date, symbol) if send_fee_aud&.positive?+ end+ nil+ rescue StandardError => e+ log_record_failure("send_receive", transaction, e)+ end++ # Imports every AUD deposit as account activity.+ def process_fiat_deposits+ failures = []+ Array(raw_transactions.dig("deposits", "deposits")).each do |deposit|+ failures << process_fiat_movement(deposit, "deposit")+ end+ failures.compact+ end++ # Imports every AUD withdrawal as account activity.+ def process_fiat_withdrawals+ failures = []+ Array(raw_transactions.dig("withdrawals", "withdrawals")).each do |withdrawal|+ failures << process_fiat_movement(withdrawal, "withdrawal")+ end+ failures.compact+ end++ # Imports one AUD deposit/withdrawal as a contribution/withdrawal transaction.+ def process_fiat_movement(transaction, type)+ date = parse_date!(transaction["created"], type)+ signed_aud = type == "deposit" ? -transaction["amount"].to_d.abs : transaction["amount"].to_d.abs+ amount, = convert_from_aud(signed_aud, date: date)+ label = type == "deposit" ? "Contribution" : "Withdrawal"+ external_id = fiat_external_id(transaction, type, date)++ import_adapter.import_transaction(+ external_id: external_id,+ amount: amount,+ currency: target_currency,+ date: date,+ name: "CoinSpot #{label.downcase}",+ source: "coinspot",+ investment_activity_label: label,+ extra: { "coinspot" => transaction.merge("type" => type) }+ )+ nil+ rescue StandardError => e+ log_record_failure(type, transaction, e)+ end++ def log_record_failure(kind, record, error)+ details = sanitized_record(record)++ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to process CoinSpot #{kind} record: #{error.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_account.coinspot_item&.family,+ metadata: { record: details, error_class: error.class.name }+ )+ { kind: kind, error: error.message, error_class: error.class.name, record: details }+ end++ # An allowlist, not a redaction list: the whole provider record used to go+ # into DebugLogEntry and into the failure result the syncer surfaces, which+ # put addresses, transaction ids and amounts in front of anyone who can+ # read the debug UI. Only what is needed to identify the failing record is+ # kept, and anything new CoinSpot adds is excluded by default.+ SAFE_RECORD_KEYS = %w[id txid reference coin market type].freeze++ def sanitized_record(record)+ return {} unless record.is_a?(Hash)++ record.slice(*SAFE_RECORD_KEYS)+ end++ # Imports a fee (already in AUD) as its own transaction, keyed off a hash+ # of the source record so re-processing the same history doesn't duplicate it.+ def import_fee(source_record, fee_aud, date, symbol)+ amount, = convert_from_aud(fee_aud.to_d.abs, date: date)+ fee_id = content_id(source_record) { |digest| "coinspot_fee_#{digest}" }+ external_id = "coinspot_fee_#{fee_id}"++ import_adapter.import_transaction(+ external_id: external_id,+ amount: amount,+ currency: target_currency,+ date: date,+ name: "CoinSpot fee #{symbol}",+ source: "coinspot",+ investment_activity_label: "Fee",+ extra: { "coinspot" => source_record.merge("fee_for" => symbol) }+ )+ end++ # Converts a network fee denominated in the transferred asset into AUD+ # using the transfer's own AUD value, which reflects the transaction date.+ def native_fee_to_aud(native_fee, transaction)+ fee = native_fee.presence&.to_d+ return nil unless fee&.positive?++ native_amount = transaction["amount"].to_d.abs+ aud_amount = transaction["aud"].to_d.abs+ unless native_amount.positive? && aud_amount.positive?+ raise NativeFeeConversionUnavailableError, "CoinSpot send fee has no transaction-date AUD valuation"+ end++ fee * aud_amount / native_amount+ end++ # The cached order/transfer/deposit/withdrawal history payload for this account.+ def raw_transactions+ coinspot_account.raw_transactions_payload || {}+ end++ # Per-unit trade price in the account's currency. Prefers deriving it+ # from the already-converted amount and quantity (correct for every+ # order type, including crypto-to-crypto market orders where CoinSpot's+ # own `rate` field is denominated in the market's quote asset rather than+ # AUD); only falls back to converting `rate` from AUD when amount or+ # quantity aren't usable.+ def trade_price(amount:, quantity:, fallback_rate:, date:)+ return amount.abs / quantity.abs if quantity.present? && !quantity.zero? && amount.present? && !amount.zero?++ fallback_price, = convert_from_aud(fallback_rate, date: date)+ fallback_price+ end++ # CoinSpot's flat market-order-history fallback doesn't split buy/sell+ # into separate lists like the primary history endpoint does, so the type+ # has to be read off each order individually. Anything unrecognised is+ # passed through verbatim for validate_order_type! to reject inside+ # process_order's rescue -- mapping it to "buy" here would silently record+ # a sell as a buy, with the wrong sign on both quantity and cash flow.+ def infer_order_type(order)+ order["type"].to_s.downcase.presence+ end++ # An order whose type isn't one of the two CoinSpot reports is a record we+ # cannot sign correctly, so it becomes a structured per-record failure+ # rather than a guess.+ def validate_order_type!(type)+ normalized = type.to_s.downcase+ return normalized if ORDER_TYPES.include?(normalized)++ raise UnknownOrderTypeError, "CoinSpot order has unknown type #{type.inspect}"+ end++ # A record whose timestamp can't be parsed would otherwise be stamped with+ # Date.current, and since the date is part of every external id, the next+ # sync that parses it correctly would import it a second time instead of+ # updating it.+ def parse_date!(value, kind)+ parsed = parse_time(value)&.to_date+ return parsed if parsed++ raise UnparseableTimestampError, "CoinSpot #{kind} record has unparseable timestamp #{value.inspect}"+ end++ # The base asset symbol from a "BASE/QUOTE" market pair (e.g. "ETH" from "ETH/BTC").+ def market_base(market)+ market.to_s.split("/").first+ end++ # Stable external id for a trade, so re-importing the same order history+ # updates rather than duplicates it. Falls back to a content hash when+ # CoinSpot doesn't supply its own order id.+ def order_external_id(order, type, symbol, date)+ id = order["id"].presence || content_id(order) { |digest| "coinspot_order_#{type}_#{symbol}_#{date}_#{digest}" }+ "coinspot_order_#{type}_#{symbol}_#{date}_#{id}"+ end++ # Stable external id for a send/receive transaction.+ def coin_movement_external_id(transaction, type, symbol, date)+ id = transaction["txid"].presence || transaction["reference"].presence ||+ content_id(transaction) { |digest| "coinspot_#{type}_#{symbol}_#{date}_#{digest}" }+ "coinspot_#{type}_#{symbol}_#{date}_#{id}"+ end++ # Stable external id for an AUD deposit/withdrawal transaction.+ def fiat_external_id(transaction, type, date)+ id = transaction["reference"].presence ||+ content_id(transaction) { |digest| "coinspot_#{type}_aud_#{date}_#{digest}" }+ "coinspot_#{type}_aud_#{date}_#{id}"+ end++ # Content hash for a record CoinSpot gave no id of its own.+ #+ # New records hash the key-sorted form, so a provider key-order change+ # can't produce a second id for the same record. Records imported before+ # that change were hashed unsorted, so the legacy digest is checked first+ # via the caller's id format: switching them to the canonical digest would+ # re-import every historical id-less trade, movement and fee as a+ # duplicate -- the exact harm the canonical form exists to prevent.+ def content_id(record)+ legacy = Digest::SHA256.hexdigest(record.to_json)[0, 24]+ return legacy if account.entries.exists?(external_id: yield(legacy), source: "coinspot")++ Digest::SHA256.hexdigest(self.class.canonical_json(record))[0, 24]+ end++ # Parses a CoinSpot timestamp string, returning nil rather than raising+ # on anything unparseable.+ def parse_time(value)+ Time.zone.parse(value.to_s)+ rescue ArgumentError, TypeError+ nil+ end++ # Metadata recording whether the account balance's AUD conversion used a+ # stale (non-exact-date) exchange rate, surfaced on the account so the UI+ # can flag an approximate balance.+ def build_stale_extra(stale, rate_date)+ {+ "coinspot" => {+ "stale_rate" => stale,+ "rate_target_date" => Date.current.to_s,+ "rate_used_date" => rate_date&.to_s+ }+ }+ end+enddiff --git a/app/models/coinspot_account/security_resolver.rb b/app/models/coinspot_account/security_resolver.rbnew file mode 100644index 0000000000..54a1d16690--- /dev/null+++ b/app/models/coinspot_account/security_resolver.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++class CoinspotAccount::SecurityResolver+ EXCHANGE_MIC = "XCSO"++ class << self+ # Resolves a CoinSpot asset symbol (e.g. "BTC") to a Security, preferring+ # a real market-data-backed match and falling back to an offline+ # placeholder security when none exists or the resolver errors. Returns+ # nil for fiat currencies and blank symbols, which aren't holdings.+ def resolve(symbol)+ normalized = normalize_symbol(symbol)+ return nil if normalized.blank? || CoinspotAccount::FIAT_CURRENCIES.include?(normalized)++ ticker = "CRYPTO:#{normalized}"+ Security::Resolver.new(ticker).resolve || offline_security!(ticker, normalized)+ rescue StandardError => e+ Rails.logger.warn "CoinspotAccount::SecurityResolver - resolver failed for #{ticker}: #{e.message}"+ offline_security!(ticker, normalized)+ end++ # Uppercases and trims a raw symbol, discarding anything CoinSpot appends+ # after a "|||" separator (seen on some market-order pair identifiers).+ # The blank check has to happen AFTER the suffix is dropped, not before:+ # "|||BTC" is not blank but yields an empty symbol, and "BTC |||AUD"+ # yields "BTC " with a trailing space that would build a bad ticker.+ def normalize_symbol(symbol)+ symbol.to_s.upcase.split("|||", 2).first&.strip.presence+ end++ private++ # Finds or creates a placeholder Security for a symbol with no real+ # market-data match, so holdings can still be recorded against it.+ def offline_security!(ticker, normalized)+ Security.find_or_initialize_by(ticker: ticker, exchange_operating_mic: EXCHANGE_MIC).tap do |security|+ security.name = normalized if security.name.blank?+ security.offline = true unless security.offline+ security.save! if security.changed?+ end+ rescue ActiveRecord::RecordNotUnique+ # Race: another sync inserted this placeholder between our SELECT and+ # INSERT. The unique index is on upper(ticker) + upper(mic), and both+ # values are already uppercase here, so the read-back matches it.+ # Same handling as ExchangeRate::Provided.+ Security.find_by!(ticker: ticker, exchange_operating_mic: EXCHANGE_MIC)+ end+ end+enddiff --git a/app/models/coinspot_item.rb b/app/models/coinspot_item.rbnew file mode 100644index 0000000000..8b9bbca3fd--- /dev/null+++ b/app/models/coinspot_item.rb@@ -0,0 +1,207 @@+# frozen_string_literal: true++class CoinspotItem < ApplicationRecord+ include Syncable, Provided, Unlinking, Encryptable++ enum :status, { good: "good", requires_update: "requires_update" }, default: :good++ if encryption_ready?+ encrypts :api_key, deterministic: true+ encrypts :api_secret+ encrypts :raw_payload+ end++ validates :name, presence: true+ validates :api_key, presence: true+ validates :api_secret, presence: true++ belongs_to :family+ has_one_attached :logo, dependent: :purge_later++ has_many :coinspot_accounts, dependent: :destroy+ has_many :accounts, through: :coinspot_accounts++ scope :active, -> { where(scheduled_for_deletion: false) }+ scope :syncable, -> { active }+ scope :ordered, -> { order(created_at: :desc) }+ scope :needs_update, -> { where(status: :requires_update) }+ scope :credentials_configured, -> { where.not(api_key: [ nil, "" ]).where.not(api_secret: nil) }++ before_validation :strip_credentials++ # Marks the connection for asynchronous deletion rather than destroying it+ # inline, so a large item with many accounts doesn't block the request.+ # `active` excludes a flagged row, so if the enqueue never lands the+ # connection disappears from the UI with no job coming to delete it and no+ # way for the user to retry. DestroyJob's own rescue only covers failures+ # once the job is *running*, which is the other side of this window.+ # perform_later can both raise (Redis down) and return false (a rejecting+ # enqueue callback), so both are restored.+ def destroy_later+ update!(scheduled_for_deletion: true)++ enqueued = DestroyJob.perform_later(self)+ update!(scheduled_for_deletion: false) if enqueued == false+ enqueued+ rescue StandardError+ update!(scheduled_for_deletion: false)+ raise+ end++ # Fetches and imports this connection's latest balances and transaction+ # history from CoinSpot. Raises if credentials aren't configured or the+ # import itself fails -- callers (the syncer) are responsible for turning+ # that into a sync status rather than this method swallowing it.+ def import_latest_coinspot_data+ provider = coinspot_provider+ raise StandardError, "CoinSpot credentials not configured" unless provider++ CoinspotItem::Importer.new(self, coinspot_provider: provider).import+ rescue StandardError => e+ Rails.logger.error "CoinspotItem #{id} - Failed to import: #{e.full_message}"+ raise+ end++ # Processes holdings and activity for every linked, visible CoinSpot+ # account. Returns a per-account result array rather than raising, so one+ # account's failure doesn't stop the rest from processing.+ def process_accounts+ return [] if coinspot_accounts.empty?++ results = []+ coinspot_accounts.joins(:account).merge(Account.visible).each do |coinspot_account|+ begin+ result = CoinspotAccount::Processor.new(coinspot_account).process+ success = result.nil? || result[:success] != false+ results << { coinspot_account_id: coinspot_account.id, success: success, result: result }+ rescue StandardError => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Failed to process CoinSpot account: #{e.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: family,+ account_provider: coinspot_account.account_provider,+ metadata: { coinspot_item_id: id, coinspot_account_id: coinspot_account.id, error_class: e.class.name }+ )+ results << { coinspot_account_id: coinspot_account.id, success: false, error: e.message }+ end+ end++ results+ end++ # Queues a Sync for every linked, visible account, chained under+ # `parent_sync` if given. Returns a per-account result array; a single+ # account's scheduling failure is logged and reported without blocking+ # the rest.+ 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 StandardError => e+ Rails.logger.error "CoinspotItem #{id} - Failed to schedule sync for account #{account.id}: #{e.full_message}"+ { account_id: account.id, success: false, error: e.message }+ end+ end++ # Stores the raw status/balances payload from the last successful fetch.+ def upsert_coinspot_snapshot!(payload)+ update!(raw_payload: payload)+ end++ # True once at least one CoinSpot account has been imported as a Sure account.+ def has_completed_initial_setup?+ accounts.any?+ end++ # Localized one-line summary of this connection's account sync state, for+ # the settings panel and account-list rows.+ def sync_status_summary+ total = total_accounts_count+ linked = linked_accounts_count+ unlinked = unlinked_accounts_count++ if total.zero?+ I18n.t("coinspot_items.coinspot_item.sync_status.no_accounts")+ elsif unlinked.zero?+ I18n.t("coinspot_items.coinspot_item.sync_status.all_synced", count: linked)+ else+ I18n.t("coinspot_items.coinspot_item.sync_status.partial_sync", linked_count: linked, unlinked_count: unlinked)+ end+ end++ # Number of CoinSpot accounts already linked to a Sure account.+ def linked_accounts_count+ coinspot_accounts.joins(:account_provider).count+ end++ # Number of CoinSpot accounts still needing account setup.+ def unlinked_accounts_count+ coinspot_accounts.left_joins(:account_provider).where(account_providers: { id: nil }).count+ end++ # Total CoinSpot accounts discovered for this connection.+ def total_accounts_count+ coinspot_accounts.count+ end++ # Active, linked accounts whose balance currently reflects a stale+ # (non-exact-date) FX conversion rather than the exact-date rate.+ def stale_rate_accounts+ coinspot_accounts+ .joins(:account)+ .where(accounts: { status: "active" })+ .where("coinspot_accounts.extra -> 'coinspot' ->> 'stale_rate' = 'true'")+ end++ # Best available label for the connection: institution name, falling back+ # to domain, then the connection's own name.+ def institution_display_name+ institution_name.presence || institution_domain.presence || name+ end++ # True when both API credentials are present (not necessarily valid).+ def credentials_configured?+ api_key.to_s.strip.present? && api_secret.to_s.strip.present?+ end++ # The next nonce to sign a request with. CoinSpot rejects a nonce that+ # doesn't strictly increase, so this is generated under a row lock and+ # compared against the last one used to guarantee monotonicity even when+ # requests race (e.g. a manual sync overlapping a scheduled one).+ def next_nonce!+ with_lock do+ candidate = Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)+ candidate = last_nonce.to_i + 1 if candidate <= last_nonce.to_i+ update!(last_nonce: candidate)+ candidate.to_s+ end+ end++ # Sets the standard CoinSpot branding/institution fields on a newly-created+ # connection (name, domain, URL, brand color).+ def set_coinspot_institution_defaults!+ update!(+ institution_name: "CoinSpot",+ institution_domain: "coinspot.com.au",+ institution_url: "https://www.coinspot.com.au",+ institution_color: "#0F6BFF"+ )+ end++ private++ # Trims whitespace a user may have pasted around their API credentials.+ def strip_credentials+ self.api_key = api_key.to_s.strip if api_key_changed? && !api_key.nil?+ self.api_secret = api_secret.to_s.strip if api_secret_changed? && !api_secret.nil?+ end+enddiff --git a/app/models/coinspot_item/importer.rb b/app/models/coinspot_item/importer.rbnew file mode 100644index 0000000000..2b40244c43--- /dev/null+++ b/app/models/coinspot_item/importer.rb@@ -0,0 +1,302 @@+# frozen_string_literal: true++class CoinspotItem::Importer+ class OrderHistoryUnavailableError < StandardError; end+ class MissingAssetPriceError < StandardError; end++ # CoinSpot's history endpoints default to the last 24 hours when `startdate`+ # is omitted, so an initial sync with no user-configured sync_start_date+ # would otherwise silently import almost nothing. Mirrors Wise::Importer's+ # DEFAULT_HISTORY_DAYS fallback for the same reason.+ DEFAULT_HISTORY_DAYS = 365++ attr_reader :coinspot_item, :coinspot_provider++ # Initializes with the connection and an authenticated Provider::Coinspot+ # client to fetch data with.+ def initialize(coinspot_item, coinspot_provider:)+ @coinspot_item = coinspot_item+ @coinspot_provider = coinspot_provider+ end++ # Fetches every kind of CoinSpot data (balances, orders, transfers,+ # deposits, withdrawals) and upserts it into the connection's single+ # combined CoinspotAccount record. Marks the item as needing updated+ # credentials on a permission failure; other errors propagate to the+ # caller (the syncer) to classify.+ def import+ status = coinspot_provider.status+ balances = coinspot_provider.get_balances+ orders = fetch_order_history+ send_receive = coinspot_provider.get_send_receive_history(**history_window)+ deposits = coinspot_provider.get_deposit_history(**history_window)+ withdrawals = coinspot_provider.get_withdrawal_history(**history_window)++ assets = parse_assets(balances)+ total_aud = assets.sum { |asset| asset[:amount_aud].to_d }.round(2)+ coinspot_account = upsert_coinspot_account(+ assets: assets,+ balances: balances,+ orders: orders,+ send_receive: send_receive,+ deposits: deposits,+ withdrawals: withdrawals,+ status: status,+ total_aud: total_aud+ )++ coinspot_item.upsert_coinspot_snapshot!({+ "status" => status,+ "balances" => balances,+ "imported_at" => Time.current.iso8601+ })++ {+ success: true,+ account_id: coinspot_account.id,+ assets_imported: assets.size,+ orders_imported: count_orders(orders),+ total_aud: total_aud+ }+ rescue Provider::Coinspot::PermissionError => e+ coinspot_item.update!(status: :requires_update)+ raise e+ end++ private++ # The startdate/enddate every history fetch is scoped to: the user's+ # configured sync_start_date, or DEFAULT_HISTORY_DAYS back when unset.+ # startdate is always present -- CoinSpot's endpoints silently default to+ # the last 24 hours when it's omitted.+ def history_window+ {+ startdate: coinspot_item.sync_start_date&.to_date || DEFAULT_HISTORY_DAYS.days.ago.to_date,+ enddate: Date.current+ }+ end++ # The three shapes CoinSpot's order-history endpoints return records in:+ # "buyorders"/"sellorders" from the primary endpoint (always that type),+ # and "orders" from the market-order fallback (mixed type, inferred per+ # order by CoinspotAccount::Processor#infer_order_type).+ ORDER_BUCKETS = %w[buyorders sellorders orders].freeze+ ORDER_HISTORY_LIMIT = Provider::Coinspot::MAX_ORDER_HISTORY_LIMIT++ # Fetches order history via the primary endpoint, falling back to the+ # market-order endpoint if the primary one errors. Partitions the date+ # range into 30-day windows, further bisecting any window whose response+ # comes back saturated (== ORDER_HISTORY_LIMIT), since that means more+ # records exist in that window than a single response can return.+ def fetch_order_history+ orders_by_id = ORDER_BUCKETS.index_with { {} }+ @failed_order_windows = []+ window_start = history_window[:startdate]+ window_end = history_window[:enddate]++ while window_start <= window_end+ current_window_end = [ window_start + 29.days, window_end ].min+ merge_window!(orders_by_id, startdate: window_start, enddate: current_window_end)+ window_start = current_window_end + 1.day+ end++ if @failed_order_windows.any?+ windows = @failed_order_windows.map { |window| "#{window[:startdate]}-#{window[:enddate]}" }.join(", ")+ raise OrderHistoryUnavailableError, "CoinSpot order history unavailable for #{windows}"+ end++ orders_by_id.transform_values(&:values)+ end++ # Fetches one date window and merges its records into `orders_by_id`+ # (deduped per bucket by order id). Bisects and retries when the+ # response is saturated, bottoming out at a single day -- CoinSpot+ # offers no finer-grained paging, so a still-saturated single day is+ # logged and accepted as an incomplete import rather than looped on.+ def merge_window!(orders_by_id, startdate:, enddate:)+ buckets = fetch_orders_for_window(startdate: startdate, enddate: enddate)++ if saturated?(buckets)+ if startdate < enddate+ midpoint = startdate + ((enddate - startdate) / 2).to_i.days+ merge_window!(orders_by_id, startdate: startdate, enddate: midpoint)+ merge_window!(orders_by_id, startdate: midpoint + 1.day, enddate: enddate)+ return+ end++ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "CoinSpot order history for #{startdate} may be incomplete: a single day hit the #{ORDER_HISTORY_LIMIT}-record response limit",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_item.family,+ metadata: { coinspot_item_id: coinspot_item.id, date: startdate.to_s }+ )+ # A saturated single day is known-truncated and CoinSpot offers no+ # finer paging, so persisting it would bake a partial history in as if+ # it were complete. Fail the window instead (fetch_order_history raises+ # on any failed window) rather than merging what came back.+ @failed_order_windows << { startdate: startdate, enddate: enddate }+ return+ end++ buckets.each do |kind, orders|+ orders.each do |order|+ order_id = order["id"] || order[:id]+ # Key-sorted before hashing: two responses describing the same order+ # with different key order would otherwise dedupe as two orders.+ deduplication_key = order_id.presence || Digest::SHA256.hexdigest(CoinspotAccount::Processor.canonical_json(order))+ orders_by_id[kind][deduplication_key] = order+ end+ end+ end++ def saturated?(buckets)+ buckets.values.any? { |orders| orders.size >= ORDER_HISTORY_LIMIT }+ end++ # Returns the primary endpoint's buy/sell orders for the window, or the+ # market-order fallback's mixed-type orders if the primary endpoint+ # errors. Both endpoints failing records the window; the importer checks+ # all remaining windows, then raises before replacing the saved snapshot.+ def fetch_orders_for_window(startdate:, enddate:)+ response = coinspot_provider.get_order_history(startdate: startdate, enddate: enddate)+ { "buyorders" => Array(response["buyorders"]), "sellorders" => Array(response["sellorders"]) }+ rescue Provider::Coinspot::ApiError => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "warn",+ message: "CoinSpot order history failed for window #{startdate}-#{enddate}; trying market order history: #{e.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_item.family,+ metadata: { coinspot_item_id: coinspot_item.id, error_class: e.class.name }+ )++ begin+ response = coinspot_provider.get_market_order_history(startdate: startdate, enddate: enddate)+ # Keep all three buckets: the market endpoint's documented response+ # also carries buyorders/sellorders, and reading only "orders"+ # discarded them. The mixed "orders" list stays as-is -- its side is+ # per-record, which is what infer_order_type reads.+ {+ "buyorders" => Array(response["buyorders"]),+ "sellorders" => Array(response["sellorders"]),+ "orders" => Array(response["orders"])+ }+ rescue Provider::Coinspot::ApiError => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "CoinSpot order history failed for window #{startdate}-#{enddate}: #{e.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_item.family,+ metadata: { coinspot_item_id: coinspot_item.id, error_class: e.class.name }+ )+ @failed_order_windows << { startdate: startdate, enddate: enddate }+ {}+ end+ end++ # Converts CoinSpot's balances response into the flat asset-list shape+ # the rest of the importer works with, dropping zero-balance/zero-value+ # entries and deriving an AUD amount from the rate when CoinSpot doesn't+ # supply one directly.+ def parse_assets(balances)+ Array(balances["balances"]).filter_map do |entry|+ symbol, balance_data = entry.first+ next if symbol.blank? || !balance_data.is_a?(Hash)++ balance = balance_data["balance"].to_d+ amount_aud = balance_data["audbalance"].presence&.to_d+ rate_aud = balance_data["rate"].presence&.to_d+ aud_asset = symbol.to_s.upcase == "AUD"+ amount_aud ||= balance if aud_asset++ if !aud_asset && balance.nonzero?+ amount_aud = balance * rate_aud if !amount_aud&.nonzero? && rate_aud&.positive?+ end++ if !aud_asset && balance.nonzero? && !amount_aud&.nonzero?+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "CoinSpot returned #{symbol.to_s.upcase} without an AUD valuation",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_item.family,+ metadata: { coinspot_item_id: coinspot_item.id, symbol: symbol.to_s.upcase, balance: balance.to_s("F") }+ )+ raise MissingAssetPriceError, "CoinSpot returned #{symbol.to_s.upcase} without an AUD balance or rate"+ end++ amount_aud ||= 0.to_d+ next if balance.zero? && amount_aud.zero?++ {+ symbol: symbol.to_s.upcase,+ balance: balance.to_s("F"),+ amount_aud: amount_aud.to_s("F"),+ price_aud: rate_aud&.to_s("F"),+ source: "spot"+ }+ end+ end++ # Finds or creates this connection's single combined CoinspotAccount+ # record and stores the freshly-fetched balance and transaction-history+ # payloads on it for CoinspotAccount::Processor to turn into activity.+ def upsert_coinspot_account(assets:, balances:, orders:, send_receive:, deposits:, withdrawals:, status:, total_aud:)+ coinspot_item.coinspot_accounts.find_or_initialize_by(account_id: "combined").tap do |account|+ account.assign_attributes(+ name: coinspot_item.institution_name.presence || "CoinSpot",+ account_type: "combined",+ currency: "AUD",+ current_balance: total_aud,+ institution_metadata: institution_metadata(assets),+ raw_payload: {+ "balances" => balances,+ "assets" => assets.map(&:stringify_keys),+ "status" => status,+ "fetched_at" => Time.current.iso8601+ },+ raw_transactions_payload: {+ "orders" => orders,+ "send_receive" => send_receive,+ "deposits" => deposits,+ "withdrawals" => withdrawals,+ "fetched_at" => Time.current.iso8601+ },+ extra: account.extra.to_h.deep_merge(price_metadata(assets))+ )+ account.save!+ end+ end++ # Institution branding plus a snapshot of which assets were seen, stored+ # on the account for display without re-parsing the raw payload.+ def institution_metadata(assets)+ {+ "name" => "CoinSpot",+ "domain" => "coinspot.com.au",+ "url" => "https://www.coinspot.com.au",+ "color" => "#0F6BFF",+ "asset_count" => assets.size,+ "assets" => assets.map { |asset| asset[:symbol] }+ }+ end++ # Flags any non-AUD asset CoinSpot returned with no price, so the UI can+ # surface which holdings' valuations are incomplete.+ def price_metadata(assets)+ missing = assets.select { |asset| asset[:price_aud].blank? && asset[:symbol] != "AUD" }.map { |asset| asset[:symbol] }+ { "coinspot" => { "missing_prices" => missing } }+ end++ # Total order count across every order-history shape CoinSpot can return.+ def count_orders(orders)+ Array(orders["buyorders"]).size + Array(orders["sellorders"]).size + Array(orders["orders"]).size+ end+enddiff --git a/app/models/coinspot_item/provided.rb b/app/models/coinspot_item/provided.rbnew file mode 100644index 0000000000..c63e31f796--- /dev/null+++ b/app/models/coinspot_item/provided.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module CoinspotItem::Provided+ extend ActiveSupport::Concern++ # A Provider::Coinspot client authenticated with this connection's stored+ # credentials, or nil until both are configured. Wires the client's nonce+ # generator to the item's own monotonic counter so concurrent requests+ # never reuse a nonce.+ def coinspot_provider+ return nil unless credentials_configured?++ Provider::Coinspot.new(+ api_key: api_key.to_s.strip,+ api_secret: api_secret.to_s.strip,+ nonce_generator: -> { next_nonce! }+ )+ end+enddiff --git a/app/models/coinspot_item/sync_complete_event.rb b/app/models/coinspot_item/sync_complete_event.rbnew file mode 100644index 0000000000..396b10db5b--- /dev/null+++ b/app/models/coinspot_item/sync_complete_event.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++class CoinspotItem::SyncCompleteEvent+ # Wraps the CoinspotItem to broadcast a sync-complete update for.+ def initialize(coinspot_item)+ unless coinspot_item.respond_to?(:family) && coinspot_item.respond_to?(:id)+ raise ArgumentError, "coinspot_item is required"+ end++ @coinspot_item = coinspot_item+ end++ # Turbo-broadcasts a re-render of this connection's card so its sync+ # status updates live in the browser without a page reload. Logs and+ # swallows failures -- a broadcast issue shouldn't fail the sync itself.+ def broadcast+ Turbo::StreamsChannel.broadcast_replace_to(+ @coinspot_item.family,+ target: ActionView::RecordIdentifier.dom_id(@coinspot_item),+ partial: "coinspot_items/coinspot_item",+ locals: { coinspot_item: @coinspot_item }+ )+ rescue StandardError => e+ Rails.logger.warn("CoinspotItem::SyncCompleteEvent failed for #{@coinspot_item.id}: #{e.class}")+ end+enddiff --git a/app/models/coinspot_item/syncer.rb b/app/models/coinspot_item/syncer.rbnew file mode 100644index 0000000000..5a073a1d1f--- /dev/null+++ b/app/models/coinspot_item/syncer.rb@@ -0,0 +1,140 @@+# frozen_string_literal: true++class CoinspotItem::Syncer+ include SyncStats::Collector++ # Raised (after logging) when one or more linked accounts fail to process+ # during a sync, so the generic StandardError rescue below doesn't also+ # catch and re-log an already-logged failure.+ class ProcessingFailureError < StandardError; end++ attr_reader :coinspot_item++ # Initializes with the connection to sync.+ def initialize(coinspot_item)+ @coinspot_item = coinspot_item+ end++ # Drives one full sync cycle: validates credentials, imports the latest+ # CoinSpot data, tracks which discovered accounts still need setup versus+ # which are already linked, processes activity for the linked ones, and+ # schedules their balance recalculation. A credential/permission failure+ # marks the connection as needing updated credentials; any linked+ # account's processing failure fails the whole sync (rather than+ # completing "successfully" with only partial history imported) after+ # capturing the failure details to DebugLogEntry.+ def perform_sync(sync)+ sync.update!(status_text: I18n.t("coinspot_item.syncer.checking_credentials")) if sync.respond_to?(:status_text)+ unless coinspot_item.credentials_configured?+ coinspot_item.update!(status: :requires_update)+ mark_failed(sync, I18n.t("coinspot_item.syncer.credentials_invalid"))+ return+ end++ sync.update!(status_text: I18n.t("coinspot_item.syncer.importing_accounts")) if sync.respond_to?(:status_text)+ coinspot_item.import_latest_coinspot_data+ coinspot_item.update!(status: :good) if coinspot_item.requires_update?++ sync.update!(status_text: I18n.t("coinspot_item.syncer.checking_configuration")) if sync.respond_to?(:status_text)+ collect_setup_stats(sync, provider_accounts: coinspot_item.coinspot_accounts.to_a)++ unlinked = coinspot_item.coinspot_accounts.left_joins(:account_provider).where(account_providers: { id: nil })+ linked = coinspot_item.coinspot_accounts.joins(:account_provider).joins(:account).merge(Account.visible)++ if unlinked.any?+ coinspot_item.update!(pending_account_setup: true)+ sync.update!(status_text: I18n.t("coinspot_item.syncer.accounts_need_setup", count: unlinked.count)) if sync.respond_to?(:status_text)+ else+ coinspot_item.update!(pending_account_setup: false)+ end++ return unless linked.any?++ sync.update!(status_text: I18n.t("coinspot_item.syncer.processing_accounts")) if sync.respond_to?(:status_text)+ process_results = coinspot_item.process_accounts+ processing_failures = process_results.select { |result| result[:success] == false }+ if processing_failures.any?+ message = I18n.t("coinspot_item.syncer.processing_failed", count: processing_failures.count)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: message,+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_item.family,+ metadata: { coinspot_item_id: coinspot_item.id, failures: processing_failures }+ )+ raise ProcessingFailureError, message+ end++ sync.update!(status_text: I18n.t("coinspot_item.syncer.calculating_balances")) if sync.respond_to?(:status_text)+ # schedule_account_syncs rescues per account and reports { success: false }+ # rather than raising. Discarding that let the sync report success while an+ # account kept a stale balance, so treat it like a processing failure.+ schedule_failures = coinspot_item.schedule_account_syncs(+ parent_sync: sync,+ window_start_date: sync.window_start_date,+ window_end_date: sync.window_end_date+ ).select { |result| result[:success] == false }++ if schedule_failures.any?+ message = I18n.t("coinspot_item.syncer.processing_failed", count: schedule_failures.count)+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: message,+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_item.family,+ metadata: { coinspot_item_id: coinspot_item.id, failures: schedule_failures }+ )+ raise ProcessingFailureError, message+ end++ account_ids = linked.map { |coinspot_account| coinspot_account.current_account&.id }.compact+ if account_ids.any?+ collect_transaction_stats(sync, account_ids: account_ids, source: "coinspot")+ collect_trades_stats(sync, account_ids: account_ids, source: "coinspot")+ end+ rescue Provider::Coinspot::AuthenticationError, Provider::Coinspot::PermissionError => e+ coinspot_item.update!(status: :requires_update)+ mark_failed(sync, e.message)+ raise+ rescue ProcessingFailureError => e+ mark_failed(sync, e.message)+ raise+ rescue StandardError => e+ DebugLogEntry.capture(+ category: "provider_sync_error",+ level: "error",+ message: "Unexpected error during CoinSpot sync: #{e.message}",+ source: self.class.name,+ provider_key: "coinspot",+ family: coinspot_item.family,+ metadata: { error_class: e.class.name, backtrace: e.backtrace&.first(5) }+ )+ mark_failed(sync, e.message)+ raise+ end++ # No follow-up work needed after a sync; required by the Syncer interface.+ def perform_post_sync+ end++ private++ # Transitions the sync record to :failed (via its state machine when+ # available) and records the error message for display.+ def mark_failed(sync, error_message)+ sync.start! if sync.respond_to?(:may_start?) && sync.may_start?++ if sync.respond_to?(:may_fail?) && sync.may_fail?+ sync.fail!+ elsif sync.respond_to?(:status)+ sync.update!(status: :failed)+ end++ sync.update!(error: error_message) if sync.respond_to?(:error)+ sync.update!(status_text: error_message) if sync.respond_to?(:status_text)+ end+enddiff --git a/app/models/coinspot_item/unlinking.rb b/app/models/coinspot_item/unlinking.rbnew file mode 100644index 0000000000..7e3abeafc9--- /dev/null+++ b/app/models/coinspot_item/unlinking.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++module CoinspotItem::Unlinking+ extend ActiveSupport::Concern++ # Detaches every CoinSpot account's link to its Sure account, clearing the+ # provider reference off any holdings first so they aren't destroyed along+ # with the link. Returns a per-account result array describing what would+ # be (or was) unlinked; pass dry_run: true to preview without changing+ # anything. A single account's unlink failure is captured on its result+ # and logged rather than aborting the rest.+ def unlink_all!(dry_run: false)+ results = []+ links_by_provider_id = AccountProvider+ .where(provider_type: CoinspotAccount.name, provider_id: coinspot_accounts.select(:id))+ .group_by { |link| link.provider_id.to_s }++ coinspot_accounts.find_each do |provider_account|+ links = links_by_provider_id[provider_account.id.to_s] || []+ link_ids = links.map(&:id)+ result = {+ provider_account_id: provider_account.id,+ name: provider_account.name,+ provider_link_ids: link_ids+ }+ results << result++ next if dry_run++ begin+ ActiveRecord::Base.transaction do+ Holding.where(account_provider_id: link_ids).update_all(account_provider_id: nil) if link_ids.any?+ links.each(&:destroy!)+ end+ rescue StandardError => e+ Rails.logger.warn("CoinspotItem Unlinker: failed to unlink ##{provider_account.id}: #{e.class} - #{e.message}")+ result[:error] = e.message+ end+ end++ results+ end+enddiff --git a/app/models/family.rb b/app/models/family.rbindex 2aee8b31fa..a97f07cfb9 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -1,7 +1,7 @@class Family < ApplicationRecordinclude Syncable, AutoTransferMatchable, Subscribeable, VectorSearchableinclude PlaidConnectable, SimplefinConnectable, LunchflowConnectable, AkahuConnectable, EnableBankingConnectable- include CoinbaseConnectable, BinanceConnectable, KrakenConnectable, CoinstatsConnectable, SnaptradeConnectable, MercuryConnectable, BrexConnectable, SophtronConnectable+ include CoinbaseConnectable, BinanceConnectable, KrakenConnectable, CoinspotConnectable, CoinstatsConnectable, SnaptradeConnectable, MercuryConnectable, BrexConnectable, SophtronConnectableinclude IndexaCapitalConnectable, IbkrConnectable, WiseConnectableinclude UpConnectableinclude MonobankConnectablediff --git a/app/models/family/coinspot_connectable.rb b/app/models/family/coinspot_connectable.rbnew file mode 100644index 0000000000..d3b8a2b939--- /dev/null+++ b/app/models/family/coinspot_connectable.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++module Family::CoinspotConnectable+ extend ActiveSupport::Concern++ included do+ has_many :coinspot_items, dependent: :destroy+ end++ # Whether this family is allowed to connect a CoinSpot account. Always+ # true today; exists as the hook other connectable concerns use for+ # plan/feature gating.+ def can_connect_coinspot?+ true+ end++ # Creates a new CoinSpot connection with the given credentials, sets its+ # institution branding, and queues the first sync.+ def create_coinspot_item!(api_key:, api_secret:, item_name: nil)+ item = coinspot_items.create!(+ name: item_name.presence || I18n.t("coinspot_items.create.default_name"),+ api_key: api_key,+ api_secret: api_secret+ )++ item.set_coinspot_institution_defaults!+ item.sync_later+ item+ end++ # True when this family has at least one active CoinSpot connection with+ # both API credentials configured.+ def has_coinspot_credentials?+ coinspot_items.active.any?(&:credentials_configured?)+ end+enddiff --git a/app/models/provider/coinspot.rb b/app/models/provider/coinspot.rbnew file mode 100644index 0000000000..a336ffdfbd--- /dev/null+++ b/app/models/provider/coinspot.rb@@ -0,0 +1,165 @@+# frozen_string_literal: true++class Provider::Coinspot+ include HTTParty+ extend SslConfigurable++ class Error < StandardError; end+ class AuthenticationError < Error; end+ class PermissionError < Error; end+ class RateLimitError < Error; end+ class NonceError < Error; end+ class ApiError < Error; end++ BASE_URL = "https://www.coinspot.com.au"+ READ_ONLY_PREFIX = "/api/v2/ro"++ # CoinSpot's order-history endpoints default to 200 records per response+ # when no `limit` is given, and cap at 500 -- always request the max so a+ # single response is less likely to silently truncate an active window.+ MAX_ORDER_HISTORY_LIMIT = 500++ base_uri BASE_URL+ default_options.merge!({ timeout: 30 }.merge(httparty_ssl_options))++ attr_reader :api_key, :api_secret++ # A client for CoinSpot's read-only v2 API, signing every request with the+ # given credentials. `nonce_generator` defaults to a millisecond+ # timestamp, but callers syncing from multiple processes/threads should+ # supply a monotonic one (e.g. CoinspotItem#next_nonce!) since CoinSpot+ # rejects a nonce that doesn't strictly increase.+ def initialize(api_key:, api_secret:, nonce_generator: nil)+ @api_key = api_key # pipelock:ignore user-supplied CoinSpot credential kept in memory for signed requests+ @api_secret = api_secret # pipelock:ignore user-supplied CoinSpot credential kept in memory for signed requests+ @nonce_generator = nonce_generator || -> { Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond).to_i }+ end++ # Confirms the credentials are valid and the API is reachable.+ def status+ read_only_post("/status")+ end++ # Current balances for every asset held on the account.+ def get_balances+ read_only_post("/my/balances")+ end++ # Completed buy/sell order history, optionally scoped to a date range.+ def get_order_history(startdate: nil, enddate: nil, limit: MAX_ORDER_HISTORY_LIMIT)+ read_only_post("/my/orders/completed", date_params(startdate: startdate, enddate: enddate).merge("limit" => limit))+ end++ # Completed market-order history -- a fallback CoinSpot exposes separately+ # from the primary order-history endpoint for market-type orders.+ def get_market_order_history(startdate: nil, enddate: nil, limit: MAX_ORDER_HISTORY_LIMIT)+ read_only_post("/my/orders/market/completed", date_params(startdate: startdate, enddate: enddate).merge("limit" => limit))+ end++ # On-chain send/receive transaction history.+ def get_send_receive_history(startdate: nil, enddate: nil)+ read_only_post("/my/sendreceive", date_params(startdate: startdate, enddate: enddate))+ end++ # AUD deposit history.+ def get_deposit_history(startdate: nil, enddate: nil)+ read_only_post("/my/deposits", date_params(startdate: startdate, enddate: enddate))+ end++ # AUD withdrawal history.+ def get_withdrawal_history(startdate: nil, enddate: nil)+ read_only_post("/my/withdrawals", date_params(startdate: startdate, enddate: enddate))+ end++ private++ attr_reader :nonce_generator++ # Builds the startdate/enddate request params CoinSpot expects+ # (YYYY-MM-DD), omitting either when not given.+ def date_params(startdate:, enddate:)+ {}.tap do |params|+ params["startdate"] = startdate.to_date.to_s if startdate.present?+ params["enddate"] = enddate.to_date.to_s if enddate.present?+ end+ end++ # Posts a signed request to CoinSpot's read-only API and returns the+ # parsed, successful response body, raising a classified error otherwise.+ def read_only_post(path, params = {})+ # CoinSpot requires an integer nonce and rejects a quoted one. The+ # injected generator (CoinspotItem#next_nonce!) returns a String so the+ # value survives a bigint column round-trip, and JSON.generate would+ # preserve that type -- sending "nonce":"1757..." in production even+ # though every test passed an Integer literal. Convert at the boundary.+ request_params = { "nonce" => Integer(nonce_generator.call) }.merge(stringify_params(params))+ body = JSON.generate(request_params)++ response = self.class.post(+ "#{READ_ONLY_PREFIX}#{path}",+ body: body,+ headers: {+ "Content-Type" => "application/json",+ "key" => api_key,+ "sign" => sign(body)+ }+ )++ handle_response(response)+ end++ # Stringifies every param key and value for a stable, predictable JSON body.+ def stringify_params(params)+ params.each_with_object({}) { |(key, value), hash| hash[key.to_s] = value.to_s }+ end++ # HMAC-SHA512 signature of the request body, as CoinSpot's API requires.+ def sign(body)+ OpenSSL::HMAC.hexdigest("sha512", api_secret, body)+ end++ # Parses and validates a CoinSpot response, raising a classified error+ # for a non-2xx status, a non-JSON-object body, or a JSON body whose own+ # "status" field reports "error".+ def handle_response(response)+ parsed = response.parsed_response++ unless response.code.between?(200, 299)+ message = (parsed["message"].presence if parsed.is_a?(Hash)) || "CoinSpot API request failed: #{response.code}"+ raise classified_error(message, http_status: response.code)+ end++ raise ApiError, "Malformed CoinSpot API response" unless parsed.is_a?(Hash)++ status = parsed["status"].to_s.downcase+ raise classified_error(parsed["message"].presence || "CoinSpot API request failed") if status == "error"++ parsed+ end++ # Classifies both by the response body's message (CoinSpot's normal error+ # shape, even on a 2xx status) and by HTTP status (401/403), since a+ # non-2xx credential/permission failure may arrive with a body CoinSpot+ # doesn't word the same way as its 2xx error responses. Either signal+ # matching is enough to classify -- the syncer only rescues+ # AuthenticationError/PermissionError to mark the item as needing updated+ # credentials, so a missed classification here silently falls through to+ # the generic failure path instead.+ def classified_error(message, http_status: nil)+ return AuthenticationError.new(message) if http_status == 401+ return PermissionError.new(message) if http_status == 403++ case message+ when /invalid key|invalid signature|authentication|unauthori[sz]ed/i+ AuthenticationError.new(message)+ when /permission|read.only|read only/i+ PermissionError.new(message)+ when /nonce/i+ NonceError.new(message)+ when /rate|too many|limit/i+ RateLimitError.new(message)+ else+ ApiError.new(message)+ end+ end+enddiff --git a/app/models/provider/coinspot_adapter.rb b/app/models/provider/coinspot_adapter.rbnew file mode 100644index 0000000000..48bc6e9314--- /dev/null+++ b/app/models/provider/coinspot_adapter.rb@@ -0,0 +1,131 @@+# frozen_string_literal: true++class Provider::CoinspotAdapter < Provider::Base+ include Provider::Syncable+ include Provider::InstitutionMetadata++ Provider::Factory.register("CoinspotAccount", self)++ # CoinSpot only supplies read-only exchange balances, so it can only back+ # the combined Crypto account type.+ def self.supported_account_types+ %w[Crypto]+ end++ # One connection card config per active, credentialed CoinSpot connection+ # the family has, for the account-linking UI. A single "connect CoinSpot"+ # card when none exist yet.+ def self.connection_configs(family:)+ return [] unless family.can_connect_coinspot?++ coinspot_items = family.coinspot_items.active.credentials_configured.ordered.select(&:credentials_configured?)+ return [ connection_config_for(nil) ] if coinspot_items.empty?++ coinspot_items.map { |coinspot_item| connection_config_for(coinspot_item) }+ end++ # Resolves and returns an authenticated Provider::Coinspot client for the+ # given family/connection, or nil if none is configured.+ def self.build_provider(family: nil, coinspot_item_id: nil)+ return nil unless family.present?++ coinspot_item = resolve_coinspot_item(family, coinspot_item_id)+ return nil unless coinspot_item&.credentials_configured?++ coinspot_item.coinspot_provider+ end++ def provider_name+ "coinspot"+ end++ # Path to trigger a manual sync of this account's connection.+ def sync_path+ return unless item++ Rails.application.routes.url_helpers.sync_coinspot_item_path(item)+ end++ # The CoinspotItem connection backing this account.+ def item+ provider_account.coinspot_item+ end++ # CoinSpot is read-only, so holdings it no longer reports are zeroed out+ # (see HoldingsProcessor#mark_absent_provider_holdings_zero!) rather than+ # deleted -- the provider adapter never deletes holdings itself.+ def can_delete_holdings?+ false+ end++ def institution_domain+ institution_metadata_value("domain")+ end++ def institution_name+ institution_metadata_value("name")+ end++ def institution_url+ institution_metadata_value("url")+ end++ def institution_color+ institution_metadata_value("color")+ end++ # Connection-card config for one CoinSpot connection (or the "connect new"+ # card when coinspot_item is nil): display name/description and the paths+ # for linking a new or existing account to it.+ def self.connection_config_for(coinspot_item)+ path_params = ->(extra = {}) do+ coinspot_item.present? ? extra.merge(coinspot_item_id: coinspot_item.id) : extra+ end++ {+ key: coinspot_item.present? ? "coinspot_#{coinspot_item.id}" : "coinspot",+ name: coinspot_item.present? ? I18n.t("coinspot_items.provider_connection.name", name: coinspot_item.name) : I18n.t("coinspot_items.provider_connection.default_name"),+ description: coinspot_item.present? ? I18n.t("coinspot_items.provider_connection.description", name: coinspot_item.name) : I18n.t("coinspot_items.provider_connection.default_description"),+ can_connect: true,+ new_account_path: ->(accountable_type, return_to) {+ Rails.application.routes.url_helpers.select_accounts_coinspot_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_coinspot_items_path(+ path_params.call(account_id: account_id)+ )+ }+ }+ end+ private_class_method :connection_config_for++ # The CoinspotItem to act on: the one explicitly given by id, or the+ # family's single credentialed connection when there's exactly one and no+ # id was given. Returns nil when ambiguous (multiple connections, no id)+ # or the resolved item lacks configured credentials.+ def self.resolve_coinspot_item(family, coinspot_item_id)+ if coinspot_item_id.present?+ item = family.coinspot_items.active.credentials_configured.find_by(id: coinspot_item_id)+ return item if item&.credentials_configured?++ return nil+ end++ credentialed_items = family.coinspot_items.active.credentials_configured.ordered.select(&:credentials_configured?)+ return credentialed_items.first if credentialed_items.one?++ nil+ end+ private_class_method :resolve_coinspot_item++ private++ # Institution metadata field, preferring the value cached on the account+ # (from its last import) and falling back to the live connection.+ def institution_metadata_value(key)+ metadata = provider_account.institution_metadata || {}+ metadata[key] || item&.public_send("institution_#{key}")+ end+enddiff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rbindex 45de6147c5..1e1b586298 100644--- a/app/models/provider/metadata.rb+++ b/app/models/provider/metadata.rb@@ -14,6 +14,7 @@ class Providercoinbase: { region: "Global", kinds: %w[Crypto], maturity: :beta, logo_text: "CB", logo_color: "#3b82f6", domain: "coinbase.com" },binance: { region: "Global", kinds: %w[Crypto], maturity: :beta, logo_text: "BI", logo_color: "#ca8a04", domain: "binance.com" },kraken: { region: "Global", kinds: %w[Crypto], maturity: :beta, logo_text: "KR", logo_color: "#7c3aed", domain: "kraken.com" },+ coinspot: { region: "AU", kinds: %w[Crypto], maturity: :beta, logo_text: "CS", logo_color: "#111827", domain: "coinspot.com.au", name: "CoinSpot" },snaptrade: { region: "US / CA", kinds: %w[Investment], maturity: :beta, logo_text: "ST", logo_color: "#16a34a", domain: "snaptrade.com" },ibkr: { region: "Global", kinds: %w[Investment], maturity: :beta, logo_text: "IB", logo_color: "#dc2626", domain: "interactivebrokers.com" },indexa_capital: { region: "ES", kinds: %w[Investment], maturity: :alpha, logo_text: "IC", logo_color: "#dc2626", domain: "indexacapital.com" },diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rbindex d3ee614b08..cbc6a09292 100644--- a/app/models/provider_connection_status.rb+++ b/app/models/provider_connection_status.rb@@ -12,6 +12,7 @@ class ProviderConnectionStatus{ key: "coinbase", type: "CoinbaseItem", association: :coinbase_items, accounts: :coinbase_accounts },{ key: "binance", type: "BinanceItem", association: :binance_items, accounts: :binance_accounts },{ key: "kraken", type: "KrakenItem", association: :kraken_items, accounts: :kraken_accounts },+ { key: "coinspot", type: "CoinspotItem", association: :coinspot_items, accounts: :coinspot_accounts },{ key: "onchain_wallet", type: "OnchainWalletItem", association: :onchain_wallet_items, accounts: :onchain_wallet_accounts },{ key: "coinstats", type: "CoinstatsItem", association: :coinstats_items, accounts: :coinstats_accounts },{ key: "snaptrade", type: "SnaptradeItem", association: :snaptrade_items, accounts: :snaptrade_accounts, linked_accounts: :linked_accounts },diff --git a/app/views/accounts/index.html.erb b/app/views/accounts/index.html.erbindex f7cd93f5da..2d8e40b347 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? && @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? && @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">@@ -84,6 +84,10 @@<%= render @kraken_items.sort_by(&:created_at) %><% end %>+ <% if @coinspot_items.any? %>+ <%= render @coinspot_items.sort_by(&:created_at) %>+ <% end %>+<% if @trading212_items.any? %><%= render @trading212_items %><% end %>diff --git a/app/views/coinspot_items/_coinspot_item.html.erb b/app/views/coinspot_items/_coinspot_item.html.erbnew file mode 100644index 0000000000..c79842c3c5--- /dev/null+++ b/app/views/coinspot_items/_coinspot_item.html.erb@@ -0,0 +1,117 @@+<%# locals: (coinspot_item:, unlinked_count: coinspot_item.unlinked_accounts_count) %>++<%= tag.div id: dom_id(coinspot_item) do %>+ <%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <div class="flex items-center gap-2 w-full">+ <%= icon "chevron-right", class: "group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>++ <div class="flex items-center justify-center h-8 w-8 rounded-full bg-surface-inset">+ <%= icon "coins", size: "sm", class: "text-primary" %>+ </div>++ <div class="pl-1 text-sm flex-1">+ <div class="flex items-center gap-2">+ <%= tag.p coinspot_item.institution_display_name, class: "font-medium text-primary" %>+ <% if coinspot_item.scheduled_for_deletion? %>+ <p class="text-destructive text-sm animate-pulse"><%= t(".deletion_in_progress") %></p>+ <% end %>+ </div>+ <p class="text-xs text-secondary"><%= t(".provider_name") %></p>++ <% if coinspot_item.syncing? %>+ <div class="text-secondary flex items-center gap-1">+ <%= icon "loader", size: "sm", class: "animate-spin" %>+ <%= tag.span t(".syncing") %>+ </div>+ <% elsif coinspot_item.requires_update? %>+ <div class="text-warning flex items-center gap-1">+ <%= icon "alert-triangle", size: "sm", color: "warning" %>+ <%= tag.span t(".reconnect") %>+ </div>+ <% else %>+ <p class="text-secondary">+ <% if coinspot_item.last_synced_at %>+ <% if coinspot_item.sync_status_summary %>+ <%= t(".status_with_summary", timestamp: time_ago_in_words(coinspot_item.last_synced_at), summary: coinspot_item.sync_status_summary) %>+ <% else %>+ <%= t(".status", timestamp: time_ago_in_words(coinspot_item.last_synced_at)) %>+ <% end %>+ <% else %>+ <%= t(".status_never") %>+ <% end %>+ </p>+ <% end %>+ </div>+ </div>+ <% end %>++ <% if Current.user&.admin? %>+ <div class="flex items-center justify-end gap-2 mt-2">+ <%= icon(+ "refresh-cw",+ as_button: true,+ href: sync_coinspot_item_path(coinspot_item),+ disabled: coinspot_item.syncing?+ ) %>++ <%= render DS::Menu.new do |menu| %>+ <% if unlinked_count.to_i > 0 %>+ <% menu.with_item(+ variant: "link",+ text: t(".import_accounts_menu"),+ icon: "plus",+ href: setup_accounts_coinspot_item_path(coinspot_item),+ frame: :modal+ ) %>+ <% end %>+ <% menu.with_item(+ variant: "button",+ text: t(".delete"),+ icon: "trash-2",+ href: coinspot_item_path(coinspot_item),+ method: :delete,+ confirm: CustomConfirm.for_resource_deletion(coinspot_item.institution_display_name, high_severity: true)+ ) %>+ <% end %>+ </div>+ <% end %>++ <% unless coinspot_item.scheduled_for_deletion? %>+ <div class="space-y-4 mt-4">+ <% if coinspot_item.accounts.any? %>+ <%= render "accounts/index/account_groups", accounts: coinspot_item.accounts %>+ <% coinspot_item.stale_rate_accounts.each do |coinspot_account| %>+ <div class="flex items-center gap-2 text-xs text-warning px-1">+ <span class="font-mono">~</span>+ <%= icon "triangle-alert", size: "sm" %>+ <span><%= t(".stale_rate_warning", date: coinspot_account.extra.dig("coinspot", "rate_target_date")) %></span>+ </div>+ <% end %>+ <% end %>++ <% stats = coinspot_item.syncs.ordered.first&.sync_stats || {} %>+ <%= render ProviderSyncSummary.new(stats: stats, provider_item: coinspot_item) %>++ <% if unlinked_count.to_i > 0 && coinspot_item.accounts.empty? %>+ <div class="p-4 flex flex-col gap-3 items-center justify-center">+ <p class="text-primary font-medium text-sm"><%= t(".setup_needed") %></p>+ <p class="text-secondary text-sm"><%= t(".setup_description") %></p>+ <%= render DS::Link.new(+ text: t(".setup_action"),+ icon: "plus",+ variant: "primary",+ href: setup_accounts_coinspot_item_path(coinspot_item),+ frame: :modal+ ) %>+ </div>+ <% elsif coinspot_item.accounts.empty? && coinspot_item.coinspot_accounts.none? %>+ <div class="p-4 flex flex-col gap-3 items-center justify-center">+ <p class="text-primary font-medium text-sm"><%= t(".no_accounts_title") %></p>+ <p class="text-secondary text-sm"><%= t(".no_accounts_message") %></p>+ </div>+ <% end %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/coinspot_items/select_existing_account.html.erb b/app/views/coinspot_items/select_existing_account.html.erbnew file mode 100644index 0000000000..63eb356969--- /dev/null+++ b/app/views/coinspot_items/select_existing_account.html.erb@@ -0,0 +1,42 @@+<%# Modal: Link an existing manual crypto exchange account to a CoinSpot account %>+<%= turbo_frame_tag "modal" do %>+ <%= render DS::Dialog.new do |dialog| %>+ <% dialog.with_header(title: t(".title")) %>++ <% dialog.with_body do %>+ <% if @available_coinspot_accounts.blank? %>+ <div class="p-4 text-sm text-secondary">+ <p class="mb-2"><%= t(".no_accounts_found") %></p>+ <ul class="list-disc list-inside space-y-1">+ <li><%= t(".wait_for_sync") %></li>+ <li><%= t(".check_provider_health") %></li>+ </ul>+ </div>+ <% else %>+ <%= form_with url: link_existing_account_coinspot_items_path, method: :post, class: "space-y-4" do %>+ <%= hidden_field_tag :account_id, @account.id %>+ <%= hidden_field_tag :coinspot_item_id, @coinspot_item.id %>++ <div class="space-y-2 max-h-64 overflow-auto">+ <% @available_coinspot_accounts.each do |coinspot_account| %>+ <label class="flex items-center gap-3 p-2 rounded border border-secondary hover:border-primary cursor-pointer">+ <%= radio_button_tag :coinspot_account_id, coinspot_account.id, false, required: true %>+ <div class="flex flex-col">+ <span class="text-sm text-primary font-medium"><%= coinspot_account.name.presence || coinspot_account.id %></span>+ <span class="text-xs text-secondary">+ <%= coinspot_account.currency %> • <%= number_with_delimiter(coinspot_account.current_balance || 0, delimiter: ",") %>+ </span>+ </div>+ </label>+ <% end %>+ </div>++ <div class="flex items-center justify-end gap-2">+ <%= render DS::Button.new(text: t(".link"), variant: :primary, icon: "link-2", type: :submit) %>+ <%= render DS::Link.new(text: t(".cancel"), variant: :secondary, href: accounts_path, data: { turbo_frame: "_top" }) %>+ </div>+ <% end %>+ <% end %>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/coinspot_items/setup_accounts.html.erb b/app/views/coinspot_items/setup_accounts.html.erbnew file mode 100644index 0000000000..f1bf985fa9--- /dev/null+++ b/app/views/coinspot_items/setup_accounts.html.erb@@ -0,0 +1,90 @@+<% 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 "coins", class: "text-primary" %>+ <span class="text-primary"><%= t(".subtitle") %></span>+ </div>+ <% end %>++ <% dialog.with_body do %>+ <%= form_with url: complete_account_setup_coinspot_item_path(@coinspot_item),+ method: :post,+ local: true,+ id: "coinspot-setup-form",+ data: {+ controller: "loading-button",+ action: "submit->loading-button#showLoading",+ loading_button_loading_text_value: t(".creating"),+ turbo_frame: "_top"+ },+ class: "space-y-6" do |form| %>+ <%= hidden_field_tag :return_to, params[:return_to] %>+ <div class="space-y-4">+ <div class="bg-surface border border-primary p-4 rounded-lg">+ <div class="flex items-start gap-3">+ <%= icon "info", size: "sm", class: "text-primary mt-0.5 flex-shrink-0" %>+ <p class="text-sm text-primary"><%= t(".instructions") %></p>+ </div>+ </div>++ <% if @coinspot_accounts.empty? %>+ <div class="text-center py-8">+ <p class="text-secondary"><%= t(".no_accounts") %></p>+ </div>+ <% else %>+ <div data-controller="select-all">+ <div class="flex items-center justify-between mb-2">+ <span class="text-sm text-secondary">+ <%= t(".accounts_count", count: @coinspot_accounts.count) %>+ </span>+ <label class="flex items-center gap-2 text-sm cursor-pointer">+ <input type="checkbox"+ id="coinspot-select-all"+ data-action="change->select-all#toggle"+ class="checkbox checkbox--dark">+ <span class="text-secondary"><%= t(".select_all") %></span>+ </label>+ </div>++ <div class="space-y-2 max-h-96 overflow-y-auto">+ <% @coinspot_accounts.each do |coinspot_account| %>+ <label for="csa_<%= coinspot_account.id %>" class="flex items-center gap-3 p-3 border border-primary rounded-lg hover:bg-surface transition-colors cursor-pointer">+ <%= check_box_tag "selected_accounts[]",+ coinspot_account.id,+ false,+ id: "csa_#{coinspot_account.id}",+ class: "checkbox checkbox--dark",+ data: { select_all_target: "checkbox" } %>+ <div class="flex-1 min-w-0">+ <p class="font-medium text-primary truncate"><%= coinspot_account.name %></p>+ <p class="text-xs text-secondary"><%= coinspot_account.account_type %></p>+ </div>+ <div class="text-right flex-shrink-0">+ <p class="text-sm font-medium text-primary">+ <%= number_with_delimiter(coinspot_account.current_balance || 0, delimiter: ",") %>+ </p>+ <p class="text-xs text-secondary"><%= coinspot_account.currency %></p>+ </div>+ </label>+ <% end %>+ </div>+ </div>+ <% end %>+ </div>++ <div class="flex gap-3">+ <%= render DS::Button.new(+ text: t(".import_selected"),+ variant: "primary",+ icon: "plus",+ type: "submit",+ class: "flex-1",+ data: { loading_button_target: "button" }+ ) %>+ <%= render DS::Link.new(text: t(".cancel"), variant: "secondary", href: accounts_path) %>+ </div>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/settings/providers/_coinspot_panel.html.erb b/app/views/settings/providers/_coinspot_panel.html.erbnew file mode 100644index 0000000000..14c6a9dd5b--- /dev/null+++ b/app/views/settings/providers/_coinspot_panel.html.erb@@ -0,0 +1,145 @@+<div id="coinspot-providers-panel" class="space-y-4">+ <% items = local_assigns[:coinspot_items] || @coinspot_items %>++ <%= render DS::Alert.new(+ variant: :warning,+ message: safe_join([+ content_tag(:p, t("settings.providers.coinspot_panel.read_only_title"), class: "font-medium"),+ content_tag(:p, t("settings.providers.coinspot_panel.read_only_body"), class: "mt-1")+ ])+ ) %>++ <%= render "settings/providers/setup_steps",+ steps: [+ t("settings.providers.coinspot_panel.step1_html").html_safe,+ t("settings.providers.coinspot_panel.step2"),+ t("settings.providers.coinspot_panel.step3")+ ] %>++ <% error_msg = local_assigns[:error_message] || @error_message %>+ <% if error_msg.present? %>+ <%= render DS::Alert.new(message: error_msg, variant: :error) %>+ <% end %>++ <% if items.any? %>+ <div class="space-y-3">+ <% 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-3 w-full">+ <div class="flex items-center gap-3 min-w-0">+ <div class="flex items-center justify-center h-8 w-8 rounded-full bg-surface-inset">+ <%= icon "coins", size: "sm", class: "text-primary" %>+ </div>+ <div class="min-w-0">+ <p class="font-medium text-primary truncate"><%= item.name %></p>+ <p class="text-xs text-secondary">+ <% if item.syncing? %>+ <%= t("settings.providers.coinspot_panel.syncing") %>+ <% else %>+ <%= item.sync_status_summary %>+ <% end %>+ </p>+ </div>+ </div>+ </div>+ <% end %>++ <div class="mt-4 space-y-4">+ <div class="flex flex-wrap items-center gap-2">+ <%= render DS::Button.new(+ text: t("settings.providers.coinspot_panel.sync"),+ icon: "refresh-cw",+ variant: :outline,+ size: :sm,+ href: sync_coinspot_item_path(item),+ method: :post,+ disabled: item.syncing?+ ) %>++ <%= render DS::Link.new(+ text: t("settings.providers.coinspot_panel.setup_accounts"),+ icon: "settings",+ variant: "secondary",+ href: setup_accounts_coinspot_item_path(item),+ frame: :modal+ ) %>++ <%= render DS::Button.new(+ text: t("settings.providers.coinspot_panel.disconnect"),+ icon: "trash-2",+ variant: :outline_destructive,+ size: :sm,+ href: coinspot_item_path(item),+ method: :delete,+ confirm: t("settings.providers.coinspot_panel.disconnect_confirm", name: item.name)+ ) %>+ </div>++ <%= styled_form_with model: item,+ url: coinspot_item_path(item),+ scope: :coinspot_item,+ method: :patch,+ data: { turbo: true },+ class: "space-y-3" do |form| %>+ <%= form.text_field :name,+ label: t("settings.providers.coinspot_panel.connection_name_label"),+ placeholder: t("settings.providers.coinspot_panel.connection_name_placeholder") %>++ <%= form.text_field :api_key,+ label: t("settings.providers.coinspot_panel.api_key_label"),+ placeholder: t("settings.providers.coinspot_panel.keep_api_key_placeholder"),+ type: :password,+ value: nil %>++ <%= form.text_field :api_secret,+ label: t("settings.providers.coinspot_panel.api_secret_label"),+ placeholder: t("settings.providers.coinspot_panel.keep_api_secret_placeholder"),+ type: :password,+ value: nil %>++ <div class="flex justify-end">+ <%= form.submit t("settings.providers.coinspot_panel.update_connection") %>+ </div>+ <% end %>+ </div>+ <% end %>+ <% end %>+ </div>+ <% end %>++ <% coinspot_item = Current.family.coinspot_items.build(name: t("settings.providers.coinspot_panel.default_connection_name")) %>+ <% if items.any? %>+ <h3 class="flex items-center gap-2 text-sm font-medium text-primary mt-4">+ <%= icon "plus", size: "sm" %>+ <%= t("settings.providers.coinspot_panel.add_connection") %>+ </h3>+ <% end %>++ <%= styled_form_with model: coinspot_item,+ url: coinspot_items_path,+ scope: :coinspot_item,+ method: :post,+ data: { turbo: true },+ class: "space-y-3" do |form| %>+ <%= form.text_field :name,+ label: t("settings.providers.coinspot_panel.connection_name_label"),+ placeholder: t("settings.providers.coinspot_panel.connection_name_placeholder") %>++ <%= form.text_field :api_key,+ label: t("settings.providers.coinspot_panel.api_key_label"),+ placeholder: t("settings.providers.coinspot_panel.api_key_placeholder"),+ type: :password,+ value: nil %>++ <%= form.text_field :api_secret,+ label: t("settings.providers.coinspot_panel.api_secret_label"),+ placeholder: t("settings.providers.coinspot_panel.api_secret_placeholder"),+ type: :password,+ value: nil %>++ <div class="flex justify-end">+ <%= form.submit t("settings.providers.coinspot_panel.add_connection") %>+ </div>+ <% end %>+</div>diff --git a/config/locales/views/coinspot_items/en.yml b/config/locales/views/coinspot_items/en.ymlnew file mode 100644index 0000000000..c2e6597198--- /dev/null+++ b/config/locales/views/coinspot_items/en.yml@@ -0,0 +1,92 @@+---+en:+ coinspot_items:+ provider_connection:+ default_name: CoinSpot+ default_description: Link to a CoinSpot exchange account+ name: "CoinSpot - %{name}"+ description: "Link to %{name}"+ create:+ default_name: CoinSpot+ success: Successfully connected to CoinSpot. Your exchange account is being synced.+ update:+ success: Successfully updated CoinSpot connection.+ destroy:+ success: Scheduled CoinSpot connection for deletion.+ unlink_failed: Could not disconnect CoinSpot connection+ select_accounts:+ select_connection: Choose a CoinSpot connection in Provider Settings.+ no_credentials_configured: Add CoinSpot API credentials before setting up accounts.+ link_accounts:+ select_connection: Choose a CoinSpot connection before linking accounts.+ select_existing_account:+ title: Link CoinSpot Account+ no_accounts_found: No CoinSpot accounts found.+ wait_for_sync: Wait for CoinSpot to finish syncing.+ check_provider_health: Check that your CoinSpot API credentials are valid.+ link: Link+ cancel: Cancel+ link_existing_account:+ success: Successfully linked to CoinSpot account+ select_connection: Choose a CoinSpot connection before linking accounts.+ errors:+ only_manual: Only manual Crypto exchange accounts without an existing provider link can be linked to CoinSpot+ invalid_coinspot_account: Invalid CoinSpot account+ coinspot_account_already_linked: This CoinSpot account is already linked+ setup_accounts:+ title: Import CoinSpot Account+ subtitle: Select the exchange account to track+ instructions: CoinSpot imports one combined Crypto exchange account for this connection, with balances, AUD values, transfers, deposits, withdrawals, and order history.+ no_accounts: All CoinSpot accounts have been imported.+ accounts_count:+ one: "%{count} account available"+ other: "%{count} accounts available"+ select_all: Select all+ import_selected: Import Selected+ cancel: Cancel+ creating: Importing...+ complete_account_setup:+ success:+ one: "Imported %{count} account"+ other: "Imported %{count} accounts"+ none_selected: No accounts selected+ no_accounts: No accounts to import+ setup_failed:+ one: "Failed to import %{count} account"+ other: "Failed to import %{count} accounts"+ coinspot_item:+ provider_name: CoinSpot+ syncing: Syncing...+ reconnect: Credentials need updating+ deletion_in_progress: Deleting...+ sync_status:+ no_accounts: No accounts found+ all_synced:+ one: "%{count} account synced"+ other: "%{count} accounts synced"+ partial_sync: "%{linked_count} synced, %{unlinked_count} need setup"+ status: "Last synced %{timestamp} ago"+ status_with_summary: "Last synced %{timestamp} ago - %{summary}"+ status_never: Never synced+ delete: Delete+ no_accounts_title: No accounts found+ no_accounts_message: Your CoinSpot exchange account will appear here after syncing.+ setup_needed: Account ready to import+ setup_description: Import this CoinSpot connection as a Crypto exchange account.+ setup_action: Import Account+ import_accounts_menu: Import Account+ stale_rate_warning: "Balance is approximate because the exact exchange rate for %{date} was unavailable. Will update on next sync."+ coinspot_item:+ syncer:+ checking_credentials: Checking credentials...+ credentials_invalid: Invalid CoinSpot API credentials. Please check your API key and secret.+ importing_accounts: Importing accounts from CoinSpot...+ checking_configuration: Checking account configuration...+ accounts_need_setup:+ one: "%{count} account needs setup"+ other: "%{count} accounts need setup"+ processing_accounts: Processing account data...+ processing_failed:+ one: "%{count} CoinSpot account failed to process"+ other: "%{count} CoinSpot accounts failed to process"+ calculating_balances: Calculating balances...diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.ymlindex 1640aa2d91..293828084a 100644--- a/config/locales/views/settings/en.yml+++ b/config/locales/views/settings/en.yml@@ -448,6 +448,7 @@ en:coinbase: Import your Coinbase crypto holdings and track performance.binance: Sync your Binance spot balances using a read-only API key.kraken: Sync Kraken balances and spot trade fills using a read-only API key.+ coinspot: Sync CoinSpot balances, AUD values, transfers, deposits, withdrawals, and order history using a read-only API key.onchain_wallet: Track self-custody Bitcoin, EVM and Solana wallets from their public addresses.snaptrade: Connect brokerage accounts via the SnapTrade aggregation network.trading212: Sync your Trading 212 investment portfolio using a read-only API key.@@ -529,6 +530,28 @@ en:sync: Syncdisconnect: Disconnectdisconnect_confirm: "Are you sure you want to disconnect %{name}?"+ coinspot_panel:+ step1_html: 'Go to <a href="https://www.coinspot.com.au/my/api" target="_blank" rel="noopener noreferrer" class="underline">CoinSpot API settings</a>'+ step2: "Create an API key with read-only access to balances and history."+ step3: "Paste the API key and secret below."+ read_only_title: "Read-only exchange sync only"+ read_only_body: "Do not grant send, withdrawal, trading, or transfer permissions. Sure only imports balances, AUD values, transfers, deposits, withdrawals, and completed order history."+ default_connection_name: CoinSpot+ add_connection: Add CoinSpot connection+ update_connection: Update connection+ connection_name_label: Connection name+ connection_name_placeholder: Main CoinSpot+ api_key_label: API Key+ api_key_placeholder: Paste your CoinSpot API key+ keep_api_key_placeholder: Leave blank to keep the existing API key+ api_secret_label: API Secret+ api_secret_placeholder: Paste your CoinSpot API secret+ keep_api_secret_placeholder: Leave blank to keep the existing API secret+ setup_accounts: Setup account+ syncing: Syncing...+ sync: Sync+ disconnect: Disconnect+ disconnect_confirm: "Are you sure you want to disconnect %{name}?"onchain_wallet_panel:add_wallet: Add walletadvanced: Advanceddiff --git a/config/routes.rb b/config/routes.rbindex ef0c2e8a97..a8ab96b5bf 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -128,6 +128,21 @@ Rails.application.routes.draw doendend+ resources :coinspot_items, only: [ :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+# Self-custody / on-chain walletsresources :onchain_wallet_items, only: [ :update, :destroy ] docollection dodiff --git a/db/migrate/20260831193000_create_coinspot_items_and_accounts.rb b/db/migrate/20260831193000_create_coinspot_items_and_accounts.rbnew file mode 100644index 0000000000..5961b115c2--- /dev/null+++ b/db/migrate/20260831193000_create_coinspot_items_and_accounts.rb@@ -0,0 +1,53 @@+# frozen_string_literal: true++class CreateCoinspotItemsAndAccounts < ActiveRecord::Migration[8.1]+ def change+ create_table :coinspot_items, id: :uuid do |t|+ t.references :family, null: false, foreign_key: true, type: :uuid+ t.string :name++ t.string :institution_name+ t.string :institution_domain+ t.string :institution_url+ t.string :institution_color++ t.string :status, default: "good", null: false+ t.boolean :scheduled_for_deletion, default: false, null: false+ t.boolean :pending_account_setup, default: false, null: false++ t.datetime :sync_start_date+ t.jsonb :raw_payload++ t.text :api_key+ t.text :api_secret+ t.bigint :last_nonce, default: 0, null: false++ t.timestamps+ end++ add_index :coinspot_items, :status++ create_table :coinspot_accounts, id: :uuid do |t|+ t.references :coinspot_item, null: false, foreign_key: true, type: :uuid++ t.string :name+ t.string :account_id, null: false+ t.string :account_type+ t.string :currency+ t.decimal :current_balance, precision: 19, scale: 4++ t.jsonb :institution_metadata+ t.jsonb :raw_payload+ t.jsonb :raw_transactions_payload+ t.jsonb :extra, default: {}, null: false++ t.timestamps+ end++ add_index :coinspot_accounts, :account_type+ add_index :coinspot_accounts,+ [ :coinspot_item_id, :account_id ],+ unique: true,+ name: "index_coinspot_accounts_on_item_and_account_id"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 388419848e..2e4ada7d3e 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -469,6 +469,45 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) dot.index ["status"], name: "index_coinbase_items_on_status"end+ create_table "coinspot_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.string "account_id", null: false+ t.string "account_type"+ t.uuid "coinspot_item_id", null: false+ t.datetime "created_at", null: false+ t.string "currency"+ t.decimal "current_balance", precision: 19, scale: 4+ t.jsonb "extra", default: {}, null: false+ t.jsonb "institution_metadata"+ t.string "name"+ t.jsonb "raw_payload"+ t.jsonb "raw_transactions_payload"+ t.datetime "updated_at", null: false+ t.index ["account_type"], name: "index_coinspot_accounts_on_account_type"+ t.index ["coinspot_item_id", "account_id"], name: "index_coinspot_accounts_on_item_and_account_id", unique: true+ t.index ["coinspot_item_id"], name: "index_coinspot_accounts_on_coinspot_item_id"+ end++ create_table "coinspot_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.text "api_key"+ t.text "api_secret"+ t.datetime "created_at", null: false+ t.uuid "family_id", null: false+ t.string "institution_color"+ t.string "institution_domain"+ t.string "institution_name"+ t.string "institution_url"+ t.bigint "last_nonce", default: 0, null: false+ t.string "name"+ t.boolean "pending_account_setup", default: false, null: false+ t.jsonb "raw_payload"+ t.boolean "scheduled_for_deletion", default: false, null: false+ t.string "status", default: "good", null: false+ t.datetime "sync_start_date"+ t.datetime "updated_at", null: false+ t.index ["family_id"], name: "index_coinspot_items_on_family_id"+ t.index ["status"], name: "index_coinspot_items_on_status"+ end+create_table "coinstats_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.string "account_id"t.string "account_status"@@ -2661,6 +2700,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) doadd_foreign_key "chats", "users"add_foreign_key "coinbase_accounts", "coinbase_items"add_foreign_key "coinbase_items", "families"+ add_foreign_key "coinspot_accounts", "coinspot_items"+ add_foreign_key "coinspot_items", "families"add_foreign_key "coinstats_accounts", "coinstats_items"add_foreign_key "coinstats_items", "families"add_foreign_key "debug_log_entries", "account_providers", on_delete: :nullifydiff --git a/test/controllers/coinspot_items_controller_test.rb b/test/controllers/coinspot_items_controller_test.rbnew file mode 100644index 0000000000..fe516d0bf4--- /dev/null+++ b/test/controllers/coinspot_items_controller_test.rb@@ -0,0 +1,434 @@+# frozen_string_literal: true++require "test_helper"++class CoinspotItemsControllerTest < ActionDispatch::IntegrationTest+ setup do+ sign_in users(:family_admin)+ SyncJob.stubs(:perform_later)++ @family = families(:dylan_family)+ @existing_item = coinspot_items(:one)+ coinspot_items(:requires_update).update!(scheduled_for_deletion: true)+ @second_item = CoinspotItem.create!(+ family: @family,+ name: "Business CoinSpot",+ api_key: "second_coinspot_key",+ api_secret: "second_coinspot_secret"+ )+ end++ test "create adds a new coinspot connection without overwriting existing credentials" do+ existing_key = @existing_item.api_key+ existing_secret = @existing_item.api_secret++ assert_difference "CoinspotItem.count", 1 do+ post coinspot_items_url, params: {+ coinspot_item: {+ name: "Joint CoinSpot",+ api_key: "joint_coinspot_key",+ api_secret: "joint_coinspot_secret"+ }+ }+ end++ assert_redirected_to settings_providers_path+ assert_equal existing_key, @existing_item.reload.api_key+ assert_equal existing_secret, @existing_item.api_secret+ assert_equal "joint_coinspot_key", @family.coinspot_items.find_by!(name: "Joint CoinSpot").api_key+ end++ test "update changes only the selected coinspot connection" do+ existing_key = @existing_item.api_key++ patch coinspot_item_url(@second_item), params: {+ coinspot_item: {+ name: "Renamed Business CoinSpot",+ api_key: "updated_second_key",+ api_secret: "updated_second_secret"+ }+ }++ assert_redirected_to settings_providers_path+ assert_equal existing_key, @existing_item.reload.api_key+ assert_equal "Renamed Business CoinSpot", @second_item.reload.name+ assert_equal "updated_second_key", @second_item.api_key+ assert_equal "updated_second_secret", @second_item.api_secret+ end++ test "blank secret update preserves the selected coinspot credentials" do+ original_key = @second_item.api_key+ original_secret = @second_item.api_secret++ patch coinspot_item_url(@second_item), params: {+ coinspot_item: {+ name: "Renamed Business CoinSpot",+ api_key: "",+ api_secret: ""+ }+ }++ assert_redirected_to settings_providers_path+ assert_equal "Renamed Business CoinSpot", @second_item.reload.name+ assert_equal original_key, @second_item.api_key+ assert_equal original_secret, @second_item.api_secret+ end++ test "create rejects whitespace-only credentials" do+ assert_no_difference "CoinspotItem.count" do+ post coinspot_items_url, params: {+ coinspot_item: {+ name: "Blank CoinSpot",+ api_key: " ",+ api_secret: "\n"+ }+ }+ end++ assert_redirected_to settings_providers_path+ assert_match(/API key can't be blank/i, flash[:alert])+ end++ test "turbo create errors render the provider panel with existing connections" do+ post coinspot_items_url, params: {+ coinspot_item: {+ name: "Broken CoinSpot",+ api_key: " ",+ api_secret: "\n"+ }+ }, as: :turbo_stream, headers: { "Turbo-Frame" => "coinspot-providers-panel" }++ assert_response :unprocessable_entity+ assert_includes @response.body, "coinspot-providers-panel"+ assert_includes @response.body, "Api key can't be blank"+ end++ test "select accounts requires an explicit connection when multiple coinspot items exist" do+ get select_accounts_coinspot_items_url, params: { accountable_type: "Crypto" }++ assert_redirected_to settings_providers_path+ assert_equal "Choose a CoinSpot connection in Provider Settings.", flash[:alert]+ end++ test "select accounts targets selected coinspot item" do+ get select_accounts_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ accountable_type: "Crypto"+ }++ assert_redirected_to setup_accounts_coinspot_item_path(@second_item, return_to: nil)+ end++ test "select accounts rejects protocol-relative return paths" do+ get select_accounts_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ accountable_type: "Crypto",+ return_to: "//evil.example/accounts"+ }++ assert_redirected_to setup_accounts_coinspot_item_path(@second_item, return_to: nil)+ end++ test "sync only queues a sync for the selected coinspot item" do+ assert_difference -> { Sync.where(syncable: @second_item).count }, 1 do+ assert_no_difference -> { Sync.where(syncable: @existing_item).count } do+ post sync_coinspot_item_url(@second_item)+ end+ end++ assert_response :redirect+ end++ test "setup accounts creates crypto exchange account for selected item only" do+ first_account = coinspot_accounts(:one)+ second_account = @second_item.coinspot_accounts.create!(+ name: "Second CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000+ )+ CoinspotAccount::Processor.any_instance.stubs(:process).returns(nil)++ assert_difference "Account.count", 1 do+ post complete_account_setup_coinspot_item_url(@second_item), params: {+ selected_accounts: [ second_account.id ]+ }+ end++ assert_redirected_to accounts_path+ assert_nil first_account.reload.current_account+ assert_equal "Crypto", second_account.reload.current_account.accountable_type+ assert_equal "exchange", second_account.current_account.accountable.subtype+ end++ test "link existing account links manual crypto exchange account to selected coinspot account" do+ manual_account = manual_crypto_exchange_account+ coinspot_account = @second_item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000+ )++ assert_difference "AccountProvider.count", 1 do+ post link_existing_account_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ account_id: manual_account.id,+ coinspot_account_id: coinspot_account.id+ }+ end++ assert_redirected_to accounts_path+ assert_equal manual_account, coinspot_account.reload.current_account+ end++ test "link existing account requires explicit connection when multiple items exist" do+ account = manual_crypto_exchange_account++ assert_no_difference "AccountProvider.count" do+ post link_existing_account_coinspot_items_url, params: {+ account_id: account.id,+ coinspot_account_id: "combined"+ }+ end++ assert_redirected_to settings_providers_path+ assert_equal "Choose a CoinSpot connection before linking accounts.", flash[:alert]+ end++ test "link existing account rejects non crypto accounts" do+ account = @family.accounts.create!(+ name: "Manual Checking",+ balance: 0,+ currency: "AUD",+ accountable: Depository.new+ )+ coinspot_account = @second_item.coinspot_accounts.create!(name: "CoinSpot", account_id: "combined", account_type: "combined", currency: "AUD")++ assert_no_difference "AccountProvider.count" do+ post link_existing_account_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ account_id: account.id,+ coinspot_account_id: coinspot_account.id+ }+ end++ assert_redirected_to account_path(account)+ end++ test "link existing account rejects accounts with existing provider links" do+ account = manual_crypto_exchange_account+ linked_coinspot_account = coinspot_accounts(:one)+ AccountProvider.create!(account: account, provider: linked_coinspot_account)+ coinspot_account = @second_item.coinspot_accounts.create!(name: "CoinSpot", account_id: "combined", account_type: "combined", currency: "AUD")++ assert_no_difference "AccountProvider.count" do+ post link_existing_account_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ account_id: account.id,+ coinspot_account_id: coinspot_account.id+ }+ end++ assert_redirected_to account_path(account)+ end++ test "link existing account rejects coinspot accounts already linked elsewhere" do+ linked_account = manual_crypto_exchange_account+ available_account = manual_crypto_exchange_account+ coinspot_account = @second_item.coinspot_accounts.create!(name: "CoinSpot", account_id: "combined", account_type: "combined", currency: "AUD")+ AccountProvider.create!(account: linked_account, provider: coinspot_account)++ assert_no_difference "AccountProvider.count" do+ post link_existing_account_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ account_id: available_account.id,+ coinspot_account_id: coinspot_account.id+ }+ end++ assert_redirected_to account_path(available_account)+ end++ # require_admin! only checks the family role, so the signed-in admin still+ # reaches these actions for an account owned by another member. Ownership is+ # reassigned and shares cleared so the actor has no permission at all:+ # auto_share_with_family! would otherwise grant read_write, which is still+ # short of the :write (owner/full_control) the guard demands.+ test "link existing account rejects an account the admin cannot write" do+ account = manual_crypto_exchange_account+ account.account_shares.destroy_all+ account.update!(owner: users(:family_member))+ coinspot_account = @second_item.coinspot_accounts.create!(+ name: "CoinSpot", account_id: "combined", account_type: "combined", currency: "AUD"+ )++ assert_no_difference "AccountProvider.count" do+ post link_existing_account_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ account_id: account.id,+ coinspot_account_id: coinspot_account.id+ }+ end++ assert_redirected_to accounts_path+ assert_equal "You don't have permission to manage this account", flash[:alert]+ assert_nil coinspot_account.reload.current_account+ end++ test "select existing account rejects an account the admin cannot write" do+ account = manual_crypto_exchange_account+ account.account_shares.destroy_all+ account.update!(owner: users(:family_member))+ @second_item.coinspot_accounts.create!(+ name: "CoinSpot", account_id: "combined", account_type: "combined", currency: "AUD"+ )++ get select_existing_account_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ account_id: account.id+ }++ assert_redirected_to accounts_path+ assert_equal "You don't have permission to manage this account", flash[:alert]+ end++ # unlink_all! captures a per-account failure on its result rather than+ # raising, so discarding the results scheduled the connection for deletion+ # while accounts were still linked to it.+ test "destroy does not schedule deletion when unlinking an account fails" do+ CoinspotItem.any_instance.stubs(:unlink_all!).returns([+ { provider_account_id: SecureRandom.uuid, name: "CoinSpot", provider_link_ids: [], error: "boom" }+ ])+ CoinspotItem.any_instance.expects(:destroy_later).never++ delete coinspot_item_url(@second_item)++ assert_redirected_to settings_providers_path+ assert_equal I18n.t("coinspot_items.destroy.unlink_failed"), flash[:alert]+ end++ test "destroy schedules deletion when every account unlinks cleanly" do+ CoinspotItem.any_instance.stubs(:unlink_all!).returns([+ { provider_account_id: SecureRandom.uuid, name: "CoinSpot", provider_link_ids: [] }+ ])+ CoinspotItem.any_instance.expects(:destroy_later).once++ delete coinspot_item_url(@second_item)++ assert_redirected_to settings_providers_path+ assert_equal I18n.t("coinspot_items.destroy.success"), flash[:notice]+ end++ test "select existing account renders selected coinspot item id" do+ account = manual_crypto_exchange_account+ @second_item.coinspot_accounts.create!(name: "CoinSpot", account_id: "combined", account_type: "combined", currency: "AUD")++ get select_existing_account_coinspot_items_url, params: {+ coinspot_item_id: @second_item.id,+ account_id: account.id+ }++ assert_response :success+ assert_includes @response.body, %(name="coinspot_item_id")+ assert_includes @response.body, %(value="#{@second_item.id}")+ end++ test "cannot access another family's coinspot item" do+ other_item = CoinspotItem.create!(+ family: families(:empty),+ name: "Other CoinSpot",+ api_key: "other_key",+ api_secret: "other_secret"+ )++ get setup_accounts_coinspot_item_url(other_item)++ assert_response :not_found+ end++ test "complete account setup respects return_to parameter" do+ second_account = @second_item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000+ )+ CoinspotAccount::Processor.any_instance.stubs(:process).returns(nil)++ post complete_account_setup_coinspot_item_url(@second_item), params: {+ selected_accounts: [ second_account.id ],+ return_to: settings_providers_path+ }++ assert_redirected_to settings_providers_path+ end++ test "complete account setup rejects malicious return_to paths" do+ second_account = @second_item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000+ )+ CoinspotAccount::Processor.any_instance.stubs(:process).returns(nil)++ post complete_account_setup_coinspot_item_url(@second_item), params: {+ selected_accounts: [ second_account.id ],+ return_to: "//evil.example/accounts"+ }++ assert_redirected_to accounts_path+ end++ test "complete account setup rejects backslash return_to paths" do+ second_account = @second_item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000+ )+ CoinspotAccount::Processor.any_instance.stubs(:process).returns(nil)++ post complete_account_setup_coinspot_item_url(@second_item), params: {+ selected_accounts: [ second_account.id ],+ return_to: "\\evil"+ }++ assert_redirected_to accounts_path+ end++ test "complete account setup rejects encoded separator return_to paths" do+ second_account = @second_item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000+ )+ CoinspotAccount::Processor.any_instance.stubs(:process).returns(nil)++ post complete_account_setup_coinspot_item_url(@second_item), params: {+ selected_accounts: [ second_account.id ],+ return_to: "/%2Fevil"+ }++ assert_redirected_to accounts_path+ end++ private++ def manual_crypto_exchange_account+ @family.accounts.create!(+ name: "Manual Crypto",+ balance: 0,+ currency: "AUD",+ accountable: Crypto.create!(subtype: "exchange")+ )+ end+enddiff --git a/test/fixtures/coinspot_accounts.yml b/test/fixtures/coinspot_accounts.ymlnew file mode 100644index 0000000000..ca975303d9--- /dev/null+++ b/test/fixtures/coinspot_accounts.yml@@ -0,0 +1,8 @@+one:+ coinspot_item: one+ name: CoinSpot+ account_id: combined+ account_type: combined+ currency: AUD+ current_balance: 1234.50+ extra: {}diff --git a/test/fixtures/coinspot_items.yml b/test/fixtures/coinspot_items.ymlnew file mode 100644index 0000000000..160340a416--- /dev/null+++ b/test/fixtures/coinspot_items.yml@@ -0,0 +1,20 @@+one:+ family: dylan_family+ name: My CoinSpot+ api_key: test_coinspot_key_123+ api_secret: test_coinspot_secret_456+ last_nonce: 0+ status: good+ institution_name: CoinSpot+ institution_domain: coinspot.com.au+ institution_url: https://www.coinspot.com.au+ institution_color: "#0F6BFF"++requires_update:+ family: dylan_family+ name: Stale CoinSpot+ api_key: old_coinspot_key+ api_secret: old_coinspot_secret+ last_nonce: 0+ status: requires_update+ institution_name: CoinSpotdiff --git a/test/models/coinspot_account/holdings_processor_test.rb b/test/models/coinspot_account/holdings_processor_test.rbnew file mode 100644index 0000000000..e73b40d940--- /dev/null+++ b/test/models/coinspot_account/holdings_processor_test.rb@@ -0,0 +1,164 @@+# frozen_string_literal: true++require "test_helper"++class CoinspotAccount::HoldingsProcessorTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @family.update!(currency: "AUD")+ @item = CoinspotItem.create!(family: @family, name: "CoinSpot", api_key: "k", api_secret: "s")+ @coinspot_account = @item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 0,+ raw_payload: { "assets" => [] }+ )+ @account = Account.create!(+ family: @family,+ name: "CoinSpot",+ balance: 0,+ currency: "AUD",+ accountable: Crypto.create!(subtype: "exchange")+ )+ @account_provider = AccountProvider.create!(account: @account, provider: @coinspot_account)+ @security = Security.create!(ticker: "CRYPTO:BTC", name: "BTC", exchange_operating_mic: "XCSO", offline: true)+ end++ test "marks provider holdings absent from latest snapshot as zero on current date" do+ @account.holdings.create!(+ security: @security,+ provider_security: @security,+ qty: 0.5,+ amount: 50_000,+ currency: "AUD",+ date: Date.current - 1.day,+ price: 100_000,+ account_provider_id: @account_provider.id,+ external_id: "coinspot_BTC_spot_#{Date.current - 1.day}"+ )++ assert_difference -> { @account.holdings.where(account_provider_id: @account_provider.id).count }, 1 do+ CoinspotAccount::HoldingsProcessor.new(@coinspot_account).process+ end++ zero_holding = @account.holdings.find_by!(+ account_provider_id: @account_provider.id,+ security: @security,+ date: Date.current+ )+ assert_equal 0.to_d, zero_holding.qty+ assert_equal 0.to_d, zero_holding.amount+ assert_empty @account.current_holdings+ end++ test "preserves an eight-decimal asset quantity from the balance snapshot" do+ @coinspot_account.update!(raw_payload: {+ "assets" => [+ {+ "symbol" => "BTC",+ "balance" => "0.00014884",+ "amount_aud" => "14.884",+ "price_aud" => "100000",+ "source" => "spot"+ }+ ]+ })+ CoinspotAccount::SecurityResolver.stubs(:resolve).with("BTC").returns(@security)++ result = CoinspotAccount::HoldingsProcessor.new(@coinspot_account).process++ assert_equal true, result[:success], result.inspect+ holding = @account.holdings.find_by!(security: @security, date: Date.current)+ assert_equal BigDecimal("0.00014884"), holding.qty+ assert_equal BigDecimal("14.884"), holding.amount+ end++ test "returns a failure and captures diagnostics when a holding cannot be imported" do+ @coinspot_account.update!(raw_payload: {+ "assets" => [+ { "symbol" => "BTC", "balance" => "0.1", "amount_aud" => "1000", "price_aud" => "100000" }+ ]+ })+ CoinspotAccount::SecurityResolver.stubs(:resolve).with("BTC").returns(@security)+ Account::ProviderImportAdapter.any_instance.stubs(:import_holding).raises(StandardError, "holding import failed")+ DebugLogEntry.expects(:capture).with(has_entries(+ category: "provider_sync_error",+ level: "error",+ provider_key: "coinspot",+ family: @family+ )).once++ result = CoinspotAccount::HoldingsProcessor.new(@coinspot_account).process++ assert_equal false, result[:success]+ assert_equal "holding", result[:failures].first[:kind]+ end++ # An unavailable snapshot is not an empty portfolio. `assets` missing used to+ # read as [], and the absent-holdings sweep then zeroed everything the+ # account held -- silent data loss on a failed fetch.+ test "does not zero holdings when the snapshot carries no assets array" do+ @account.holdings.create!(+ security: @security,+ provider_security: @security,+ qty: 0.5,+ amount: 50_000,+ currency: "AUD",+ date: Date.current - 1.day,+ price: 100_000,+ account_provider_id: @account_provider.id,+ external_id: "coinspot_BTC_spot_#{Date.current - 1.day}"+ )+ @coinspot_account.update!(raw_payload: { "status" => "error" })++ result = nil+ assert_no_difference -> { @account.holdings.where(account_provider_id: @account_provider.id).count } do+ result = CoinspotAccount::HoldingsProcessor.new(@coinspot_account).process+ end++ assert_equal false, result[:success]+ assert_equal 0.5.to_d, @account.holdings.where(account_provider_id: @account_provider.id).order(:date).last.qty+ end++ # Same guard, non-array shape: a payload whose `assets` is a Hash or String+ # is malformed, not empty. A count assertion alone cannot catch the+ # regression, because zeroing rewrites the row rather than removing it --+ # hence the explicit quantity assertion.+ test "does not zero holdings when assets is present but not an array" do+ @account.holdings.create!(+ security: @security,+ provider_security: @security,+ qty: 0.5,+ amount: 50_000,+ currency: "AUD",+ date: Date.current - 1.day,+ price: 100_000,+ account_provider_id: @account_provider.id,+ external_id: "coinspot_BTC_spot_#{Date.current - 1.day}"+ )+ @coinspot_account.update!(raw_payload: { "assets" => { "btc" => { "balance" => "0.5" } } })++ result = CoinspotAccount::HoldingsProcessor.new(@coinspot_account).process++ assert_equal false, result[:success]+ assert_equal 0.5.to_d, @account.holdings.where(account_provider_id: @account_provider.id).order(:date).last.qty+ end++ test "does not import a holding when its non-AUD valuation cannot be converted" do+ @family.update!(currency: "USD")+ @coinspot_account.update!(raw_payload: {+ "assets" => [+ { "symbol" => "BTC", "balance" => "0.1", "amount_aud" => "1000", "price_aud" => "100000" }+ ]+ })+ CoinspotAccount::SecurityResolver.stubs(:resolve).with("BTC").returns(@security)+ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)++ result = CoinspotAccount::HoldingsProcessor.new(@coinspot_account).process++ assert_equal false, result[:success]+ assert_empty @account.holdings.where(account_provider_id: @account_provider.id)+ end+enddiff --git a/test/models/coinspot_account/processor_test.rb b/test/models/coinspot_account/processor_test.rbnew file mode 100644index 0000000000..7bafd4d4db--- /dev/null+++ b/test/models/coinspot_account/processor_test.rb@@ -0,0 +1,363 @@+# frozen_string_literal: true++require "test_helper"++class CoinspotAccount::ProcessorTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @family.update!(currency: "AUD")+ @item = CoinspotItem.create!(family: @family, name: "CoinSpot", api_key: "k", api_secret: "s")+ @coinspot_account = @item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000,+ raw_payload: {+ "assets" => [+ { "symbol" => "BTC", "balance" => "0.01", "amount_aud" => "1000.00", "price_aud" => "100000.00" }+ ]+ },+ raw_transactions_payload: {+ "orders" => {+ "buyorders" => [+ order_payload("buy-1", "btc", "0.001", "100.00", "100000.00", "1.00")+ ],+ "sellorders" => [+ order_payload("sell-1", "btc", "0.002", "220.00", "110000.00", "2.00")+ ]+ },+ "send_receive" => {+ "sendtransactions" => [+ { "txid" => "send-1", "coin" => "btc", "amount" => "0.001", "aud" => "100.00", "sendfee" => "0.00001", "timestamp" => "2026-01-04T10:00:00Z" }+ ],+ "receivetransactions" => [+ { "txid" => "receive-1", "coin" => "btc", "amount" => "0.002", "aud" => "200.00", "timestamp" => "2026-01-05T10:00:00Z" }+ ]+ },+ "deposits" => {+ "deposits" => [+ { "reference" => "deposit-1", "amount" => "300.00", "created" => "2026-01-06T10:00:00Z" }+ ]+ },+ "withdrawals" => {+ "withdrawals" => [+ { "reference" => "withdrawal-1", "amount" => "150.00", "created" => "2026-01-07T10:00:00Z" }+ ]+ }+ }+ )+ @account = Account.create!(+ family: @family,+ name: "CoinSpot",+ balance: 0,+ currency: "AUD",+ accountable: Crypto.create!(subtype: "exchange")+ )+ AccountProvider.create!(account: @account, provider: @coinspot_account)+ @security = Security.create!(ticker: "CRYPTO:BTC", name: "BTC", exchange_operating_mic: "XCSO", offline: true)+ CoinspotAccount::SecurityResolver.stubs(:resolve).returns(@security)+ CoinspotAccount::HoldingsProcessor.any_instance.stubs(:process).returns(nil)+ end++ test "imports orders, transfers, fiat movements, and native send fees" do+ result = nil+ assert_difference -> { @account.entries.where(source: "coinspot").count }, 9 do+ result = CoinspotAccount::Processor.new(@coinspot_account).process+ end+ assert_equal true, result[:success], result.inspect++ buy = @account.entries.find_by!(external_id: "coinspot_order_buy_BTC_2026-01-02_buy-1", source: "coinspot")+ assert_equal(-100.to_d, buy.amount)+ assert_equal 0.001.to_d, buy.trade.qty+ assert_equal 100_000.to_d, buy.trade.price+ assert_equal "Buy", buy.trade.investment_activity_label++ sell = @account.entries.find_by!(external_id: "coinspot_order_sell_BTC_2026-01-03_sell-1", source: "coinspot")+ assert_equal 220.to_d, sell.amount+ assert_equal(-0.002.to_d, sell.trade.qty)+ assert_equal "Sell", sell.trade.investment_activity_label++ send_record = @coinspot_account.raw_transactions_payload.dig("send_receive", "sendtransactions").first+ fee_digest = Digest::SHA256.hexdigest(CoinspotAccount::Processor.canonical_json(send_record))[0, 24]+ fee = @account.entries.find_by!(external_id: "coinspot_fee_#{fee_digest}", source: "coinspot")+ assert_equal 1.to_d, fee.amount+ assert_equal "Fee", fee.transaction.investment_activity_label++ deposit = @account.entries.find_by!(external_id: "coinspot_deposit_aud_2026-01-06_deposit-1", source: "coinspot")+ assert_equal(-300.to_d, deposit.amount)+ assert_equal "Contribution", deposit.transaction.investment_activity_label++ withdrawal = @account.entries.find_by!(external_id: "coinspot_withdrawal_aud_2026-01-07_withdrawal-1", source: "coinspot")+ assert_equal 150.to_d, withdrawal.amount+ assert_equal "Withdrawal", withdrawal.transaction.investment_activity_label+ end++ test "prices a historical send fee from the transfer instead of the current holdings snapshot" do+ @coinspot_account.update!(+ raw_payload: { "assets" => [] },+ raw_transactions_payload: {+ "send_receive" => {+ "sendtransactions" => [+ { "txid" => "historical-send", "coin" => "btc", "amount" => "0.01", "aud" => "1000", "sendfee" => "0.00001", "timestamp" => "2025-01-04T10:00:00Z" }+ ]+ }+ }+ )++ result = CoinspotAccount::Processor.new(@coinspot_account).process++ assert_equal true, result[:success], result.inspect+ source_record = @coinspot_account.raw_transactions_payload.dig("send_receive", "sendtransactions").first+ digest = Digest::SHA256.hexdigest(CoinspotAccount::Processor.canonical_json(source_record))[0, 24]+ fee = @account.entries.find_by!(external_id: "coinspot_fee_#{digest}")+ assert_equal BigDecimal("1"), fee.amount+ end++ test "rolls back a movement when its native fee has no transaction-date AUD valuation" do+ @coinspot_account.update!(raw_transactions_payload: {+ "send_receive" => {+ "sendtransactions" => [+ { "txid" => "unpriced-fee", "coin" => "btc", "amount" => "0.01", "aud" => "0", "sendfee" => "0.00001", "timestamp" => "2025-01-04T10:00:00Z" }+ ]+ }+ })++ result = CoinspotAccount::Processor.new(@coinspot_account).process++ assert_equal false, result[:success]+ assert_equal "send_receive", result[:failures].first[:kind]+ assert_not @account.entries.exists?(external_id: "coinspot_send_BTC_2025-01-04_unpriced-fee")+ end++ test "rolls back an order when its fee cannot be imported" do+ @coinspot_account.update!(raw_transactions_payload: {+ "orders" => {+ "buyorders" => [ order_payload("atomic-buy", "btc", "0.001", "100.00", "100000.00", "1.00") ]+ }+ })+ processor = CoinspotAccount::Processor.new(@coinspot_account)+ processor.stubs(:import_fee).raises(StandardError, "fee import failed")++ result = processor.process++ assert_equal false, result[:success]+ assert_equal "order", result[:failures].first[:kind]+ assert_not @account.entries.exists?(external_id: "coinspot_order_buy_BTC_2026-01-03_atomic-buy")+ end++ test "processing is idempotent by external id and source" do+ assert_difference -> { @account.entries.where(source: "coinspot").count }, 9 do+ CoinspotAccount::Processor.new(@coinspot_account).process+ end++ assert_no_difference -> { @account.entries.where(source: "coinspot").count } do+ CoinspotAccount::Processor.new(@coinspot_account).process+ end+ end++ test "updates linked crypto account balance without cash balance" do+ CoinspotAccount::Processor.new(@coinspot_account).process++ @account.reload+ assert_equal 1000.to_d, @account.balance+ assert_equal 0.to_d, @account.cash_balance+ assert_equal "AUD", @account.currency+ end++ test "does not persist an AUD amount under a non-AUD account currency when FX is unavailable" do+ @family.update!(currency: "USD")+ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)++ assert_raises(CoinspotAccount::AudConverter::ConversionUnavailableError) do+ CoinspotAccount::Processor.new(@coinspot_account).process+ end++ @account.reload+ assert_equal 0.to_d, @account.balance+ assert_equal "AUD", @account.currency+ end++ test "derives market order price from aud total instead of quote asset rate" do+ @coinspot_account.update!(+ raw_transactions_payload: {+ "orders" => {+ "orders" => [+ {+ "id" => "eth-btc-1",+ "market" => "ETH/BTC",+ "amount" => "2.0",+ "audtotal" => "6000.00",+ "rate" => "0.05",+ "created" => "2026-01-08T10:00:00Z",+ "type" => "buy"+ }+ ]+ }+ }+ )+ eth = Security.create!(ticker: "CRYPTO:ETH", name: "ETH", exchange_operating_mic: "XCSO", offline: true)+ CoinspotAccount::SecurityResolver.stubs(:resolve).with("ETH").returns(eth)++ CoinspotAccount::Processor.new(@coinspot_account).process++ trade = @account.entries.find_by!(external_id: "coinspot_order_buy_ETH_2026-01-08_eth-btc-1", source: "coinspot").trade+ assert_equal 2.to_d, trade.qty+ assert_equal 3000.to_d, trade.price+ end++ # The whole provider record used to go into DebugLogEntry metadata and into+ # the failure result the syncer surfaces, putting addresses and amounts in+ # front of anyone who can read the debug UI.+ test "a record failure reports only allowlisted fields, not the whole record" do+ @coinspot_account.update!(raw_transactions_payload: {+ "send_receive" => {+ "sendtransactions" => [ {+ "txid" => "send-9", "coin" => "btc", "amount" => "0.001", "aud" => "100.00",+ "timestamp" => "2026-01-04T10:00:00Z",+ "address" => "bc1qsecretdestinationaddress", "sendfee" => "0.00001"+ } ]+ }+ })+ Account::ProviderImportAdapter.any_instance.stubs(:import_transaction).raises(StandardError, "boom")++ result = CoinspotAccount::Processor.new(@coinspot_account).process++ assert_equal false, result[:success]+ record = result[:failures].first[:record]+ assert_equal "send-9", record["txid"]+ assert_equal "btc", record["coin"]+ assert_nil record["address"]+ assert_nil record["aud"]+ assert_nil record["amount"]+ assert_not_includes record.to_json, "bc1qsecretdestinationaddress"+ end++ # ExchangeRate validates presence but not numericality, so a zero or negative+ # rate is storable -- multiplying by one writes a zeroed valuation instead of+ # failing.+ test "refuses to convert with a non-positive exchange rate" do+ @family.update!(currency: "USD")+ ExchangeRate.stubs(:find_or_fetch_rate).returns(+ ExchangeRate.new(from_currency: "AUD", to_currency: "USD", rate: 0, date: Date.current)+ )++ assert_raises(CoinspotAccount::AudConverter::ConversionUnavailableError) do+ CoinspotAccount::Processor.new(@coinspot_account).process+ end++ @account.reload+ assert_equal 0.to_d, @account.balance+ assert_equal "AUD", @account.currency+ end++ test "imports an order without a provider id using a stable content hash" do+ order = {+ "coin" => "btc",+ "amount" => "0.001",+ "audtotal" => "100.00",+ "rate" => "100000.00",+ "created" => "2026-01-09T10:00:00Z"+ }+ @coinspot_account.update!(raw_transactions_payload: { "orders" => { "buyorders" => [ order ] } })++ CoinspotAccount::Processor.new(@coinspot_account).process++ digest = Digest::SHA256.hexdigest(CoinspotAccount::Processor.canonical_json(order))[0, 24]+ assert @account.entries.exists?(external_id: "coinspot_order_buy_BTC_2026-01-09_#{digest}", source: "coinspot")+ end++ # The id-less fallback hashes the record's content, so the same order arriving+ # with its JSON keys in a different order must not import a second time.+ test "an id-less order re-imports as the same entry when its key order changes" do+ order = {+ "coin" => "btc", "amount" => "0.001", "audtotal" => "100.00",+ "rate" => "100000.00", "created" => "2026-01-09T10:00:00Z"+ }+ @coinspot_account.update!(raw_transactions_payload: { "orders" => { "buyorders" => [ order ] } })+ CoinspotAccount::Processor.new(@coinspot_account).process++ reordered = { "created" => "2026-01-09T10:00:00Z", "rate" => "100000.00",+ "audtotal" => "100.00", "amount" => "0.001", "coin" => "btc" }+ assert_not_equal order.to_json, reordered.to_json+ @coinspot_account.update!(raw_transactions_payload: { "orders" => { "buyorders" => [ reordered ] } })++ assert_no_difference -> { @account.entries.where(source: "coinspot").count } do+ CoinspotAccount::Processor.new(@coinspot_account).process+ end+ end++ # Records imported before canonical hashing keep the id they were stored+ # under, so an upgrade doesn't re-import a family's whole CoinSpot history.+ test "an order already stored under the legacy content hash keeps that id" do+ order = {+ "coin" => "btc", "amount" => "0.001", "audtotal" => "100.00",+ "rate" => "100000.00", "created" => "2026-01-09T10:00:00Z"+ }+ legacy_digest = Digest::SHA256.hexdigest(order.to_json)[0, 24]+ legacy_id = "coinspot_order_buy_BTC_2026-01-09_#{legacy_digest}"+ @account.entries.create!(+ external_id: legacy_id, source: "coinspot", name: "legacy", date: Date.new(2026, 1, 9),+ amount: -100, currency: "AUD",+ entryable: Trade.new(security: @security, qty: 0.001, price: 100_000, currency: "AUD")+ )+ @coinspot_account.update!(raw_transactions_payload: { "orders" => { "buyorders" => [ order ] } })++ assert_no_difference -> { @account.entries.where(source: "coinspot").count } do+ CoinspotAccount::Processor.new(@coinspot_account).process+ end+ assert @account.entries.exists?(external_id: legacy_id, source: "coinspot")+ end++ # A record whose date can't be parsed would be stamped Date.current, and the+ # date is part of every external id -- so the next sync that parses it+ # correctly would import it again instead of updating it.+ test "rejects an order whose timestamp cannot be parsed instead of dating it today" do+ @coinspot_account.update!(raw_transactions_payload: {+ "orders" => { "buyorders" => [ { "id" => "bad-date", "coin" => "btc", "amount" => "0.001",+ "audtotal" => "100.00", "created" => "not-a-date" } ] }+ })++ result = nil+ assert_no_difference -> { @account.entries.where(source: "coinspot").count } do+ result = CoinspotAccount::Processor.new(@coinspot_account).process+ end++ assert_equal false, result[:success]+ assert_equal "order", result[:failures].first[:kind]+ assert_equal "CoinspotAccount::Processor::UnparseableTimestampError", result[:failures].first[:error_class]+ end++ # The market-order fallback carries its side per record. Defaulting an+ # unreadable one to "buy" books a sell with the wrong sign on both the+ # quantity and the cash flow.+ test "rejects a market order whose type is missing rather than treating it as a buy" do+ @coinspot_account.update!(raw_transactions_payload: {+ "orders" => { "orders" => [ { "id" => "no-type", "coin" => "btc", "amount" => "0.001",+ "audtotal" => "100.00", "created" => "2026-01-09T10:00:00Z" } ] }+ })++ result = nil+ assert_no_difference -> { @account.entries.where(source: "coinspot").count } do+ result = CoinspotAccount::Processor.new(@coinspot_account).process+ end++ assert_equal false, result[:success]+ assert_equal "CoinspotAccount::Processor::UnknownOrderTypeError", result[:failures].first[:error_class]+ end++ private++ def order_payload(id, coin, amount, audtotal, rate, fee)+ {+ "id" => id,+ "coin" => coin,+ "amount" => amount,+ "audtotal" => audtotal,+ "rate" => rate,+ "audfeeExGst" => fee,+ "audGst" => "0.00",+ "created" => id.start_with?("buy") ? "2026-01-02T10:00:00Z" : "2026-01-03T10:00:00Z"+ }+ end+enddiff --git a/test/models/coinspot_account/security_resolver_test.rb b/test/models/coinspot_account/security_resolver_test.rbnew file mode 100644index 0000000000..b8d54a28ac--- /dev/null+++ b/test/models/coinspot_account/security_resolver_test.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++require "test_helper"++class CoinspotAccount::SecurityResolverTest < ActiveSupport::TestCase+ # The blank check used to run before the "|||" suffix was dropped, so a+ # symbol that is only a delimiter survived it and a symbol with whitespace+ # before the delimiter kept a trailing space -- both of which build a bad+ # "CRYPTO:" ticker.+ test "normalize_symbol drops the suffix before validating the remainder" do+ assert_nil CoinspotAccount::SecurityResolver.normalize_symbol("|||BTC")+ assert_equal "BTC", CoinspotAccount::SecurityResolver.normalize_symbol("BTC |||AUD")+ end++ test "normalize_symbol uppercases, trims, and rejects blanks" do+ assert_equal "BTC", CoinspotAccount::SecurityResolver.normalize_symbol(" btc ")+ assert_equal "ETH", CoinspotAccount::SecurityResolver.normalize_symbol("eth")+ assert_nil CoinspotAccount::SecurityResolver.normalize_symbol("")+ assert_nil CoinspotAccount::SecurityResolver.normalize_symbol(nil)+ assert_nil CoinspotAccount::SecurityResolver.normalize_symbol(" ")+ end++ # find_or_initialize_by checks before save!, so two overlapping syncs+ # resolving a new symbol can both miss and both insert. The unique index+ # rejects the loser, and that exception used to escape into a per-record+ # import failure instead of simply reading back the row that won.+ test "resolve reads back the placeholder when a concurrent insert wins the race" do+ existing = Security.create!(+ ticker: "CRYPTO:XYZ", name: "XYZ", exchange_operating_mic: "XCSO", offline: true+ )+ Security::Resolver.any_instance.stubs(:resolve).returns(nil)+ Security.stubs(:find_or_initialize_by).returns(+ Security.new(ticker: "CRYPTO:XYZ", exchange_operating_mic: "XCSO")+ )+ Security.any_instance.stubs(:save!).raises(ActiveRecord::RecordNotUnique.new("duplicate key"))++ assert_equal existing, CoinspotAccount::SecurityResolver.resolve("XYZ")+ end+enddiff --git a/test/models/coinspot_item/importer_test.rb b/test/models/coinspot_item/importer_test.rbnew file mode 100644index 0000000000..f2e44cae8e--- /dev/null+++ b/test/models/coinspot_item/importer_test.rb@@ -0,0 +1,196 @@+# frozen_string_literal: true++require "test_helper"++class CoinspotItem::ImporterTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @item = CoinspotItem.create!(+ family: @family,+ name: "CoinSpot",+ api_key: "k",+ api_secret: "s"+ )+ @provider = mock+ @provider.stubs(:status).returns({ "status" => "ok" })+ @provider.stubs(:get_order_history).returns({ "buyorders" => [], "sellorders" => [] })+ @provider.stubs(:get_send_receive_history).returns({ "sendtransactions" => [], "receivetransactions" => [] })+ @provider.stubs(:get_deposit_history).returns({ "deposits" => [] })+ @provider.stubs(:get_withdrawal_history).returns({ "withdrawals" => [] })+ end++ test "creates a combined coinspot account from balances" do+ @provider.stubs(:get_balances).returns(+ "status" => "ok",+ "balances" => [+ { "btc" => { "balance" => "0.5", "audbalance" => "50000.00", "rate" => "100000.00" } },+ { "aud" => { "balance" => "125.50", "audbalance" => "125.50", "rate" => "1.00" } },+ { "eth" => { "balance" => "0", "audbalance" => "0", "rate" => "5000.00" } }+ ]+ )++ assert_difference "@item.coinspot_accounts.count", 1 do+ result = CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import+ assert_equal 2, result[:assets_imported]+ assert_in_delta 50_125.50, result[:total_aud], 0.01+ end++ account = @item.coinspot_accounts.first+ assert_equal "combined", account.account_id+ assert_equal "combined", account.account_type+ assert_equal "AUD", account.currency+ assert_in_delta 50_125.50, account.current_balance, 0.01++ btc = account.raw_payload["assets"].find { |asset| asset["symbol"] == "BTC" }+ assert_equal "0.5", btc["balance"]+ assert_equal "50000.0", btc["amount_aud"]+ assert_equal "100000.0", btc["price_aud"]+ end++ test "falls back to market order history when standard order history is unavailable" do+ @provider.stubs(:get_balances).returns("balances" => [])+ @provider.stubs(:get_order_history).raises(Provider::Coinspot::ApiError, "unavailable")+ @provider.stubs(:get_market_order_history).returns({ "orders" => [ { "id" => "m1", "coin" => "BTC" } ] })++ result = CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import++ assert_equal 1, result[:orders_imported]+ payload = @item.coinspot_accounts.first.raw_transactions_payload+ assert_equal [ { "id" => "m1", "coin" => "BTC" } ], payload.dig("orders", "orders")+ assert_equal [], payload.dig("orders", "buyorders")+ end++ # The fallback read only response["orders"], so buy/sell orders the market+ # endpoint does return were dropped on the floor.+ test "market order fallback keeps buyorders and sellorders alongside orders" do+ @provider.stubs(:get_balances).returns("balances" => [])+ @provider.stubs(:get_order_history).raises(Provider::Coinspot::ApiError, "unavailable")+ @provider.stubs(:get_market_order_history).returns({+ "orders" => [ { "id" => "m1", "coin" => "BTC" } ],+ "buyorders" => [ { "id" => "b1", "coin" => "BTC" } ],+ "sellorders" => [ { "id" => "s1", "coin" => "BTC" } ]+ })++ result = CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import++ payload = @item.coinspot_accounts.first.raw_transactions_payload+ assert_equal %w[b1], payload.dig("orders", "buyorders").map { |o| o["id"] }+ assert_equal %w[s1], payload.dig("orders", "sellorders").map { |o| o["id"] }+ assert_equal %w[m1], payload.dig("orders", "orders").map { |o| o["id"] }+ assert_equal 3, result[:orders_imported]+ end++ test "fails without persisting a partial snapshot when both order history endpoints fail" do+ @provider.stubs(:get_balances).returns("balances" => [])+ @provider.stubs(:get_order_history).raises(Provider::Coinspot::ApiError, "unavailable")+ @provider.stubs(:get_market_order_history).raises(Provider::Coinspot::ApiError, "also unavailable")+ @item.update!(sync_start_date: Date.current)++ error = assert_raises(CoinspotItem::Importer::OrderHistoryUnavailableError) do+ CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import+ end++ assert_includes error.message, Date.current.to_s+ assert_empty @item.coinspot_accounts+ end++ # A single day at the record limit is known-truncated and CoinSpot offers no+ # finer paging, so persisting it would record a partial history as complete.+ test "fails without persisting when a single-day window is still saturated" do+ travel_to Date.new(2026, 1, 2) do+ @provider.stubs(:get_balances).returns("balances" => [])+ @item.update!(sync_start_date: Date.new(2026, 1, 2))++ saturated = Array.new(CoinspotItem::Importer::ORDER_HISTORY_LIMIT) { |i| { "id" => "sat-#{i}", "coin" => "BTC" } }+ @provider.stubs(:get_order_history).returns("buyorders" => saturated, "sellorders" => [])++ error = assert_raises(CoinspotItem::Importer::OrderHistoryUnavailableError) do+ CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import+ end++ assert_includes error.message, "2026-01-02"+ assert_empty @item.coinspot_accounts+ end+ end++ test "fails rather than valuing a nonzero asset at zero when its AUD price is missing" do+ @provider.stubs(:get_balances).returns(+ "balances" => [ { "xyz" => { "balance" => "12.5" } } ]+ )++ error = nil+ assert_difference -> { DebugLogEntry.count }, 1 do+ error = assert_raises(CoinspotItem::Importer::MissingAssetPriceError) do+ CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import+ end+ end++ assert_equal "CoinSpot returned XYZ without an AUD balance or rate", error.message+ assert_empty @item.coinspot_accounts+ end++ test "preserves sell orders alongside buy orders from the primary endpoint" do+ @provider.stubs(:get_balances).returns("balances" => [])+ @provider.stubs(:get_order_history).returns(+ "buyorders" => [ { "id" => "b1", "coin" => "BTC" } ],+ "sellorders" => [ { "id" => "s1", "coin" => "BTC" } ]+ )++ result = CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import++ assert_equal 2, result[:orders_imported]+ payload = @item.coinspot_accounts.first.raw_transactions_payload+ assert_equal [ { "id" => "b1", "coin" => "BTC" } ], payload.dig("orders", "buyorders")+ assert_equal [ { "id" => "s1", "coin" => "BTC" } ], payload.dig("orders", "sellorders")+ end++ test "preserves distinct orders that do not have provider ids" do+ @provider.stubs(:get_balances).returns("balances" => [])+ @provider.stubs(:get_order_history).returns(+ "buyorders" => [+ { "coin" => "BTC", "amount" => "0.1", "audtotal" => "1000", "created" => "2026-01-02T10:00:00Z" },+ { "coin" => "BTC", "amount" => "0.2", "audtotal" => "2000", "created" => "2026-01-03T10:00:00Z" }+ ],+ "sellorders" => []+ )++ result = CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import++ assert_equal 2, result[:orders_imported]+ orders = @item.coinspot_accounts.first.raw_transactions_payload.dig("orders", "buyorders")+ assert_equal [ "0.1", "0.2" ], orders.map { |order| order["amount"] }+ end++ test "bisects a window that comes back saturated at the record limit" do+ travel_to Date.new(2026, 1, 20) do+ @provider.stubs(:get_balances).returns("balances" => [])+ @item.update!(sync_start_date: Date.new(2026, 1, 1))++ full_window_orders = Array.new(CoinspotItem::Importer::ORDER_HISTORY_LIMIT) { |i| { "id" => "sat-#{i}", "coin" => "BTC" } }+ first_half_orders = [ { "id" => "half-1", "coin" => "BTC" } ]+ second_half_orders = [ { "id" => "half-2", "coin" => "BTC" } ]++ @provider.stubs(:get_order_history).with(startdate: Date.new(2026, 1, 1), enddate: Date.new(2026, 1, 20))+ .returns("buyorders" => full_window_orders, "sellorders" => [])+ @provider.stubs(:get_order_history).with(startdate: Date.new(2026, 1, 1), enddate: Date.new(2026, 1, 10))+ .returns("buyorders" => first_half_orders, "sellorders" => [])+ @provider.stubs(:get_order_history).with(startdate: Date.new(2026, 1, 11), enddate: Date.new(2026, 1, 20))+ .returns("buyorders" => second_half_orders, "sellorders" => [])++ CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import++ buyorders = @item.coinspot_accounts.first.raw_transactions_payload.dig("orders", "buyorders")+ assert_equal %w[half-1 half-2], buyorders.map { |order| order["id"] }.sort+ end+ end++ test "marks item requires update when permissions are invalid" do+ @provider.stubs(:get_balances).raises(Provider::Coinspot::PermissionError, "Permission denied")++ assert_raises(Provider::Coinspot::PermissionError) do+ CoinspotItem::Importer.new(@item, coinspot_provider: @provider).import+ end++ assert @item.reload.requires_update?+ end+enddiff --git a/test/models/coinspot_item/syncer_test.rb b/test/models/coinspot_item/syncer_test.rbnew file mode 100644index 0000000000..e0ccbf2f05--- /dev/null+++ b/test/models/coinspot_item/syncer_test.rb@@ -0,0 +1,82 @@+# frozen_string_literal: true++require "test_helper"++class CoinspotItem::SyncerTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @item = CoinspotItem.create!(family: @family, name: "CoinSpot", api_key: "k", api_secret: "s")+ @coinspot_account = @item.coinspot_accounts.create!(+ name: "CoinSpot",+ account_id: "combined",+ account_type: "combined",+ currency: "AUD",+ current_balance: 1000+ )+ @account = Account.create!(+ family: @family,+ name: "CoinSpot",+ balance: 0,+ currency: "AUD",+ accountable: Crypto.create!(subtype: "exchange")+ )+ AccountProvider.create!(account: @account, provider: @coinspot_account)+ end++ test "raises and captures debug log when linked account processing fails" do+ sync = @item.syncs.create!+ @item.expects(:import_latest_coinspot_data).returns(success: true)+ @item.expects(:process_accounts).returns([+ { coinspot_account_id: @coinspot_account.id, success: false, error: "boom" }+ ])+ @item.expects(:schedule_account_syncs).never+ DebugLogEntry.expects(:capture).with(has_entries(+ category: "provider_sync_error",+ level: "error",+ provider_key: "coinspot",+ family: @family,+ metadata: has_entries(coinspot_item_id: @item.id)+ ))++ error = assert_raises(StandardError) do+ CoinspotItem::Syncer.new(@item).perform_sync(sync)+ end++ assert_equal I18n.t("coinspot_item.syncer.processing_failed", count: 1), error.message+ assert sync.reload.failed?+ assert_equal error.message, sync.error+ end++ # schedule_account_syncs rescues per account and reports { success: false }+ # instead of raising, so discarding its result let a sync report success+ # while an account kept a stale balance.+ test "fails the sync when scheduling an account's balance sync fails" do+ sync = @item.syncs.create!+ @item.expects(:import_latest_coinspot_data).returns(success: true)+ @item.expects(:process_accounts).returns([+ { coinspot_account_id: @coinspot_account.id, success: true }+ ])+ @item.expects(:schedule_account_syncs).returns([+ { account_id: @account.id, success: false, error: "boom" }+ ])++ error = assert_raises(CoinspotItem::Syncer::ProcessingFailureError) do+ CoinspotItem::Syncer.new(@item).perform_sync(sync)+ end++ assert_equal I18n.t("coinspot_item.syncer.processing_failed", count: 1), error.message+ assert sync.reload.failed?+ end++ test "propagates per-account processor failures to the syncer" do+ CoinspotAccount::Processor.any_instance.stubs(:process).returns(+ success: false,+ failures: [ { kind: "holding", error: "boom" } ]+ )++ result = @item.process_accounts++ assert_equal false, result.first[:success]+ assert_equal "holding", result.first[:result][:failures].first[:kind]+ end+enddiff --git a/test/models/coinspot_item_test.rb b/test/models/coinspot_item_test.rbnew file mode 100644index 0000000000..4b20d03cdf--- /dev/null+++ b/test/models/coinspot_item_test.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++require "test_helper"++class CoinspotItemTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @item = CoinspotItem.create!(+ family: @family,+ name: "My CoinSpot",+ api_key: "test_key",+ api_secret: "test_secret"+ )+ end++ # `active` excludes a flagged row, so a flag that survives a failed enqueue+ # hides the connection from the UI with no job coming to delete it, and no+ # way for the user to retry. DestroyJob's own rescue only covers a failure+ # once the job is running -- this is the other side of that window.+ test "destroy_later restores the flag when enqueueing raises" do+ DestroyJob.stubs(:perform_later).raises(StandardError, "queue offline")++ assert_raises(StandardError) { @item.destroy_later }++ assert_not @item.reload.scheduled_for_deletion?+ end++ test "destroy_later restores the flag when enqueueing returns false" do+ DestroyJob.stubs(:perform_later).returns(false)++ @item.destroy_later++ assert_not @item.reload.scheduled_for_deletion?+ end++ test "destroy_later keeps the flag when the job is enqueued" do+ DestroyJob.stubs(:perform_later).returns(true)++ @item.destroy_later++ assert @item.reload.scheduled_for_deletion?+ end++ test "next_nonce! is monotonic even when the clock does not advance" do+ first = @item.next_nonce!+ second = @item.next_nonce!++ assert_operator Integer(second), :>, Integer(first)+ end+enddiff --git a/test/models/provider/coinspot_adapter_test.rb b/test/models/provider/coinspot_adapter_test.rbnew file mode 100644index 0000000000..5029da06d8--- /dev/null+++ b/test/models/provider/coinspot_adapter_test.rb@@ -0,0 +1,134 @@+# frozen_string_literal: true++require "test_helper"+require "uri"++class Provider::CoinspotAdapterTest < ActiveSupport::TestCase+ setup do+ coinspot_items(:requires_update).update!(scheduled_for_deletion: true)+ end++ test "supports Crypto accounts only" do+ assert_includes Provider::CoinspotAdapter.supported_account_types, "Crypto"+ assert_not_includes Provider::CoinspotAdapter.supported_account_types, "Depository"+ end++ test "returns fallback connection config when no credentials exist yet" do+ family = families(:empty)+ configs = Provider::CoinspotAdapter.connection_configs(family: family)++ assert_equal 1, configs.length+ assert_equal "coinspot", configs.first[:key]+ assert_equal I18n.t("coinspot_items.provider_connection.default_name"), configs.first[:name]+ assert configs.first[:can_connect]+ end++ test "returns one connection config per credentialed coinspot item" do+ family = families(:dylan_family)+ first_item = coinspot_items(:one)+ second_item = CoinspotItem.create!(+ family: family,+ name: "Business CoinSpot",+ api_key: "second_coinspot_key",+ api_secret: "second_coinspot_secret"+ )++ configs = Provider::CoinspotAdapter.connection_configs(family: family)++ assert_equal [ "coinspot_#{second_item.id}", "coinspot_#{first_item.id}" ], configs.map { |config| config[:key] }+ assert_equal [+ I18n.t("coinspot_items.provider_connection.name", name: second_item.name),+ I18n.t("coinspot_items.provider_connection.name", name: first_item.name)+ ], configs.map { |config| config[:name] }++ new_account_uri = URI.parse(configs.first[:new_account_path].call("Crypto", "/accounts"))+ assert_equal "/coinspot_items/select_accounts", new_account_uri.path+ assert_includes new_account_uri.query, "coinspot_item_id=#{second_item.id}"++ existing_account_uri = URI.parse(configs.first[:existing_account_path].call(accounts(:crypto).id))+ assert_equal "/coinspot_items/select_existing_account", existing_account_uri.path+ assert_includes existing_account_uri.query, "coinspot_item_id=#{second_item.id}"+ end++ test "connection configs ignore whitespace-only credentials" do+ family = families(:dylan_family)+ blank_item = CoinspotItem.create!(+ family: family,+ name: "Blank CoinSpot",+ api_key: "temporary_key",+ api_secret: "temporary_secret"+ )+ blank_item.update_columns(api_key: " ", api_secret: " ")++ configs = Provider::CoinspotAdapter.connection_configs(family: family)++ assert_equal [ "coinspot_#{coinspot_items(:one).id}" ], configs.map { |config| config[:key] }+ end++ test "build_provider returns nil when family is nil" do+ assert_nil Provider::CoinspotAdapter.build_provider(family: nil)+ end++ test "build_provider returns nil when family has no coinspot items" do+ assert_nil Provider::CoinspotAdapter.build_provider(family: families(:empty))+ end++ test "build_provider returns CoinSpot provider when only one credentialed item exists" do+ provider = Provider::CoinspotAdapter.build_provider(family: families(:dylan_family))++ assert_instance_of Provider::Coinspot, provider+ end++ test "build_provider requires explicit item when multiple credentialed items exist" do+ family = families(:dylan_family)+ CoinspotItem.create!(+ family: family,+ name: "Second CoinSpot",+ api_key: "second_coinspot_key",+ api_secret: "second_coinspot_secret"+ )++ assert_nil Provider::CoinspotAdapter.build_provider(family: family)+ end++ test "build_provider uses explicit coinspot item credentials" do+ family = families(:dylan_family)+ second_item = CoinspotItem.create!(+ family: family,+ name: "Second CoinSpot",+ api_key: " second_coinspot_key \n",+ api_secret: " second_coinspot_secret \n"+ )++ provider = Provider::CoinspotAdapter.build_provider(family: family, coinspot_item_id: second_item.id)++ assert_instance_of Provider::Coinspot, provider+ assert_equal "second_coinspot_key", provider.api_key+ assert_equal "second_coinspot_secret", provider.api_secret+ end++ test "build_provider refuses coinspot items outside the family" do+ family = families(:dylan_family)+ other_item = CoinspotItem.create!(+ family: families(:empty),+ name: "Other CoinSpot",+ api_key: "other_coinspot_key",+ api_secret: "other_coinspot_secret"+ )++ assert_nil Provider::CoinspotAdapter.build_provider(family: family, coinspot_item_id: other_item.id)+ end++ test "build_provider refuses explicit coinspot item without usable credentials" do+ family = families(:dylan_family)+ blank_item = CoinspotItem.create!(+ family: family,+ name: "Blank CoinSpot",+ api_key: "temporary_key",+ api_secret: "temporary_secret"+ )+ blank_item.update_columns(api_key: " ", api_secret: " ")++ assert_nil Provider::CoinspotAdapter.build_provider(family: family, coinspot_item_id: blank_item.id)+ end+enddiff --git a/test/models/provider/coinspot_test.rb b/test/models/provider/coinspot_test.rbnew file mode 100644index 0000000000..8d3698ac7a--- /dev/null+++ b/test/models/provider/coinspot_test.rb@@ -0,0 +1,154 @@+# frozen_string_literal: true++require "test_helper"++class Provider::CoinspotTest < ActiveSupport::TestCase+ setup do+ @provider = Provider::Coinspot.new(api_key: "test_key", api_secret: "test_secret", nonce_generator: -> { 1616492376594 })+ end++ test "read only requests send compact json body signed with hmac sha512" do+ expected_body = JSON.generate({ "nonce" => 1616492376594 })+ expected_signature = OpenSSL::HMAC.hexdigest("sha512", "test_secret", expected_body)+ response = mock_httparty_response(200, { "status" => "ok", "balances" => [] })++ Provider::Coinspot.expects(:post)+ .with(+ "/api/v2/ro/my/balances",+ has_entries(+ body: expected_body,+ headers: has_entries(+ "Content-Type" => "application/json",+ "key" => "test_key",+ "sign" => expected_signature+ )+ )+ )+ .returns(response)++ assert_equal({ "status" => "ok", "balances" => [] }, @provider.get_balances)+ end++ # CoinspotItem#next_nonce! returns a String (it round-trips a bigint column),+ # and JSON.generate preserves that type -- so production sent "nonce":"..."+ # while every test here passed an Integer literal and saw nothing. CoinSpot+ # requires an integer nonce and can reject the quoted form.+ test "serializes a string-returning nonce generator as a json integer" do+ provider = Provider::Coinspot.new(+ api_key: "test_key", api_secret: "test_secret",+ nonce_generator: -> { "1616492376594" }+ )+ expected_body = JSON.generate({ "nonce" => 1616492376594 })+ response = mock_httparty_response(200, { "status" => "ok" })++ Provider::Coinspot.expects(:post)+ .with("/api/v2/ro/status", has_entries(body: expected_body))+ .returns(response)++ provider.status+ end++ test "history requests include date params and the max record limit in signed body" do+ response = mock_httparty_response(200, { "status" => "ok", "buyorders" => [] })++ Provider::Coinspot.expects(:post)+ .with(+ "/api/v2/ro/my/orders/completed",+ has_entries(body: JSON.generate({+ "nonce" => 1616492376594,+ "startdate" => "2026-01-01",+ "enddate" => "2026-01-31",+ "limit" => "500"+ }))+ )+ .returns(response)++ result = @provider.get_order_history(startdate: Date.new(2026, 1, 1), enddate: Date.new(2026, 1, 31))+ assert_equal({ "status" => "ok", "buyorders" => [] }, result)+ end++ test "handle response raises api error for non 2xx" do+ response = mock_httparty_response(500, { "status" => "error", "message" => "unavailable" })++ assert_raises(Provider::Coinspot::ApiError) do+ @provider.send(:handle_response, response)+ end+ end++ test "handle response maps a 401 to an authentication error even without a classifiable message" do+ response = mock_httparty_response(401, { "status" => "error", "message" => "unavailable" })++ assert_raises(Provider::Coinspot::AuthenticationError) do+ @provider.send(:handle_response, response)+ end+ end++ test "handle response maps a 403 to a permission error even without a classifiable message" do+ response = mock_httparty_response(403, { "status" => "error", "message" => "unavailable" })++ assert_raises(Provider::Coinspot::PermissionError) do+ @provider.send(:handle_response, response)+ end+ end++ test "handle response maps a non-2xx response with a classifiable message even at a non-401/403 status" do+ response = mock_httparty_response(400, { "message" => "Invalid key or signature" })++ assert_raises(Provider::Coinspot::AuthenticationError) do+ @provider.send(:handle_response, response)+ end+ end++ test "handle response falls back to a generic api error for a non-2xx response with no body" do+ response = mock_httparty_response(502, nil)++ error = assert_raises(Provider::Coinspot::ApiError) do+ @provider.send(:handle_response, response)+ end+ assert_match(/502/, error.message)+ end++ test "handle response rejects malformed payloads" do+ response = mock_httparty_response(200, [ "not", "a", "hash" ])++ error = assert_raises(Provider::Coinspot::ApiError) do+ @provider.send(:handle_response, response)+ end++ assert_equal "Malformed CoinSpot API response", error.message+ end++ test "handle response maps authentication errors" do+ assert_raises(Provider::Coinspot::AuthenticationError) do+ @provider.send(:handle_response, coinspot_error_response("Invalid key or signature"))+ end+ end++ test "handle response maps permission errors" do+ assert_raises(Provider::Coinspot::PermissionError) do+ @provider.send(:handle_response, coinspot_error_response("Permission denied"))+ end+ end++ test "handle response maps nonce errors" do+ assert_raises(Provider::Coinspot::NonceError) do+ @provider.send(:handle_response, coinspot_error_response("Invalid nonce"))+ end+ end++ test "handle response maps rate limit errors" do+ assert_raises(Provider::Coinspot::RateLimitError) do+ @provider.send(:handle_response, coinspot_error_response("Rate limit exceeded"))+ end+ end++ private++ def coinspot_error_response(message)+ mock_httparty_response(200, { "status" => "error", "message" => message })+ end++ def mock_httparty_response(code, body)+ OpenStruct.new(code: code, parsed_response: body)+ end+end