Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add Sharesight as an investment provider (#4462)

Alexander Cafarella508cd19f1273
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index f1cb4f4073..2c523dc0f6 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -46,6 +46,7 @@ class AccountsController < ApplicationController
@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))
+ @sharesight_items = visible_provider_items(family.sharesight_items.ordered.with_attached_logo.includes(sharesight_accounts: [ :account, :linked_account ])).sort_by(&:created_at)
@wise_items = visible_provider_items(family.wise_items.ordered.includes(:wise_accounts, :accounts))
@trade_republic_items = visible_provider_items(
family.trade_republic_items.ordered.includes(trade_republic_accounts: { account_provider: :account })
@@ -546,6 +547,7 @@ class AccountsController < ApplicationController
@coinspot_items,
@trading212_items,
@questrade_items,
+ @sharesight_items,
@wise_items,
@trade_republic_items,
@onchain_wallet_items
diff --git a/app/controllers/investments_controller.rb b/app/controllers/investments_controller.rb
index 5fa25f1232..32740822ee 100644
--- a/app/controllers/investments_controller.rb
+++ b/app/controllers/investments_controller.rb
@@ -2,4 +2,38 @@ class InvestmentsController < ApplicationController
include AccountableResource
permitted_accountable_attributes :id, :subtype
+
+ def update
+ super
+ # Only if the account itself saved (we redirected). A failed update renders
+ # :edit and shouldn't save the portfolio's settings either.
+ update_sharesight_settings if response.redirect?
+ end
+
+ private
+
+ def update_sharesight_settings
+ sharesight_account = @account.provider_account_for("SharesightAccount")
+ return unless sharesight_account
+
+ settings = params.permit(account: { sharesight: SharesightAccount::SETTINGS_ATTRIBUTES }).dig(:account, :sharesight)
+ return if settings.blank?
+
+ sharesight_account.assign_cash_settings(settings)
+ if new_accounts_writable?(sharesight_account) && sharesight_account.save
+ sharesight_account.sharesight_item.sync_later if sharesight_account.cash_settings_changed?
+ else
+ flash.delete(:notice)
+ flash[:alert] = sharesight_account.errors.full_messages.to_sentence.presence || t("accounts.not_authorized")
+ end
+ end
+
+ # You have to be able to edit any settlement, dividend or funding account you
+ # newly choose. One that's already saved can stay even if you can't edit it.
+ def new_accounts_writable?(sharesight_account)
+ ids = %w[settlement_account_id dividend_account_id funding_account_id].filter_map do |attribute|
+ sharesight_account.public_send(attribute) if sharesight_account.attribute_changed?(attribute)
+ end.uniq
+ ids.empty? || Current.family.accounts.writable_by(Current.user).where(id: ids).count == ids.size
+ end
end
diff --git a/app/controllers/settings/providers_controller.rb b/app/controllers/settings/providers_controller.rb
index 56eed30582..fa27c7fd49 100644
--- a/app/controllers/settings/providers_controller.rb
+++ b/app/controllers/settings/providers_controller.rb
@@ -227,7 +227,8 @@ class Settings::ProvidersController < ApplicationController
{ key: "trade_republic", title: "Trade Republic", turbo_id: "trade-republic", partial: "trade_republic_panel" },
{ key: "indexa_capital", title: "Indexa Capital", turbo_id: "indexa_capital", partial: "indexa_capital_panel" },
{ key: "sophtron", title: "Sophtron", turbo_id: "sophtron", partial: "sophtron_panel" },
- { key: "questrade", title: "Questrade", turbo_id: "questrade", partial: "questrade_panel" }
+ { key: "questrade", title: "Questrade", turbo_id: "questrade", partial: "questrade_panel" },
+ { key: "sharesight", title: "Sharesight", turbo_id: "sharesight", partial: "sharesight_panel" }
].freeze
FAMILY_PANEL_KEYS = FAMILY_PANELS.map { |p| p[:key] }.freeze
@@ -255,6 +256,7 @@ class Settings::ProvidersController < ApplicationController
"onchain_wallet" => "OnchainWalletItem",
"snaptrade" => "SnaptradeItem",
"questrade" => "QuestradeItem",
+ "sharesight" => "SharesightItem",
"ibkr" => "IbkrItem",
"trading212" => "Trading212Item",
"trade_republic" => "TradeRepublicItem",
@@ -314,6 +316,8 @@ class Settings::ProvidersController < ApplicationController
@sophtron_items = Current.family.sophtron_items.ordered
when "questrade"
@questrade_items = Current.family.questrade_items.active.ordered
+ when "sharesight"
+ @sharesight_items = Current.family.sharesight_items.active.ordered
end
end
@@ -353,6 +357,7 @@ class Settings::ProvidersController < ApplicationController
@coinspot_items = Current.family.coinspot_items.active.ordered
@onchain_wallet_items = Current.family.onchain_wallet_items.active.ordered
@questrade_items = Current.family.questrade_items.active.ordered.select(:id)
+ @sharesight_items = Current.family.sharesight_items.active.ordered
@fio_items = Current.family.fio_items.active.ordered
# Wallet uploads are managed on iOS. Only expose linked accounts the
@@ -401,6 +406,7 @@ class Settings::ProvidersController < ApplicationController
"onchain_wallet" => @onchain_wallet_items,
"snaptrade" => @snaptrade_items,
"questrade" => @questrade_items,
+ "sharesight" => @sharesight_items,
"ibkr" => @ibkr_items,
"trading212" => @trading212_items,
"trade_republic" => @trade_republic_items,
diff --git a/app/controllers/sharesight_items_controller.rb b/app/controllers/sharesight_items_controller.rb
new file mode 100644
index 0000000000..9c16f3dabe
--- /dev/null
+++ b/app/controllers/sharesight_items_controller.rb
@@ -0,0 +1,210 @@
+class SharesightItemsController < ApplicationController
+ before_action :set_sharesight_item, only: [ :update, :destroy, :sync, :setup_accounts, :complete_account_setup ]
+ before_action :require_admin!, only: [ :create, :select_accounts, :select_existing_account, :link_existing_account, :update, :destroy, :sync, :setup_accounts, :complete_account_setup ]
+
+ def create
+ @sharesight_item = Current.family.sharesight_items.build(sharesight_item_params)
+ @sharesight_item.name ||= t("sharesight_items.defaults.name")
+
+ if @sharesight_item.save
+ @sharesight_item.sync_later
+
+ redirect_to accounts_path, notice: t(".success"), status: :see_other
+ else
+ render_provider_panel("sharesight", alert: @sharesight_item.errors.full_messages.join(", "))
+ end
+ end
+
+ def update
+ attrs = sharesight_item_params.to_h
+ attrs["client_id"] = @sharesight_item.client_id if attrs["client_id"].blank?
+ attrs["client_secret"] = @sharesight_item.client_secret if attrs["client_secret"].blank?
+
+ if @sharesight_item.update(attrs.merge(status: :good))
+ @sharesight_item.sync_later unless @sharesight_item.syncing?
+
+ render_provider_panel("sharesight", notice: t(".success"), fallback_path: accounts_path)
+ else
+ render_provider_panel("sharesight", alert: @sharesight_item.errors.full_messages.join(", "))
+ end
+ end
+
+ def destroy
+ @sharesight_item.unlink_all!(dry_run: false)
+ @sharesight_item.destroy_later
+ redirect_to settings_providers_path, notice: t(".success"), status: :see_other
+ end
+
+ def sync
+ @sharesight_item.sync_later unless @sharesight_item.syncing?
+ return render_provider_panel("sharesight", notice: t("settings.providers.sync_provider_in_progress")) if provider_panel_form?
+
+ respond_to do |format|
+ format.html { redirect_back_or_to accounts_path }
+ format.json { head :ok }
+ end
+ end
+
+ def select_accounts
+ item = current_sharesight_item
+ unless item
+ frame_redirect_to settings_providers_path, alert: t(".not_configured")
+ return
+ end
+
+ redirect_to setup_accounts_sharesight_item_path(item)
+ end
+
+ def select_existing_account
+ @account = linkable_accounts.find(params[:account_id])
+ @available_sharesight_accounts = Current.family.sharesight_items
+ .includes(sharesight_accounts: { account_provider: :account })
+ .flat_map(&:sharesight_accounts)
+ .select { |sharesight_account| sharesight_account.account_provider.nil? }
+ .sort_by { |sharesight_account| sharesight_account.updated_at || sharesight_account.created_at }
+ .reverse
+
+ render :select_existing_account, layout: false
+ end
+
+ def link_existing_account
+ account = linkable_accounts.find_by(id: params[:account_id])
+ sharesight_account = SharesightAccount
+ .joins(:sharesight_item)
+ .where(sharesight_items: { family_id: Current.family.id })
+ .find_by(id: params[:sharesight_account_id])
+
+ if account.blank? || sharesight_account.blank?
+ redirect_to settings_providers_path, alert: t(".not_found")
+ return
+ end
+
+ if account.accountable_type != "Investment" || account.account_providers.any? || account.plaid_account_id.present? || account.simplefin_account_id.present?
+ redirect_to account_path(account), alert: t(".only_manual_investment")
+ return
+ end
+
+ provider = nil
+
+ sharesight_account.with_lock do
+ if sharesight_account.current_account.present?
+ redirect_to account_path(account), alert: t(".already_linked")
+ return
+ end
+
+ provider = sharesight_account.ensure_account_provider!(account)
+ end
+
+ raise "Failed to create AccountProvider link" unless provider
+
+ process_after_linking(sharesight_account)
+
+ sharesight_account.sharesight_item.sync_later unless sharesight_account.sharesight_item.syncing?
+ redirect_to account_path(account), notice: t(".success"), status: :see_other
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Failed to link existing Sharesight portfolio: #{e.class} - #{e.message}",
+ source: "sharesight",
+ family: Current.family,
+ provider_key: "sharesight"
+ )
+ redirect_to settings_providers_path, alert: t(".failed"), status: :see_other
+ end
+
+ def setup_accounts
+ @sharesight_accounts = @sharesight_item.sharesight_accounts.includes(account_provider: :account).order(:name)
+ @linked_accounts = @sharesight_accounts.select { |a| a.current_account.present? }
+ @unlinked_accounts = @sharesight_accounts.reject { |a| a.current_account.present? }
+
+ no_accounts = @linked_accounts.blank? && @unlinked_accounts.blank?
+ latest_sync = @sharesight_item.syncs.ordered.first
+ should_sync = latest_sync.nil? || !latest_sync.completed?
+
+ if no_accounts && !@sharesight_item.syncing? && should_sync
+ @sharesight_item.sync_later
+ end
+
+ @linkable_accounts = linkable_accounts
+ .visible
+ .where(accountable_type: "Investment")
+ .where(plaid_account_id: nil, simplefin_account_id: nil)
+ .left_joins(:account_providers)
+ .where(account_providers: { id: nil })
+ .order(:name)
+
+ @syncing = @sharesight_item.syncing?
+ @waiting_for_sync = no_accounts && @syncing
+ @no_accounts_found = no_accounts && !@syncing && @sharesight_item.last_synced_at.present?
+ end
+
+ def complete_account_setup
+ selected_accounts = Array(params[:account_ids]).reject(&:blank?)
+ created_accounts = []
+
+ selected_accounts.each do |sharesight_account_id|
+ sharesight_account = @sharesight_item.sharesight_accounts.find_by(id: sharesight_account_id)
+ next unless sharesight_account
+
+ linked = false
+ sharesight_account.with_lock do
+ next if sharesight_account.current_account.present?
+
+ account = Account.create_from_sharesight_account(sharesight_account)
+ # ensure_account_provider! returns nil if linking fails, so don't keep an account we couldn't link.
+ raise ActiveRecord::Rollback unless sharesight_account.ensure_account_provider!(account)
+
+ created_accounts << account
+ linked = true
+ end
+
+ process_after_linking(sharesight_account) if linked
+ end
+
+ @sharesight_item.update!(pending_account_setup: @sharesight_item.unlinked_accounts_count.positive?)
+ @sharesight_item.sync_later if created_accounts.any?
+
+ if created_accounts.any?
+ redirect_to accounts_path, notice: t(".success", count: created_accounts.count), status: :see_other
+ elsif selected_accounts.empty?
+ redirect_to setup_accounts_sharesight_item_path(@sharesight_item), alert: t(".none_selected"), status: :see_other
+ else
+ redirect_to setup_accounts_sharesight_item_path(@sharesight_item), alert: t(".none_created"), status: :see_other
+ end
+ end
+
+ private
+
+ def set_sharesight_item
+ @sharesight_item = Current.family.sharesight_items.find(params[:id])
+ end
+
+ def current_sharesight_item
+ active_items = Current.family.sharesight_items.active
+ active_items.syncable.ordered.first || active_items.ordered.first
+ end
+
+ def linkable_accounts
+ Current.family.accounts.writable_by(Current.user)
+ end
+
+ # The value and holdings are already imported, so show them straight away.
+ # The sync after this brings in the activity.
+ def process_after_linking(sharesight_account)
+ SharesightAccount::Processor.new(sharesight_account.reload).process
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "Failed to process Sharesight portfolio #{sharesight_account.id} after linking: #{e.class} - #{e.message}",
+ source: "sharesight",
+ family: Current.family,
+ provider_key: "sharesight"
+ )
+ end
+
+ def sharesight_item_params
+ params.require(:sharesight_item).permit(:client_id, :client_secret)
+ end
+end
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 88e75f825d..ed21543d52 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -134,6 +134,9 @@ module SettingsHelper
when "questrade"
return { status: :off } unless @questrade_items&.any?
sync_based_summary(key)
+ when "sharesight"
+ return { status: :off } unless @sharesight_items&.any?
+ sync_based_summary(key)
else
{ status: :off }
end
diff --git a/app/javascript/controllers/sharesight_settings_controller.js b/app/javascript/controllers/sharesight_settings_controller.js
new file mode 100644
index 0000000000..08cb74f602
--- /dev/null
+++ b/app/javascript/controllers/sharesight_settings_controller.js
@@ -0,0 +1,26 @@
+import { Controller } from "@hotwired/stimulus";
+
+// Only shows the Sharesight settings that matter for the chosen cash and
+// dividend options. Hidden fields keep their values.
+export default class extends Controller {
+ static targets = ["cashMode", "dividendMode", "section"];
+
+ connect() {
+ this.update();
+ }
+
+ update() {
+ const cashMode = this.cashModeTarget.value;
+ const dividendMode = this.dividendModeTarget.value;
+
+ for (const section of this.sectionTargets) {
+ const cashModes = section.dataset.cashModes?.split(" ");
+ const dividendModes = section.dataset.dividendModes?.split(" ");
+ const visible =
+ (!cashModes || cashModes.includes(cashMode)) &&
+ (!dividendModes || dividendModes.includes(dividendMode));
+
+ section.classList.toggle("hidden", !visible);
+ }
+ }
+}
diff --git a/app/models/account.rb b/app/models/account.rb
index 827a33d98b..6029927a3d 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -495,6 +495,24 @@ class Account < ApplicationRecord
create_and_sync(attributes, skip_initial_sync: true)
end
+ def create_from_sharesight_account(sharesight_account)
+ family = sharesight_account.sharesight_item.family
+
+ attributes = {
+ family: family,
+ name: sharesight_account.name.presence || I18n.t("sharesight_items.defaults.name"),
+ balance: 0,
+ cash_balance: 0,
+ currency: sharesight_account.currency.presence || family.currency,
+ accountable_type: "Investment",
+ accountable_attributes: {
+ subtype: "brokerage"
+ }
+ }
+
+ create_and_sync(attributes, skip_initial_sync: true)
+ end
+
TRADE_REPUBLIC_ACCOUNT_TYPES = {
"portfolio" => [ "Investment", "brokerage", "Trade Republic Portfolio" ],
"cash" => [ "Depository", "checking", "Trade Republic Cash" ],
diff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rb
index 7137576cca..59fbbb3f72 100644
--- a/app/models/data_enrichment.rb
+++ b/app/models/data_enrichment.rb
@@ -19,6 +19,7 @@ class DataEnrichment < ApplicationRecord
questrade: "questrade",
redbark: "redbark",
rule: "rule",
+ sharesight: "sharesight",
similar: "similar",
simplefin: "simplefin",
sophtron: "sophtron",
diff --git a/app/models/family.rb b/app/models/family.rb
index 2ecd7519d6..f23fe86105 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -15,6 +15,7 @@ class Family < ApplicationRecord
include QuestradeConnectable
include RedbarkConnectable
include OnchainWalletConnectable
+ include SharesightConnectable
include AiPromptable
DATE_FORMATS = [
diff --git a/app/models/family/sharesight_connectable.rb b/app/models/family/sharesight_connectable.rb
new file mode 100644
index 0000000000..2413e5211d
--- /dev/null
+++ b/app/models/family/sharesight_connectable.rb
@@ -0,0 +1,11 @@
+module Family::SharesightConnectable
+ extend ActiveSupport::Concern
+
+ included do
+ has_many :sharesight_items, dependent: :destroy
+ end
+
+ def can_connect_sharesight?
+ true
+ end
+end
diff --git a/app/models/provider/metadata.rb b/app/models/provider/metadata.rb
index a92c52165b..9aaa4d2d8f 100644
--- a/app/models/provider/metadata.rb
+++ b/app/models/provider/metadata.rb
@@ -27,6 +27,7 @@ class Provider
plaid: { region: "US", kinds: %w[Bank], maturity: :stable, logo_text: "PL", logo_color: "#4f46e5", domain: "plaid.com", tier: "Paid" },
plaid_eu: { region: "EU", kinds: %w[Bank], maturity: :stable, logo_text: "PL", logo_color: "#4f46e5", domain: "plaid.com", tier: "Paid", name: "Plaid EU" },
questrade: { region: "CA", kinds: %w[Investment], maturity: :beta, logo_text: "QT", logo_color: "#0d9488", domain: "questrade.com" },
+ sharesight: { region: "Global", kinds: %w[Investment], maturity: :alpha, logo_text: "SS", logo_color: "#0d9488", domain: "sharesight.com" },
redbark: { region: "AU", kinds: %w[Bank], maturity: :beta, logo_text: "RB", logo_color: "#b91c1c", domain: "redbark.com" },
onchain_wallet: { region: "Global", kinds: %w[Crypto], maturity: :alpha, logo_text: "OC", logo_color: "#d97706", domain: nil, logo_icon: "wallet", name: "On-chain wallets" },
# Property valuation (AVM) providers
diff --git a/app/models/provider/sharesight.rb b/app/models/provider/sharesight.rb
new file mode 100644
index 0000000000..6b439f4d81
--- /dev/null
+++ b/app/models/provider/sharesight.rb
@@ -0,0 +1,162 @@
+class Provider::Sharesight
+ include HTTParty
+ extend SslConfigurable
+
+ class Error < StandardError; end
+ class AuthenticationError < Error; end
+ class ConfigurationError < Error; end
+ class RateLimitError < Error; end
+ class ApiError < Error
+ attr_reader :status_code, :response_body
+
+ def initialize(message, status_code: nil, response_body: nil)
+ super(message)
+ @status_code = status_code
+ @response_body = response_body
+ end
+ end
+
+ BASE_URI = "https://api.sharesight.com".freeze
+ USER_AGENT = "Sure Finance Sharesight Client".freeze
+
+ RETRYABLE_ERRORS = [
+ SocketError,
+ Net::OpenTimeout,
+ Net::ReadTimeout,
+ Errno::ECONNRESET,
+ Errno::ECONNREFUSED,
+ Errno::ETIMEDOUT,
+ EOFError
+ ].freeze
+
+ default_options.merge!({ timeout: 60 }.merge(httparty_ssl_options))
+
+ attr_reader :client_id, :client_secret
+
+ # Sharesight hands out API clients on request. We swap the id and secret for
+ # a 30 minute token (client_credentials), so there's no refresh token to keep.
+ def initialize(client_id:, client_secret:)
+ raise ConfigurationError, "client_id is required" if client_id.blank?
+ raise ConfigurationError, "client_secret is required" if client_secret.blank?
+
+ @client_id = client_id.to_s.strip
+ @client_secret = client_secret.to_s.strip
+ end
+
+ def fetch_portfolios
+ Array(get("/api/v2/portfolios.json")["portfolios"])
+ end
+
+ # Holdings (with each instrument's currency and price), cash accounts and the
+ # total value. Sold holdings are included so we can still find every trade's
+ # holding.
+ def fetch_performance(portfolio_id)
+ get("/api/v3/portfolios/#{portfolio_id}/performance", query: { include_sales: true })["report"] || {}
+ end
+
+ def fetch_trades(portfolio_id)
+ Array(get("/api/v2/portfolios/#{portfolio_id}/trades.json")["trades"])
+ end
+
+ def fetch_payouts(portfolio_id, start_date:, end_date: Date.current)
+ query = { start_date: start_date.iso8601, end_date: end_date.iso8601 }
+ Array(get("/api/v2/portfolios/#{portfolio_id}/payouts.json", query: query)["payouts"])
+ end
+
+ def fetch_cash_accounts
+ Array(get("/api/v2/cash_accounts.json")["cash_accounts"])
+ end
+
+ def fetch_cash_account_transactions(cash_account_id)
+ Array(get("/api/v2/cash_accounts/#{cash_account_id}/cash_account_transactions.json")["cash_account_transactions"])
+ end
+
+ private
+
+ def get(path, query: {})
+ response = request(path, query)
+
+ # A long sync can outlast the 30 minute token, so get a new one and retry once.
+ if response.code == 401
+ @access_token = nil
+ response = request(path, query)
+ end
+
+ handle_response(response)
+ end
+
+ def request(path, query)
+ with_retries(path) do
+ self.class.get("#{BASE_URI}#{path}", headers: auth_headers, query: query.compact)
+ end
+ end
+
+ def auth_headers
+ {
+ "Authorization" => "Bearer #{access_token}",
+ "Accept" => "application/json",
+ "User-Agent" => USER_AGENT
+ }
+ end
+
+ def access_token
+ @access_token ||= fetch_access_token
+ end
+
+ def fetch_access_token
+ response = with_retries("/oauth2/token") do
+ self.class.post(
+ "#{BASE_URI}/oauth2/token",
+ body: { grant_type: "client_credentials", client_id: client_id, client_secret: client_secret },
+ headers: { "Accept" => "application/json", "User-Agent" => USER_AGENT }
+ )
+ end
+
+ case response.code
+ when 200
+ token = response.parsed_response.is_a?(Hash) ? response.parsed_response["access_token"] : nil
+ token.presence || raise(ApiError.new("Sharesight returned no access token", status_code: response.code))
+ when 400, 401
+ raise AuthenticationError, "Sharesight rejected the API client (#{response.code}). Check your client ID and secret."
+ else
+ raise ApiError.new("Sharesight token request failed (status #{response.code})", status_code: response.code, response_body: response.body)
+ end
+ end
+
+ def handle_response(response)
+ case response.code
+ when 200
+ parsed = response.parsed_response
+ return parsed if parsed.is_a?(Hash)
+
+ raise ApiError.new("Sharesight returned an unexpected response", status_code: response.code, response_body: response.body)
+ when 401, 403
+ raise AuthenticationError, "Sharesight authentication failed (#{response.code}). Check your API client and that your plan includes API access."
+ when 429
+ raise RateLimitError, "Sharesight rate limit exceeded. Please wait before retrying."
+ else
+ raise ApiError.new("Sharesight API error (status #{response.code})", status_code: response.code, response_body: response.body)
+ end
+ end
+
+ def with_retries(label, max_retries: 3)
+ attempt = 0
+ begin
+ attempt += 1
+ yield
+ rescue *RETRYABLE_ERRORS => e
+ raise if attempt >= max_retries
+
+ delay = [ 2**attempt, 30 ].min
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "Provider::Sharesight #{label} attempt #{attempt} failed: #{e.message}. Retrying in #{delay}s",
+ source: "sharesight",
+ provider_key: "sharesight"
+ )
+ sleep(delay)
+ retry
+ end
+ end
+end
diff --git a/app/models/provider/sharesight_adapter.rb b/app/models/provider/sharesight_adapter.rb
new file mode 100644
index 0000000000..e4a25865b3
--- /dev/null
+++ b/app/models/provider/sharesight_adapter.rb
@@ -0,0 +1,59 @@
+class Provider::SharesightAdapter < Provider::Base
+ include Provider::Syncable
+ include Provider::InstitutionMetadata
+
+ Provider::Factory.register("SharesightAccount", self)
+
+ def self.supported_account_types
+ %w[Investment]
+ end
+
+ def self.connection_configs(family:)
+ return [] unless family.can_connect_sharesight?
+
+ [ {
+ key: "sharesight",
+ name: I18n.t("providers.sharesight.name"),
+ description: I18n.t("providers.sharesight.connection_description"),
+ can_connect: true,
+ new_account_path: ->(_accountable_type, _return_to) {
+ Rails.application.routes.url_helpers.select_accounts_sharesight_items_path
+ },
+ existing_account_path: ->(account_id) {
+ Rails.application.routes.url_helpers.select_existing_account_sharesight_items_path(account_id: account_id)
+ }
+ } ]
+ end
+
+ def provider_name
+ "sharesight"
+ end
+
+ def sync_path
+ Rails.application.routes.url_helpers.sync_sharesight_item_path(item)
+ end
+
+ def item
+ provider_account.sharesight_item
+ end
+
+ def can_delete_holdings?
+ false
+ end
+
+ def institution_domain
+ "sharesight.com"
+ end
+
+ def institution_name
+ I18n.t("providers.sharesight.institution_name")
+ end
+
+ def institution_url
+ "https://www.sharesight.com"
+ end
+
+ def institution_color
+ "#0d9488"
+ end
+end
diff --git a/app/models/provider_connection_status.rb b/app/models/provider_connection_status.rb
index f6670c1caf..c4c0dcfa89 100644
--- a/app/models/provider_connection_status.rb
+++ b/app/models/provider_connection_status.rb
@@ -27,6 +27,7 @@ class ProviderConnectionStatus
{ key: "trading212", type: "Trading212Item", association: :trading212_items, accounts: :trading212_accounts },
{ key: "trade_republic", type: "TradeRepublicItem", association: :trade_republic_items, accounts: :trade_republic_accounts },
{ key: "questrade", type: "QuestradeItem", association: :questrade_items, accounts: :questrade_accounts },
+ { key: "sharesight", type: "SharesightItem", association: :sharesight_items, accounts: :sharesight_accounts },
{ key: "redbark", type: "RedbarkItem", association: :redbark_items, accounts: :redbark_accounts },
{ key: "wise", type: "WiseItem", association: :wise_items, accounts: :wise_accounts }
].freeze
diff --git a/app/models/sharesight_account.rb b/app/models/sharesight_account.rb
new file mode 100644
index 0000000000..7f7d498ffd
--- /dev/null
+++ b/app/models/sharesight_account.rb
@@ -0,0 +1,69 @@
+class SharesightAccount < ApplicationRecord
+ include Encryptable
+ include SharesightAccount::DataHelpers, SharesightAccount::CashSettings
+
+ if encryption_ready?
+ encrypts :raw_payload
+ encrypts :raw_holdings_payload
+ encrypts :raw_trades_payload
+ encrypts :raw_payouts_payload
+ encrypts :raw_cash_transactions_payload
+ end
+
+ belongs_to :sharesight_item
+
+ has_one :account_provider, as: :provider, dependent: :destroy
+ has_one :account, through: :account_provider, source: :account
+ has_one :linked_account, through: :account_provider, source: :account
+
+ validates :name, :currency, presence: true
+ validates :sharesight_account_id, uniqueness: { scope: :sharesight_item_id, allow_nil: true }
+
+ def current_account
+ account || linked_account
+ end
+
+ def ensure_account_provider!(account = nil)
+ if account_provider.present?
+ account_provider.update!(account: account) if account && account_provider.account_id != account.id
+ return account_provider
+ end
+
+ acct = account || current_account
+ return nil unless acct
+
+ provider = AccountProvider
+ .find_or_initialize_by(provider_type: "SharesightAccount", provider_id: id)
+ .tap do |record|
+ record.account = acct
+ record.save!
+ end
+
+ reload_account_provider
+ provider
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "SharesightAccount##{id}: failed to ensure AccountProvider link: #{e.class} - #{e.message}",
+ source: "sharesight",
+ family: sharesight_item.family,
+ provider_key: "sharesight"
+ )
+ nil
+ end
+
+ # Holding id => the currency it trades in, for trades and payouts that only
+ # give the holding. Crypto's left out because Sharesight treats the coin as
+ # its own currency (Bitcoin is priced at 1 BTC), so we book it in the
+ # portfolio's currency instead.
+ def holding_currencies
+ @holding_currencies ||= Array(raw_holdings_payload).each_with_object({}) do |holding, map|
+ code = holding.dig("instrument_currency", "code").presence || holding.dig("instrument", "currency_code")
+ next if code.to_s.casecmp?(holding.dig("instrument", "code").to_s)
+
+ currency = parse_currency(code)
+ map[holding["id"].to_s] = currency if currency
+ end
+ end
+end
diff --git a/app/models/sharesight_account/activities_processor.rb b/app/models/sharesight_account/activities_processor.rb
new file mode 100644
index 0000000000..0658d0ec45
--- /dev/null
+++ b/app/models/sharesight_account/activities_processor.rb
@@ -0,0 +1,485 @@
+class SharesightAccount::ActivitiesProcessor
+ include SharesightAccount::DataHelpers
+
+ # Trade types we book as trades. Capital returns go in as cash. Everything
+ # else (splits, bonus issues, consolidations, cost base adjustments,
+ # transfers) changes units or cost with no price we can use, so it's logged
+ # and skipped. The holdings snapshot still has the right number of units.
+ TRADE_LABELS = {
+ "BUY" => "Buy",
+ "OPENING_BALANCE" => "Buy",
+ "SELL" => "Sell"
+ }.freeze
+
+ CAPITAL_RETURN = "CAPITAL_RETURN".freeze
+ OPENING_BALANCE = "OPENING_BALANCE".freeze
+
+ # Sharesight creates some records itself (dividends, DRP allotments,
+ # maturities) and leaves them unconfirmed, with no id, until you confirm them.
+ # Its holdings and value already count them, so we book them under this
+ # prefix and swap them out once the confirmed record turns up with an id.
+ PROVISIONAL_PREFIX = "sharesight_unconfirmed_".freeze
+
+ BOOKED_STATES = %w[confirmed unconfirmed].freeze
+
+ # How much cash a record moved in the investment account, so CashRouter can
+ # settle it somewhere else. kind is :trade or :dividend. matchable is false
+ # when no bank would ever see it (opening balances). leftover is true for
+ # what's left of a reinvested dividend, which the registry often keeps for
+ # the next reinvestment, so it might never reach a bank either.
+ Movement = Data.define(:key, :kind, :date, :currency, :amount, :matchable, :leftover, :description)
+
+ attr_reader :movements
+
+ def initialize(sharesight_account)
+ @sharesight_account = sharesight_account
+ @provisional_ids = []
+ @provisional_counts = Hash.new(0)
+ @movements = []
+ @kept_provisional_bases = []
+ @allotments = {}.compare_by_identity
+ @payout_allotments = {}.compare_by_identity
+ @allotment_entries = {}.compare_by_identity
+ end
+
+ def process
+ return { trades: 0, dividends: 0, transactions: 0 } unless account.present?
+
+ remove_entries_settings_exclude
+
+ capital_returns, trades = booked_trades.partition { |trade| trade["transaction_type"].to_s.upcase == CAPITAL_RETURN }
+ payouts = booked(@sharesight_account.raw_payouts_payload, "paid_on")
+ match_reinvested_allotments(payouts)
+
+ trade_count = trades.sum { |trade| process_trade(trade) ? 1 : 0 }
+ dividend_count = payouts.sum { |payout| process_payout(payout) ? 1 : 0 }
+ transaction_count = capital_returns.sum { |trade| process_capital_return(trade) ? 1 : 0 }
+ transaction_count += Array(@sharesight_account.raw_cash_transactions_payload).sum do |transaction|
+ process_cash_transaction(transaction) ? 1 : 0
+ end
+
+ remove_replaced_provisional_entries
+
+ { trades: trade_count, dividends: dividend_count, transactions: transaction_count }
+ end
+
+ private
+
+ def account
+ @sharesight_account.current_account
+ end
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+
+ def portfolio_currency
+ @sharesight_account.currency
+ end
+
+ def booked_trades
+ @booked_trades ||= booked(@sharesight_account.raw_trades_payload, "transaction_date")
+ end
+
+ # Confirmed and unconfirmed records from the sync start date up to today.
+ # Future unconfirmed ones are just announcements, like a dividend that
+ # hasn't been paid yet.
+ def booked(records, date_key)
+ Array(records).select do |record|
+ date = parse_date(record[date_key])
+ BOOKED_STATES.include?(record.fetch("state", "confirmed").to_s) && date.present? && date <= Date.current &&
+ !@sharesight_account.before_sync_start?(date)
+ end
+ end
+
+ # The record's id if it has one. Otherwise a provisional key made from what
+ # the record is about, numbered if two records end up with the same key.
+ def external_id_for(kind, record, *identity)
+ return "sharesight_#{kind}_#{record['id']}" if record["id"].present?
+
+ base = "#{PROVISIONAL_PREFIX}#{kind}_#{identity.join('_')}"
+ count = (@provisional_counts[base] += 1)
+ (count == 1 ? base : "#{base}_#{count}").tap { |id| @provisional_ids << id }
+ end
+
+ def remove_replaced_provisional_entries
+ account.entries
+ .where(source: "sharesight")
+ .where("external_id LIKE ?", "#{Entry.sanitize_sql_like(PROVISIONAL_PREFIX)}%")
+ .where.not(external_id: @provisional_ids)
+ .reject { |entry| kept_provisional?(entry.external_id) }
+ .each(&:destroy!)
+ end
+
+ # If a confirmed record fails to import, hang on to the provisional entry it
+ # was going to replace until a later sync gets the confirmed one in.
+ def keep_provisional_for(kind, *identity)
+ @kept_provisional_bases << "#{PROVISIONAL_PREFIX}#{kind}_#{identity.join('_')}"
+ end
+
+ def kept_provisional?(external_id)
+ @kept_provisional_bases.any? { |base| external_id == base || external_id.match?(/\A#{Regexp.escape(base)}_\d+\z/) }
+ end
+
+ # Clean up entries from earlier syncs that the current settings leave out.
+ def remove_entries_settings_exclude
+ entries = account.entries.where(source: "sharesight").where.not(entryable_type: "Valuation")
+
+ if @sharesight_account.sync_start_date
+ entries.where(entries: { date: ...@sharesight_account.sync_start_date }).destroy_all
+ end
+
+ if @sharesight_account.dividends_skipped?
+ entries.where(entryable_type: "Transaction").where(external_id_like_any(%w[payout capital_return])).destroy_all
+ end
+
+ # Cash account movements only belong here while the broker holds the cash.
+ entries.where(external_id_like_any(%w[cash])).find_each do |entry|
+ entry.destroy! unless @sharesight_account.holds_cash_at_broker_on?(entry.date)
+ end
+ end
+
+ def external_id_like_any(kinds)
+ patterns = kinds.flat_map { |kind| [ "sharesight_#{kind}_", "#{PROVISIONAL_PREFIX}#{kind}_" ] }
+ clause = patterns.map { "entries.external_id LIKE ?" }.join(" OR ")
+ [ clause, *patterns.map { |prefix| "#{Entry.sanitize_sql_like(prefix)}%" } ]
+ end
+
+ def record_movement(entries, kind:, matchable:, leftover: false)
+ entries = Array(entries).compact
+ return if entries.empty?
+
+ # A dividend and its traded allotment can be in different currencies, so
+ # keep one movement per currency rather than adding them together.
+ entries.group_by(&:currency).each do |currency, same_currency|
+ first = same_currency.first
+ @movements << Movement.new(
+ key: first.external_id.delete_prefix("sharesight_"),
+ kind: kind,
+ date: first.date,
+ currency: currency,
+ amount: same_currency.sum(&:amount),
+ matchable: matchable,
+ leftover: leftover,
+ description: first.name
+ )
+ end
+ end
+
+ def process_trade(trade)
+ type = trade["transaction_type"].to_s.upcase
+ label = TRADE_LABELS[type]
+ unless label
+ log_skipped_trade(trade, type)
+ return false
+ end
+
+ quantity = parse_decimal(trade["quantity"])&.abs
+ date = parse_date(trade["transaction_date"])
+ return false if quantity.nil? || quantity.zero? || date.nil?
+
+ identity = [ trade["holding_id"], trade["transaction_date"], type, quantity.to_s("F") ]
+ external_id = external_id_for("trade", trade, *identity)
+ security = resolve_security(trade["symbol"], trade["market"])
+ unless security
+ keep_provisional_for("trade", *identity)
+ return false
+ end
+
+ # Sharesight's exchange_rate is instrument currency per unit of portfolio
+ # currency. Sure's trade rate is the other way round.
+ sharesight_rate = parse_decimal(trade["exchange_rate"])
+ sharesight_rate = nil unless sharesight_rate&.positive?
+ currency, price = trade_price(trade, type, quantity, sharesight_rate)
+ if price.nil?
+ keep_provisional_for("trade", *identity)
+ return false
+ end
+
+ fee = trade_fee(trade, currency, sharesight_rate, date)
+ gross = quantity * price
+ signed_quantity = label == "Sell" ? -quantity : quantity
+ amount = (label == "Sell" ? -gross : gross) + fee
+ # A dividend's reinvested units cost nothing here if the dividend isn't imported.
+ amount = 0 if @allotments.key?(trade) && @sharesight_account.dividends_skipped?
+
+ entry = import_adapter.import_trade(
+ external_id: external_id,
+ security: security,
+ quantity: signed_quantity,
+ price: price,
+ amount: amount,
+ currency: currency,
+ date: date,
+ source: "sharesight",
+ activity_label: label,
+ exchange_rate: currency != portfolio_currency && sharesight_rate ? (1 / sharesight_rate).to_f : nil,
+ fee: fee
+ )
+ if @allotments.key?(trade)
+ # Paired with its dividend in process_payout instead.
+ @allotment_entries[trade] = entry
+ else
+ record_movement(entry, kind: :trade, matchable: type != OPENING_BALANCE)
+ end
+
+ true
+ rescue => e
+ keep_provisional_for("trade", *identity) if identity
+ log_failure("trade", trade["id"], e)
+ false
+ end
+
+ # The instrument's currency, if Sharesight or the market tells us.
+ def instrument_currency(record)
+ @sharesight_account.holding_currencies[record["holding_id"].to_s] || market_currency(record["market"])
+ end
+
+ # Trades are booked in the instrument's currency. If we don't know it (or
+ # it's crypto) we fall back to the portfolio's and convert the price with
+ # the trade's rate.
+ def trade_price(trade, type, quantity, sharesight_rate)
+ price = parse_decimal(trade["price"])
+ price = nil if price&.zero?
+
+ # An opening balance might only have a cost base, in the portfolio's
+ # currency. Without the trade's rate we can't convert it, so keep it in the
+ # portfolio's currency.
+ if price.nil? && type == OPENING_BALANCE
+ cost_base = parse_decimal(trade["cost_base"])
+ return [ nil, nil ] unless cost_base
+ return [ portfolio_currency, cost_base / quantity ] unless sharesight_rate
+
+ price = cost_base * sharesight_rate / quantity
+ end
+ return [ nil, nil ] if price.nil?
+
+ currency = instrument_currency(trade)
+ return [ currency, price ] if currency
+
+ [ portfolio_currency, sharesight_rate ? price / sharesight_rate : price ]
+ end
+
+ # Brokerage is usually charged in the portfolio's currency. Convert it with
+ # the trade's rate when we can, otherwise Sure's rate for that day.
+ def trade_fee(trade, currency, sharesight_rate, date)
+ fee = parse_decimal(trade["brokerage"]) || BigDecimal("0")
+ fee_currency = parse_currency(trade["brokerage_currency_code"]) || currency
+ return fee if fee.zero? || fee_currency == currency
+
+ if sharesight_rate && fee_currency == portfolio_currency
+ fee * sharesight_rate
+ elsif sharesight_rate && currency == portfolio_currency
+ fee / sharesight_rate
+ else
+ Money.new(fee, fee_currency).exchange_to(currency, date: date).amount
+ end
+ rescue Money::ConversionError
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "Left the #{fee_currency} brokerage on Sharesight trade #{trade['id']} out: no rate to #{currency} for #{date}",
+ source: "sharesight",
+ family: @sharesight_account.sharesight_item.family,
+ provider_key: "sharesight"
+ )
+ BigDecimal("0")
+ end
+
+ # A capital return pays cash back without changing the units. Sure can't
+ # lower the cost base, so we only book the cash. The trade's value is in the
+ # portfolio's currency; capital_return_value is the fallback.
+ def process_capital_return(trade)
+ return false if @sharesight_account.dividends_skipped?
+
+ amount = parse_decimal(trade["value"])&.abs
+ currency = portfolio_currency
+ unless amount&.positive?
+ amount = parse_decimal(trade["capital_return_value"])
+ currency = instrument_currency(trade) || portfolio_currency
+ end
+ date = parse_date(trade["transaction_date"])
+ return false unless amount&.positive? && date
+
+ external_id = external_id_for("capital_return", trade, trade["holding_id"], trade["transaction_date"])
+ security = resolve_security(trade["symbol"], trade["market"])
+
+ entry = import_adapter.import_transaction(
+ external_id: external_id,
+ amount: -amount,
+ currency: currency,
+ date: date,
+ name: security ? "Capital return from #{security.ticker}" : "Capital return",
+ source: "sharesight",
+ investment_activity_label: "Other",
+ extra: {
+ security_id: security&.id,
+ sharesight: { trade_id: trade["id"], symbol: trade["symbol"], market: trade["market"] }.compact
+ }
+ )
+ record_movement(entry, kind: :dividend, matchable: true)
+
+ true
+ rescue => e
+ keep_provisional_for("capital_return", trade["holding_id"], trade["transaction_date"])
+ log_failure("capital return", trade["id"], e)
+ false
+ end
+
+ # If dividends aren't imported, a reinvested one still buys units. Those go
+ # in with no cash, since the dividend that paid for them isn't here.
+ def process_payout(payout)
+ date = parse_date(payout["paid_on"])
+ return false unless date
+
+ external_id = external_id_for("payout", payout, payout["holding_id"], payout["paid_on"])
+ security = resolve_security(payout["symbol"], payout["market"])
+ currency = parse_currency(payout["currency"]) || @sharesight_account.holding_currencies[payout["holding_id"].to_s] || portfolio_currency
+ amount = parse_decimal(payout["amount"])
+
+ skipped = @sharesight_account.dividends_skipped?
+ dividend = nil
+ if amount&.positive? && !skipped
+ dividend = import_adapter.import_transaction(
+ external_id: external_id,
+ amount: -amount,
+ currency: currency,
+ date: date,
+ name: security ? "Dividend from #{security.ticker}" : "Dividend",
+ source: "sharesight",
+ investment_activity_label: "Dividend",
+ extra: {
+ security_id: security&.id,
+ sharesight: { payout_id: payout["id"], symbol: payout["symbol"], market: payout["market"] }.compact
+ }
+ )
+ end
+
+ reinvestment = import_reinvestment(payout, security, currency, date, paid_for: !skipped) || @allotment_entries[@payout_allotments[payout]]
+ record_movement([ dividend, reinvestment ], kind: :dividend, matchable: true, leftover: reinvestment.present?) unless skipped
+ dividend.present?
+ rescue => e
+ keep_provisional_for("payout", payout["holding_id"], payout["paid_on"])
+ keep_provisional_for("drp", payout["holding_id"], payout["paid_on"])
+ log_failure("payout", payout["id"], e)
+ false
+ end
+
+ # A reinvested dividend buys units. Some portfolios record the allotment as
+ # a trade too, so don't book it twice.
+ def import_reinvestment(payout, security, currency, date, paid_for:)
+ drp = payout["drp_trade_attributes"] || {}
+ return unless security && drp["dividend_reinvested"]
+
+ quantity = parse_decimal(drp["quantity"])&.abs
+ price = parse_decimal(drp["price"])
+ return unless quantity&.positive? && price&.positive?
+ return if allotment_trade_for(payout, quantity)
+
+ import_adapter.import_trade(
+ external_id: external_id_for("drp", payout, payout["holding_id"], payout["paid_on"]),
+ security: security,
+ quantity: quantity,
+ price: price,
+ amount: paid_for ? quantity * price : 0,
+ currency: currency,
+ date: date,
+ source: "sharesight",
+ activity_label: "Reinvestment"
+ )
+ end
+
+ def allotment_trade_for(payout, quantity)
+ booked_trades.find do |trade|
+ trade["holding_id"].to_s == payout["holding_id"].to_s &&
+ parse_date(trade["transaction_date"]) == parse_date(payout["paid_on"]) &&
+ parse_decimal(trade["quantity"])&.abs == quantity
+ end
+ end
+
+ # Trades that are really a payout's reinvested units. Their cash goes with
+ # the dividend, so they're settled together as what's left over, not as a
+ # buy through the bank.
+ def match_reinvested_allotments(payouts)
+ payouts.each do |payout|
+ drp = payout["drp_trade_attributes"] || {}
+ quantity = parse_decimal(drp["quantity"])&.abs
+ next unless drp["dividend_reinvested"] && quantity&.positive?
+
+ trade = allotment_trade_for(payout, quantity)
+ next if trade.nil? || @allotments.key?(trade)
+
+ @allotments[trade] = payout
+ @payout_allotments[payout] = trade
+ end
+ end
+
+ # Deposits, withdrawals, interest and fees from a Sharesight cash account,
+ # while the broker holds the cash. Skips the cash side of trades and
+ # payouts, since those already book it.
+ def process_cash_transaction(transaction)
+ return false if transaction["id"].blank?
+ return false if transaction["trade_id"].present? || transaction["payout_id"].present?
+
+ amount = parse_decimal(transaction["amount"])
+ date = parse_date(transaction["date_time"].to_s.first(10))
+ return false if amount.nil? || amount.zero? || date.nil?
+ return false if @sharesight_account.before_sync_start?(date) || !@sharesight_account.holds_cash_at_broker_on?(date)
+
+ label = cash_transaction_label(transaction, amount)
+
+ import_adapter.import_transaction(
+ external_id: "sharesight_cash_#{transaction['id']}",
+ amount: -amount,
+ currency: parse_currency(transaction["currency"]) || portfolio_currency,
+ date: date,
+ name: transaction["description"].presence || label,
+ source: "sharesight",
+ investment_activity_label: label
+ )
+
+ true
+ rescue => e
+ log_failure("cash transaction", transaction["id"], e)
+ false
+ end
+
+ def cash_transaction_label(transaction, amount)
+ type = transaction.dig("cash_account_transaction_type", "name").to_s.upcase
+
+ if type.include?("INTEREST")
+ "Interest"
+ elsif type.include?("FEE")
+ "Fee"
+ elsif amount.positive?
+ "Contribution"
+ else
+ "Withdrawal"
+ end
+ end
+
+ def log_skipped_trade(trade, type)
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "info",
+ message: "SharesightAccount::ActivitiesProcessor - Skipped #{type} trade #{trade['id']} " \
+ "(#{trade['symbol']} on #{trade['transaction_date']}): Sure has no equivalent",
+ source: "sharesight",
+ family: @sharesight_account.sharesight_item.family,
+ provider_key: "sharesight",
+ metadata: { trade_id: trade["id"], sharesight_account_id: @sharesight_account.id }
+ )
+ end
+
+ def log_failure(kind, id, error)
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightAccount::ActivitiesProcessor - Failed to process #{kind} #{id}: #{error.message}",
+ source: "sharesight",
+ family: @sharesight_account.sharesight_item.family,
+ provider_key: "sharesight",
+ metadata: { id: id, sharesight_account_id: @sharesight_account.id }
+ )
+ end
+end
diff --git a/app/models/sharesight_account/cash_router.rb b/app/models/sharesight_account/cash_router.rb
new file mode 100644
index 0000000000..dd74f678ec
--- /dev/null
+++ b/app/models/sharesight_account/cash_router.rb
@@ -0,0 +1,276 @@
+# Keeps the investment account to just its shares when the money lives
+# somewhere else (see SharesightAccount::CashSettings).
+#
+# Every record that moved cash in the investment account gets an opposite
+# "Transfer" entry there, so the cash nets to zero all the way back through the
+# history. If the money went to an account in Sure, we link that entry to the
+# other side as a confirmed transfer:
+# - If the account comes from a bank feed, the transaction's already there, so
+# we look for it by amount (to the cent) and direction within the settlement
+# window, including a day's trades settled as one amount. Anything not found
+# is retried each sync and reported once it's overdue.
+# - If it's a manual account, we book the other side ourselves.
+class SharesightAccount::CashRouter
+ include SharesightAccount::TransferLinking
+
+ OFFSET_PREFIX = "sharesight_offset_".freeze
+ COUNTERPART_PREFIX = "sharesight_counterpart_".freeze
+
+ # One offset entry, for one record or a day's trades settled together.
+ Unit = Struct.new(:key, :kind, :date, :currency, :amount, :target, :leftover, :description, :bank_entry, keyword_init: true)
+
+ attr_reader :notices
+
+ def initialize(sharesight_account, movements)
+ @sharesight_account = sharesight_account
+ @movements = movements
+ @notices = []
+ end
+
+ def route
+ return unless account
+
+ units = match_bank_transactions(build_units)
+ counterpart_ids = units.filter_map { |unit| settle(unit) }
+
+ remove_stale_offsets(units)
+ remove_stale_counterparts(counterpart_ids)
+ report_unsettled(units)
+ end
+
+ private
+
+ def account
+ @account ||= @sharesight_account.current_account
+ end
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+
+ def build_units
+ @movements.filter_map do |movement|
+ destination = if movement.kind == :dividend
+ @sharesight_account.dividend_destination_on(movement.date)
+ else
+ @sharesight_account.trade_destination_on(movement.date)
+ end
+ next if destination.nil? || destination == :skip || movement.amount.zero?
+
+ # Opening balances never go near a bank, and a settlement account can
+ # only settle in its own currency.
+ target = destination if destination.is_a?(Account) && movement.matchable && destination.currency == movement.currency
+ # A reinvested dividend's leftover is only linked if a bank feed shows
+ # it arriving. We don't book it into a manual account on a guess.
+ target = nil if movement.leftover && !bank_fed?(target)
+
+ Unit.new(
+ key: movement.key,
+ kind: movement.kind,
+ date: movement.date,
+ currency: movement.currency,
+ amount: movement.amount,
+ target: target,
+ leftover: movement.leftover,
+ description: movement.description
+ )
+ end
+ end
+
+ def bank_fed?(target)
+ target&.linked?
+ end
+
+ # Keep links from earlier syncs first, so a later look-alike can't steal them.
+ def match_bank_transactions(units)
+ claimed = Set.new
+ matchable = units.select { |unit| bank_fed?(unit.target) }
+
+ matchable.each do |unit|
+ linked = linked_bank_entry(unit.key, unit.target)
+ next unless linked
+
+ if linked.amount == in_cents(unit) && claimed.add?(linked.id)
+ unit.bank_entry = linked
+ else
+ offset_entry(unit.key).entryable.transfer&.destroy!
+ end
+ end
+
+ matchable.each do |unit|
+ next if unit.bank_entry
+
+ unit.bank_entry = find_bank_entry(unit, claimed)
+ claimed << unit.bank_entry.id if unit.bank_entry
+ end
+
+ combine_days(units, claimed)
+ end
+
+ # Some brokers settle a day's trades as one net amount.
+ def combine_days(units, claimed)
+ groups = units.select { |unit| unit.kind == :trade && bank_fed?(unit.target) && unit.bank_entry.nil? }
+ .group_by { |unit| [ unit.target, unit.date, unit.currency ] }
+ .select { |_, group| group.size > 1 }
+
+ groups.each do |(target, date, currency), group|
+ day = Unit.new(
+ key: "day_#{date.iso8601}_#{currency}",
+ kind: :trade,
+ date: date,
+ currency: currency,
+ amount: group.sum(&:amount),
+ target: target,
+ description: "Sharesight trades on #{date.iso8601}"
+ )
+ next if day.amount.zero?
+
+ linked = linked_bank_entry(day.key, target)
+ day.bank_entry = linked if linked && linked.amount == in_cents(day) && claimed.add?(linked.id)
+ day.bank_entry ||= find_bank_entry(day, claimed)
+ next unless day.bank_entry
+
+ claimed << day.bank_entry.id
+ units = (units - group) + [ day ]
+ end
+
+ units
+ end
+
+ def find_bank_entry(unit, claimed)
+ window = @sharesight_account.settlement_window_days
+ rejected = rejected_partner_ids(unit.key)
+
+ unit.target.entries
+ .where(entryable_type: "Transaction", excluded: false, currency: unit.currency, amount: in_cents(unit))
+ .where(date: (unit.date - 1)..(unit.date + window))
+ .where.not(id: claimed.to_a)
+ .includes(:entryable)
+ .reject { |entry| entry.entryable.transfer.present? || rejected.include?(entry.entryable_id) }
+ .min_by { |entry| [ (entry.date - unit.date).abs, entry.date ] }
+ end
+
+ def offset_entry(key)
+ account.entries.find_by(source: "sharesight", external_id: "#{OFFSET_PREFIX}#{key}")
+ end
+
+ # The other side of an offset entry's transfer, if it's in the target account.
+ def linked_bank_entry(key, target)
+ transfer = offset_entry(key)&.entryable&.transfer
+ return unless transfer
+
+ [ transfer.inflow_transaction, transfer.outflow_transaction ].map(&:entry).find { |entry| entry.account_id == target.id }
+ end
+
+ def rejected_partner_ids(key)
+ leg_transaction_id = offset_entry(key)&.entryable_id
+ return Set.new unless leg_transaction_id
+
+ RejectedTransfer.where(inflow_transaction_id: leg_transaction_id).pluck(:outflow_transaction_id).to_set |
+ RejectedTransfer.where(outflow_transaction_id: leg_transaction_id).pluck(:inflow_transaction_id)
+ end
+
+ # Books the offset entry and links it. Returns the counterpart's entry id if
+ # we booked one in a manual account.
+ def settle(unit)
+ leg = import_adapter.import_transaction(
+ external_id: "#{OFFSET_PREFIX}#{unit.key}",
+ # Linked to an account, the two sides have to add up exactly, so use whole cents.
+ amount: unit.target ? -in_cents(unit) : -unit.amount,
+ currency: unit.currency,
+ date: unit.date,
+ name: offset_name(unit),
+ source: "sharesight",
+ investment_activity_label: "Transfer",
+ allow_heuristic_matching: false,
+ extra: { sharesight: { settles: unit.key } }
+ )
+
+ if unit.bank_entry
+ link_transfer!(leg, unit.bank_entry)
+ nil
+ elsif unit.target && !bank_fed?(unit.target)
+ counterpart = book_counterpart(unit)
+ link_transfer!(leg, counterpart)
+ counterpart.id
+ end
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightAccount::CashRouter - Failed to settle #{unit.key}: #{e.message}",
+ source: "sharesight",
+ family: @sharesight_account.sharesight_item.family,
+ provider_key: "sharesight"
+ )
+ nil
+ end
+
+ def offset_name(unit)
+ return "Settled outside Sure" unless unit.target && (unit.bank_entry || !unit.leftover)
+
+ unit.amount.positive? ? "Transfer from #{unit.target.name}" : "Transfer to #{unit.target.name}"
+ end
+
+ def book_counterpart(unit)
+ Account::ProviderImportAdapter.new(unit.target).import_transaction(
+ external_id: counterpart_external_id(unit),
+ amount: in_cents(unit),
+ currency: unit.currency,
+ date: unit.date,
+ name: unit.description,
+ source: "sharesight",
+ allow_heuristic_matching: false,
+ extra: { sharesight: { settles: unit.key } }
+ )
+ end
+
+ # Banks deal in whole cents, but a trade's amount (quantity x price + fee)
+ # can come to a fraction of one.
+ def in_cents(unit)
+ unit.amount.round(Money::Currency.new(unit.currency).default_precision)
+ end
+
+ def counterpart_external_id(unit)
+ "#{COUNTERPART_PREFIX}#{@sharesight_account.id}_#{unit.key}"
+ end
+
+ def remove_stale_offsets(units)
+ current = units.map { |unit| "#{OFFSET_PREFIX}#{unit.key}" }
+
+ account.entries
+ .where(source: "sharesight")
+ .where("entries.external_id LIKE ?", "#{Entry.sanitize_sql_like(OFFSET_PREFIX)}%")
+ .where.not(external_id: current)
+ .destroy_all
+ end
+
+ # By entry id, since a counterpart keeps its external id when the settlement
+ # account changes, and the old account's copy has to go.
+ def remove_stale_counterparts(current)
+ Entry.joins(:account)
+ .where(accounts: { family_id: account.family_id }, source: "sharesight")
+ .where("entries.external_id LIKE ?", "#{Entry.sanitize_sql_like("#{COUNTERPART_PREFIX}#{@sharesight_account.id}_")}%")
+ .where.not(id: current)
+ .destroy_all
+ end
+
+ def report_unsettled(units)
+ window = @sharesight_account.settlement_window_days
+
+ units.each do |unit|
+ next unless bank_fed?(unit.target) && unit.bank_entry.nil? && !unit.leftover && unit.date + window < Date.current
+
+ @notices << {
+ message: I18n.t(
+ unit.amount.positive? ? "sharesight_accounts.notices.unsettled_debit" : "sharesight_accounts.notices.unsettled_credit",
+ amount: Money.new(unit.amount.abs, unit.currency).format,
+ account: unit.target.name,
+ description: unit.description,
+ date: I18n.l(unit.date)
+ ),
+ severity: "warning"
+ }
+ end
+ end
+end
diff --git a/app/models/sharesight_account/cash_settings.rb b/app/models/sharesight_account/cash_settings.rb
new file mode 100644
index 0000000000..3d77df4027
--- /dev/null
+++ b/app/models/sharesight_account/cash_settings.rb
@@ -0,0 +1,153 @@
+# Where a portfolio's cash lives, and where its dividends go.
+#
+# cash_mode
+# broker The broker holds the cash (the default). Top-ups from a funding
+# account can be mirrored in, and you can give a balance for cash
+# Sharesight can't see.
+# settlement Trades settle against another account from settlement_starts_on
+# (the broker had the cash before that). The investment account
+# only shows shares.
+# untracked Shares only, the cash isn't tracked anywhere.
+#
+# dividend_mode
+# with_cash Goes wherever the cash is: kept by the broker, or paid out to
+# the settlement account (or outside Sure).
+# other_account Paid out to dividend_account.
+# skip Not imported, because another connection already has them.
+module SharesightAccount::CashSettings
+ extend ActiveSupport::Concern
+
+ CASH_MODES = %w[broker settlement untracked].freeze
+ DIVIDEND_MODES = %w[with_cash other_account skip].freeze
+ MAX_SETTLEMENT_WINDOW_DAYS = 30
+
+ SETTINGS_ATTRIBUTES = %i[
+ cash_mode settlement_account_id settlement_starts_on settlement_window_days
+ dividend_mode dividend_account_id funding_account_id funding_match_terms
+ cash_anchor_amount cash_anchor_on sync_start_date
+ ].freeze
+
+ # Money that went somewhere Sure doesn't track.
+ OUTSIDE = :outside
+
+ included do
+ belongs_to :settlement_account, class_name: "Account", optional: true
+ belongs_to :dividend_account, class_name: "Account", optional: true
+ belongs_to :funding_account, class_name: "Account", optional: true
+
+ validates :cash_mode, inclusion: { in: CASH_MODES }
+ validates :dividend_mode, inclusion: { in: DIVIDEND_MODES }
+ validates :settlement_window_days, numericality: { only_integer: true, in: 0..MAX_SETTLEMENT_WINDOW_DAYS }
+ # Only checked when these settings change. If the chosen account gets deleted later (the
+ # foreign key clears it), syncs keep going and treat that money as going outside Sure.
+ validate :settlement_account_present, if: -> { will_save_change_to_cash_mode? || will_save_change_to_settlement_account_id? }
+ validate :dividend_account_present, if: -> { will_save_change_to_dividend_mode? || will_save_change_to_dividend_account_id? }
+ validate :cash_anchor_complete
+ validate :dates_readable
+ validate :other_accounts_belong_to_family
+ end
+
+ # Settings from the account form. Blank ids and dates clear the setting, and
+ # the funding terms come in as one comma-separated string.
+ def assign_cash_settings(attributes)
+ attributes = attributes.to_h.symbolize_keys.slice(*SETTINGS_ATTRIBUTES)
+ attributes.transform_values! { |value| value.presence }
+ if attributes.key?(:funding_match_terms)
+ attributes[:funding_match_terms] = attributes[:funding_match_terms].to_s.split(",").map(&:strip).reject(&:blank?).uniq
+ end
+ attributes[:settlement_window_days] ||= 7 if attributes.key?(:settlement_window_days)
+ attributes[:cash_mode] ||= "broker" if attributes.key?(:cash_mode)
+ attributes[:dividend_mode] ||= "with_cash" if attributes.key?(:dividend_mode)
+
+ assign_attributes(attributes)
+ end
+
+ def cash_settings_changed?
+ (saved_changes.keys & SETTINGS_ATTRIBUTES.map(&:to_s)).any?
+ end
+
+ def holds_cash_at_broker_on?(date)
+ case cash_mode
+ when "broker" then true
+ when "settlement" then settlement_starts_on.present? && date < settlement_starts_on
+ else false
+ end
+ end
+
+ # Where a trade on this date settles. nil while the broker has the cash,
+ # otherwise the settlement account (or OUTSIDE).
+ def trade_destination_on(date)
+ return nil if holds_cash_at_broker_on?(date)
+
+ (cash_mode == "settlement" && settlement_account) || OUTSIDE
+ end
+
+ # Where a dividend paid on this date goes. nil if the broker keeps it, :skip
+ # if we're not importing them, otherwise an account (or OUTSIDE).
+ def dividend_destination_on(date)
+ case dividend_mode
+ when "skip" then :skip
+ when "other_account" then dividend_account || OUTSIDE
+ else trade_destination_on(date)
+ end
+ end
+
+ def dividends_skipped?
+ dividend_mode == "skip"
+ end
+
+ def funding_terms
+ Array(funding_match_terms).map { |term| term.to_s.strip }.reject(&:blank?)
+ end
+
+ def cash_anchor?
+ cash_anchor_amount.present? && cash_anchor_on.present?
+ end
+
+ def before_sync_start?(date)
+ sync_start_date.present? && date.present? && date < sync_start_date
+ end
+
+ private
+
+ def settlement_account_present
+ return unless cash_mode == "settlement" && settlement_account_id.blank?
+
+ errors.add(:base, I18n.t("sharesight_accounts.errors.settlement_account_missing"))
+ end
+
+ def dividend_account_present
+ return unless dividend_mode == "other_account" && dividend_account_id.blank?
+
+ errors.add(:base, I18n.t("sharesight_accounts.errors.dividend_account_missing"))
+ end
+
+ def cash_anchor_complete
+ return if cash_anchor_amount.present? == cash_anchor_on.present?
+
+ errors.add(:base, I18n.t("sharesight_accounts.errors.cash_anchor_incomplete"))
+ end
+
+ # Rails reads a date it can't parse as nil, which would quietly clear the
+ # setting. Blank is still fine, that's how you clear one on purpose.
+ def dates_readable
+ %i[settlement_starts_on cash_anchor_on sync_start_date].each do |attribute|
+ next if read_attribute_before_type_cast(attribute).blank? || public_send(attribute).present?
+
+ errors.add(:base, I18n.t("sharesight_accounts.errors.invalid_date.#{attribute}"))
+ end
+ end
+
+ def other_accounts_belong_to_family
+ family = sharesight_item&.family
+ own_account_id = account_provider&.account_id
+
+ [ settlement_account, dividend_account, funding_account ].compact.each do |other|
+ if other.family_id != family&.id
+ errors.add(:base, I18n.t("sharesight_accounts.errors.account_not_in_family", name: other.name))
+ elsif other.id == own_account_id
+ errors.add(:base, I18n.t("sharesight_accounts.errors.account_is_portfolio", name: other.name))
+ end
+ end
+ end
+end
diff --git a/app/models/sharesight_account/data_helpers.rb b/app/models/sharesight_account/data_helpers.rb
new file mode 100644
index 0000000000..9400369bb1
--- /dev/null
+++ b/app/models/sharesight_account/data_helpers.rb
@@ -0,0 +1,100 @@
+module SharesightAccount::DataHelpers
+ extend ActiveSupport::Concern
+ include CurrencyNormalizable
+
+ # Sharesight market codes (plus a few aliases broker imports use) to MICs.
+ # Anything not in here gets an offline security, because searching a price
+ # provider could pick up the same ticker on a different exchange.
+ MARKET_MICS = {
+ "ASX" => "XASX",
+ "NZX" => "XNZE",
+ "NYSE" => "XNYS",
+ "NASDAQ" => "XNAS",
+ "ARCA" => "ARCX",
+ "NYSE_ARCA" => "ARCX",
+ "NYSEARCA" => "ARCX",
+ "AMEX" => "XASE",
+ "NYSE_AMERICAN" => "XASE",
+ "BATS" => "BATS",
+ "LSE" => "XLON",
+ "TSX" => "XTSE",
+ "TSXV" => "XTSX",
+ "HKG" => "XHKG",
+ "HKEX" => "XHKG",
+ "SGX" => "XSES",
+ "XETRA" => "XETR",
+ "FWB" => "XFRA",
+ "EPA" => "XPAR",
+ "AMS" => "XAMS",
+ "SIX" => "XSWX",
+ "TYO" => "XJPX"
+ }.freeze
+
+ # The currency each exchange trades in, for trades whose holding doesn't say.
+ MIC_CURRENCIES = {
+ "XASX" => "AUD", "XNZE" => "NZD", "XNYS" => "USD", "XNAS" => "USD", "ARCX" => "USD",
+ "XASE" => "USD", "BATS" => "USD", "XLON" => "GBP", "XTSE" => "CAD", "XTSX" => "CAD",
+ "XHKG" => "HKD", "XSES" => "SGD", "XETR" => "EUR", "XFRA" => "EUR", "XPAR" => "EUR",
+ "XAMS" => "EUR", "XSWX" => "CHF", "XJPX" => "JPY"
+ }.freeze
+
+ private
+
+ def parse_decimal(value)
+ return nil if value.nil?
+
+ normalized = value.is_a?(String) ? value.strip : value.to_s
+ return nil if normalized.blank?
+
+ BigDecimal(normalized)
+ rescue ArgumentError
+ nil
+ end
+
+ # Sharesight dates are ISO 8601, except the portfolio's inception date,
+ # which can look like "03 Feb 2021".
+ def parse_date(value)
+ return nil if value.blank?
+ return value.to_date if value.respond_to?(:to_date) && !value.is_a?(String)
+
+ Date.parse(value.to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ def market_mic(market_code)
+ MARKET_MICS[market_code.to_s.strip.upcase]
+ end
+
+ def market_currency(market_code)
+ MIC_CURRENCIES[market_mic(market_code)]
+ end
+
+ def resolve_security(symbol, market_code, name = nil)
+ ticker = symbol.to_s.strip.upcase
+ return nil if ticker.blank?
+
+ mic = market_mic(market_code)
+ security = if mic
+ begin
+ Security::Resolver.new(ticker, exchange_operating_mic: mic).resolve
+ rescue => e
+ Rails.logger.warn("SharesightAccount: resolving #{ticker}|#{mic} failed (#{e.class}: #{e.message}); using an offline security")
+ nil
+ end
+ end
+ security ||= offline_security(ticker, mic)
+
+ security.update!(name: name) if name.present? && security.name.blank?
+ security
+ end
+
+ def offline_security(ticker, mic)
+ Security.find_or_initialize_by_ticker_and_exchange(ticker: ticker, exchange_operating_mic: mic).tap do |security|
+ security.offline = true if security.new_record?
+ security.save! if security.changed?
+ end
+ rescue ActiveRecord::RecordNotUnique
+ Security.find_by_ticker_and_exchange(ticker: ticker, exchange_operating_mic: mic)
+ end
+end
diff --git a/app/models/sharesight_account/funding_mirror.rb b/app/models/sharesight_account/funding_mirror.rb
new file mode 100644
index 0000000000..1d499ea4d0
--- /dev/null
+++ b/app/models/sharesight_account/funding_mirror.rb
@@ -0,0 +1,84 @@
+# Top-ups to the broker from a bank account that's already in Sure. Sharesight
+# never sees them, so Sure would only show the bank side, as spending. While
+# the broker holds the cash, any bank transaction with one of the funding terms
+# in its name or notes gets mirrored into the investment account and linked as
+# a transfer.
+class SharesightAccount::FundingMirror
+ include SharesightAccount::TransferLinking
+
+ PREFIX = "sharesight_funding_".freeze
+
+ def initialize(sharesight_account)
+ @sharesight_account = sharesight_account
+ end
+
+ def mirror
+ return unless account
+
+ entries = funding_entries
+ entries.each do |bank_entry|
+ leg = book_mirror(bank_entry)
+ link_transfer!(leg, bank_entry)
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightAccount::FundingMirror - Failed to mirror #{bank_entry.id}: #{e.message}",
+ source: "sharesight",
+ family: @sharesight_account.sharesight_item.family,
+ provider_key: "sharesight"
+ )
+ end
+
+ # Based on what matched rather than what worked this time, so one failure
+ # doesn't delete a mirror (and its transfer) that's still right.
+ remove_stale_mirrors(entries.map { |bank_entry| "#{PREFIX}#{bank_entry.id}" })
+ end
+
+ private
+
+ def account
+ @account ||= @sharesight_account.current_account
+ end
+
+ def funding_account
+ @sharesight_account.funding_account
+ end
+
+ def funding_entries
+ terms = @sharesight_account.funding_terms
+ return [] unless funding_account && terms.any?
+
+ patterns = terms.map { |term| "%#{Entry.sanitize_sql_like(term)}%" }
+ funding_account.entries
+ .where(entryable_type: "Transaction", excluded: false)
+ .where(date: ..Date.current)
+ .where("entries.name ILIKE ANY (ARRAY[?]) OR entries.notes ILIKE ANY (ARRAY[?])", patterns, patterns)
+ .includes(:entryable)
+ .select { |entry| @sharesight_account.holds_cash_at_broker_on?(entry.date) && !@sharesight_account.before_sync_start?(entry.date) }
+ .reject { |entry| entry.amount.zero? || transferred_elsewhere?(entry, account) }
+ end
+
+ # Money out of the bank lands at the broker, and the other way round.
+ def book_mirror(bank_entry)
+ Account::ProviderImportAdapter.new(account).import_transaction(
+ external_id: "#{PREFIX}#{bank_entry.id}",
+ amount: -bank_entry.amount,
+ currency: bank_entry.currency,
+ date: bank_entry.date,
+ name: bank_entry.amount.positive? ? "Transfer from #{funding_account.name}" : "Transfer to #{funding_account.name}",
+ source: "sharesight",
+ investment_activity_label: "Transfer",
+ allow_heuristic_matching: false,
+ extra: { sharesight: { funding_entry_id: bank_entry.id } }
+ )
+ end
+
+ def remove_stale_mirrors(current)
+ account.entries
+ .where(source: "sharesight")
+ .where("entries.external_id LIKE ?", "#{Entry.sanitize_sql_like(PREFIX)}%")
+ .where.not(external_id: current)
+ .destroy_all
+ end
+end
diff --git a/app/models/sharesight_account/holdings_processor.rb b/app/models/sharesight_account/holdings_processor.rb
new file mode 100644
index 0000000000..dcd7a142a8
--- /dev/null
+++ b/app/models/sharesight_account/holdings_processor.rb
@@ -0,0 +1,82 @@
+class SharesightAccount::HoldingsProcessor
+ include SharesightAccount::DataHelpers
+
+ def initialize(sharesight_account)
+ @sharesight_account = sharesight_account
+ end
+
+ def process
+ return unless account.present?
+
+ Array(@sharesight_account.raw_holdings_payload).each do |holding|
+ process_holding(holding)
+ end
+ end
+
+ private
+
+ def account
+ @sharesight_account.current_account
+ end
+
+ def import_adapter
+ @import_adapter ||= Account::ProviderImportAdapter.new(account)
+ end
+
+ def portfolio_currency
+ @sharesight_account.currency
+ end
+
+ def process_holding(holding)
+ instrument = holding["instrument"] || {}
+ quantity = parse_decimal(holding["quantity"])
+ # Sold holdings come back with no units, and "limited" ones (hidden on
+ # cheaper plans) have no numbers at all.
+ return unless quantity&.positive?
+ return if holding["limited"]
+
+ security = resolve_security(instrument["code"], instrument["market_code"], instrument["name"])
+ return unless security
+
+ currency, price = holding_price(holding, quantity)
+ return unless price
+
+ date = Date.current
+
+ import_adapter.import_holding(
+ security: security,
+ quantity: quantity,
+ amount: quantity * price,
+ currency: currency,
+ date: date,
+ price: price,
+ external_id: "sharesight_holding_#{@sharesight_account.sharesight_account_id}_#{holding['id']}_#{date}",
+ source: "sharesight",
+ account_provider_id: @sharesight_account.account_provider&.id,
+ delete_future_holdings: false
+ )
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightAccount::HoldingsProcessor - Failed to process holding #{holding['id']}: #{e.message}",
+ source: "sharesight",
+ family: @sharesight_account.sharesight_item.family,
+ provider_key: "sharesight",
+ metadata: { holding_id: holding["id"], sharesight_account_id: @sharesight_account.id }
+ )
+ end
+
+ # Use the instrument's own price and currency when we have both, otherwise
+ # the holding's value per unit in the portfolio's currency.
+ def holding_price(holding, quantity)
+ price = parse_decimal(holding["instrument_price"])
+ currency = @sharesight_account.holding_currencies[holding["id"].to_s]
+ return [ currency, price ] if currency && price
+
+ value = parse_decimal(holding["value"])
+ return [ portfolio_currency, value / quantity ] if value
+
+ [ portfolio_currency, price ]
+ end
+end
diff --git a/app/models/sharesight_account/processor.rb b/app/models/sharesight_account/processor.rb
new file mode 100644
index 0000000000..b31e70f1a9
--- /dev/null
+++ b/app/models/sharesight_account/processor.rb
@@ -0,0 +1,111 @@
+class SharesightAccount::Processor
+ # Sharesight's quantities arrive as JSON floats, so units are compared to this
+ # many decimal places rather than exactly.
+ UNITS_PRECISION = 8
+
+ attr_reader :sharesight_account
+
+ def initialize(sharesight_account)
+ @sharesight_account = sharesight_account
+ end
+
+ def process
+ return unless account.present?
+
+ SharesightAccount::HoldingsProcessor.new(sharesight_account).process
+
+ activities = SharesightAccount::ActivitiesProcessor.new(sharesight_account)
+ result = activities.process
+ router = SharesightAccount::CashRouter.new(sharesight_account, activities.movements)
+ router.route
+ SharesightAccount::FundingMirror.new(sharesight_account).mirror
+
+ update_account_balance!
+
+ account.broadcast_sync_complete
+ result.merge(notices: router.notices + drift_notices)
+ end
+
+ private
+
+ def account
+ @account ||= sharesight_account.current_account
+ end
+
+ def update_account_balance!
+ holdings_value = (sharesight_account.current_balance || 0) - (sharesight_account.cash_balance || 0)
+ cash_balance = current_cash
+ total_balance = holdings_value + cash_balance
+
+ account.assign_attributes(
+ balance: total_balance,
+ cash_balance: cash_balance,
+ currency: sharesight_account.currency
+ )
+ account.save!
+ account.set_current_balance(total_balance)
+ end
+
+ # Zero once the cash lives somewhere else. While the broker has it, either
+ # the balance you saw rolled forward through everything booked since, or
+ # Sharesight's own cash accounts.
+ def current_cash
+ return BigDecimal("0") unless sharesight_account.holds_cash_at_broker_on?(Date.current)
+ return sharesight_account.cash_balance || BigDecimal("0") unless sharesight_account.cash_anchor?
+
+ moved = account.entries
+ .where(entryable_type: %w[Transaction Trade])
+ .where(date: (sharesight_account.cash_anchor_on + 1)..Date.current)
+ .includes(:entryable)
+ .sum(BigDecimal("0")) { |entry| in_portfolio_currency(entry) }
+ sharesight_account.cash_anchor_amount - moved
+ end
+
+ # A foreign trade is still paid from the portfolio's cash, so convert it with
+ # the trade's own rate, or Sure's rate for that day if it doesn't have one.
+ def in_portfolio_currency(entry)
+ return entry.amount if entry.currency == sharesight_account.currency
+
+ Money.new(entry.amount, entry.currency)
+ .exchange_to(sharesight_account.currency, date: entry.date, custom_rate: entry.entryable.try(:exchange_rate))
+ .amount
+ rescue Money::ConversionError
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "Left #{entry.name} (#{entry.currency}) out of the cash at the broker: no exchange rate for #{entry.date}",
+ source: "sharesight",
+ family: sharesight_account.sharesight_item.family,
+ provider_key: "sharesight"
+ )
+ BigDecimal("0")
+ end
+
+ # Compares the units Sharesight holds with what the trades add up to. A gap
+ # usually means a split or transfer we don't book. Skipped with a sync
+ # start date, since the older trades are left out on purpose.
+ def drift_notices
+ return [] if sharesight_account.sync_start_date.present?
+
+ holdings = Array(sharesight_account.raw_holdings_payload)
+ # Limited holdings (hidden on cheaper plans) aren't imported, so there's nothing to compare.
+ limited = holdings.select { |holding| holding["limited"] }.map { |holding| holding.dig("instrument", "code").to_s.upcase }
+ held = holdings.reject { |holding| holding["limited"] }.each_with_object(Hash.new(BigDecimal("0"))) do |holding, units|
+ units[holding.dig("instrument", "code").to_s.upcase] += BigDecimal(holding["quantity"].to_s.presence || "0")
+ end
+ traded = Trade.joins(:entry, :security).where(entries: { account_id: account.id }).group("securities.ticker").sum(:qty)
+
+ ((held.keys | traded.keys) - limited).sort.filter_map do |ticker|
+ held_units = held[ticker].round(UNITS_PRECISION)
+ traded_units = (traded[ticker] || BigDecimal("0")).to_d.round(UNITS_PRECISION)
+ next if held_units == traded_units
+
+ {
+ message: I18n.t("sharesight_accounts.notices.units_drift",
+ account: account.name, ticker: ticker,
+ held: held_units.to_s("F"), traded: traded_units.to_s("F")),
+ severity: "warning"
+ }
+ end
+ end
+end
diff --git a/app/models/sharesight_account/transfer_linking.rb b/app/models/sharesight_account/transfer_linking.rb
new file mode 100644
index 0000000000..f5fa776b43
--- /dev/null
+++ b/app/models/sharesight_account/transfer_linking.rb
@@ -0,0 +1,45 @@
+# Links an entry on the investment account to its other side in another
+# account as a confirmed transfer, like Trade Republic does for settlements.
+# Confirming sets the kinds: money into the portfolio counts as an investment
+# contribution, money out of it as a funds movement.
+module SharesightAccount::TransferLinking
+ extend ActiveSupport::Concern
+
+ private
+
+ def link_transfer!(leg, other)
+ leg_transaction = leg.entryable
+ other_transaction = other.entryable
+ return false unless leg_transaction.is_a?(Transaction) && other_transaction.is_a?(Transaction)
+
+ existing = leg_transaction.transfer
+ return true if existing && [ existing.inflow_transaction_id, existing.outflow_transaction_id ].include?(other_transaction.id)
+ # Already linked to something else (by you or Sure's matching), so leave it.
+ return false if existing || other_transaction.transfer
+
+ inflow, outflow = leg.amount.negative? ? [ leg_transaction, other_transaction ] : [ other_transaction, leg_transaction ]
+ # If you unlinked this pair before, it stays unlinked.
+ return false if RejectedTransfer.exists?(inflow_transaction_id: inflow.id, outflow_transaction_id: outflow.id)
+
+ Transfer.create!(inflow_transaction: inflow, outflow_transaction: outflow, status: "confirmed").confirm!
+ true
+ rescue ActiveRecord::RecordInvalid => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "Sharesight couldn't link #{leg.external_id} to #{other.name} as a transfer: #{e.message}",
+ source: "sharesight",
+ family: @sharesight_account.sharesight_item.family,
+ provider_key: "sharesight"
+ )
+ false
+ end
+
+ # Already part of a transfer with some account other than the portfolio's.
+ def transferred_elsewhere?(entry, portfolio_account)
+ transfer = entry.entryable.try(:transfer)
+ return false unless transfer
+
+ [ transfer.inflow_transaction, transfer.outflow_transaction ].none? { |transaction| transaction.entry.account_id == portfolio_account.id }
+ end
+end
diff --git a/app/models/sharesight_item.rb b/app/models/sharesight_item.rb
new file mode 100644
index 0000000000..98783040a2
--- /dev/null
+++ b/app/models/sharesight_item.rb
@@ -0,0 +1,145 @@
+class SharesightItem < ApplicationRecord
+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLater, ProviderDisconnectable
+
+ # Disconnecting keeps the accounts and their history. Deleting them isn't supported yet.
+ self.supports_discard = false
+
+ enum :status, { good: "good", requires_update: "requires_update" }, default: :good
+
+ if encryption_ready?
+ encrypts :client_id, deterministic: true
+ encrypts :client_secret
+ end
+
+ belongs_to :family
+ has_one_attached :logo, dependent: :purge_later
+ has_many :sharesight_accounts, dependent: :destroy
+
+ validates :client_id, presence: true, on: :create
+ validates :client_secret, presence: true, on: :create
+
+ scope :active, -> { where(scheduled_for_deletion: false) }
+ scope :syncable, -> { active.where.not(client_id: [ nil, "" ]) }
+ scope :ordered, -> { order(created_at: :desc) }
+ scope :needs_update, -> { where(status: :requires_update) }
+
+ def credentials_configured?
+ client_id.present? && client_secret.present?
+ end
+
+ def import_latest_data
+ provider = sharesight_provider
+ raise Provider::Sharesight::ConfigurationError, "Sharesight API client is not configured" unless provider
+
+ SharesightItem::Importer.new(self, provider: provider).import
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightItem #{id} - Failed to import data: #{e.message}",
+ source: "sharesight",
+ family: family,
+ provider_key: "sharesight"
+ )
+ raise
+ end
+
+ def process_accounts
+ return [] if sharesight_accounts.empty?
+
+ linked_sharesight_accounts.includes(account_provider: :account).each_with_object([]) do |sharesight_account, results|
+ account = sharesight_account.current_account
+ next unless account
+ next if account.pending_deletion? || account.disabled?
+
+ begin
+ result = SharesightAccount::Processor.new(sharesight_account).process
+ results << { sharesight_account_id: sharesight_account.id, success: true, result: result }
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightItem #{id} - Failed to process account #{sharesight_account.id}: #{e.message}",
+ source: "sharesight",
+ family: family,
+ provider_key: "sharesight",
+ account_provider_id: sharesight_account.account_provider&.id
+ )
+ results << { sharesight_account_id: sharesight_account.id, success: false, error: e.message }
+ end
+ end
+ end
+
+ def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)
+ accounts.reject { |account| account.pending_deletion? || account.disabled? }.each_with_object([]) do |account, results|
+ begin
+ account.sync_later(
+ parent_sync: parent_sync,
+ window_start_date: window_start_date,
+ window_end_date: window_end_date
+ )
+ results << { account_id: account.id, success: true }
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightItem #{id} - Failed to schedule sync for account #{account.id}: #{e.message}",
+ source: "sharesight",
+ family: family,
+ provider_key: "sharesight",
+ account_id: account.id
+ )
+ results << { account_id: account.id, success: false, error: e.message }
+ end
+ end
+ end
+
+ # Uses the portfolios if they're already loaded, so pages listing several
+ # connections (like the accounts page) don't query each one again.
+ def accounts
+ portfolios = sharesight_accounts.loaded? ? sharesight_accounts : sharesight_accounts.includes(:account, :linked_account)
+ portfolios.filter_map(&:current_account).uniq
+ end
+
+ def linked_sharesight_accounts
+ sharesight_accounts.joins(:account_provider)
+ end
+
+ def unlinked_sharesight_accounts
+ sharesight_accounts.left_joins(:account_provider).where(account_providers: { id: nil })
+ end
+
+ def linked_accounts_count
+ linked_sharesight_accounts.count
+ end
+
+ def unlinked_accounts_count
+ unlinked_sharesight_accounts.count
+ end
+
+ def total_accounts_count
+ sharesight_accounts.count
+ end
+
+ def has_completed_initial_setup?
+ accounts.any?
+ end
+
+ def sync_status_summary
+ total = total_accounts_count
+ linked = linked_accounts_count
+ unlinked = unlinked_accounts_count
+
+ if total.zero?
+ I18n.t("sharesight_items.sync_status.no_accounts")
+ elsif unlinked.zero?
+ I18n.t("sharesight_items.sync_status.all_linked", count: linked)
+ else
+ I18n.t("sharesight_items.sync_status.partial", linked: linked, unlinked: unlinked)
+ end
+ end
+
+ def institution_display_name
+ I18n.t("sharesight_items.defaults.name")
+ end
+end
diff --git a/app/models/sharesight_item/importer.rb b/app/models/sharesight_item/importer.rb
new file mode 100644
index 0000000000..00c69970ca
--- /dev/null
+++ b/app/models/sharesight_item/importer.rb
@@ -0,0 +1,123 @@
+class SharesightItem::Importer
+ include SharesightAccount::DataHelpers
+
+ attr_reader :sharesight_item, :provider
+
+ def initialize(sharesight_item, provider:)
+ @sharesight_item = sharesight_item
+ @provider = provider
+ end
+
+ # Every portfolio gets its value and holdings, since the setup screen shows
+ # them. Trades, payouts and cash transactions are only fetched once a
+ # portfolio is linked to an account.
+ def import
+ portfolios = provider.fetch_portfolios
+ portfolio_ids = portfolios.filter_map { |portfolio| portfolio["id"]&.to_s.presence }
+
+ portfolios.each do |portfolio|
+ import_portfolio(portfolio) if portfolio["id"].present?
+ end
+
+ remove_unlinked_portfolios_missing_from(portfolio_ids)
+ sharesight_item.update!(status: :good)
+ rescue Provider::Sharesight::AuthenticationError
+ sharesight_item.update!(status: :requires_update)
+ raise
+ end
+
+ private
+
+ def import_portfolio(portfolio)
+ portfolio_id = portfolio["id"].to_s
+ currency = parse_currency(portfolio["currency_code"]) || sharesight_item.family.currency
+ report = provider.fetch_performance(portfolio_id)
+ holdings = Array(report["holdings"])
+ cash = cash_balance(report, currency)
+
+ sharesight_account = sharesight_item.sharesight_accounts.find_or_initialize_by(sharesight_account_id: portfolio_id)
+ sharesight_account.assign_attributes(
+ name: portfolio["name"].presence || I18n.t("sharesight_items.defaults.portfolio_name", id: portfolio_id),
+ currency: currency,
+ current_balance: holdings_value(holdings) + cash,
+ cash_balance: cash,
+ raw_payload: portfolio,
+ raw_holdings_payload: holdings
+ )
+
+ if sharesight_account.persisted? && sharesight_account.current_account.present?
+ trades = provider.fetch_trades(portfolio_id)
+ sharesight_account.assign_attributes(
+ raw_trades_payload: trades,
+ raw_payouts_payload: provider.fetch_payouts(portfolio_id, start_date: payouts_start_date(portfolio, trades)),
+ raw_cash_transactions_payload: cash_transactions(portfolio_id, currency)
+ )
+ end
+
+ sharesight_account.save!
+ end
+
+ # The report's value already includes every cash account in any currency,
+ # so we add up the holdings ourselves and add the cash we count below.
+ def holdings_value(holdings)
+ holdings.sum(BigDecimal("0")) { |holding| parse_decimal(holding["value"]) || 0 }
+ end
+
+ # Only cash accounts in the portfolio's currency count.
+ def cash_balance(report, currency)
+ Array(report["cash_accounts"]).sum(BigDecimal("0")) do |cash_account|
+ if cash_account_currency(cash_account, currency) == currency
+ parse_decimal(cash_account["value"]) || 0
+ else
+ log_skipped_cash_account(cash_account)
+ 0
+ end
+ end
+ end
+
+ def cash_transactions(portfolio_id, currency)
+ cash_accounts.select { |cash_account| cash_account["portfolio_id"].to_s == portfolio_id }.flat_map do |cash_account|
+ next [] unless cash_account_currency(cash_account, currency) == currency
+
+ provider.fetch_cash_account_transactions(cash_account["id"]).map do |transaction|
+ transaction.merge("currency" => currency)
+ end
+ end
+ end
+
+ def cash_accounts
+ @cash_accounts ||= provider.fetch_cash_accounts
+ end
+
+ def cash_account_currency(cash_account, fallback)
+ currency = cash_account["currency"]
+ currency = currency["code"] if currency.is_a?(Hash)
+ parse_currency(currency) || fallback
+ end
+
+ # Payouts are fetched by date range, from when the portfolio started (or
+ # its first trade if Sharesight doesn't say).
+ def payouts_start_date(portfolio, trades)
+ parse_date(portfolio["inception_date"]) ||
+ trades.filter_map { |trade| parse_date(trade["transaction_date"]) }.min ||
+ Date.current
+ end
+
+ def remove_unlinked_portfolios_missing_from(portfolio_ids)
+ return if portfolio_ids.empty?
+
+ sharesight_item.unlinked_sharesight_accounts.where.not(sharesight_account_id: portfolio_ids).destroy_all
+ end
+
+ def log_skipped_cash_account(cash_account)
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "warn",
+ message: "SharesightItem #{sharesight_item.id} - Leaving cash account #{cash_account['id']} out: " \
+ "it isn't in the portfolio's currency",
+ source: "sharesight",
+ family: sharesight_item.family,
+ provider_key: "sharesight"
+ )
+ end
+end
diff --git a/app/models/sharesight_item/provided.rb b/app/models/sharesight_item/provided.rb
new file mode 100644
index 0000000000..a1058c9eea
--- /dev/null
+++ b/app/models/sharesight_item/provided.rb
@@ -0,0 +1,9 @@
+module SharesightItem::Provided
+ extend ActiveSupport::Concern
+
+ def sharesight_provider
+ return nil unless credentials_configured?
+
+ Provider::Sharesight.new(client_id: client_id, client_secret: client_secret)
+ end
+end
diff --git a/app/models/sharesight_item/syncer.rb b/app/models/sharesight_item/syncer.rb
new file mode 100644
index 0000000000..317d061a1c
--- /dev/null
+++ b/app/models/sharesight_item/syncer.rb
@@ -0,0 +1,82 @@
+class SharesightItem::Syncer
+ include SyncStats::Collector
+
+ attr_reader :sharesight_item
+
+ def initialize(sharesight_item)
+ @sharesight_item = sharesight_item
+ end
+
+ def perform_sync(sync)
+ sync.update!(status_text: I18n.t("sharesight_items.sync.status.checking_credentials")) if sync.respond_to?(:status_text)
+ unless sharesight_item.credentials_configured?
+ sharesight_item.update!(status: :requires_update)
+ raise Provider::Sharesight::ConfigurationError, "Sharesight API client is missing."
+ end
+
+ sync.update!(status_text: I18n.t("sharesight_items.sync.status.importing_portfolios")) if sync.respond_to?(:status_text)
+ sharesight_item.import_latest_data
+
+ sync.update!(status_text: I18n.t("sharesight_items.sync.status.checking_configuration")) if sync.respond_to?(:status_text)
+ collect_setup_stats(sync, provider_accounts: sharesight_item.sharesight_accounts.to_a)
+
+ unlinked_accounts = sharesight_item.unlinked_sharesight_accounts
+ linked_accounts = sharesight_item.sharesight_accounts.joins(:account).merge(Account.visible)
+
+ if unlinked_accounts.any?
+ sharesight_item.update!(pending_account_setup: true)
+ sync.update!(status_text: I18n.t("sharesight_items.sync.status.accounts_need_setup", count: unlinked_accounts.count)) if sync.respond_to?(:status_text)
+ else
+ sharesight_item.update!(pending_account_setup: false)
+ end
+
+ if linked_accounts.any?
+ sync.update!(status_text: I18n.t("sharesight_items.sync.status.processing_activity")) if sync.respond_to?(:status_text)
+ results = sharesight_item.process_accounts
+ collect_notices(sync, results)
+
+ sync.update!(status_text: I18n.t("sharesight_items.sync.status.calculating_balances")) if sync.respond_to?(:status_text)
+ sharesight_item.schedule_account_syncs(
+ parent_sync: sync,
+ window_start_date: sync.window_start_date,
+ window_end_date: sync.window_end_date
+ )
+
+ account_ids = linked_accounts.includes(:account).filter_map { |sa| sa.account&.id }
+ collect_transaction_stats(sync, account_ids: account_ids, source: "sharesight") if account_ids.any?
+ collect_trades_stats(sync, account_ids: account_ids, source: "sharesight") if account_ids.any?
+ collect_holdings_stats(sync, holdings_count: count_holdings, label: "processed")
+ end
+
+ collect_health_stats(sync, errors: nil)
+ rescue Provider::Sharesight::AuthenticationError, Provider::Sharesight::ConfigurationError => e
+ sharesight_item.update!(status: :requires_update)
+ collect_health_stats(sync, errors: [ { message: e.message, category: "auth_error" } ])
+ raise
+ rescue => e
+ collect_health_stats(sync, errors: [ { message: e.message, category: "sync_error" } ])
+ raise
+ end
+
+ def perform_post_sync
+ end
+
+ private
+
+ def count_holdings
+ sharesight_item.linked_sharesight_accounts.sum { |sa| Array(sa.raw_holdings_payload).size }
+ end
+
+ # Shows settlements still missing from the bank feed, and units the trades
+ # don't add up to, in the connection's sync summary.
+ def collect_notices(sync, results)
+ notices = Array(results).flat_map { |result| Array(result.dig(:result, :notices)) if result[:success] }.compact
+ return if notices.empty?
+
+ collect_data_quality_stats(
+ sync,
+ warnings: notices.count { |notice| notice[:severity] == "warning" },
+ details: notices
+ )
+ end
+end
diff --git a/app/models/sharesight_item/unlinking.rb b/app/models/sharesight_item/unlinking.rb
new file mode 100644
index 0000000000..d1f661a76d
--- /dev/null
+++ b/app/models/sharesight_item/unlinking.rb
@@ -0,0 +1,46 @@
+module SharesightItem::Unlinking
+ extend ActiveSupport::Concern
+
+ # Unlinks this connection's portfolios from their accounts. Only "retain" is
+ # supported, so the accounts and their history stay.
+ def unlink_all!(dry_run: false, disposition: ProviderDisconnectable::DEFAULT_DISPOSITION)
+ unless disposition.to_s == ProviderDisconnectable::RETAIN
+ raise ArgumentError, "SharesightItem does not implement the #{disposition} disposition"
+ end
+
+ results = []
+
+ sharesight_accounts.find_each do |provider_account|
+ links = AccountProvider.where(provider_type: "SharesightAccount", provider_id: provider_account.id).to_a
+ link_ids = links.map(&:id)
+ result = {
+ provider_account_id: provider_account.id,
+ name: provider_account.name,
+ provider_link_ids: link_ids
+ }
+ results << result
+
+ next if dry_run
+
+ begin
+ ActiveRecord::Base.transaction do
+ Holding.where(account_provider_id: link_ids).update_all(account_provider_id: nil) if link_ids.any?
+ links.each(&:destroy!)
+ end
+ rescue => e
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "error",
+ message: "SharesightItem Unlinker: failed to fully unlink provider account ##{provider_account.id} " \
+ "(links=#{link_ids.inspect}): #{e.class} - #{e.message}",
+ source: "sharesight",
+ family: family,
+ provider_key: "sharesight"
+ )
+ result[:error] = e.message
+ end
+ end
+
+ results
+ end
+end
diff --git a/app/views/accounts/index.html.erb b/app/views/accounts/index.html.erb
index dbfe96a69d..9eeec24b04 100644
--- a/app/views/accounts/index.html.erb
+++ b/app/views/accounts/index.html.erb
@@ -10,7 +10,7 @@
) %>
<% end %>
-<% if @manual_accounts.empty? && @financekit_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @truelayer_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_items.empty? && @monobank_items.empty? && @fio_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @kraken_items.empty? && @coinspot_items.empty? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? && @trading212_items.empty? %>
+<% if @manual_accounts.empty? && @financekit_accounts.empty? && @plaid_items.empty? && @simplefin_items.empty? && @lunchflow_items.empty? && @truelayer_items.empty? && @redbark_items.empty? && @akahu_items.empty? && @up_items.empty? && @monobank_items.empty? && @fio_items.empty? && @enable_banking_items.empty? && @coinstats_items.empty? && @coinbase_items.empty? && @mercury_items.empty? && @brex_items.empty? && @ibkr_items.empty? && @snaptrade_items.empty? && @indexa_capital_items.empty? && @sophtron_items.empty? && @binance_items.empty? && @kraken_items.empty? && @coinspot_items.empty? && @questrade_items.empty? && @wise_items.empty? && @onchain_wallet_items.empty? && @trade_republic_items.empty? && @trading212_items.empty? && @sharesight_items.empty? %>
<%= render "empty" %>
<% else %>
<div class="space-y-2">
@@ -136,6 +136,12 @@
<% end %>
<% end %>
+ <% if @sharesight_items.any? %>
+ <% @sharesight_items.each do |item| %>
+ <%= render item, visible_accounts: visible_card_accounts(item) %>
+ <% end %>
+ <% end %>
+
<% if @wise_items.any? %>
<% @wise_items.sort_by(&:created_at).each do |item| %>
<%= render item, visible_accounts: visible_card_accounts(item) %>
diff --git a/app/views/investments/_form.html.erb b/app/views/investments/_form.html.erb
index be4004d271..c41c25b04c 100644
--- a/app/views/investments/_form.html.erb
+++ b/app/views/investments/_form.html.erb
@@ -6,4 +6,9 @@
grouped_options_for_select(Investment.subtypes_grouped_for_select(currency: Current.family.currency), account.accountable.subtype),
{ label: true, prompt: t("investments.form.subtype_prompt"), include_blank: t("investments.form.none") } %>
<% end %>
+
+ <% sharesight_account = account.provider_account_for("SharesightAccount") if account.persisted? %>
+ <% if sharesight_account %>
+ <%= render "sharesight_accounts/settings_fields", form: form, sharesight_account: sharesight_account, account: account %>
+ <% end %>
<% end %>
diff --git a/app/views/settings/providers/_sharesight_panel.html.erb b/app/views/settings/providers/_sharesight_panel.html.erb
new file mode 100644
index 0000000000..b2c535a4fc
--- /dev/null
+++ b/app/views/settings/providers/_sharesight_panel.html.erb
@@ -0,0 +1,45 @@
+<div id="sharesight-providers-panel" class="space-y-4">
+ <%= render "settings/providers/setup_steps",
+ steps: [
+ t(".steps.step_1"),
+ t(".steps.step_2"),
+ t(".steps.step_3")
+ ] %>
+
+ <% error_msg = local_assigns[:error_message] || @error_message %>
+ <% if error_msg.present? %>
+ <%= render DS::Alert.new(message: error_msg, variant: :error) %>
+ <% end %>
+
+ <% sharesight_item = Current.family.sharesight_items.active.ordered.first || Current.family.sharesight_items.build %>
+ <% is_new_record = sharesight_item.new_record? %>
+
+ <%= styled_form_with model: sharesight_item,
+ url: is_new_record ? sharesight_items_path : sharesight_item_path(sharesight_item),
+ scope: :sharesight_item,
+ method: is_new_record ? :post : :patch,
+ data: { turbo: true },
+ class: "space-y-3" do |form| %>
+ <%= form.password_field :client_id,
+ label: t(".client_id_label"),
+ placeholder: is_new_record ? t(".client_id_placeholder_new") : t(".client_id_placeholder_existing"),
+ autocomplete: "off" %>
+
+ <%= form.password_field :client_secret,
+ label: t(".client_secret_label"),
+ placeholder: is_new_record ? t(".client_secret_placeholder_new") : t(".client_secret_placeholder_existing"),
+ autocomplete: "off" %>
+
+ <div class="flex justify-end">
+ <%= form.submit is_new_record ? t(".save_configuration") : t(".update_configuration") %>
+ </div>
+ <% end %>
+
+ <% unless is_new_record %>
+ <p class="text-sm text-secondary">
+ <%= t(".status_configured_prefix") %>
+ <%= link_to t(".accounts_tab"), accounts_path, class: "link" %>
+ <%= t(".status_configured_suffix") %>
+ </p>
+ <% end %>
+</div>
diff --git a/app/views/sharesight_accounts/_settings_fields.html.erb b/app/views/sharesight_accounts/_settings_fields.html.erb
new file mode 100644
index 0000000000..23d3509afd
--- /dev/null
+++ b/app/views/sharesight_accounts/_settings_fields.html.erb
@@ -0,0 +1,64 @@
+<%# locals: (form:, sharesight_account:, account:) %>
+
+<% other_accounts = Current.family.accounts.writable_by(Current.user).visible.where.not(id: account.id).alphabetically.to_a %>
+<%# Keep saved choices listed even if you can't edit them, so saving other settings doesn't clear them. %>
+<% saved_ids = [ sharesight_account.settlement_account_id, sharesight_account.dividend_account_id, sharesight_account.funding_account_id ].compact %>
+<% other_accounts |= Current.family.accounts.where(id: saved_ids).where.not(id: account.id).to_a %>
+<% account_options = other_accounts.map { |other| [ other.name, other.id ] } %>
+
+<div class="space-y-4 pt-4 border-t border-primary" data-controller="sharesight-settings">
+ <div class="space-y-1">
+ <h3 class="text-sm font-medium text-primary"><%= t(".title") %></h3>
+ <p class="text-xs text-secondary"><%= t(".description") %></p>
+ </div>
+
+ <%= form.fields_for :sharesight, sharesight_account do |sharesight_form| %>
+ <div class="space-y-1">
+ <%= sharesight_form.select :cash_mode,
+ SharesightAccount::CASH_MODES.map { |mode| [ t(".cash_modes.#{mode}"), mode ] },
+ { label: t(".cash_mode") },
+ data: { sharesight_settings_target: "cashMode", action: "sharesight-settings#update" } %>
+ <p class="text-xs text-secondary"><%= t(".cash_mode_help") %></p>
+ </div>
+
+ <div class="space-y-3" data-sharesight-settings-target="section" data-cash-modes="settlement">
+ <%= sharesight_form.select :settlement_account_id, account_options,
+ { label: t(".settlement_account"), include_blank: t(".choose_account") } %>
+ <%= sharesight_form.date_field :settlement_starts_on, label: t(".settlement_starts_on") %>
+ <%= sharesight_form.number_field :settlement_window_days, label: t(".settlement_window_days"),
+ min: 0, max: SharesightAccount::MAX_SETTLEMENT_WINDOW_DAYS %>
+ <p class="text-xs text-secondary"><%= t(".settlement_help") %></p>
+ </div>
+
+ <div class="space-y-3" data-sharesight-settings-target="section" data-cash-modes="broker settlement">
+ <%= sharesight_form.select :funding_account_id, account_options,
+ { label: t(".funding_account"), include_blank: t(".no_account") } %>
+ <%= sharesight_form.text_field :funding_match_terms, label: t(".funding_match_terms"),
+ value: sharesight_account.funding_terms.join(", "),
+ placeholder: t(".funding_match_terms_placeholder") %>
+ <p class="text-xs text-secondary"><%= t(".funding_help") %></p>
+
+ <%= sharesight_form.number_field :cash_anchor_amount, label: t(".cash_anchor_amount"), step: "any" %>
+ <%= sharesight_form.date_field :cash_anchor_on, label: t(".cash_anchor_on") %>
+ <p class="text-xs text-secondary"><%= t(".cash_anchor_help") %></p>
+ </div>
+
+ <div class="space-y-1">
+ <%= sharesight_form.select :dividend_mode,
+ SharesightAccount::DIVIDEND_MODES.map { |mode| [ t(".dividend_modes.#{mode}"), mode ] },
+ { label: t(".dividend_mode") },
+ data: { sharesight_settings_target: "dividendMode", action: "sharesight-settings#update" } %>
+ <p class="text-xs text-secondary"><%= t(".dividend_mode_help") %></p>
+ </div>
+
+ <div data-sharesight-settings-target="section" data-dividend-modes="other_account">
+ <%= sharesight_form.select :dividend_account_id, account_options,
+ { label: t(".dividend_account"), include_blank: t(".choose_account") } %>
+ </div>
+
+ <div class="space-y-1">
+ <%= sharesight_form.date_field :sync_start_date, label: t(".sync_start_date") %>
+ <p class="text-xs text-secondary"><%= t(".sync_start_date_help") %></p>
+ </div>
+ <% end %>
+</div>
diff --git a/app/views/sharesight_items/_sharesight_item.html.erb b/app/views/sharesight_items/_sharesight_item.html.erb
new file mode 100644
index 0000000000..5da3e643af
--- /dev/null
+++ b/app/views/sharesight_items/_sharesight_item.html.erb
@@ -0,0 +1,113 @@
+<%# locals: (sharesight_item:, visible_accounts:) %>
+
+<%= tag.div id: dom_id(sharesight_item) do %>
+ <% unlinked_count = sharesight_item.unlinked_accounts_count %>
+
+ <%= render DS::Disclosure.new(variant: :card, open: true) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center justify-between gap-2 w-full">
+ <div class="flex items-center gap-2">
+ <%= icon "chevron-right", class: "group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>
+
+ <%= render ProviderLogo.new(provider_key: :sharesight) %>
+
+ <div class="pl-1 text-sm">
+ <div class="flex items-center gap-2">
+ <%= tag.p sharesight_item.institution_display_name, class: "font-medium text-primary" %>
+ <% if sharesight_item.scheduled_for_deletion? %>
+ <p class="text-destructive text-sm animate-pulse"><%= t(".deletion_in_progress") %></p>
+ <% end %>
+ </div>
+ <% if sharesight_item.syncing? %>
+ <div class="text-secondary flex items-center gap-1">
+ <%= icon "loader", size: "sm", class: "animate-spin" %>
+ <%= tag.span t(".syncing") %>
+ </div>
+ <% elsif sharesight_item.requires_update? %>
+ <div class="text-warning flex items-center gap-1">
+ <%= icon "alert-triangle", size: "sm", color: "warning" %>
+ <%= tag.span t(".requires_update") %>
+ </div>
+ <% elsif sharesight_item.sync_error.present? %>
+ <div class="text-secondary flex items-center gap-1">
+ <%= render DS::Tooltip.new(text: sharesight_item.sync_error, icon: "alert-circle", size: "sm", color: "destructive", as: :span) %>
+ <%= tag.span t(".error"), class: "text-destructive" %>
+ </div>
+ <% else %>
+ <p class="text-secondary">
+ <% if sharesight_item.last_synced_at %>
+ <%= t(".synced", time: time_ago_in_words(sharesight_item.last_synced_at), summary: sharesight_item.sync_status_summary) %>
+ <% else %>
+ <%= t(".never_synced") %>
+ <% end %>
+ </p>
+ <% end %>
+ </div>
+ </div>
+
+ <% if Current.user&.admin? %>
+ <div class="flex items-center gap-2">
+ <%= icon(
+ "refresh-cw",
+ as_button: true,
+ href: sync_sharesight_item_path(sharesight_item),
+ disabled: sharesight_item.syncing?
+ ) %>
+
+ <%= render DS::Menu.new do |menu| %>
+ <% if unlinked_count > 0 %>
+ <% menu.with_item(
+ variant: "link",
+ text: t(".setup_accounts"),
+ icon: "settings",
+ href: setup_accounts_sharesight_item_path(sharesight_item),
+ frame: :modal
+ ) %>
+ <% end %>
+ <% menu.with_item(
+ variant: "button",
+ text: t(".delete"),
+ icon: "trash-2",
+ href: sharesight_item_path(sharesight_item),
+ method: :delete,
+ confirm: CustomConfirm.for_resource_deletion(sharesight_item.institution_display_name, high_severity: true)
+ ) %>
+ <% end %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+
+ <% unless sharesight_item.scheduled_for_deletion? %>
+ <div class="space-y-4 mt-4">
+ <% if visible_accounts.any? %>
+ <%= render "accounts/index/account_groups", accounts: visible_accounts %>
+ <% end %>
+
+ <% stats = sharesight_item.syncs.ordered.first&.sync_stats || {} %>
+ <%= render ProviderSyncSummary.new(stats: stats, provider_item: sharesight_item, show_account_details: visible_accounts.size == sharesight_item.accounts.size) %>
+
+ <% if Current.user&.admin? %>
+ <% if unlinked_count > 0 && sharesight_item.accounts.empty? %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".accounts_need_setup") %></p>
+ <p class="text-secondary text-sm"><%= t(".accounts_need_setup_description") %></p>
+ <%= render DS::Link.new(
+ text: t(".setup_accounts"),
+ icon: "settings",
+ variant: "primary",
+ href: setup_accounts_sharesight_item_path(sharesight_item),
+ frame: :modal
+ ) %>
+ </div>
+ <% elsif sharesight_item.sharesight_accounts.none? %>
+ <div class="p-4 flex flex-col gap-3 items-center justify-center">
+ <p class="text-primary font-medium text-sm"><%= t(".no_accounts_discovered") %></p>
+ <p class="text-secondary text-sm"><%= t(".no_accounts_discovered_description") %></p>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/sharesight_items/select_existing_account.html.erb b/app/views/sharesight_items/select_existing_account.html.erb
new file mode 100644
index 0000000000..e5dd67c7c8
--- /dev/null
+++ b/app/views/sharesight_items/select_existing_account.html.erb
@@ -0,0 +1,37 @@
+<%= render DS::Dialog.new do |dialog| %>
+ <% dialog.with_header(title: t(".title")) %>
+
+ <% dialog.with_body do %>
+ <% if @available_sharesight_accounts.blank? %>
+ <div class="p-4 text-sm text-secondary">
+ <p class="mb-2"><%= t(".no_accounts_available") %></p>
+ <ul class="list-disc list-inside space-y-1">
+ <li><%= t(".run_sync_hint") %></li>
+ <li><%= t(".wait_for_sync") %></li>
+ </ul>
+ </div>
+ <% else %>
+ <%= form_with url: link_existing_account_sharesight_items_path, method: :post, data: { turbo_frame: "_top" }, class: "space-y-4" do %>
+ <%= hidden_field_tag :account_id, @account.id %>
+ <div class="space-y-2 max-h-64 overflow-auto">
+ <% @available_sharesight_accounts.each do |sharesight_account| %>
+ <label class="flex items-center gap-3 p-2 rounded border border-secondary hover:border-primary cursor-pointer">
+ <%= radio_button_tag :sharesight_account_id, sharesight_account.id, false, required: true %>
+ <div class="flex flex-col">
+ <span class="text-sm text-primary font-medium"><%= sharesight_account.name.presence || sharesight_account.sharesight_account_id %></span>
+ <span class="text-xs text-secondary">
+ <%= sharesight_account.currency %> • <%= t(".balance") %>: <%= number_to_currency((sharesight_account.current_balance || 0), unit: Money::Currency.new(sharesight_account.currency.presence || Current.family.currency).symbol) %>
+ </span>
+ </div>
+ </label>
+ <% end %>
+ </div>
+
+ <div class="flex items-center justify-end gap-2">
+ <%= render DS::Button.new(text: t(".link"), variant: :primary, icon: "link-2", type: :submit) %>
+ <%= render DS::Link.new(text: t(".cancel"), variant: :secondary, href: accounts_path, data: { turbo_frame: "_top" }) %>
+ </div>
+ <% end %>
+ <% end %>
+ <% end %>
+<% end %>
diff --git a/app/views/sharesight_items/setup_accounts.html.erb b/app/views/sharesight_items/setup_accounts.html.erb
new file mode 100644
index 0000000000..4aa9e54a0a
--- /dev/null
+++ b/app/views/sharesight_items/setup_accounts.html.erb
@@ -0,0 +1,170 @@
+<% content_for :title, t(".page_title") %>
+
+<%= render DS::Dialog.new(disable_click_outside: true) do |dialog| %>
+ <% dialog.with_header(title: t(".dialog_title")) do %>
+ <div class="flex items-center gap-2">
+ <%= icon "chart-line", class: "text-primary" %>
+ <span class="text-primary"><%= t(".subtitle") %></span>
+ </div>
+ <% end %>
+
+ <% dialog.with_body do %>
+ <div class="space-y-6">
+ <div class="bg-surface border border-primary p-4 rounded-lg">
+ <div class="flex items-start gap-3">
+ <%= icon "info", size: "sm", class: "text-primary mt-0.5 flex-shrink-0" %>
+ <div>
+ <p class="text-sm text-primary mb-2"><strong><%= t(".info_box.title") %></strong></p>
+ <ul class="text-xs text-secondary space-y-1 list-disc list-inside">
+ <li><%= t(".info_box.items.item_1") %></li>
+ <li><%= t(".info_box.items.item_2") %></li>
+ <li><%= t(".info_box.items.item_3") %></li>
+ </ul>
+ </div>
+ </div>
+ </div>
+
+ <% if @waiting_for_sync %>
+ <div class="flex flex-col items-center justify-center py-6 space-y-3">
+ <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
+ <p class="text-secondary text-center"><%= t(".status.fetching_accounts") %></p>
+ </div>
+ <div class="flex gap-3 justify-center">
+ <%= render DS::Link.new(
+ text: t(".buttons.refresh"),
+ variant: "secondary",
+ icon: "refresh-cw",
+ href: setup_accounts_sharesight_item_path(@sharesight_item),
+ frame: "_top"
+ ) %>
+ <%= render DS::Link.new(
+ text: t(".buttons.cancel"),
+ variant: "ghost",
+ href: accounts_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% elsif @no_accounts_found %>
+ <div class="flex flex-col items-center justify-center py-6 space-y-3">
+ <%= icon "alert-circle", size: "lg", class: "text-warning" %>
+ <p class="text-primary text-center font-medium"><%= t(".status.no_accounts_found_title") %></p>
+ <p class="text-secondary text-center text-sm"><%= t(".status.no_accounts_found_description") %></p>
+ </div>
+ <div class="flex gap-3 justify-center">
+ <%= render DS::Link.new(
+ text: t(".buttons.back_to_settings"),
+ variant: "secondary",
+ href: settings_providers_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% else %>
+ <%= form_with url: complete_account_setup_sharesight_item_path(@sharesight_item), method: :post, data: { turbo_frame: "_top" } do %>
+ <% if @unlinked_accounts.any? %>
+ <div class="space-y-4">
+ <h3 class="font-medium text-primary"><%= t(".available_accounts.title") %></h3>
+
+ <% @unlinked_accounts.each do |sharesight_account| %>
+ <div class="border border-primary rounded-lg p-4 hover:bg-surface transition-colors">
+ <div class="flex items-center gap-3">
+ <input type="checkbox"
+ id="account_<%= sharesight_account.id %>"
+ name="account_ids[]"
+ value="<%= sharesight_account.id %>"
+ checked
+ class="cursor-pointer">
+ <label for="account_<%= sharesight_account.id %>" class="flex-1 cursor-pointer">
+ <h4 class="font-medium text-primary"><%= sharesight_account.name %></h4>
+ <p class="text-sm text-secondary">
+ <%= t(
+ ".available_accounts.account_summary",
+ account_type: t(".available_accounts.account_type_investment"),
+ balance: number_to_currency(sharesight_account.current_balance || 0, unit: Money::Currency.new(sharesight_account.currency.presence || Current.family.currency).symbol)
+ ) %>
+ </p>
+ <% if sharesight_account.sharesight_account_id.present? %>
+ <p class="text-xs text-secondary"><%= t(".available_accounts.account_id", account_id: sharesight_account.sharesight_account_id) %></p>
+ <% end %>
+ </label>
+ </div>
+ </div>
+ <% end %>
+ </div>
+
+ <div class="flex gap-3 mt-6">
+ <%= render DS::Button.new(
+ text: t(".buttons.create_selected_accounts"),
+ variant: "primary",
+ icon: "plus",
+ type: "submit",
+ class: "flex-1"
+ ) %>
+ <%= render DS::Link.new(
+ text: t(".buttons.cancel"),
+ variant: "secondary",
+ href: accounts_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+
+ <% if @unlinked_accounts.any? && @linkable_accounts.any? %>
+ <div class="border-t border-secondary pt-4 mt-2">
+ <p class="text-xs text-secondary mb-3"><%= t(".link_existing.description") %></p>
+ <div class="space-y-2">
+ <% @unlinked_accounts.each do |sharesight_account| %>
+ <%= form_with url: link_existing_account_sharesight_items_path, method: :post, data: { turbo_frame: "_top" } do |link_form| %>
+ <%= link_form.hidden_field :sharesight_account_id, value: sharesight_account.id %>
+ <p class="text-xs text-primary mb-1"><%= sharesight_account.name %></p>
+ <div class="flex items-center gap-2">
+ <%= link_form.select :account_id,
+ options_for_select(@linkable_accounts.map { |a| [ t(".link_existing.manual_account_option", name: a.name, balance: number_to_currency(a.balance, unit: Money::Currency.new(a.currency.presence || Current.family.currency).symbol)), a.id ] }),
+ { prompt: t(".link_existing.select_prompt") },
+ class: "bg-container border border-primary rounded px-2 py-1 text-sm text-primary flex-1 min-w-0" %>
+ <%= render DS::Button.new(
+ text: t(".buttons.link"),
+ variant: "secondary",
+ size: "sm",
+ type: "submit"
+ ) %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ </div>
+ <% end %>
+
+ <% if @linked_accounts.any? %>
+ <div class="<%= "border-t border-primary pt-6 mt-4" if @unlinked_accounts.any? %>">
+ <h3 class="font-medium text-primary mb-4"><%= t(".linked_accounts.title") %></h3>
+ <% @linked_accounts.each do |sharesight_account| %>
+ <div class="border border-success/20 bg-success/5 rounded-lg p-4 mb-2">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-3">
+ <%= icon "check-circle", class: "text-success" %>
+ <div>
+ <h4 class="font-medium text-primary"><%= sharesight_account.name %></h4>
+ <p class="text-sm text-secondary"><%= t(".linked_accounts.linked_to_html", account: link_to(sharesight_account.current_account.name, account_path(sharesight_account.current_account), class: "link")) %></p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <% end %>
+
+ <% if @unlinked_accounts.blank? %>
+ <div class="flex justify-end mt-4">
+ <%= render DS::Link.new(
+ text: t(".buttons.done"),
+ variant: "primary",
+ href: accounts_path,
+ frame: "_top"
+ ) %>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 4f04bf9f3b..8329091375 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -491,6 +491,7 @@ en:
onchain_wallet: Track self-custody Bitcoin, EVM, Solana, Cosmos and Polkadot 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.
+ sharesight: Sync the portfolios you track in Sharesight using its API.
trade_republic: Sync your Trade Republic investment account via secure read-only web login.
ibkr: Sync Interactive Brokers investment accounts via Flex Query imports.
questrade: Sync your Questrade investment accounts directly via the Questrade API.
@@ -798,6 +799,22 @@ en:
other: "%{count} Trade Republic accounts discovered."
status_configured_suffix: tab to manage discovered accounts.
not_configured: Not configured.
+ sharesight_panel:
+ steps:
+ step_1: Ask Sharesight support to enable API access. It's available on paid plans.
+ step_2: In your Sharesight account settings, open the API page and copy the client ID and client secret.
+ step_3: Paste both below and save. Sure then finds your portfolios so you can link them.
+ client_id_label: Client ID
+ client_id_placeholder_new: Paste your Sharesight client ID
+ client_id_placeholder_existing: Leave blank to keep the current client ID
+ client_secret_label: Client secret
+ client_secret_placeholder_new: Paste your Sharesight client secret
+ client_secret_placeholder_existing: Leave blank to keep the current client secret
+ save_configuration: Save Configuration
+ update_configuration: Update Configuration
+ status_configured_prefix: "Configured. Visit the"
+ accounts_tab: Accounts
+ status_configured_suffix: tab to link your portfolios.
trading212_panel:
steps:
step_1: Go to Trading 212 → Settings → API (web or mobile app).
diff --git a/config/locales/views/sharesight_items/en.yml b/config/locales/views/sharesight_items/en.yml
new file mode 100644
index 0000000000..7d8bc52e6a
--- /dev/null
+++ b/config/locales/views/sharesight_items/en.yml
@@ -0,0 +1,157 @@
+---
+en:
+ providers:
+ sharesight:
+ name: Sharesight
+ connection_description: Connect your Sharesight portfolios via the Sharesight API
+ institution_name: Sharesight
+ sharesight_accounts:
+ settings_fields:
+ title: Sharesight cash and dividends
+ description: Choose where this portfolio's cash and dividends live, so Sure doesn't count them twice.
+ cash_mode: Cash
+ cash_modes:
+ broker: Held by the broker
+ settlement: Settled through another account
+ untracked: Not tracked (shares only)
+ cash_mode_help: >-
+ With another account or no cash tracked, this account shows shares only. Each trade's cash is offset with a
+ transfer, linked to the account it settled through.
+ settlement_account: Settlement account
+ settlement_starts_on: Settles there from
+ settlement_window_days: Days the bank can take to show it
+ settlement_help: >-
+ Each buy and sell, and each dividend paid there, is matched by amount to a transaction in that account and
+ linked as a transfer. A manual account gets the transaction booked for it. Before the start date, the broker
+ held the cash.
+ choose_account: Choose an account
+ no_account: None
+ funding_account: Funding account
+ funding_match_terms: Funding transaction text
+ funding_match_terms_placeholder: CMC Share Transfer, CMC Markets
+ funding_help: >-
+ Top-ups and withdrawals in the funding account whose name or notes contain any of these (comma-separated)
+ are mirrored here and linked as transfers.
+ cash_anchor_amount: Cash at the broker
+ cash_anchor_on: On
+ cash_anchor_help: >-
+ For cash Sharesight can't see: the balance on that date, rolled forward through everything booked here since.
+ Update it whenever you check the broker.
+ dividend_mode: Dividends and distributions
+ dividend_modes:
+ with_cash: Wherever the cash is
+ other_account: Paid to another account
+ skip: Don't import (another connection shows them)
+ dividend_mode_help: >-
+ Paid out ones are still counted as income here, then linked to the deposit in the account they were paid to.
+ dividend_account: Paid to
+ sync_start_date: Import activity from
+ sync_start_date_help: Older trades and dividends are left out, and any already imported are removed.
+ errors:
+ settlement_account_missing: Choose the account the portfolio settles through.
+ dividend_account_missing: Choose the account dividends are paid to.
+ cash_anchor_incomplete: Give both the cash at the broker and the date you saw it.
+ invalid_date:
+ settlement_starts_on: The date it settles there from isn't a valid date.
+ cash_anchor_on: The date you saw the cash at the broker isn't a valid date.
+ sync_start_date: The date to import activity from isn't a valid date.
+ account_not_in_family: "%{name} isn't one of your accounts."
+ account_is_portfolio: "%{name} is this portfolio's own account."
+ notices:
+ unsettled_debit: "No %{amount} debit in %{account} for %{description} on %{date} yet."
+ unsettled_credit: "No %{amount} credit in %{account} for %{description} on %{date} yet."
+ units_drift: "%{account}: Sharesight holds %{held} %{ticker}, but the trades add up to %{traded}."
+ sharesight_items:
+ defaults:
+ name: Sharesight
+ portfolio_name: Sharesight portfolio %{id}
+ sharesight_item:
+ deletion_in_progress: Deletion in progress
+ syncing: Syncing
+ requires_update: API client needs attention
+ error: Error
+ synced: Synced %{time} ago. %{summary}.
+ never_synced: Never synced.
+ setup_accounts: Set up portfolios
+ delete: Delete
+ accounts_need_setup: Portfolios need setup
+ accounts_need_setup_description: Your Sharesight portfolios need to be linked to Sure accounts.
+ no_accounts_discovered: No Sharesight portfolios discovered yet.
+ no_accounts_discovered_description: Run a sync after saving your API client to discover your portfolios.
+ setup_accounts:
+ page_title: Set Up Sharesight Portfolios
+ dialog_title: Set Up Your Sharesight Portfolios
+ subtitle: Link your Sharesight portfolios to investment accounts.
+ info_box:
+ title: Sharesight API Import
+ items:
+ item_1: Current holdings with prices and quantities, and the portfolio's value
+ item_2: Buys, sells, opening balances, capital returns and dividends, including reinvested ones
+ item_3: Deposits, withdrawals, interest and fees from any Sharesight cash account
+ status:
+ fetching_accounts: Fetching portfolios from Sharesight...
+ no_accounts_found_title: No portfolios found.
+ no_accounts_found_description: Sure could not find any Sharesight portfolios. Check that your API client is valid.
+ available_accounts:
+ title: Available portfolios
+ account_type_investment: Investment
+ account_summary: "%{account_type} • Balance: %{balance}"
+ account_id: "Portfolio ID: %{account_id}"
+ link_existing:
+ description: Or link a discovered portfolio to an existing manual investment account.
+ manual_account_option: "%{name} (%{balance})"
+ select_prompt: Select an account...
+ linked_accounts:
+ title: Already linked
+ linked_to_html: "Linked to: %{account}"
+ buttons:
+ refresh: Refresh
+ cancel: Cancel
+ back_to_settings: Back to Settings
+ create_selected_accounts: Create selected accounts
+ link: Link
+ done: Done
+ sync:
+ status:
+ checking_credentials: Checking Sharesight credentials...
+ importing_portfolios: Importing Sharesight portfolios...
+ checking_configuration: Checking portfolio configuration...
+ accounts_need_setup:
+ one: 1 Sharesight portfolio needs setup...
+ other: "%{count} Sharesight portfolios need setup..."
+ processing_activity: Processing holdings and activity...
+ calculating_balances: Calculating balances...
+ sync_status:
+ no_accounts: No Sharesight portfolios discovered yet
+ all_linked:
+ one: 1 portfolio linked
+ other: "%{count} portfolios linked"
+ partial: "%{linked} linked, %{unlinked} need setup"
+ select_existing_account:
+ title: Link Sharesight portfolio
+ no_accounts_available: No unlinked Sharesight portfolios are available yet.
+ run_sync_hint: "Run a sync from Settings > Providers after saving your API client."
+ wait_for_sync: Wait for the portfolio discovery sync to finish.
+ balance: Balance
+ link: Link
+ cancel: Cancel
+ create:
+ success: Successfully configured Sharesight.
+ update:
+ success: Successfully updated Sharesight configuration.
+ destroy:
+ success: Scheduled Sharesight connection for deletion.
+ select_accounts:
+ not_configured: Sharesight is not configured.
+ link_existing_account:
+ not_found: Account or Sharesight portfolio not found.
+ only_manual_investment: Only manual investment accounts can be linked to Sharesight.
+ already_linked: This Sharesight portfolio is already linked.
+ success: Successfully linked to Sharesight portfolio.
+ failed: Failed to link Sharesight portfolio.
+ complete_account_setup:
+ success:
+ one: Successfully created %{count} Sharesight account.
+ other: Successfully created %{count} Sharesight accounts.
+ none_selected: No portfolios were selected.
+ none_created: No accounts were created.
diff --git a/config/routes.rb b/config/routes.rb
index 000f894da5..c218acf702 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -214,6 +214,20 @@ Rails.application.routes.draw do
end
end
+ resources :sharesight_items, only: [ :create, :update, :destroy ] do
+ collection do
+ get :select_accounts
+ get :select_existing_account
+ post :link_existing_account
+ end
+
+ member do
+ post :sync
+ get :setup_accounts
+ post :complete_account_setup
+ end
+ end
+
# Trade Republic routes (login steps are TR-specific: web login needs a
# two-phase initiate/confirm handshake with the Trade Republic app)
resources :trade_republic_items, only: [ :show, :create, :update, :destroy ] do
diff --git a/db/migrate/20261023072123_create_sharesight_items_and_accounts.rb b/db/migrate/20261023072123_create_sharesight_items_and_accounts.rb
new file mode 100644
index 0000000000..acf84e6db3
--- /dev/null
+++ b/db/migrate/20261023072123_create_sharesight_items_and_accounts.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+class CreateSharesightItemsAndAccounts < ActiveRecord::Migration[8.1]
+ def change
+ create_table :sharesight_items, id: :uuid do |t|
+ t.references :family, null: false, foreign_key: true, type: :uuid
+ t.string :name
+ t.string :status, default: "good", null: false
+ t.boolean :scheduled_for_deletion, default: false, null: false
+ t.boolean :pending_account_setup, default: false, null: false
+ t.string :client_id
+ t.string :client_secret
+
+ t.timestamps
+ end
+
+ add_index :sharesight_items, :status
+
+ # One row per Sharesight portfolio. sharesight_account_id is the portfolio's id.
+ create_table :sharesight_accounts, id: :uuid do |t|
+ t.references :sharesight_item, null: false, foreign_key: true, type: :uuid
+ t.string :name
+ t.string :sharesight_account_id
+ t.string :currency
+ t.decimal :current_balance, precision: 19, scale: 4
+ t.decimal :cash_balance, precision: 19, scale: 4
+ t.jsonb :raw_payload
+ t.jsonb :raw_holdings_payload, default: [], null: false
+ t.jsonb :raw_trades_payload, default: [], null: false
+ t.jsonb :raw_payouts_payload, default: [], null: false
+ t.jsonb :raw_cash_transactions_payload, default: [], null: false
+
+ t.timestamps
+ end
+
+ add_index :sharesight_accounts, [ :sharesight_item_id, :sharesight_account_id ],
+ unique: true,
+ where: "(sharesight_account_id IS NOT NULL)",
+ name: "index_sharesight_accounts_on_item_and_account_id"
+ end
+end
diff --git a/db/migrate/20261024010000_add_cash_settings_to_sharesight_accounts.rb b/db/migrate/20261024010000_add_cash_settings_to_sharesight_accounts.rb
new file mode 100644
index 0000000000..95edcdfcb9
--- /dev/null
+++ b/db/migrate/20261024010000_add_cash_settings_to_sharesight_accounts.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+class AddCashSettingsToSharesightAccounts < ActiveRecord::Migration[8.1]
+ def change
+ change_table :sharesight_accounts, bulk: true do |t|
+ # Where the cash lives: with the broker, in a settlement account, or not tracked.
+ t.string :cash_mode, default: "broker", null: false
+ t.references :settlement_account, type: :uuid, foreign_key: { to_table: :accounts, on_delete: :nullify }
+ t.date :settlement_starts_on
+ t.integer :settlement_window_days, default: 7, null: false
+
+ # Where dividends and distributions get paid.
+ t.string :dividend_mode, default: "with_cash", null: false
+ t.references :dividend_account, type: :uuid, foreign_key: { to_table: :accounts, on_delete: :nullify }
+
+ # Top-ups from a bank account that's already in Sure.
+ t.references :funding_account, type: :uuid, foreign_key: { to_table: :accounts, on_delete: :nullify }
+ t.jsonb :funding_match_terms, default: [], null: false
+
+ # Broker cash Sharesight can't see, as you saw it on a date.
+ t.decimal :cash_anchor_amount, precision: 19, scale: 4
+ t.date :cash_anchor_on
+
+ t.date :sync_start_date
+ end
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index a6d49a005e..13bebdc592 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2408,6 +2408,52 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) do
t.index ["var"], name: "index_settings_on_var", unique: true
end
+ create_table "sharesight_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.decimal "cash_anchor_amount", precision: 19, scale: 4
+ t.date "cash_anchor_on"
+ t.decimal "cash_balance", precision: 19, scale: 4
+ t.string "cash_mode", default: "broker", null: false
+ t.datetime "created_at", null: false
+ t.string "currency"
+ t.decimal "current_balance", precision: 19, scale: 4
+ t.uuid "dividend_account_id"
+ t.string "dividend_mode", default: "with_cash", null: false
+ t.uuid "funding_account_id"
+ t.jsonb "funding_match_terms", default: [], null: false
+ t.string "name"
+ t.jsonb "raw_cash_transactions_payload", default: [], null: false
+ t.jsonb "raw_holdings_payload", default: [], null: false
+ t.jsonb "raw_payload"
+ t.jsonb "raw_payouts_payload", default: [], null: false
+ t.jsonb "raw_trades_payload", default: [], null: false
+ t.uuid "settlement_account_id"
+ t.date "settlement_starts_on"
+ t.integer "settlement_window_days", default: 7, null: false
+ t.string "sharesight_account_id"
+ t.uuid "sharesight_item_id", null: false
+ t.date "sync_start_date"
+ t.datetime "updated_at", null: false
+ t.index ["dividend_account_id"], name: "index_sharesight_accounts_on_dividend_account_id"
+ t.index ["funding_account_id"], name: "index_sharesight_accounts_on_funding_account_id"
+ t.index ["settlement_account_id"], name: "index_sharesight_accounts_on_settlement_account_id"
+ t.index ["sharesight_item_id", "sharesight_account_id"], name: "index_sharesight_accounts_on_item_and_account_id", unique: true, where: "(sharesight_account_id IS NOT NULL)"
+ t.index ["sharesight_item_id"], name: "index_sharesight_accounts_on_sharesight_item_id"
+ end
+
+ create_table "sharesight_items", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.string "client_id"
+ t.string "client_secret"
+ t.datetime "created_at", null: false
+ t.uuid "family_id", null: false
+ t.string "name"
+ t.boolean "pending_account_setup", default: false, null: false
+ t.boolean "scheduled_for_deletion", default: false, null: false
+ t.string "status", default: "good", null: false
+ t.datetime "updated_at", null: false
+ t.index ["family_id"], name: "index_sharesight_items_on_family_id"
+ t.index ["status"], name: "index_sharesight_items_on_status"
+ end
+
create_table "simplefin_accounts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.string "account_id"
t.string "account_subtype"
@@ -3197,6 +3243,11 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_01_120000) do
add_foreign_key "security_splits", "securities", on_delete: :cascade
add_foreign_key "sessions", "impersonation_sessions", column: "active_impersonator_session_id", on_delete: :nullify
add_foreign_key "sessions", "users"
+ add_foreign_key "sharesight_accounts", "accounts", column: "dividend_account_id", on_delete: :nullify
+ add_foreign_key "sharesight_accounts", "accounts", column: "funding_account_id", on_delete: :nullify
+ add_foreign_key "sharesight_accounts", "accounts", column: "settlement_account_id", on_delete: :nullify
+ add_foreign_key "sharesight_accounts", "sharesight_items"
+ add_foreign_key "sharesight_items", "families"
add_foreign_key "simplefin_accounts", "simplefin_items"
add_foreign_key "simplefin_items", "families"
add_foreign_key "snaptrade_accounts", "snaptrade_items"
diff --git a/test/controllers/sharesight_account_settings_test.rb b/test/controllers/sharesight_account_settings_test.rb
new file mode 100644
index 0000000000..67c789d1ad
--- /dev/null
+++ b/test/controllers/sharesight_account_settings_test.rb
@@ -0,0 +1,79 @@
+require "test_helper"
+
+class SharesightAccountSettingsTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in @user = users(:family_admin)
+ @family = @user.family
+ @item = @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ @account = @family.accounts.create!(name: "CMC Invest", balance: 0, currency: "AUD", owner: @user, accountable: Investment.new)
+ @bank = @family.accounts.create!(name: "Macquarie CMA", balance: 0, currency: "AUD", owner: @user, accountable: Depository.new)
+ @sharesight_account = @item.sharesight_accounts.create!(name: "Shares", sharesight_account_id: "42", currency: "AUD")
+ @sharesight_account.ensure_account_provider!(@account)
+ end
+
+ test "the investment form shows the portfolio's cash settings" do
+ ensure_tailwind_build
+
+ get edit_investment_url(@account)
+
+ assert_response :success
+ assert_select "select[name=?]", "account[sharesight][cash_mode]"
+ assert_select "select[name=?] option", "account[sharesight][settlement_account_id]", text: "Macquarie CMA"
+ end
+
+ test "saving the settings stores them and syncs the portfolio" do
+ assert_difference -> { @item.syncs.count }, 1 do
+ patch investment_url(@account), params: { account: { name: "CMC Invest", sharesight: {
+ cash_mode: "settlement", settlement_account_id: @bank.id, settlement_starts_on: "2026-11-03",
+ settlement_window_days: "5", dividend_mode: "with_cash", funding_match_terms: "CMC Share Transfer, CMC Markets"
+ } } }
+ end
+
+ @sharesight_account.reload
+ assert_equal [ "settlement", @bank, Date.new(2026, 11, 3), 5, [ "CMC Share Transfer", "CMC Markets" ] ],
+ [ @sharesight_account.cash_mode, @sharesight_account.settlement_account, @sharesight_account.settlement_starts_on,
+ @sharesight_account.settlement_window_days, @sharesight_account.funding_match_terms ]
+ end
+
+ test "a saved account you can't edit stays when you change other settings" do
+ ensure_tailwind_build
+ partners = @family.accounts.create!(name: "Partner's CMA", balance: 0, currency: "AUD", owner: users(:family_member), accountable: Depository.new)
+ @sharesight_account.update!(cash_mode: "settlement", settlement_account: partners)
+
+ get edit_investment_url(@account)
+ assert_select "select[name=?] option[value=?]", "account[sharesight][settlement_account_id]", partners.id
+
+ patch investment_url(@account), params: { account: { name: "CMC Invest", sharesight: {
+ cash_mode: "settlement", settlement_account_id: partners.id, settlement_window_days: "5"
+ } } }
+
+ assert_nil flash[:alert]
+ @sharesight_account.reload
+ assert_equal [ partners, 5 ], [ @sharesight_account.settlement_account, @sharesight_account.settlement_window_days ]
+ end
+
+ test "an account the user can't write to is refused" do
+ private_account = @family.accounts.create!(name: "Not mine", balance: 0, currency: "AUD", owner: users(:family_member), accountable: Depository.new)
+
+ patch investment_url(@account), params: { account: { name: "CMC Invest", sharesight: { cash_mode: "settlement", settlement_account_id: private_account.id } } }
+
+ assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
+ assert_equal "broker", @sharesight_account.reload.cash_mode
+ end
+
+ test "invalid settings are explained and not saved" do
+ patch investment_url(@account), params: { account: { name: "CMC Invest", sharesight: { cash_mode: "settlement", settlement_account_id: "" } } }
+
+ assert_equal I18n.t("sharesight_accounts.errors.settlement_account_missing"), flash[:alert]
+ assert_equal "broker", @sharesight_account.reload.cash_mode
+ end
+
+ test "a date that can't be read is explained and the saved one kept" do
+ @sharesight_account.update!(sync_start_date: Date.new(2025, 7, 1))
+
+ patch investment_url(@account), params: { account: { name: "CMC Invest", sharesight: { sync_start_date: "not a date" } } }
+
+ assert_equal I18n.t("sharesight_accounts.errors.invalid_date.sync_start_date"), flash[:alert]
+ assert_equal Date.new(2025, 7, 1), @sharesight_account.reload.sync_start_date
+ end
+end
diff --git a/test/controllers/sharesight_items_controller_test.rb b/test/controllers/sharesight_items_controller_test.rb
new file mode 100644
index 0000000000..6762903b8f
--- /dev/null
+++ b/test/controllers/sharesight_items_controller_test.rb
@@ -0,0 +1,168 @@
+require "test_helper"
+
+class SharesightItemsControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ sign_in @user = users(:family_admin)
+ @family = @user.family
+ end
+
+ test "create saves the API client and starts a sync" do
+ post sharesight_items_url, params: { sharesight_item: { client_id: "client-id", client_secret: "client-secret" } }
+
+ assert_redirected_to accounts_url
+ item = @family.sharesight_items.sole
+ assert_equal [ "client-id", "client-secret", "Sharesight" ], [ item.client_id, item.client_secret, item.name ]
+ assert_equal 1, item.syncs.count
+ end
+
+ test "create without a secret shows the error in the panel" do
+ post sharesight_items_url, params: { sharesight_item: { client_id: "client-id", client_secret: "" } }
+
+ assert_redirected_to settings_providers_url
+ assert_empty @family.sharesight_items
+ end
+
+ test "update keeps the stored credentials when the fields are left blank" do
+ item = sharesight_item(status: :requires_update)
+
+ patch sharesight_item_url(item), params: { sharesight_item: { client_id: "", client_secret: "" } }
+
+ item.reload
+ assert_equal [ "client-id", "client-secret" ], [ item.client_id, item.client_secret ]
+ assert item.good?
+ end
+
+ test "settings panel never renders the stored secrets" do
+ sharesight_item
+
+ get connect_form_settings_providers_url(provider_key: "sharesight")
+
+ assert_response :success
+ assert_select "#sharesight-providers-panel"
+ assert_no_match(/value="client-(id|secret)"/, response.body)
+ end
+
+ test "setup lists discovered portfolios" do
+ item = sharesight_item
+ item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42", current_balance: 1500)
+
+ get setup_accounts_sharesight_item_url(item)
+
+ assert_response :success
+ assert_select "input[name='account_ids[]']", 1
+ end
+
+ test "completing setup creates a linked investment account with the portfolio's balance" do
+ item = sharesight_item
+ portfolio = item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42", current_balance: 1500, cash_balance: 0)
+
+ assert_difference -> { @family.accounts.count }, 1 do
+ post complete_account_setup_sharesight_item_url(item), params: { account_ids: [ portfolio.id ] }
+ end
+
+ assert_redirected_to accounts_url
+ account = portfolio.reload.current_account
+ assert_equal [ "Shares", "Investment", "brokerage", BigDecimal("1500") ],
+ [ account.name, account.accountable_type, account.accountable.subtype, account.balance ]
+ assert_not item.reload.pending_account_setup?
+ end
+
+ test "setup only offers manual accounts to link" do
+ item = sharesight_item
+ item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42")
+ manual = investment_account(owner: @user)
+ plaid_linked = investment_account(owner: @user)
+ plaid_linked.update_columns(plaid_account_id: plaid_accounts(:one).id)
+
+ get setup_accounts_sharesight_item_url(item)
+
+ assert_select "option[value=?]", manual.id
+ assert_select "option[value=?]", plaid_linked.id, count: 0
+ end
+
+ test "completing setup doesn't keep an account it couldn't link" do
+ item = sharesight_item
+ portfolio = item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42")
+ SharesightAccount.any_instance.stubs(:ensure_account_provider!).returns(nil)
+
+ assert_no_difference -> { @family.accounts.count } do
+ post complete_account_setup_sharesight_item_url(item), params: { account_ids: [ portfolio.id ] }
+ end
+
+ assert_redirected_to setup_accounts_sharesight_item_url(item)
+ assert_nil portfolio.reload.current_account
+ end
+
+ test "the link dialog renders one modal frame" do
+ sharesight_item
+
+ get select_existing_account_sharesight_items_url(account_id: investment_account(owner: @user).id)
+
+ assert_response :success
+ assert_select "turbo-frame#modal", count: 1
+ end
+
+ test "the link dialog needs a portfolio picked before it submits" do
+ sharesight_item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42")
+
+ get select_existing_account_sharesight_items_url(account_id: investment_account(owner: @user).id)
+
+ assert_select "input[type=radio][name=sharesight_account_id][required]", count: 1
+ end
+
+ test "links a portfolio to an existing manual investment account" do
+ item = sharesight_item
+ portfolio = item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42", current_balance: 1500)
+ account = investment_account(owner: @user)
+
+ post link_existing_account_sharesight_items_url, params: { account_id: account.id, sharesight_account_id: portfolio.id }
+
+ assert_redirected_to account_url(account)
+ assert_equal account, portfolio.reload.current_account
+ end
+
+ test "won't link a portfolio to an account the user can't edit" do
+ item = sharesight_item
+ portfolio = item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42")
+ private_account = investment_account(owner: users(:family_member))
+
+ post link_existing_account_sharesight_items_url, params: { account_id: private_account.id, sharesight_account_id: portfolio.id }
+
+ assert_redirected_to settings_providers_url
+ assert_nil portfolio.reload.current_account
+ end
+
+ test "the accounts page shows the Sharesight connection" do
+ item = sharesight_item
+
+ get accounts_url
+
+ assert_response :success
+ assert_select "##{ActionView::RecordIdentifier.dom_id(item)}"
+ end
+
+ test "members can't change the connection" do
+ item = sharesight_item
+ sign_in users(:family_member)
+
+ delete sharesight_item_url(item)
+
+ assert_not item.reload.scheduled_for_deletion?
+ end
+
+ private
+
+ def sharesight_item(**attributes)
+ @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret", **attributes)
+ end
+
+ def investment_account(owner:)
+ @family.accounts.create!(
+ name: "Brokerage #{owner.id.first(4)}",
+ balance: 0,
+ currency: "AUD",
+ owner: owner,
+ accountable: Investment.new(subtype: "brokerage")
+ )
+ end
+end
diff --git a/test/models/provider/sharesight_test.rb b/test/models/provider/sharesight_test.rb
new file mode 100644
index 0000000000..2624293844
--- /dev/null
+++ b/test/models/provider/sharesight_test.rb
@@ -0,0 +1,97 @@
+require "test_helper"
+
+class Provider::SharesightTest < ActiveSupport::TestCase
+ API = Provider::Sharesight::BASE_URI
+ PORTFOLIOS_URL = "#{API}/api/v2/portfolios.json".freeze
+
+ setup do
+ @provider = Provider::Sharesight.new(client_id: " client-id ", client_secret: "client-secret")
+ end
+
+ test "exchanges the client credentials for a token and reuses it" do
+ token = stub_request(:post, "#{API}/oauth2/token")
+ .with(body: { grant_type: "client_credentials", client_id: "client-id", client_secret: "client-secret" })
+ .to_return(json_response(access_token: "token-1", expires_in: 1800))
+ portfolios = stub_request(:get, PORTFOLIOS_URL)
+ .with(headers: { "Authorization" => "Bearer token-1" })
+ .to_return(json_response(portfolios: [ { id: 42, name: "Shares", currency_code: "AUD" } ]))
+
+ assert_equal [ { "id" => 42, "name" => "Shares", "currency_code" => "AUD" } ], @provider.fetch_portfolios
+ @provider.fetch_portfolios
+
+ assert_requested token, times: 1
+ assert_requested portfolios, times: 2
+ end
+
+ test "asks for a new token once when the current one has expired" do
+ stub_request(:post, "#{API}/oauth2/token")
+ .to_return(json_response(access_token: "stale"), json_response(access_token: "fresh"))
+ stub_request(:get, PORTFOLIOS_URL).with(headers: { "Authorization" => "Bearer stale" }).to_return(status: 401)
+ stub_request(:get, PORTFOLIOS_URL).with(headers: { "Authorization" => "Bearer fresh" }).to_return(json_response(portfolios: []))
+
+ assert_equal [], @provider.fetch_portfolios
+ end
+
+ test "rejected client credentials raise an authentication error" do
+ stub_request(:post, "#{API}/oauth2/token").to_return(status: 401, body: "invalid_client")
+
+ error = assert_raises(Provider::Sharesight::AuthenticationError) { @provider.fetch_portfolios }
+ assert_match "client ID and secret", error.message
+ end
+
+ test "an account without API access raises an authentication error" do
+ stub_token
+ stub_request(:get, PORTFOLIOS_URL).to_return(status: 403)
+
+ assert_raises(Provider::Sharesight::AuthenticationError) { @provider.fetch_portfolios }
+ end
+
+ test "rate limiting raises a rate limit error" do
+ stub_token
+ stub_request(:get, PORTFOLIOS_URL).to_return(status: 429)
+
+ assert_raises(Provider::Sharesight::RateLimitError) { @provider.fetch_portfolios }
+ end
+
+ test "fetches a portfolio's report, trades, payouts and cash account transactions" do
+ stub_token
+ stub_request(:get, "#{API}/api/v3/portfolios/42/performance")
+ .with(query: { include_sales: "true" })
+ .to_return(json_response(report: { value: 100.0, holdings: [] }))
+ stub_request(:get, "#{API}/api/v2/portfolios/42/trades.json").to_return(json_response(trades: [ { id: 1 } ]))
+ stub_request(:get, "#{API}/api/v2/portfolios/42/payouts.json")
+ .with(query: { start_date: "2021-02-03", end_date: "2026-10-23" })
+ .to_return(json_response(payouts: [ { id: 2 } ]))
+ stub_request(:get, "#{API}/api/v2/cash_accounts.json").to_return(json_response(cash_accounts: [ { id: 7 } ]))
+ stub_request(:get, "#{API}/api/v2/cash_accounts/7/cash_account_transactions.json")
+ .to_return(json_response(cash_account_transactions: [ { id: 3 } ]))
+
+ assert_equal({ "value" => 100.0, "holdings" => [] }, @provider.fetch_performance("42"))
+ assert_equal [ { "id" => 1 } ], @provider.fetch_trades("42")
+ assert_equal [ { "id" => 2 } ], @provider.fetch_payouts("42", start_date: Date.new(2021, 2, 3), end_date: Date.new(2026, 10, 23))
+ assert_equal [ { "id" => 7 } ], @provider.fetch_cash_accounts
+ assert_equal [ { "id" => 3 } ], @provider.fetch_cash_account_transactions(7)
+ end
+
+ test "a response that isn't JSON raises an API error" do
+ stub_token
+ stub_request(:get, PORTFOLIOS_URL).to_return(status: 200, body: "<html>maintenance</html>", headers: { "Content-Type" => "text/html" })
+
+ assert_raises(Provider::Sharesight::ApiError) { @provider.fetch_portfolios }
+ end
+
+ test "requires a client id and secret" do
+ assert_raises(Provider::Sharesight::ConfigurationError) { Provider::Sharesight.new(client_id: "", client_secret: "secret") }
+ assert_raises(Provider::Sharesight::ConfigurationError) { Provider::Sharesight.new(client_id: "id", client_secret: nil) }
+ end
+
+ private
+
+ def stub_token
+ stub_request(:post, "#{API}/oauth2/token").to_return(json_response(access_token: "token"))
+ end
+
+ def json_response(body)
+ { status: 200, body: body.to_json, headers: { "Content-Type" => "application/json" } }
+ end
+end
diff --git a/test/models/sharesight_account/cash_router_test.rb b/test/models/sharesight_account/cash_router_test.rb
new file mode 100644
index 0000000000..5e0a69f507
--- /dev/null
+++ b/test/models/sharesight_account/cash_router_test.rb
@@ -0,0 +1,300 @@
+require "test_helper"
+
+class SharesightAccount::CashRouterTest < ActiveSupport::TestCase
+ HOLDINGS = [
+ { "id" => 1, "quantity" => 20.0, "value" => 2100.0, "instrument_price" => 105.0,
+ "instrument" => { "code" => "VAS", "market_code" => "ASX", "currency_code" => "AUD" }, "instrument_currency" => { "code" => "AUD" } }
+ ].freeze
+
+ TRADES = [
+ { "id" => 1, "transaction_type" => "BUY", "transaction_date" => "2026-09-01", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 10, "price" => 100.0, "exchange_rate" => 1.0, "brokerage" => 0, "holding_id" => 1, "state" => "confirmed" },
+ { "id" => 2, "transaction_type" => "BUY", "transaction_date" => "2026-09-10", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 5, "price" => 100.0, "exchange_rate" => 1.0, "brokerage" => 0, "holding_id" => 1, "state" => "confirmed" },
+ { "id" => 3, "transaction_type" => "BUY", "transaction_date" => "2026-09-10", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 5, "price" => 120.0, "exchange_rate" => 1.0, "brokerage" => 0, "holding_id" => 1, "state" => "confirmed" }
+ ].freeze
+
+ PAYOUTS = [
+ { "id" => 50, "symbol" => "VAS", "market" => "ASX", "paid_on" => "2026-09-20", "amount" => 30.0, "currency" => "AUD",
+ "holding_id" => 1, "state" => "confirmed" }
+ ].freeze
+
+ # A$120 dividend, A$98 of it reinvested, so A$22 left over.
+ REINVESTED = PAYOUTS.first.merge("amount" => 120.0, "drp_trade_attributes" => { "dividend_reinvested" => true, "quantity" => 1, "price" => 98.0 })
+ # Some portfolios also record those reinvested units as a trade.
+ ALLOTMENT = { "id" => 4, "transaction_type" => "BUY", "transaction_date" => "2026-09-20", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 1, "price" => 98.0, "exchange_rate" => 1.0, "brokerage" => 0, "holding_id" => 1, "state" => "confirmed" }.freeze
+
+ setup do
+ @family = families(:dylan_family)
+ item = @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ @account = @family.accounts.create!(name: "Shares", balance: 0, currency: "AUD", accountable: Investment.new)
+ @bank = @family.accounts.create!(name: "Macquarie CMA", balance: 0, currency: "AUD", accountable: Depository.new)
+ @sharesight_account = item.sharesight_accounts.create!(
+ name: "Shares", sharesight_account_id: "42", currency: "AUD", current_balance: 2100, cash_balance: 0,
+ raw_holdings_payload: HOLDINGS, raw_trades_payload: TRADES, raw_payouts_payload: PAYOUTS,
+ cash_mode: "settlement", settlement_account: @bank
+ )
+ @sharesight_account.ensure_account_provider!(@account)
+ Security.find_or_create_by!(ticker: "VAS", exchange_operating_mic: "XASX")
+ end
+
+ test "trades and dividends settle against the bank feed as confirmed transfers" do
+ bank_fed!
+ buy = bank_transaction(1000, "2026-09-03", "CMC Markets buy")
+ deposit = bank_transaction(-30, "2026-09-21", "VAS dividend")
+
+ process
+
+ leg = offset("trade_1")
+ assert_equal [ BigDecimal("-1000"), "Transfer from Macquarie CMA" ], [ leg.amount, leg.name ]
+ assert_linked leg, buy
+ assert_equal "investment_contribution", buy.entryable.reload.kind
+
+ dividend_leg = offset("payout_50")
+ assert_equal BigDecimal("30"), dividend_leg.amount
+ assert_linked dividend_leg, deposit
+ assert_equal "funds_movement", deposit.entryable.reload.kind
+ end
+
+ test "the investment account holds shares only" do
+ bank_fed!
+
+ process
+
+ assert_equal BigDecimal("0"), @account.entries.where(entryable_type: %w[Transaction Trade]).sum(:amount)
+ @account.reload
+ assert_equal [ BigDecimal("2100"), BigDecimal("0") ], [ @account.balance, @account.cash_balance ]
+ end
+
+ test "a trade worth a fraction of a cent still matches the bank in whole cents" do
+ bank_fed!
+ fractional = TRADES.map { |t| t["id"] == 1 ? t.merge("price" => 100.0004) : t }
+ @sharesight_account.update!(raw_trades_payload: fractional)
+ buy = bank_transaction(1000, "2026-09-03", "CMC Markets buy")
+
+ process
+
+ leg = offset("trade_1")
+ assert_equal BigDecimal("-1000"), leg.amount
+ assert_linked leg, buy
+ end
+
+ test "a day's trades settled as one amount are matched together" do
+ bank_fed!
+ settlement = bank_transaction(1100, "2026-09-12", "CMC Markets net settlement")
+
+ process
+
+ day = offset("day_2026-09-10_AUD")
+ assert_equal BigDecimal("-1100"), day.amount
+ assert_linked day, settlement
+ assert_nil offset("trade_2", required: false)
+ assert_nil offset("trade_3", required: false)
+ end
+
+ test "a settlement missing from the bank feed keeps the shares-only offset and is reported once overdue" do
+ bank_fed!
+
+ notices = process[:notices]
+
+ assert_nil offset("trade_1").entryable.transfer
+ assert_includes notices.map { |notice| notice[:message] }.join("\n"), "debit in Macquarie CMA for Buy 10"
+ end
+
+ test "earlier matches stay put when a look-alike turns up" do
+ bank_fed!
+ first = bank_transaction(1000, "2026-09-03", "CMC Markets buy")
+ process
+ bank_transaction(1000, "2026-09-02", "Something else")
+
+ process
+
+ assert_linked offset("trade_1"), first
+ end
+
+ test "a manual settlement account gets the other side booked for it" do
+ process
+
+ counterpart = @bank.entries.find_by!(external_id: "sharesight_counterpart_#{@sharesight_account.id}_trade_1")
+ assert_equal [ BigDecimal("1000"), Date.new(2026, 9, 1) ], [ counterpart.amount, counterpart.date ]
+ assert_linked offset("trade_1"), counterpart
+ assert_equal BigDecimal("-30"), @bank.entries.find_by!(external_id: "sharesight_counterpart_#{@sharesight_account.id}_payout_50").amount
+ end
+
+ test "a reinvested dividend's leftover is linked when the bank feed shows it" do
+ bank_fed!
+ @sharesight_account.update!(raw_payouts_payload: [ REINVESTED ])
+ leftover = bank_transaction(-22, "2026-09-21", "VAS dividend balance")
+
+ process
+
+ leg = offset("payout_50")
+ assert_equal [ BigDecimal("22"), "Transfer to Macquarie CMA" ], [ leg.amount, leg.name ]
+ assert_linked leg, leftover
+ end
+
+ test "reinvested units recorded as a trade settle with their dividend" do
+ bank_fed!
+ @sharesight_account.update!(raw_trades_payload: TRADES + [ ALLOTMENT ], raw_payouts_payload: [ REINVESTED ])
+ leftover = bank_transaction(-22, "2026-09-21", "VAS dividend balance")
+
+ notices = process[:notices].map { |notice| notice[:message] }
+
+ assert_nil offset("trade_4", required: false)
+ leg = offset("payout_50")
+ assert_equal BigDecimal("22"), leg.amount
+ assert_linked leg, leftover
+ assert notices.none? { |message| message.include?("Buy 1.0 shares of VAS") || message.include?("Dividend from VAS") }
+ end
+
+ test "a dividend and its allotment in different currencies stay apart" do
+ bank_fed!
+ usd_dividend = REINVESTED.merge("currency" => "USD")
+ @sharesight_account.update!(raw_trades_payload: TRADES + [ ALLOTMENT ], raw_payouts_payload: [ usd_dividend ])
+
+ process
+
+ assert_equal [ BigDecimal("120"), "USD" ], offset("payout_50").then { |leg| [ leg.amount, leg.currency ] }
+ assert_equal [ BigDecimal("-98"), "AUD" ], offset("trade_4").then { |leg| [ leg.amount, leg.currency ] }
+ end
+
+ test "reinvested units recorded as a trade cost nothing when dividends aren't imported" do
+ @sharesight_account.update!(
+ cash_mode: "broker", settlement_account: nil, dividend_mode: "skip",
+ raw_trades_payload: TRADES + [ ALLOTMENT ], raw_payouts_payload: [ REINVESTED ]
+ )
+
+ process
+
+ assert_equal BigDecimal("0"), @account.entries.find_by!(external_id: "sharesight_trade_4").amount
+ assert_nil @account.entries.find_by(external_id: "sharesight_payout_50")
+ end
+
+ test "a leftover the bank never shows isn't flagged as overdue" do
+ bank_fed!
+ @sharesight_account.update!(raw_payouts_payload: [ REINVESTED ])
+
+ notices = process[:notices].map { |notice| notice[:message] }
+
+ assert_equal "Settled outside Sure", offset("payout_50").name
+ assert notices.none? { |message| message.include?("Dividend from VAS") }
+ end
+
+ test "a leftover isn't booked into a manual account" do
+ @sharesight_account.update!(raw_payouts_payload: [ REINVESTED ])
+
+ process
+
+ assert_nil @bank.entries.find_by(external_id: "sharesight_counterpart_#{@sharesight_account.id}_payout_50")
+ assert_equal "Settled outside Sure", offset("payout_50").name
+ end
+
+ test "switching manual settlement accounts moves the counterparts" do
+ process
+ ing = @family.accounts.create!(name: "ING Savings", balance: 0, currency: "AUD", accountable: Depository.new)
+ @sharesight_account.update!(settlement_account: ing)
+
+ process
+ process
+
+ assert_empty @bank.entries.where("external_id LIKE 'sharesight_counterpart_%'")
+ assert_linked offset("trade_1"), ing.entries.find_by!(external_id: "sharesight_counterpart_#{@sharesight_account.id}_trade_1")
+ end
+
+ test "untracked cash is offset without a counterpart anywhere" do
+ @sharesight_account.update!(cash_mode: "untracked", settlement_account: nil)
+
+ process
+
+ leg = offset("trade_1")
+ assert_equal [ BigDecimal("-1000"), "Settled outside Sure" ], [ leg.amount, leg.name ]
+ assert_nil leg.entryable.transfer
+ assert_empty @bank.entries
+ end
+
+ test "before the settlement start date the broker held the cash" do
+ bank_fed!
+ @sharesight_account.update!(settlement_starts_on: Date.new(2026, 9, 5))
+
+ process
+
+ assert_nil offset("trade_1", required: false)
+ assert offset("trade_2")
+ end
+
+ test "dividends paid to another account are matched there" do
+ bank_fed!
+ other = @family.accounts.create!(name: "CommBank", balance: 0, currency: "AUD", accountable: Depository.new)
+ deposit = other.entries.create!(name: "VAS dividend", date: Date.new(2026, 9, 20), amount: -30, currency: "AUD", entryable: Transaction.new)
+ @sharesight_account.update!(cash_mode: "broker", settlement_account: nil, dividend_mode: "other_account", dividend_account: other)
+
+ process
+
+ assert_nil offset("trade_1", required: false)
+ assert_linked offset("payout_50"), deposit
+ assert_equal BigDecimal("-30"), @account.entries.find_by!(external_id: "sharesight_payout_50").amount
+ end
+
+ test "skipped dividends aren't imported and reinvested ones cost nothing" do
+ reinvested = PAYOUTS.first.merge("drp_trade_attributes" => { "dividend_reinvested" => true, "quantity" => 1, "price" => 30.0 })
+ @sharesight_account.update!(cash_mode: "broker", settlement_account: nil, dividend_mode: "skip", raw_payouts_payload: [ reinvested ])
+
+ process
+
+ assert_nil @account.entries.find_by(external_id: "sharesight_payout_50")
+ assert_equal BigDecimal("0"), @account.entries.find_by!(external_id: "sharesight_drp_50").amount
+ end
+
+ test "switching back to the broker removes the offsets and frees the bank transactions" do
+ bank_fed!
+ buy = bank_transaction(1000, "2026-09-03", "CMC Markets buy")
+ process
+ @sharesight_account.update!(cash_mode: "broker", settlement_account: nil)
+
+ process
+
+ assert_empty @account.entries.where("external_id LIKE 'sharesight_offset_%'")
+ assert_nil buy.entryable.reload.transfer
+ assert_equal "standard", buy.entryable.kind
+ end
+
+ test "a pair the user unlinked stays unlinked" do
+ bank_fed!
+ buy = bank_transaction(1000, "2026-09-03", "CMC Markets buy")
+ process
+ offset("trade_1").entryable.transfer.reject!
+
+ process
+
+ assert_nil offset("trade_1").entryable.reload.transfer
+ assert_nil buy.entryable.reload.transfer
+ end
+
+ private
+
+ def process
+ SharesightAccount::Processor.new(@sharesight_account.reload).process
+ end
+
+ # Pretend the settlement account comes from a bank feed.
+ def bank_fed!
+ Account.any_instance.stubs(:linked?).returns(true)
+ end
+
+ def bank_transaction(amount, date, name)
+ @bank.entries.create!(name: name, date: Date.parse(date), amount: amount, currency: "AUD", entryable: Transaction.new)
+ end
+
+ def offset(key, required: true)
+ scope = @account.entries.where(external_id: "sharesight_offset_#{key}")
+ required ? scope.first! : scope.first
+ end
+
+ def assert_linked(leg, other)
+ transfer = leg.entryable.reload.transfer
+ assert transfer&.confirmed?, "#{leg.external_id} isn't a confirmed transfer"
+ assert_includes [ transfer.inflow_transaction_id, transfer.outflow_transaction_id ], other.entryable_id
+ end
+end
diff --git a/test/models/sharesight_account/cash_settings_test.rb b/test/models/sharesight_account/cash_settings_test.rb
new file mode 100644
index 0000000000..1d5422e0cb
--- /dev/null
+++ b/test/models/sharesight_account/cash_settings_test.rb
@@ -0,0 +1,95 @@
+require "test_helper"
+
+class SharesightAccount::CashSettingsTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ item = @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ @account = @family.accounts.create!(name: "CMC Invest", balance: 0, currency: "AUD", accountable: Investment.new)
+ @bank = @family.accounts.create!(name: "Macquarie CMA", balance: 0, currency: "AUD", accountable: Depository.new)
+ @sharesight_account = item.sharesight_accounts.create!(name: "Shares", sharesight_account_id: "42", currency: "AUD")
+ @sharesight_account.ensure_account_provider!(@account)
+ end
+
+ test "the form's settings are normalised" do
+ @sharesight_account.assign_cash_settings(
+ "cash_mode" => "settlement", "settlement_account_id" => @bank.id, "settlement_starts_on" => "2026-11-03",
+ "settlement_window_days" => "", "funding_match_terms" => " CMC Share Transfer, , CMC Markets,CMC Markets ",
+ "sync_start_date" => "", "ignored" => "x"
+ )
+
+ assert @sharesight_account.save
+ assert_equal [ "settlement", @bank, Date.new(2026, 11, 3), 7, [ "CMC Share Transfer", "CMC Markets" ], nil ],
+ [ @sharesight_account.cash_mode, @sharesight_account.settlement_account, @sharesight_account.settlement_starts_on,
+ @sharesight_account.settlement_window_days, @sharesight_account.funding_match_terms, @sharesight_account.sync_start_date ]
+ assert @sharesight_account.cash_settings_changed?
+ end
+
+ test "each mode needs its account" do
+ @sharesight_account.cash_mode = "settlement"
+ @sharesight_account.dividend_mode = "other_account"
+
+ assert_not @sharesight_account.valid?
+ assert_includes @sharesight_account.errors.full_messages, I18n.t("sharesight_accounts.errors.settlement_account_missing")
+ assert_includes @sharesight_account.errors.full_messages, I18n.t("sharesight_accounts.errors.dividend_account_missing")
+ end
+
+ test "linked accounts belong to the family and aren't the portfolio's own" do
+ stranger = families(:empty).accounts.create!(name: "Not ours", balance: 0, currency: "AUD", accountable: Depository.new)
+ @sharesight_account.assign_attributes(funding_account: stranger, dividend_mode: "other_account", dividend_account: @account)
+
+ assert_not @sharesight_account.valid?
+ assert_includes @sharesight_account.errors.full_messages, I18n.t("sharesight_accounts.errors.account_not_in_family", name: "Not ours")
+ assert_includes @sharesight_account.errors.full_messages, I18n.t("sharesight_accounts.errors.account_is_portfolio", name: "CMC Invest")
+ end
+
+ test "a deleted settlement account doesn't stop syncs" do
+ @sharesight_account.update!(cash_mode: "settlement", settlement_account: @bank)
+
+ @bank.destroy!
+ @sharesight_account.reload
+
+ assert_nil @sharesight_account.settlement_account
+ assert @sharesight_account.update(raw_payload: { "id" => 42 }), "an import can still save the portfolio"
+ assert_equal SharesightAccount::OUTSIDE, @sharesight_account.trade_destination_on(Date.current)
+ end
+
+ test "a cash anchor needs both its amount and date" do
+ @sharesight_account.cash_anchor_amount = 2049.29
+
+ assert_not @sharesight_account.valid?
+ assert_includes @sharesight_account.errors.full_messages, I18n.t("sharesight_accounts.errors.cash_anchor_incomplete")
+ end
+
+ test "a date that can't be read is refused instead of clearing the setting" do
+ @sharesight_account.update!(sync_start_date: Date.new(2025, 7, 1), settlement_starts_on: Date.new(2026, 11, 3))
+
+ @sharesight_account.assign_cash_settings("sync_start_date" => "2025-02-30", "settlement_starts_on" => "soon", "cash_anchor_on" => "")
+
+ assert_not @sharesight_account.valid?
+ assert_equal [ I18n.t("sharesight_accounts.errors.invalid_date.settlement_starts_on"), I18n.t("sharesight_accounts.errors.invalid_date.sync_start_date") ],
+ @sharesight_account.errors.full_messages
+ end
+
+ test "blank dates still clear their settings" do
+ @sharesight_account.update!(sync_start_date: Date.new(2025, 7, 1))
+
+ @sharesight_account.assign_cash_settings("sync_start_date" => "")
+
+ assert @sharesight_account.save
+ assert_nil @sharesight_account.reload.sync_start_date
+ end
+
+ test "where cash and dividends go on a given date" do
+ @sharesight_account.assign_attributes(cash_mode: "settlement", settlement_account: @bank, settlement_starts_on: Date.new(2026, 11, 3))
+
+ assert_nil @sharesight_account.trade_destination_on(Date.new(2026, 11, 2))
+ assert_equal @bank, @sharesight_account.trade_destination_on(Date.new(2026, 11, 3))
+ assert_equal @bank, @sharesight_account.dividend_destination_on(Date.new(2026, 11, 3))
+
+ @sharesight_account.cash_mode = "untracked"
+ assert_equal SharesightAccount::OUTSIDE, @sharesight_account.trade_destination_on(Date.new(2026, 1, 1))
+
+ @sharesight_account.dividend_mode = "skip"
+ assert_equal :skip, @sharesight_account.dividend_destination_on(Date.new(2026, 1, 1))
+ end
+end
diff --git a/test/models/sharesight_account/funding_mirror_test.rb b/test/models/sharesight_account/funding_mirror_test.rb
new file mode 100644
index 0000000000..38ee9080aa
--- /dev/null
+++ b/test/models/sharesight_account/funding_mirror_test.rb
@@ -0,0 +1,82 @@
+require "test_helper"
+
+class SharesightAccount::FundingMirrorTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ item = @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ @account = @family.accounts.create!(name: "CMC Invest", balance: 0, currency: "AUD", accountable: Investment.new)
+ @bank = @family.accounts.create!(name: "CommBank", balance: 0, currency: "AUD", accountable: Depository.new)
+ @sharesight_account = item.sharesight_accounts.create!(
+ name: "Shares", sharesight_account_id: "42", currency: "AUD", current_balance: 0, cash_balance: 0,
+ funding_account: @bank, funding_match_terms: [ "CMC Share Transfer", "CMC Markets" ]
+ )
+ @sharesight_account.ensure_account_provider!(@account)
+
+ @top_up = bank_transaction(815, "2026-09-01", "CMC Share Transfer 1364731")
+ @withdrawal = bank_transaction(-100, "2026-09-15", "Payment from CMC MARKETS")
+ @coffee = bank_transaction(5, "2026-09-02", "Coffee")
+ end
+
+ test "top-ups and withdrawals are mirrored and linked as transfers" do
+ mirror
+
+ top_up = mirror_of(@top_up)
+ assert_equal [ BigDecimal("-815"), "Transfer from CommBank", Date.new(2026, 9, 1) ], [ top_up.amount, top_up.name, top_up.date ]
+ assert top_up.entryable.transfer.confirmed?
+ assert_equal "investment_contribution", @top_up.entryable.reload.kind
+
+ assert_equal BigDecimal("100"), mirror_of(@withdrawal).amount
+ assert_nil mirror_of(@coffee, required: false)
+ end
+
+ test "a failed run keeps the mirrors it couldn't refresh" do
+ mirror
+ SharesightAccount::FundingMirror.any_instance.stubs(:link_transfer!).raises(StandardError, "database blip")
+
+ mirror
+
+ assert mirror_of(@top_up)
+ assert @top_up.entryable.reload.transfer&.confirmed?
+ end
+
+ test "bank transactions already paired with another account are left alone" do
+ savings = @family.accounts.create!(name: "Savings", balance: 0, currency: "AUD", accountable: Depository.new)
+ other_side = savings.entries.create!(name: "From CommBank", date: Date.new(2026, 9, 1), amount: -815, currency: "AUD", entryable: Transaction.new)
+ Transfer.create!(inflow_transaction: other_side.entryable, outflow_transaction: @top_up.entryable, status: "confirmed")
+
+ mirror
+
+ assert_nil mirror_of(@top_up, required: false)
+ end
+
+ test "mirrors stop where the settlement account takes over and go when the terms change" do
+ mirror
+ @sharesight_account.update!(cash_mode: "settlement", settlement_account: @bank, settlement_starts_on: Date.new(2026, 9, 10))
+
+ mirror
+
+ assert mirror_of(@top_up)
+ assert_nil mirror_of(@withdrawal, required: false)
+
+ @sharesight_account.update!(funding_match_terms: [])
+ mirror
+
+ assert_empty @account.entries.where("external_id LIKE 'sharesight_funding_%'")
+ assert_nil @top_up.entryable.reload.transfer
+ end
+
+ private
+
+ def mirror
+ SharesightAccount::FundingMirror.new(@sharesight_account.reload).mirror
+ end
+
+ def bank_transaction(amount, date, name)
+ @bank.entries.create!(name: name, date: Date.parse(date), amount: amount, currency: "AUD", entryable: Transaction.new)
+ end
+
+ def mirror_of(bank_entry, required: true)
+ scope = @account.entries.where(external_id: "sharesight_funding_#{bank_entry.id}")
+ required ? scope.first! : scope.first
+ end
+end
diff --git a/test/models/sharesight_account/processor_cash_test.rb b/test/models/sharesight_account/processor_cash_test.rb
new file mode 100644
index 0000000000..751b1b4ed2
--- /dev/null
+++ b/test/models/sharesight_account/processor_cash_test.rb
@@ -0,0 +1,127 @@
+require "test_helper"
+
+class SharesightAccount::ProcessorCashTest < ActiveSupport::TestCase
+ HOLDINGS = [
+ { "id" => 1, "quantity" => 20.0, "value" => 2100.0, "instrument_price" => 105.0,
+ "instrument" => { "code" => "VAS", "market_code" => "ASX", "currency_code" => "AUD" }, "instrument_currency" => { "code" => "AUD" } },
+ { "id" => 2, "quantity" => 50.0, "value" => 2750.0, "instrument_price" => 55.0,
+ "instrument" => { "code" => "BHP", "market_code" => "ASX", "currency_code" => "AUD" }, "instrument_currency" => { "code" => "AUD" } }
+ ].freeze
+
+ TRADES = [
+ { "id" => 1, "transaction_type" => "BUY", "transaction_date" => "2026-09-01", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 10, "price" => 100.0, "exchange_rate" => 1.0, "holding_id" => 1, "state" => "confirmed" },
+ { "id" => 2, "transaction_type" => "BUY", "transaction_date" => "2026-09-10", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 10, "price" => 110.0, "exchange_rate" => 1.0, "holding_id" => 1, "state" => "confirmed" }
+ ].freeze
+
+ PAYOUTS = [
+ { "id" => 50, "symbol" => "VAS", "market" => "ASX", "paid_on" => "2026-09-20", "amount" => 30.0, "currency" => "AUD",
+ "holding_id" => 1, "state" => "confirmed" }
+ ].freeze
+
+ setup do
+ @family = families(:dylan_family)
+ @item = @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ @account = @family.accounts.create!(name: "CMC Invest", balance: 0, currency: "AUD", accountable: Investment.new)
+ @sharesight_account = @item.sharesight_accounts.create!(
+ name: "Shares", sharesight_account_id: "42", currency: "AUD", current_balance: 4850, cash_balance: 0,
+ raw_holdings_payload: HOLDINGS, raw_trades_payload: TRADES, raw_payouts_payload: PAYOUTS
+ )
+ @sharesight_account.ensure_account_provider!(@account)
+ %w[VAS BHP].each { |ticker| Security.find_or_create_by!(ticker: ticker, exchange_operating_mic: "XASX") }
+ end
+
+ test "observed broker cash is rolled forward through what's been booked since" do
+ @sharesight_account.update!(cash_anchor_amount: 2000, cash_anchor_on: Date.new(2026, 9, 5))
+
+ process
+
+ # 2000 - the 1100 buy on 10 Sep + the 30 dividend on 20 Sep.
+ @account.reload
+ assert_equal [ BigDecimal("930"), BigDecimal("5780") ], [ @account.cash_balance, @account.balance ]
+ end
+
+ test "a foreign trade after the anchor is paid from the portfolio's cash" do
+ us_buy = { "id" => 3, "transaction_type" => "BUY", "transaction_date" => "2026-09-15", "symbol" => "AAPL", "market" => "NASDAQ",
+ "quantity" => 10, "price" => 100.0, "exchange_rate" => 0.5, "holding_id" => 3, "state" => "confirmed" }
+ us_holding = { "id" => 3, "quantity" => 10.0, "value" => 2000.0, "instrument_price" => 100.0,
+ "instrument" => { "code" => "AAPL", "market_code" => "NASDAQ", "currency_code" => "USD" }, "instrument_currency" => { "code" => "USD" } }
+ @sharesight_account.update!(
+ raw_trades_payload: TRADES + [ us_buy ], raw_holdings_payload: HOLDINGS + [ us_holding ], current_balance: 6850,
+ cash_anchor_amount: 5000, cash_anchor_on: Date.new(2026, 9, 5)
+ )
+
+ process
+
+ # US$1,000 at 0.5 USD per AUD is A$2,000: 5000 - 1100 + 30 - 2000.
+ assert_equal BigDecimal("1930"), @account.reload.cash_balance
+ end
+
+ test "a portfolio settled elsewhere is shares only" do
+ @sharesight_account.update!(cash_mode: "untracked", cash_anchor_amount: 2000, cash_anchor_on: Date.new(2026, 9, 5))
+
+ process
+
+ @account.reload
+ assert_equal [ BigDecimal("0"), BigDecimal("4850") ], [ @account.cash_balance, @account.balance ]
+ end
+
+ test "units the trades don't account for are reported" do
+ notices = process[:notices]
+
+ assert_equal [ I18n.t("sharesight_accounts.notices.units_drift", account: "CMC Invest", ticker: "BHP", held: "50.0", traded: "0.0") ],
+ notices.map { |notice| notice[:message] }
+ end
+
+ test "limited holdings aren't compared" do
+ hidden = { "id" => 9, "quantity" => 5.0, "limited" => true, "instrument" => { "code" => "HIDDEN", "market_code" => "ASX" } }
+ hidden_buy = { "id" => 9, "transaction_type" => "BUY", "transaction_date" => "2026-09-12", "symbol" => "HIDDEN", "market" => "ASX",
+ "quantity" => 3, "price" => 10.0, "exchange_rate" => 1.0, "holding_id" => 9, "state" => "confirmed" }
+ Security.find_or_create_by!(ticker: "HIDDEN", exchange_operating_mic: "XASX")
+ @sharesight_account.update!(raw_holdings_payload: HOLDINGS + [ hidden ], raw_trades_payload: TRADES + [ hidden_buy ])
+
+ notices = process[:notices].map { |notice| notice[:message] }
+
+ assert notices.none? { |message| message.include?("HIDDEN") }
+ end
+
+ test "units that match to 8 decimal places aren't reported" do
+ noisy = HOLDINGS.map { |holding| holding.dig("instrument", "code") == "VAS" ? holding.merge("quantity" => 20.000000000000004) : holding }
+ @sharesight_account.update!(raw_holdings_payload: noisy)
+
+ notices = process[:notices].map { |notice| notice[:message] }
+
+ assert notices.none? { |message| message.include?("VAS") }
+ end
+
+ test "a sync start date leaves older activity out and removes what was imported" do
+ process
+ assert @account.entries.find_by(external_id: "sharesight_trade_1")
+
+ @sharesight_account.update!(sync_start_date: Date.new(2026, 9, 5))
+ notices = process[:notices]
+
+ assert_nil @account.entries.find_by(external_id: "sharesight_trade_1")
+ assert @account.entries.find_by(external_id: "sharesight_trade_2")
+ assert_empty notices, "units can't reconcile without the older trades"
+ end
+
+ test "the sync summary shows the notices" do
+ sync = @item.syncs.create!
+ @item.stubs(:import_latest_data)
+ SharesightItem.any_instance.stubs(:schedule_account_syncs)
+
+ SharesightItem::Syncer.new(@item).perform_sync(sync)
+
+ details = sync.reload.sync_stats["data_quality_details"]
+ assert_equal 1, sync.sync_stats["data_warnings"]
+ assert_match "BHP", details.first["message"]
+ end
+
+ private
+
+ def process
+ SharesightAccount::Processor.new(@sharesight_account.reload).process
+ end
+end
diff --git a/test/models/sharesight_account/processor_test.rb b/test/models/sharesight_account/processor_test.rb
new file mode 100644
index 0000000000..e936fef345
--- /dev/null
+++ b/test/models/sharesight_account/processor_test.rb
@@ -0,0 +1,289 @@
+require "test_helper"
+
+class SharesightAccount::ProcessorTest < ActiveSupport::TestCase
+ HOLDINGS = [
+ { "id" => 1, "quantity" => 100.0, "value" => 10500.0, "instrument_price" => 105.0,
+ "instrument" => { "code" => "VAS", "market_code" => "ASX", "name" => "Vanguard Australian Shares", "currency_code" => "AUD" },
+ "instrument_currency" => { "code" => "AUD" } },
+ { "id" => 2, "quantity" => 10.0, "value" => 4500.0, "instrument_price" => 290.0,
+ "instrument" => { "code" => "AAPL", "market_code" => "NASDAQ", "currency_code" => "USD" },
+ "instrument_currency" => { "code" => "USD" } },
+ { "id" => 3, "quantity" => 0.0, "value" => 0.0, "instrument_price" => 40.0,
+ "instrument" => { "code" => "OLD", "market_code" => "ASX", "currency_code" => "AUD" } },
+ { "id" => 4, "quantity" => 5.0, "limited" => true, "instrument" => { "code" => "HIDDEN", "market_code" => "ASX" } },
+ # Sharesight treats the coin as its own currency. Price and value are in AUD.
+ { "id" => 5, "quantity" => 0.25, "value" => 29091.85, "instrument_price" => 116367.39,
+ "instrument" => { "code" => "BTC", "market_code" => "CRYPTO", "currency_code" => "BTC" },
+ "instrument_currency" => { "code" => "BTC" } }
+ ].freeze
+
+ TRADES = [
+ { "id" => 100, "transaction_type" => "OPENING_BALANCE", "transaction_date" => "2021-02-03", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 90, "price" => nil, "cost_base" => 8100.0, "exchange_rate" => 1.0, "brokerage" => 0, "holding_id" => 1, "state" => "confirmed" },
+ { "id" => 101, "transaction_type" => "BUY", "transaction_date" => "2025-06-02", "symbol" => "AAPL", "market" => "NASDAQ",
+ "quantity" => 10, "price" => 200.0, "exchange_rate" => 0.65, "brokerage" => 10.0, "brokerage_currency_code" => "AUD",
+ "holding_id" => 2, "state" => "confirmed" },
+ { "id" => 102, "transaction_type" => "SPLIT", "transaction_date" => "2025-07-01", "symbol" => "AAPL", "market" => "NASDAQ",
+ "quantity" => 10, "price" => 0, "holding_id" => 2, "state" => "confirmed" },
+ { "id" => 103, "transaction_type" => "SELL", "transaction_date" => "2025-08-01", "symbol" => "OLD", "market" => "ASX",
+ "quantity" => -50, "price" => 40.0, "exchange_rate" => 1.0, "brokerage" => 9.5, "holding_id" => 3, "state" => "confirmed" },
+ { "id" => nil, "transaction_type" => "BUY", "transaction_date" => "2026-01-15", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 2, "price" => 99.0, "exchange_rate" => 1.0, "holding_id" => 1, "state" => "unconfirmed" },
+ { "id" => 105, "transaction_type" => "BUY", "transaction_date" => "2015-12-01", "symbol" => "BTC", "market" => "CRYPTO",
+ "quantity" => 0.25, "price" => 1.0, "exchange_rate" => 0.002, "brokerage" => 0.0, "brokerage_currency_code" => "AUD",
+ "holding_id" => 5, "state" => "confirmed" },
+ { "id" => 106, "transaction_type" => "CAPITAL_RETURN", "transaction_date" => "2025-11-05", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 0.0, "price" => 0.0, "value" => -34.5, "capital_return_value" => 34.5, "holding_id" => 1, "state" => "confirmed" }
+ ].freeze
+
+ PAYOUTS = [
+ { "id" => 500, "symbol" => "VAS", "market" => "ASX", "paid_on" => "2026-01-15", "amount" => 120.0, "currency" => "AUD",
+ "holding_id" => 1, "state" => "confirmed",
+ "drp_trade_attributes" => { "dividend_reinvested" => true, "quantity" => 1.0, "price" => 98.0 } },
+ { "id" => nil, "symbol" => "VAS", "market" => "ASX", "paid_on" => "2026-04-15", "amount" => 95.0, "currency" => "AUD",
+ "holding_id" => 1, "state" => "unconfirmed" }
+ ].freeze
+
+ CASH_TRANSACTIONS = [
+ { "id" => 900, "date_time" => "2021-02-01T00:00:00Z", "amount" => 10000, "description" => "Initial funding",
+ "cash_account_transaction_type" => { "name" => "DEPOSIT" }, "currency" => "AUD" },
+ { "id" => 901, "date_time" => "2025-06-02T00:00:00Z", "amount" => -1316.88, "trade_id" => 101,
+ "cash_account_transaction_type" => { "name" => "TRADE" }, "currency" => "AUD" },
+ { "id" => 902, "date_time" => "2026-03-01T00:00:00Z", "amount" => -500, "cash_account_transaction_type" => { "name" => "WITHDRAWAL" },
+ "currency" => "AUD" },
+ { "id" => 903, "date_time" => "2026-03-31T00:00:00Z", "amount" => 1.23, "cash_account_transaction_type" => { "name" => "INTEREST" },
+ "currency" => "AUD" }
+ ].freeze
+
+ setup do
+ @family = families(:dylan_family)
+ item = @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ @sharesight_account = item.sharesight_accounts.create!(
+ name: "Shares",
+ sharesight_account_id: "42",
+ currency: "AUD",
+ current_balance: 44342.35,
+ cash_balance: 250.5,
+ raw_holdings_payload: HOLDINGS,
+ raw_trades_payload: TRADES,
+ raw_payouts_payload: PAYOUTS,
+ raw_cash_transactions_payload: CASH_TRANSACTIONS
+ )
+ @account = @family.accounts.create!(name: "Shares", balance: 0, cash_balance: 0, currency: "AUD", accountable: Investment.new)
+ @sharesight_account.ensure_account_provider!(@account)
+
+ # Already in the DB, so the resolver doesn't go searching a price provider.
+ %w[VAS OLD].each do |ticker|
+ Security.find_or_create_by!(ticker: ticker, exchange_operating_mic: "XASX")
+ end
+ end
+
+ test "sets the balance from Sharesight's portfolio value and cash" do
+ process
+
+ @account.reload
+ assert_equal BigDecimal("44342.35"), @account.balance
+ assert_equal BigDecimal("250.5"), @account.cash_balance
+ end
+
+ test "imports held units at Sharesight's price in each instrument's currency" do
+ process
+
+ holdings = @account.holdings.where(date: Date.current).includes(:security).to_h do |holding|
+ [ holding.security.ticker, [ holding.qty, holding.price, holding.currency ] ]
+ end
+ assert_equal({
+ "VAS" => [ BigDecimal("100"), BigDecimal("105"), "AUD" ],
+ "AAPL" => [ BigDecimal("10"), BigDecimal("290"), "USD" ],
+ "BTC" => [ BigDecimal("0.25"), BigDecimal("116367.4"), "AUD" ]
+ }, holdings)
+ assert_equal "XNAS", @account.holdings.joins(:security).find_by(securities: { ticker: "AAPL" }).security.exchange_operating_mic
+ end
+
+ test "books buys, sells and opening balances, skipping splits" do
+ result = process
+
+ assert_equal 5, result[:trades]
+
+ opening = trade("sharesight_trade_100")
+ assert_equal [ BigDecimal("90"), BigDecimal("90"), "AUD", BigDecimal("8100"), "Buy" ],
+ [ opening.entryable.qty, opening.entryable.price, opening.currency, opening.amount, opening.entryable.investment_activity_label ]
+
+ sell = trade("sharesight_trade_103")
+ assert_equal [ BigDecimal("-50"), BigDecimal("9.5"), BigDecimal("-1990.5"), "Sell" ],
+ [ sell.entryable.qty, sell.entryable.fee, sell.amount, sell.entryable.investment_activity_label ]
+
+ assert_nil @account.entries.find_by(external_id: "sharesight_trade_102")
+ end
+
+ test "a foreign trade is booked in its own currency with the fee and rate converted" do
+ process
+
+ buy = trade("sharesight_trade_101")
+ # 10 AUD of brokerage at 0.65 USD per AUD.
+ assert_equal [ "USD", BigDecimal("200"), BigDecimal("6.5"), BigDecimal("2006.5") ],
+ [ buy.currency, buy.entryable.price, buy.entryable.fee, buy.amount ]
+ assert_in_delta 1 / 0.65, buy.entryable.exchange_rate, 1e-9
+ end
+
+ test "crypto is booked in the portfolio's currency" do
+ process
+
+ # Priced at 1 BTC, at 0.002 BTC per AUD, so A$500 each.
+ bitcoin = trade("sharesight_trade_105")
+ assert_equal [ "AUD", BigDecimal("500"), BigDecimal("125") ], [ bitcoin.currency, bitcoin.entryable.price, bitcoin.amount ]
+ assert_nil bitcoin.entryable.exchange_rate
+ end
+
+ test "a foreign opening balance with no rate stays in the portfolio's currency" do
+ opening = { "id" => 110, "transaction_type" => "OPENING_BALANCE", "transaction_date" => "2021-02-03", "symbol" => "AAPL", "market" => "NASDAQ",
+ "quantity" => 5, "price" => nil, "cost_base" => 1500.0, "exchange_rate" => nil, "holding_id" => 2, "state" => "confirmed" }
+ @sharesight_account.update!(raw_trades_payload: TRADES + [ opening ])
+
+ process
+
+ entry = trade("sharesight_trade_110")
+ assert_equal [ "AUD", BigDecimal("300") ], [ entry.currency, entry.entryable.price ]
+ end
+
+ test "brokerage in a third currency is converted at Sure's rate for the day" do
+ ExchangeRate.where(from_currency: "GBP", to_currency: "USD").delete_all
+ ExchangeRate.create!(from_currency: "GBP", to_currency: "USD", date: Date.new(2025, 6, 2), rate: 1.25)
+ gbp_fee = TRADES[1].merge("id" => 111, "brokerage" => 10.0, "brokerage_currency_code" => "GBP")
+ @sharesight_account.update!(raw_trades_payload: TRADES + [ gbp_fee ])
+
+ process
+
+ # 200 x 10 USD, plus GBP 10 at 1.25 USD per GBP.
+ buy = trade("sharesight_trade_111")
+ assert_equal [ BigDecimal("12.5"), BigDecimal("2012.5") ], [ buy.entryable.fee, buy.amount ]
+ end
+
+ test "brokerage with no way to convert it is left out and logged" do
+ ExchangeRate.where(from_currency: "GBP", to_currency: "USD").delete_all
+ ExchangeRate.stubs(:provider).returns(nil)
+ gbp_fee = TRADES[1].merge("id" => 112, "brokerage" => 10.0, "brokerage_currency_code" => "GBP")
+ @sharesight_account.update!(raw_trades_payload: TRADES + [ gbp_fee ])
+
+ process
+
+ assert_equal BigDecimal("0"), trade("sharesight_trade_112").entryable.fee
+ assert DebugLogEntry.where(source: "sharesight").where("message LIKE ?", "%GBP brokerage on Sharesight trade 112%").exists?
+ end
+
+ test "a reinvested dividend is income and a reinvestment trade" do
+ result = process
+
+ assert_equal 2, result[:dividends]
+ dividend = @account.entries.find_by!(external_id: "sharesight_payout_500")
+ assert_equal [ BigDecimal("-120"), "Dividend from VAS", "Dividend" ],
+ [ dividend.amount, dividend.name, dividend.entryable.investment_activity_label ]
+
+ drp = trade("sharesight_drp_500")
+ assert_equal [ BigDecimal("1"), BigDecimal("98"), "Reinvestment" ],
+ [ drp.entryable.qty, drp.entryable.price, drp.entryable.investment_activity_label ]
+ end
+
+ test "a reinvestment Sharesight also records as a trade isn't booked twice" do
+ allotment = { "id" => nil, "transaction_type" => "BUY", "transaction_date" => "2026-01-15", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 1, "price" => 98.0, "exchange_rate" => 1.0, "holding_id" => 1, "state" => "unconfirmed" }
+ @sharesight_account.update!(raw_trades_payload: TRADES + [ allotment ])
+
+ process
+
+ assert trade("sharesight_unconfirmed_trade_1_2026-01-15_BUY_1.0")
+ assert_nil @account.entries.find_by(external_id: "sharesight_drp_500")
+ end
+
+ test "unconfirmed records are booked provisionally until Sharesight confirms them" do
+ process
+
+ assert trade("sharesight_unconfirmed_trade_1_2026-01-15_BUY_2.0")
+ provisional = @account.entries.find_by!(external_id: "sharesight_unconfirmed_payout_1_2026-04-15")
+ assert_equal BigDecimal("-95"), provisional.amount
+
+ confirmed_trades = TRADES.map { |t| t["id"].nil? ? t.merge("id" => 104, "state" => "confirmed") : t }
+ confirmed_payouts = PAYOUTS.map { |p| p["id"].nil? ? p.merge("id" => 501, "state" => "confirmed") : p }
+ @sharesight_account.update!(raw_trades_payload: confirmed_trades, raw_payouts_payload: confirmed_payouts)
+ process
+
+ assert_empty @account.entries.where("external_id LIKE 'sharesight_unconfirmed_%'")
+ assert_equal BigDecimal("2"), trade("sharesight_trade_104").entryable.qty
+ assert_equal BigDecimal("-95"), @account.entries.find_by!(external_id: "sharesight_payout_501").amount
+ end
+
+ test "a provisional entry stays if its confirmed version can't be booked yet" do
+ process
+ assert trade("sharesight_unconfirmed_trade_1_2026-01-15_BUY_2.0")
+
+ # Confirmed now, but with no price this time, so it can't be booked.
+ confirmed = TRADES.map { |t| t["id"].nil? ? t.merge("id" => 104, "state" => "confirmed", "price" => 0) : t }
+ @sharesight_account.update!(raw_trades_payload: confirmed)
+ process
+
+ assert trade("sharesight_unconfirmed_trade_1_2026-01-15_BUY_2.0")
+ assert_nil @account.entries.find_by(external_id: "sharesight_trade_104")
+ end
+
+ test "unconfirmed records dated after today wait until they happen" do
+ announced = { "id" => nil, "symbol" => "VAS", "market" => "ASX", "paid_on" => (Date.current + 10).iso8601, "amount" => 80.0,
+ "currency" => "AUD", "holding_id" => 1, "state" => "unconfirmed" }
+ @sharesight_account.update!(raw_payouts_payload: PAYOUTS + [ announced ])
+
+ process
+
+ assert_nil @account.entries.find_by(date: Date.current + 10)
+ end
+
+ test "a capital return is booked as cash" do
+ process
+
+ capital_return = @account.entries.find_by!(external_id: "sharesight_capital_return_106")
+ assert_equal [ BigDecimal("-34.5"), "Capital return from VAS", "Other", "Transaction" ],
+ [ capital_return.amount, capital_return.name, capital_return.entryable.investment_activity_label, capital_return.entryable_type ]
+ end
+
+ test "a foreign capital return is booked at its value in the portfolio's currency" do
+ foreign = { "id" => 107, "transaction_type" => "CAPITAL_RETURN", "transaction_date" => "2025-09-01", "symbol" => "AAPL", "market" => "NASDAQ",
+ "quantity" => 0.0, "price" => 0.0, "value" => -65.0, "capital_return_value" => 42.25, "holding_id" => 2, "state" => "confirmed" }
+ @sharesight_account.update!(raw_trades_payload: TRADES + [ foreign ])
+
+ process
+
+ capital_return = @account.entries.find_by!(external_id: "sharesight_capital_return_107")
+ assert_equal [ BigDecimal("-65"), "AUD" ], [ capital_return.amount, capital_return.currency ]
+ end
+
+ test "cash account movements are booked, leaving out the cash legs of trades" do
+ result = process
+
+ assert_equal 4, result[:transactions]
+ cash = @account.entries.where("external_id LIKE 'sharesight_cash_%'").order(:date).map do |entry|
+ [ entry.external_id, entry.amount, entry.entryable.investment_activity_label ]
+ end
+ assert_equal [
+ [ "sharesight_cash_900", BigDecimal("-10000"), "Contribution" ],
+ [ "sharesight_cash_902", BigDecimal("500"), "Withdrawal" ],
+ [ "sharesight_cash_903", BigDecimal("-1.23"), "Interest" ]
+ ], cash
+ end
+
+ test "processing again updates entries instead of duplicating them" do
+ process
+ count = @account.entries.count
+
+ process
+
+ assert_equal count, @account.entries.reload.count
+ end
+
+ private
+
+ def process
+ SharesightAccount::Processor.new(@sharesight_account.reload).process
+ end
+
+ def trade(external_id)
+ @account.entries.find_by!(external_id: external_id, entryable_type: "Trade")
+ end
+end
diff --git a/test/models/sharesight_item/importer_test.rb b/test/models/sharesight_item/importer_test.rb
new file mode 100644
index 0000000000..90a3b284b1
--- /dev/null
+++ b/test/models/sharesight_item/importer_test.rb
@@ -0,0 +1,149 @@
+require "test_helper"
+
+class SharesightItem::ImporterTest < ActiveSupport::TestCase
+ # A fake Provider::Sharesight with canned responses.
+ class FakeProvider
+ attr_reader :calls
+
+ def initialize(portfolios:, reports: {}, cash_accounts: [], error: nil)
+ @portfolios = portfolios
+ @reports = reports
+ @cash_accounts = cash_accounts
+ @error = error
+ @calls = []
+ end
+
+ def fetch_portfolios
+ raise @error if @error
+
+ @portfolios
+ end
+
+ def fetch_performance(portfolio_id)
+ @calls << [ :performance, portfolio_id ]
+ @reports.fetch(portfolio_id, {})
+ end
+
+ def fetch_trades(portfolio_id)
+ @calls << [ :trades, portfolio_id ]
+ [ { "id" => 1, "transaction_type" => "BUY", "transaction_date" => "2021-03-01" } ]
+ end
+
+ def fetch_payouts(portfolio_id, start_date:)
+ @calls << [ :payouts, portfolio_id, start_date ]
+ [ { "id" => 2 } ]
+ end
+
+ def fetch_cash_accounts
+ @calls << [ :cash_accounts ]
+ @cash_accounts
+ end
+
+ def fetch_cash_account_transactions(cash_account_id)
+ @calls << [ :cash_transactions, cash_account_id ]
+ [ { "id" => "#{cash_account_id}-1", "amount" => 10 } ]
+ end
+ end
+
+ PORTFOLIOS = [
+ { "id" => 42, "name" => "Shares", "currency_code" => "AUD", "inception_date" => "03 Feb 2021" },
+ { "id" => 43, "name" => "US shares", "currency_code" => "USD" }
+ ].freeze
+
+ # Sharesight's value includes every cash account (converted to AUD).
+ REPORT = {
+ "value" => 15400.5,
+ "holdings" => [ { "id" => 1, "quantity" => 100.0, "value" => 10500.0 }, { "id" => 2, "quantity" => 10.0, "value" => 4500.0 } ],
+ "cash_accounts" => [
+ { "id" => 7, "value" => 250.5, "currency" => { "code" => "AUD" } },
+ { "id" => 8, "value" => 99.0, "currency" => { "code" => "USD" } }
+ ]
+ }.freeze
+
+ setup do
+ @family = families(:dylan_family)
+ @item = @family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ end
+
+ test "imports each portfolio's holdings value and same-currency cash, counting cash once" do
+ provider = FakeProvider.new(portfolios: PORTFOLIOS, reports: { "42" => REPORT })
+
+ import(provider)
+
+ shares = @item.sharesight_accounts.find_by!(sharesight_account_id: "42")
+ assert_equal [ "Shares", "AUD", BigDecimal("15250.5"), BigDecimal("250.5") ],
+ [ shares.name, shares.currency, shares.current_balance, shares.cash_balance ]
+ assert_equal [ 1, 2 ], shares.raw_holdings_payload.map { |holding| holding["id"] }
+ assert_equal "USD", @item.sharesight_accounts.find_by!(sharesight_account_id: "43").currency
+ assert @item.reload.good?
+ end
+
+ test "only fetches activity for portfolios linked to an account" do
+ provider = FakeProvider.new(portfolios: PORTFOLIOS, reports: { "42" => REPORT })
+ import(provider)
+ assert_empty provider.calls.reject { |call| call.first == :performance }
+
+ link(@item.sharesight_accounts.find_by!(sharesight_account_id: "42"))
+ provider = FakeProvider.new(
+ portfolios: PORTFOLIOS,
+ reports: { "42" => REPORT },
+ cash_accounts: [
+ { "id" => 7, "portfolio_id" => 42, "currency" => "AUD" },
+ { "id" => 8, "portfolio_id" => 42, "currency" => "USD" },
+ { "id" => 9, "portfolio_id" => 99, "currency" => "AUD" }
+ ]
+ )
+ import(provider)
+
+ shares = @item.sharesight_accounts.find_by!(sharesight_account_id: "42")
+ assert_includes provider.calls, [ :payouts, "42", Date.new(2021, 2, 3) ]
+ assert_equal [ [ :cash_transactions, 7 ] ], provider.calls.select { |call| call.first == :cash_transactions }
+ assert_equal [ 1 ], shares.raw_trades_payload.map { |trade| trade["id"] }
+ assert_equal [ { "id" => 2 } ], shares.raw_payouts_payload
+ assert_equal [ { "id" => "7-1", "amount" => 10, "currency" => "AUD" } ], shares.raw_cash_transactions_payload
+ assert_not provider.calls.include?([ :trades, "43" ])
+ end
+
+ test "payouts start at the first trade when Sharesight gives no inception date" do
+ link(@item.sharesight_accounts.create!(name: "US shares", currency: "USD", sharesight_account_id: "43"))
+ provider = FakeProvider.new(portfolios: PORTFOLIOS)
+
+ import(provider)
+
+ assert_includes provider.calls, [ :payouts, "43", Date.new(2021, 3, 1) ]
+ end
+
+ test "removes unlinked portfolios Sharesight no longer returns and keeps linked ones" do
+ stale = @item.sharesight_accounts.create!(name: "Closed", currency: "AUD", sharesight_account_id: "1")
+ linked = @item.sharesight_accounts.create!(name: "Sold down", currency: "AUD", sharesight_account_id: "2")
+ link(linked)
+
+ import(FakeProvider.new(portfolios: PORTFOLIOS))
+
+ assert_not SharesightAccount.exists?(stale.id)
+ assert SharesightAccount.exists?(linked.id)
+ end
+
+ test "rejected credentials mark the connection as needing an update" do
+ provider = FakeProvider.new(portfolios: [], error: Provider::Sharesight::AuthenticationError.new("rejected"))
+
+ assert_raises(Provider::Sharesight::AuthenticationError) { import(provider) }
+ assert @item.reload.requires_update?
+ end
+
+ private
+
+ def import(provider)
+ SharesightItem::Importer.new(@item, provider: provider).import
+ end
+
+ def link(sharesight_account)
+ account = @family.accounts.create!(
+ name: sharesight_account.name,
+ balance: 0,
+ currency: sharesight_account.currency,
+ accountable: Investment.new
+ )
+ sharesight_account.ensure_account_provider!(account)
+ end
+end
diff --git a/test/models/sharesight_item/syncer_test.rb b/test/models/sharesight_item/syncer_test.rb
new file mode 100644
index 0000000000..79c1fa20d1
--- /dev/null
+++ b/test/models/sharesight_item/syncer_test.rb
@@ -0,0 +1,25 @@
+require "test_helper"
+
+class SharesightItem::SyncerTest < ActiveSupport::TestCase
+ setup do
+ @item = families(:dylan_family).sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ @sync = @item.syncs.create!
+ end
+
+ test "a connection without its API client needs an update" do
+ @item.update_columns(client_secret: nil)
+
+ assert_raises(Provider::Sharesight::ConfigurationError) { SharesightItem::Syncer.new(@item).perform_sync(@sync) }
+ assert @item.reload.requires_update?
+ end
+
+ test "flags portfolios that still need linking" do
+ @item.sharesight_accounts.create!(name: "Shares", currency: "AUD", sharesight_account_id: "42")
+ @item.expects(:import_latest_data)
+ @item.expects(:process_accounts).never
+
+ SharesightItem::Syncer.new(@item).perform_sync(@sync)
+
+ assert @item.reload.pending_account_setup?
+ end
+end
diff --git a/test/models/sharesight_item_test.rb b/test/models/sharesight_item_test.rb
new file mode 100644
index 0000000000..cc799b9ef6
--- /dev/null
+++ b/test/models/sharesight_item_test.rb
@@ -0,0 +1,16 @@
+require "test_helper"
+
+class SharesightItemTest < ActiveSupport::TestCase
+ test "accounts uses portfolios that are already loaded" do
+ family = families(:dylan_family)
+ item = family.sharesight_items.create!(name: "Sharesight", client_id: "client-id", client_secret: "client-secret")
+ 2.times do |i|
+ account = family.accounts.create!(name: "Shares #{i}", balance: 0, currency: "AUD", accountable: Investment.new)
+ item.sharesight_accounts.create!(name: "Shares #{i}", currency: "AUD", sharesight_account_id: i.to_s).ensure_account_provider!(account)
+ end
+
+ loaded = SharesightItem.includes(sharesight_accounts: [ :account, :linked_account ]).find(item.id)
+
+ assert_queries_count(0) { assert_equal 2, loaded.accounts.size }
+ end
+end