Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
46.1 KB
Raw Blame
class Account < ApplicationRecord
  include AASM, Syncable, Monetizable, Chartable, Linkable, Enrichable, Anchorable, Reconcileable, TaxTreatable, Logoable

  before_validation :assign_default_owner, if: -> { owner_id.blank? }

  before_destroy :capture_account_statement_ids_to_move
  before_destroy :cleanup_transfers

  after_destroy_commit :move_account_statements_to_inbox

  # Property checks its cost tag once it belongs to a saved account; a new
  # one cannot reach the family yet, so the new account checks it.
  validate :cost_tag_in_family, if: -> { new_record? && property? && accountable&.cost_tag_id.present? }
  validates :name, :balance, :currency, presence: true
  validate :owner_belongs_to_family, if: -> { owner_id.present? && family_id.present? }

  belongs_to :family
  belongs_to :owner, class_name: "User", optional: true
  belongs_to :import, optional: true

  has_many :account_shares, dependent: :destroy
  has_many :shared_users, through: :account_shares, source: :user
  has_many :import_mappings, as: :mappable, dependent: :destroy, class_name: "Import::Mapping"
  has_many :entries, dependent: :destroy
  has_many :transactions, through: :entries, source: :entryable, source_type: "Transaction"
  has_many :valuations, through: :entries, source: :entryable, source_type: "Valuation"
  has_many :trades, through: :entries, source: :entryable, source_type: "Trade"
  has_many :holdings, dependent: :destroy
  has_many :holding_lots
  has_many :holding_lot_disposals
  has_many :balances, dependent: :destroy
  has_many :recurring_transactions, dependent: :destroy
  has_many :goal_accounts, dependent: :destroy
  has_many :goals, through: :goal_accounts
  has_many :goal_pledges, dependent: :destroy
  # Inverse for recurring transfers where this account is the destination.
  # Account#recurring_transactions only matches account_id; without this
  # association, destroying the destination account would hit the FK
  # cascade silently and the AR cache wouldn't reflect the deletion.
  has_many :inbound_recurring_transfers,
           class_name: "RecurringTransaction",
           foreign_key: :destination_account_id,
           dependent: :destroy

  monetize :balance, :cash_balance

  # Sum of scheduled (future-dated) entries, signed and converted the same way
  # Balance::BaseCalculator#signed_entry_flows treats real flows -- so the
  # projection stays consistent with what the balance will actually become
  # once these entries land. Non-cash valuation-only accounts (Property,
  # Vehicle, etc.) ignore transactions entirely for balance purposes, same as
  # Balance::BaseCalculator#flows_for_date -- see Entry#scheduled?.
  #
  # Trades are included only when qty is 0 (Dividend/Interest): those are pure
  # cash flows with no offsetting holdings change, same shape as a Transaction.
  # A Buy/Sell/Transfer/etc. moves value between cash and holdings rather than
  # into or out of the account, so summing its raw amount here would
  # double-count against Balance::BaseCalculator#market_value_change_on_date
  # once the trade lands.
  # `through_date` bounds the scheduled window to entries dated on or before
  # it (inclusive) -- used to project the balance as of a specific future
  # date (see Account::ActivityFeedData) instead of the account's fully
  # projected total.
  #
  # The flows are loaded and converted once per instance (see
  # #scheduled_entry_flows), so the chart tooltip and every projected date
  # group in the activity feed share one query and one FX pass.
  def scheduled_entries_total_money(through_date: nil)
    flows = scheduled_entry_flows
    flows = flows.select { |date, _| date <= through_date } if through_date

    Money.new(flows.sum { |_, amount| amount }, currency)
  end

  def reload(*)
    @scheduled_entry_flows = nil
    @current_holdings_total = nil
    super
  end

  def projected_balance_money
    balance_money + scheduled_entries_total_money
  end

  enum :classification, { asset: "asset", liability: "liability" }, validate: { allow_nil: true }
  # Which lots a sale consumes: pro rata (the default) or oldest first.
  enum :cost_basis_method, { average: "average", fifo: "fifo" }, prefix: :cost_basis, validate: true

  VISIBLE_STATUSES = %w[draft active].freeze
  HISTORICAL_STATUSES = (VISIBLE_STATUSES + %w[disabled]).freeze

  scope :visible, -> { where(status: VISIBLE_STATUSES) }
  scope :historical, -> { where(status: HISTORICAL_STATUSES) }
  # Accounts whose data should be included in financial reports, dashboards,
  # and exports. Excludes accounts where the user has opted to suppress them.
  scope :included_in_reports, -> { where(exclude_from_reports: false) }
  scope :assets, -> { where(classification: "asset") }
  scope :liabilities, -> { where(classification: "liability") }
  scope :alphabetically, -> { order(:name) }
  scope :manual, -> {
    left_joins(:account_providers)
      .where(account_providers: { id: nil })
      .where(plaid_account_id: nil, simplefin_account_id: nil)
  }

  scope :visible_manual, -> {
    visible.manual
  }

  # The manual accounts +user+ may see, as /accounts lists them. Admins are
  # not exempt: an admin sees what they own or were shared, as on /accounts.
  scope :visible_manual_for, ->(user) {
    visible_manual.where(id: user.accessible_accounts.select(:id))
  }

  scope :listable_manual, -> {
    manual.where.not(status: :pending_deletion)
  }

  # All accounts a user can access (owned + shared with them)
  scope :accessible_by, ->(user) {
    left_joins(:account_shares)
      .where("accounts.owner_id = :uid OR account_shares.user_id = :uid", uid: user.id)
      .distinct
  }

  # Accounts every active member of the account's family can access (owned or
  # shared with them), the same test as accessible_by applied to all of them.
  # Family-wide surfaces such as the insights feed name accounts and amounts
  # to everyone, so they draw only from this set.
  scope :accessible_by_all_active_members, -> {
    where(<<~SQL.squish)
      NOT EXISTS (
        SELECT 1 FROM users
        WHERE users.family_id = accounts.family_id
          AND users.active = TRUE
          AND users.id IS DISTINCT FROM accounts.owner_id
          AND NOT EXISTS (
            SELECT 1 FROM account_shares
            WHERE account_shares.account_id = accounts.id
              AND account_shares.user_id = users.id
          )
      )
    SQL
  }

  # SHA-256 of a set of account ids, in id order, joined by commas. An
  # aggregate over no rows still yields one value, the hash of "". Insight
  # generators store it with a total and Insight.about_shared_accounts
  # recomputes it on read, so both share this one expression.
  ID_SET_DIGEST_SQL = Arel.sql(<<~SQL.squish)
    encode(sha256(convert_to(coalesce(string_agg(accounts.id::text, ',' ORDER BY accounts.id), ''), 'UTF8')), 'hex')
  SQL

  # Accounts a user can write to (owned or shared with full_control)
  WRITABLE_BY_CONDITION = "accounts.owner_id = :uid OR (account_shares.user_id = :uid AND account_shares.permission = 'full_control')".freeze

  scope :writable_by, ->(user) {
    left_joins(:account_shares)
      .where(WRITABLE_BY_CONDITION, uid: user.id)
      .distinct
  }

  # SQL boolean for "user may write to this account", for selecting next to
  # rows already joined with account_shares (e.g. through annotatable_by).
  def self.writable_by_sql(user)
    Arel.sql("(#{sanitize_sql([ WRITABLE_BY_CONDITION, uid: user.id ])})")
  end

  # Accounts a user can annotate (category, tags, notes, merchant): owned,
  # or shared with full_control or read_write
  scope :annotatable_by, ->(user) {
    left_joins(:account_shares)
      .where("accounts.owner_id = :uid OR (account_shares.user_id = :uid AND account_shares.permission IN (:permissions))",
             uid: user.id, permissions: AccountShare::ANNOTATE_PERMISSIONS)
      .distinct
  }

  # Accounts that count in a user's financial calculations
  scope :included_in_finances_for, ->(user) {
    left_joins(:account_shares)
      .where(
        "accounts.owner_id = :uid OR " \
        "(account_shares.user_id = :uid AND account_shares.include_in_finances = true)",
        uid: user.id
      )
      .distinct
  }

  # People paste whole URLs ("https://www.tbank.ru/") into the domain field,
  # but the Brandfetch logo URL needs the bare host ("tbank.ru").
  normalizes :institution_domain, with: ->(value) { normalize_institution_domain(value) }
  # No dependent: option; before_destroy captures IDs, after_destroy_commit moves statements back to inbox.
  has_many :account_statements

  delegated_type :accountable, types: Accountable::TYPES, dependent: :destroy
  delegate :subtype, to: :accountable, allow_nil: true

  # Writer for subtype that delegates to the accountable, allowing forms to set
  # subtype directly on the account.
  #
  # On create the accountable is not built yet, and the chosen subtype is easy to
  # drop because of mass-assignment ordering. Two cases:
  #
  #   1. `subtype` is applied while `accountable_type` is already known — build
  #      the accountable from the delegated type so the value lands on it. The
  #      later `accountable_attributes` assignment (update_only) then updates that
  #      same record instead of building a new one.
  #   2. `subtype` is applied *before* `accountable_type` — this is the real
  #      controller path: strong-params `permit` preserves filter order, and
  #      `account_params` lists `:subtype` before `:accountable_type`, so the
  #      writer runs while the type (and thus `accountable_class`) is still
  #      unknown. We can't build the accountable yet, so stash the value and
  #      apply it from `accountable_type=` once the type is set.
  def subtype=(value)
    self.accountable = accountable_class.new if accountable.nil? && accountable_type.present?

    if accountable
      accountable.subtype = value
    else
      @deferred_subtype = value
    end
  end

  # Applies a subtype that arrived before the type was known (see `subtype=`
  # case 2). `super` resolves `accountable_type`/`accountable_class` first, then
  # the re-entrant `subtype=` builds the accountable and assigns the value.
  def accountable_type=(value)
    super

    if defined?(@deferred_subtype)
      pending = @deferred_subtype
      remove_instance_variable(:@deferred_subtype)
      self.subtype = pending
    end
  end

  accepts_nested_attributes_for :accountable, update_only: true

  # Account state machine
  aasm column: :status, timestamps: true do
    state :active, initial: true
    state :draft
    state :disabled
    state :pending_deletion

    # `timestamps: true` stamps disabled_at on entering disabled but never
    # clears it, so leaving disabled clears it here. A present disabled_at then
    # means the account was disabled, which the failed-deletion restore relies on.
    event :activate do
      transitions from: [ :draft, :disabled ], to: :active, after: :clear_disabled_at
    end

    event :disable do
      transitions from: [ :draft, :active ], to: :disabled
    end

    event :enable do
      transitions from: :disabled, to: :active, after: :clear_disabled_at
    end

    # An active or draft account can still carry a disabled_at from before enable
    # cleared it. Drop it here, so a failed deletion (below) stamps the failure
    # rather than reviving that stale date as the cutoff. A disabled account
    # keeps its date.
    event :mark_for_deletion do
      transitions from: [ :draft, :active ], to: :pending_deletion, after: :clear_disabled_at
      transitions from: :disabled, to: :pending_deletion
    end

    # The AASM way out of pending_deletion (destroy_later's enqueue failure
    # restores by update_column instead): Account#destroy fires it when the
    # destroy raises, so the account is visible again and can be re-deleted.
    # A separate event rather than widening `disable`, which would let every
    # `disable!`/`may_disable?` caller act on an account being deleted.
    #
    # disabled_at is the net-worth cutoff, so an account that was already
    # disabled keeps the date it was disabled; only one deleted from active or
    # draft is stamped at the failure.
    event :restore_after_failed_deletion do
      transitions from: :pending_deletion, to: :disabled, after: :keep_original_disabled_at
    end
  end

  class << self
    def normalize_institution_domain(value)
      host = value.to_s.strip.downcase
        .sub(%r{\A[a-z][a-z0-9+.-]*://}, "")
        .split(%r{[/?#]}, 2).first.to_s
        .sub(/:\d+\z/, "")
        .delete_prefix("www.")
      host.presence
    end

    def human_attribute_name(attribute, options = {})
      options = { moniker: Current.family&.moniker_label || "Family" }.merge(options)
      super(attribute, options)
    end

    def create_and_sync(attributes, skip_initial_sync: false, opening_balance_date: nil)
      attributes[:accountable_attributes] ||= {} # Ensure accountable is created, even if empty
      # Default cash_balance to balance unless explicitly provided (e.g., Crypto sets it to 0)
      attrs = attributes.dup
      attrs[:cash_balance] = attrs[:balance] unless attrs.key?(:cash_balance)
      account = new(attrs)
      # Presence is read from the raw value: a blank form field arrives as ""
      # and would convert to a very present-looking 0.
      raw_initial_balance = attributes.dig(:accountable_attributes, :initial_balance)
      initial_balance = raw_initial_balance.to_d if raw_initial_balance.present?

      transaction do
        account.save!

        # A loan's original principal was its balance on the day it was drawn
        # down, so that is where its opening anchor belongs. The form always
        # sends an opening balance date (defaulting to two years ago), so the
        # server cannot tell a deliberate one from the default: the loan's
        # start date wins. Loan validates start_date as on or before today, so
        # the anchor never lands after the reconciliation below. Entry rejects
        # a date on or before Entry.min_supported_date, so a loan started that
        # long ago keeps the form's date; its schedule still uses start_date.
        loan_start_date = account.accountable.start_date if initial_balance && account.loan?
        opening_balance_date = loan_start_date if loan_start_date && loan_start_date > Entry.min_supported_date

        manager = Account::OpeningBalanceManager.new(account)
        result = manager.set_opening_balance(
          balance: initial_balance || account.balance,
          date: opening_balance_date
        )
        raise result.error if result.error

        # When the opening balance differs from the entered current balance
        # (a loan created with its original principal), the opening anchor is
        # the account's only entry — the initial sync would recalculate
        # today's balance back to it, silently discarding what the user just
        # typed. Anchor today's balance too so both survive.
        #
        # Only when the opening anchor is on an earlier day: the opening date
        # is user-supplied and may be today, and a same-day reconciliation
        # would be matched to the opening anchor by date and overwrite it.
        # On its own date the opening balance wins.
        if initial_balance && initial_balance != account.balance && manager.opening_date < Date.current
          # An explicit reconciliation, not CurrentBalanceManager: for cash
          # accounts its transaction-adjustment strategy computes a zero delta
          # here (account.balance already holds the entered value) and would
          # only rewrite the opening anchor, leaving today's balance unanchored
          # for the first sync.
          reconciliation = Account::ReconciliationManager.new(account).reconcile_balance(
            balance: account.balance,
            date: Date.current
          )
          raise reconciliation.error_message unless reconciliation.success?
        end

        account.auto_share_with_family! if account.family.share_all_by_default?
      end

      # Skip initial sync for linked accounts - the provider sync will handle balance creation
      # after the correct currency is known
      account.sync_later unless skip_initial_sync
      account
    end


    def create_from_simplefin_account(simplefin_account, account_type, subtype = nil)
      # Respect user choice when provided; otherwise infer a sensible default
      # Require an explicit account_type; do not infer on the backend
      if account_type.blank? || account_type.to_s == "unknown"
        raise ArgumentError, "account_type is required when creating an account from SimpleFIN"
      end

      # Get the balance from SimpleFin
      balance = simplefin_account.current_balance || simplefin_account.available_balance || 0

      # SimpleFin returns negative balances for credit cards (liabilities)
      # But Sure expects positive balances for liabilities
      if account_type == "CreditCard" || account_type == "Loan"
        balance = balance.abs
      end

      # Calculate cash balance correctly for investment accounts
      cash_balance = balance
      if account_type == "Investment"
        begin
          calculator = SimplefinAccount::Investments::BalanceCalculator.new(simplefin_account)
          calculated = calculator.cash_balance
          cash_balance = calculated unless calculated.nil?
        rescue => e
          Rails.logger.warn(
            "Investment cash_balance calculation failed for " \
            "SimpleFin account #{simplefin_account.id}: #{e.class} - #{e.message}"
          )
          # Fallback to zero as suggested
          cash_balance = 0
        end
      end

      family = simplefin_account.simplefin_item.family
      attributes = {
        family: family,
        name: simplefin_account.name,
        balance: balance,
        cash_balance: cash_balance,
        currency: simplefin_account.currency,
        accountable_type: account_type,
        accountable_attributes: build_simplefin_accountable_attributes(simplefin_account, account_type, subtype),
        simplefin_account_id: simplefin_account.id
      }

      # Skip initial sync - provider sync will handle balance creation with correct currency
      create_and_sync(attributes, skip_initial_sync: true)
    end

    def create_from_enable_banking_account(enable_banking_account, account_type, subtype = nil)
      # Get the balance from Enable Banking
      balance = enable_banking_account.current_balance || 0

      # Enable Banking may return negative balances for liabilities
      # Sure expects positive balances for liabilities
      if account_type == "CreditCard" || account_type == "Loan"
        balance = balance.abs
      end

      cash_balance = balance

      family = enable_banking_account.enable_banking_item.family
      attributes = {
        family: family,
        name: enable_banking_account.name,
        balance: balance,
        cash_balance: cash_balance,
        currency: enable_banking_account.currency || "EUR"
      }

      accountable_attributes = {}
      accountable_attributes[:subtype] = subtype if subtype.present?

      # Skip initial sync - provider sync will handle balance creation with correct currency
      create_and_sync(
        attributes.merge(
          accountable_type: account_type,
          accountable_attributes: accountable_attributes
        ),
        skip_initial_sync: true
      )
    end

    def create_from_wise_account(wise_account)
      family = wise_account.wise_item.family

      account = create_and_sync(
        {
          family: family,
          name: wise_account.name || "Wise #{wise_account.currency}",
          balance: wise_account.current_balance || 0,
          cash_balance: wise_account.current_balance || 0,
          currency: wise_account.currency,
          accountable_type: "Depository",
          accountable_attributes: { subtype: wise_account.account_subtype }
        },
        skip_initial_sync: true
      )

      # When Sure imports a balance's whole history, it opens at 0 the day
      # before Wise opened it, not at today's balance two years back.
      if (opening_date = wise_account.opening_date)
        manager = Account::OpeningBalanceManager.new(account)
        date = [ opening_date, manager.oldest_entry_date&.prev_day ].compact.min
        result = manager.set_opening_balance(balance: 0, date: date)
        Rails.logger.warn "Account.create_from_wise_account - Opening balance kept for account #{account.id}: #{result.error}" if result.error
        # So later syncs may move it again (WiseAccount::Processor).
        if result.changes_made?
          wise_account.remember_opening_anchor!(account.valuations.opening_anchor.includes(:entry).first.entry)
        end
      end

      account
    end

    def create_from_coinbase_account(coinbase_account)
      # All Coinbase accounts are crypto exchange accounts
      family = coinbase_account.coinbase_item.family

      # Extract native balance and currency from Coinbase (e.g., USD, EUR, GBP)
      native_balance = coinbase_account.raw_payload&.dig("native_balance", "amount").to_d
      native_currency = coinbase_account.raw_payload&.dig("native_balance", "currency") || family.currency

      attributes = {
        family: family,
        name: coinbase_account.name,
        balance: native_balance,
        cash_balance: 0, # No cash - all value is in holdings
        currency: native_currency,
        accountable_type: "Crypto",
        accountable_attributes: {
          subtype: "exchange",
          tax_treatment: "taxable"
        }
      }

      # Skip initial sync - provider sync will handle balance/holdings creation
      create_and_sync(attributes, skip_initial_sync: true)
    end

    def create_from_binance_account(binance_account)
      create_from_crypto_exchange_account(binance_account, family: binance_account.binance_item.family)
    end

    def create_from_ibkr_account(ibkr_account)
      family = ibkr_account.ibkr_item.family
      default_name = if ibkr_account.ibkr_account_id.present?
        "Interactive Brokers (#{ibkr_account.ibkr_account_id})"
      else
        "Interactive Brokers"
      end

      attributes = {
        family: family,
        name: default_name,
        balance: 0,
        cash_balance: 0,
        currency: ibkr_account.currency.presence || family.currency,
        accountable_type: "Investment",
        accountable_attributes: {
          subtype: "brokerage"
        }
      }

      # Capture the created account in a variable
      create_and_sync(attributes, skip_initial_sync: true)
    end

    def create_from_trading212_account(trading212_account)
      family = trading212_account.trading212_item.family

      attributes = {
        family: family,
        name: trading212_account.name.presence || "Trading 212",
        balance: 0,
        cash_balance: 0,
        currency: trading212_account.currency.presence || family.currency,
        accountable_type: "Investment",
        accountable_attributes: {
          subtype: "brokerage"
        }
      }

      create_and_sync(attributes, skip_initial_sync: true)
    end

    def create_from_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" ],
      # The exchange subtype is the Crypto subtype that supports trades.
      "crypto" => [ "Crypto", "exchange", "Trade Republic Crypto" ]
    }.freeze

    def create_from_trade_republic_account(trade_republic_account)
      family = trade_republic_account.trade_republic_item.family
      accountable_type, subtype, default_name = TRADE_REPUBLIC_ACCOUNT_TYPES.fetch(trade_republic_account.kind)

      attributes = {
        family: family,
        name: trade_republic_account.name.presence || default_name,
        balance: 0,
        cash_balance: 0,
        currency: trade_republic_account.currency.presence || family.currency,
        accountable_type: accountable_type,
        accountable_attributes: {
          subtype: subtype
        }
      }

      create_and_sync(attributes, skip_initial_sync: true)
    end

    def create_from_kraken_account(kraken_account)
      create_from_crypto_exchange_account(kraken_account, family: kraken_account.kraken_item.family)
    end

    # Creates a manual Crypto account for a newly-selected CoinSpot account,
    # owned by the connection's family.
    def create_from_coinspot_account(coinspot_account)
      create_from_crypto_exchange_account(coinspot_account, family: coinspot_account.coinspot_item.family)
    end

    # Self-custody assets are wallets, not exchanges: no trade entry by hand,
    # and no cash side. The balance is written by the provider sync, which is
    # the only thing that knows what the chain says.
    def create_from_onchain_wallet_account(onchain_wallet_account)
      family = onchain_wallet_account.onchain_wallet_item.family

      create_and_sync(
        {
          family: family,
          name: onchain_wallet_account.display_name,
          balance: 0,
          cash_balance: 0,
          currency: onchain_wallet_account.currency.presence || family.currency,
          accountable_type: "Crypto",
          accountable_attributes: {
            subtype: "wallet",
            tax_treatment: "taxable"
          }
        },
        skip_initial_sync: true
      )
    end

    private

      def create_from_crypto_exchange_account(provider_account, family:)
        # The provider record carries the exchange's *reporting* currency -- Kraken
        # quotes everything in USD -- which says nothing about what the user
        # values the account in. The account's own currency is the one its
        # balance and holdings are shown in, so it is the family's; entries keep
        # whatever currency they were made in and convert at display, as on
        # every other account.
        provider_currency = provider_account.currency.presence || family.currency
        balance = (provider_account.current_balance || 0).to_d
        # With no rate the figure cannot be stated in the family currency, and
        # relabelling it would be wrong by the whole rate. Zero is honest: the
        # first sync writes the converted balance minutes later, and the
        # opening anchor is zeroed below regardless.
        balance = convert_provider_balance(balance, from: provider_currency, to: family.currency) || 0

        attributes = {
          family: family,
          name: provider_account.name,
          balance: balance,
          cash_balance: 0,
          currency: family.currency,
          accountable_type: "Crypto",
          accountable_attributes: {
            subtype: "exchange",
            tax_treatment: "taxable"
          }
        }

        # An exchange account's ledger is imported from inception, so it opens at
        # zero. Without this it inherits create_and_sync's default: an opening
        # balance equal to what the account is worth *today*, dated two years ago
        # -- so an exchange older than that imports its whole history on top of
        # its present value, and every entry before the anchor sits ahead of its
        # own opening balance.
        #
        # Through the manager, not set_opening_anchor_balance: that queues a
        # sync, which is what skip_initial_sync below just declined. Running
        # before the provider link exists, it would see one zero anchor and no
        # entries and write that zero over the balance set here.
        #
        # Both in one transaction: creation commits on its own, so a failure
        # while zeroing the anchor would otherwise leave an account behind
        # carrying today's balance as its opening one, and the retry would
        # create a second.
        account = nil
        transaction do
          account = create_and_sync(attributes, skip_initial_sync: true)
          result = Account::OpeningBalanceManager.new(account).set_opening_balance(balance: 0)
          raise result.error if result.error
        end

        account
      end

      def convert_provider_balance(amount, from:, to:)
        return amount if from == to || amount.zero?

        Money.new(amount, from).exchange_to(to).amount
      rescue Money::ConversionError
        nil
      end

      def build_simplefin_accountable_attributes(simplefin_account, account_type, subtype)
        attributes = {}
        attributes[:subtype] = subtype if subtype.present?

        # Set account-type-specific attributes from SimpleFin data
        case account_type
        when "CreditCard"
          # For credit cards, available_balance often represents available credit
          if simplefin_account.available_balance.present? && simplefin_account.available_balance > 0
            attributes[:available_credit] = simplefin_account.available_balance
          end
        when "Loan"
          # For loans, we might get additional data from the raw_payload
          # This is where loan-specific information could be extracted if available
          # Currently we don't have specific loan fields from SimpleFin protocol
        end

        attributes
      end
  end

  def institution_name
    read_attribute(:institution_name).presence || provider&.institution_name
  end

  def institution_domain
    # Normalized on read too, so domains saved before normalization existed still resolve a logo.
    self.class.normalize_institution_domain(read_attribute(:institution_domain)) || provider&.institution_domain
  end

  def manual_crypto_exchange?
    accountable_type == "Crypto" &&
      accountable&.subtype == "exchange" &&
      manual?
  end

  # Only an account linked to a goal can hold a goal pledge, so callers use
  # this to skip pledge reconciliation for every other account.
  def linked_to_goal?
    goal_accounts.exists?
  end

  # True when the account has no live sync provider attached. Mirrors the
  # `Account.manual` scope so per-instance checks don't drift from the query.
  def manual?
    account_providers.none? &&
      plaid_account_id.blank? &&
      simplefin_account_id.blank?
  end

  # Default GoalPledge kind for this account. Manual accounts get
  # `manual_save` (resolves on the next valuation), live-synced accounts
  # get `transfer` (resolves when the synced deposit posts). Keeps the
  # decision in one place so the new-pledge controller / preview helper
  # can't disagree on what they're going to save.
  def default_pledge_kind
    # Investment and crypto accounts never use manual_save: a positive valuation
    # delta there is usually a market move, not a deposit, and would false-match
    # a pledge. They resolve on transfer (cash-inflow) entries only.
    manual? && balance_type != :investment ? "manual_save" : "transfer"
  end

  # Total fixed earmark this account currently has reserved across every goal
  # still holding its money (unallocated/whole-balance links reserve no fixed
  # slice). Mirrors Budget#allocated_spending. Scoped to Goal::RELEASED_STATES
  # so this and Goal.pooled_allocations_for never disagree — if they did,
  # free_to_earmark would contradict the figures the goals themselves show.
  def goal_earmarked_total
    GoalAccount.joins(:goal)
               .where(account_id: id)
               .where.not(allocated_amount: nil)
               .where.not(goals: { state: Goal::RELEASED_STATES })
               .sum(:allocated_amount)
               .to_d
  end

  # Headroom left to earmark toward goals before fixed allocations exceed the
  # balance. Negative means the account is over-earmarked. Intended to back a
  # non-blocking over-allocation warning (UI is a follow-up). Mirrors
  # Budget#available_to_allocate.
  def free_to_earmark
    balance.to_d - goal_earmarked_total
  end

  # Marks the account pending_deletion and enqueues DestroyJob. If the enqueue
  # fails, the account goes back to the status it had, so it is not left hidden
  # from every list with no job coming to delete it. Mirrors DestroyableLater,
  # except that the claim is made under a row lock (see below).
  #
  # ApplicationJob defers enqueues until commit, so perform_later inside a
  # transaction returns before the push is tried. The enqueue therefore runs
  # once every open transaction has committed: immediately when there is none,
  # so the caller sees the outcome, and after the outer commit for a caller that
  # holds one (the relink cleanup), when the push really happens. A rolled-back
  # outer transaction undoes the mark and never enqueues.
  #
  # The prior status is read and the mark made under a row lock, which reloads
  # the account first. A second request for the same account (a double submit)
  # waits for the first to commit, sees pending_deletion and raises
  # AASM::InvalidTransition before it captures a status or schedules an
  # enqueue, so a restore only ever undoes the mark its own call made. Callers
  # pass a freshly loaded record: lock! refuses one with unsaved changes.
  #
  # Returns the job, or false when the enqueue was rejected. Inside an outer
  # transaction the enqueue has not run yet, so it returns nil.
  def destroy_later
    previous_status = with_lock do
      status.tap { mark_for_deletion! }
    end

    enqueued = nil
    ActiveRecord.after_all_transactions_commit do
      enqueued = enqueue_destroy_job(restoring: previous_status)
    end
    enqueued
  end

  # Override destroy to handle error recovery for accounts
  def destroy
    super
  rescue ActiveRecord::Deadlocked
    # DestroyJob retries a deadlock, so the account stays pending_deletion (and
    # out of the user's reach) until it gives up and restores it.
    raise
  rescue => e
    # An error after the delete committed leaves a frozen record to restore.
    restore_after_failed_destroy unless destroyed?
    raise e
  end

  # Leaves the account disabled so it stays visible and can be deleted again.
  # DestroyJob's scheduled_for_deletion reset is for provider items; accounts
  # track deletion in `status`.
  #
  # Mirrors the restore_after_failed_deletion and disable events, but written
  # directly: an unrelated validation (an owner who has since left the family,
  # say) must not leave the account hidden in pending_deletion or replace the
  # destroy error with its own. Only while the row still holds the status this
  # record saw, so a newer write (another worker's restore the user has since
  # re-enabled, say) is not overwritten.
  def restore_after_failed_destroy
    return unless may_restore_after_failed_deletion? || may_disable?

    restored = {
      status: "disabled",
      disabled_at: (disabled_at_in_database if pending_deletion?) || Time.current,
      updated_at: Time.current
    }
    return unless Account.where(id: id, status: status_in_database).update_all(restored) == 1

    assign_attributes(restored)
    clear_attribute_changes(restored.keys)
  end

  def current_holdings_total
    # A holding with no exchange rate is left out rather than counted 1:1.
    @current_holdings_total ||= current_holdings.sum { |h| h.amount_in_account_currency(unconvertible: 0) }
  end

  def current_holdings
    if holdings.where.not(account_provider_id: nil).exists?
      closed_provider_ids = account_providers.where(provider_type: "SimplefinAccount").includes(:provider).filter_map do |link|
        link.id if link.provider.raw_holdings_payload == []
      end

      eligible_holdings = holdings.where.not(account_provider_id: [ nil, *closed_provider_ids ])
      eligible_holdings
        .where(date: eligible_holdings.maximum(:date))
        .where.not(qty: 0)
        .order(amount: :desc)
    else
      holdings
        .where(currency: currency)
        .where.not(qty: 0)
        .where(
          id: holdings.select("DISTINCT ON (security_id) id")
                      .where(currency: currency)
                      .order(:security_id, date: :desc)
        )
        .order(amount: :desc)
    end
  end

  def latest_provider_holdings_snapshot_date
    holdings.where.not(account_provider_id: nil).maximum(:date)
  end

  def start_date
    first_entry_date = entries.minimum(:date) || Date.current
    first_entry_date - 1.day
  end

  def lock_saved_attributes!
    super
    accountable.lock_saved_attributes!
  end

  def first_valuation
    entries.valuations.order(:date).first
  end

  def first_valuation_amount
    first_valuation&.amount_money || balance_money
  end

  # Get short version of the subtype label
  def short_subtype_label
    accountable_class.short_subtype_label_for(subtype) || accountable_class.display_name
  end

  # Get long version of the subtype label
  def long_subtype_label
    accountable_class.long_subtype_label_for(subtype) || accountable_class.display_name
  end

  def supports_default?
    depository? || credit_card?
  end

  def eligible_for_transaction_default?
    supports_default? && active? && !linked?
  end

  # Determines if this account supports manual trade entry
  # Investment accounts always support trades; Crypto only if subtype is "exchange"
  def supports_trades?
    return true if investment?
    return accountable.supports_trades? if crypto? && accountable.respond_to?(:supports_trades?)
    false
  end

  def traded_standard_securities
    Security.where(id: holdings.select(:security_id))
            .standard
            .distinct
            .order(:ticker)
  end

  NegativePosition = Data.define(:security, :first_date, :lowest_qty)

  # Securities whose calculated position dropped below zero on some day, for
  # example after a sale without its purchase or after deleting a purchase.
  # The account status (Account::HealthStatus) shows them instead of hiding the gap.
  # Linked accounts are left out entirely: their provider's holdings are the
  # truth, so a negative quantity there (reported, or carried back by the
  # reverse calculator) is a short position, not missing data.
  def negative_positions
    return [] if linked? || balance_type != :investment

    rows = holdings
      .joins(:security)
      .merge(Security.standard)
      .where(account_provider_id: nil)
      .where("holdings.qty < 0")
      .group(:security_id)
      .pluck(:security_id, Arel.sql("MIN(holdings.date)"), Arel.sql("MIN(holdings.qty)"))
    return [] if rows.empty?

    securities = Security.where(id: rows.map(&:first)).index_by(&:id)
    rows.map { |security_id, first_date, lowest_qty| NegativePosition.new(securities[security_id], first_date, lowest_qty) }
        .sort_by { |position| [ position.first_date, position.security.ticker, position.security.id ] }
  end

  # The balance type determines which "component" of balance is being tracked.
  # This is primarily used for balance related calculations and updates.
  #
  # "Cash" = "Liquid"
  # "Non-cash" = "Illiquid"
  # "Investment" = A mix of both, including brokerage cash (liquid) and holdings (illiquid)
  def balance_type
    case accountable_type
    when "Depository", "CreditCard"
      :cash
    when "Property", "Vehicle", "OtherAsset", "Loan", "OtherLiability"
      :non_cash
    when "Investment", "Crypto"
      :investment
    else
      raise "Unknown account type: #{accountable_type}"
    end
  end

  # Whether the activity feed hides balance updates unless asked to show them.
  #
  # A linked account gets one from almost every daily sync, and users can't add
  # their own there, so they bury the transactions they sit between. Property,
  # vehicle, loan and other non-cash accounts are valued by those entries, so
  # they keep showing them.
  def hides_balance_updates_by_default?
    linked? && balance_type != :non_cash
  end

  def owned_by?(user)
    user.present? && owner_id == user.id
  end

  def shared_with?(user)
    return false if user.nil?

    owned_by?(user) ||
      if account_shares.loaded?
        account_shares.any? { |s| s.user_id == user.id }
      else
        account_shares.exists?(user: user)
      end
  end

  def shared?
    account_shares.any?
  end

  def permission_for(user)
    return :owner if owned_by?(user)
    account_shares.find_by(user: user)&.permission&.to_sym
  end

  def share_with!(user, permission: "read_only", include_in_finances: true)
    account_shares.create!(user: user, permission: permission, include_in_finances: include_in_finances)
  end

  def unshare_with!(user)
    account_shares.where(user: user).destroy_all
  end

  def auto_share_with_family!
    # Guests get read_only, everyone else read_write. This mirrors
    # Family#auto_share_existing_accounts_with so a guest's permission on an
    # account is the same whether they joined before or after it was created.
    records = family.users.where.not(id: owner_id).pluck(:id, :role).map do |user_id, role|
      { account_id: id, user_id: user_id,
        permission: role == "guest" ? "read_only" : "read_write",
        include_in_finances: true, created_at: Time.current, updated_at: Time.current }
    end

    AccountShare.insert_all(records, unique_by: %i[account_id user_id]) if records.any?
  end

  private
    # [date, signed amount in account currency] for each scheduled entry that
    # contributes to the projection.
    def scheduled_entry_flows
      @scheduled_entry_flows ||= if balance_type == :non_cash && accountable_type != "Loan"
        []
      else
        entries.excluding_pending.excluding_split_parents
          .where(entryable_type: [ "Transaction", "Trade" ])
          .where("entries.date > ?", Date.current)
          .includes(:entryable)
          .filter_map { |entry| (amount = convert_scheduled_entry_amount(entry)) && [ entry.date, amount ] }
      end
    end

    # Converts a scheduled entry's amount into this account's currency, signed
    # the same way flows_for_date treats it (see Balance::BaseCalculator).
    # Returns nil when the entry should not contribute -- a Buy/Sell trade
    # (moves value between cash and holdings, not into/out of the account) or
    # an unconvertible currency pair. Dropping the latter instead of using the
    # raw, unconverted amount matches Balance::SyncCache#converted_entries,
    # which drops the same entry outright once it materializes (see #1143) --
    # a projection that doesn't drop it would disagree with the balance it's
    # supposed to preview.
    def convert_scheduled_entry_amount(entry)
      return nil if entry.entryable_type == "Trade" && entry.entryable.qty.nonzero?

      custom_rate = entry.entryable.exchange_rate if entry.entryable.respond_to?(:exchange_rate)
      converted = begin
        entry.amount_money.exchange_to(currency, date: entry.date, custom_rate: custom_rate).amount
      rescue Money::ConversionError
        return nil
      end

      asset? ? -converted : converted
    end

    # perform_later raises (the Sidekiq adapter re-raises RedisClient errors) or
    # returns false (ActiveJob::EnqueueError). Either way the status goes back.
    def enqueue_destroy_job(restoring:)
      enqueued = begin
        DestroyJob.perform_later(self)
      rescue StandardError
        restore_status_after_failed_enqueue(restoring)
        raise
      end

      # Match false exactly, as DestroyableLater does: a bare mock of
      # perform_later returns nil, which is not a rejected enqueue.
      restore_status_after_failed_enqueue(restoring) if enqueued == false
      enqueued
    end

    # The row lock covers only the mark, and the push runs after commit, so
    # another request may have written a newer status by now (toggle_active
    # waiting on the lock, say). Undo the mark only while the row still holds
    # it. A direct write, because AASM has no event back to the prior status and
    # the restore must not fail on an unrelated validation and mask the error.
    def restore_status_after_failed_enqueue(restoring)
      restored = Account.where(id: id, status: "pending_deletion").update_all(status: restoring)
      self.status = restoring if restored == 1
      clear_attribute_changes([ :status ])
    end

    def assign_default_owner
      return if owner.present?

      if Current.user.present? && Current.user.family_id == family_id
        self.owner = Current.user
      else
        # `id` breaks ties on `created_at`. Two users of the same role can share
        # a timestamp (they are created in one transaction, or the column is
        # backfilled), and ordering on `created_at` alone leaves the winner to
        # the query plan — so the same family can get a different default owner
        # from one call to the next.
        self.owner =
          family&.users&.where(role: "admin")&.order(:created_at, :id)&.first ||
          family&.users&.where(role: "super_admin")&.order(:created_at, :id)&.first ||
          family&.users&.order(:created_at, :id)&.first
      end
    end

    def owner_belongs_to_family
      owner_user = User.lock.find_by(id: owner_id)
      return if owner_user&.family_id == family_id

      errors.add(:owner, :invalid, message: "must belong to the same family as the account")
    end

    def cost_tag_in_family
      return if family && accountable.cost_tag_in?(family)

      errors.add(:base, :cost_tag_other_family)
    end

    # AASM transition callbacks run after the timestamp is set and before the
    # state is saved, so both land in the event's own save.
    def clear_disabled_at
      self.disabled_at = nil
    end

    def keep_original_disabled_at
      self.disabled_at = disabled_at_in_database if disabled_at_in_database.present?
    end

    def capture_account_statement_ids_to_move
      @statement_ids_to_move = account_statements.ids
    end

    def move_account_statements_to_inbox
      statement_ids = Array(@statement_ids_to_move).compact
      return if statement_ids.empty?

      # Bypass callbacks deliberately: the account was destroyed, so linked statements need a direct inbox move.
      AccountStatement.where(id: statement_ids).update_all(
        account_id: nil,
        review_status: "unmatched",
        match_confidence: nil,
        updated_at: Time.current
      )
    end

    def cleanup_transfers
      transaction_ids = entries.where(entryable_type: "Transaction").pluck(:entryable_id)

      transfers = Transfer.where(inflow_transaction_id: transaction_ids).or(Transfer.where(outflow_transaction_id: transaction_ids))
                         .includes(inflow_transaction: { entry: { account: :family } }, outflow_transaction: { entry: { account: :family } })

      transfers.find_each(&:destroy!)
    end
end