Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
21.4 KB
Raw Blame
module TransactionsHelper
  # @param exclude [Array<String>] filter keys to leave out (e.g. the account
  #   tab doesn't apply to the account activity feed, which is already scoped
  #   to one account)
  # @param balance_updates [Boolean] offer the filter that shows a linked
  #   account's synced balance updates (account activity feed only)
  # @return [Array<Hash>] the filters offered above the transaction list, each
  #   with the key its partial is named for, a translated label and an icon
  def transaction_search_filters(exclude: [], balance_updates: false)
    filters = [
      { key: "account_filter", label: t("transactions.search.filters.account"), icon: "layers" },
      { key: "date_filter", label: t("transactions.search.filters.date"), icon: "calendar" },
      { key: "type_filter", label: t("transactions.search.filters.type"), icon: "tag" },
      { key: "status_filter", label: t("transactions.search.filters.status"), icon: "clock" },
      { key: "amount_filter", label: t("transactions.search.filters.amount"), icon: "hash" },
      { key: "category_filter", label: t("transactions.search.filters.category"), icon: "shapes" },
      { key: "tag_filter", label: t("transactions.search.filters.tag"), icon: "tags" },
      { key: "merchant_filter", label: t("transactions.search.filters.merchant"), icon: "store" },
      { key: "ai_filter", label: t("transactions.search.filters.ai"), icon: "sparkles" },
      { key: "attachment_filter", label: t("transactions.search.filters.attachment"), icon: "paperclip" }
    ]

    if manual_reconciliation_filter_available?
      filters.insert(4, { key: "reconcile_status_filter", label: t("transactions.search.filters.reconcile_status"), icon: "check-circle" })
    end

    if balance_updates
      filters << { key: "balance_updates_filter", label: t("transactions.search.filters.balance_updates"), icon: "scale" }
    end

    filters.reject { |filter| exclude.include?(filter[:key]) }
  end

  # Whether the reconciliation filter is worth offering. The setting alone is
  # not enough: the filter only matches manual accounts, so it would return an
  # empty list for a user with no accessible manual account.
  def manual_reconciliation_filter_available?
    Current.family&.manual_reconciliation? &&
      (Current.user ? Current.user.accessible_accounts.manual.exists? : Current.family.accounts.manual.exists?)
  end

  # @param label [String] a stored investment_activity_label such as "Sweep In"
  # @return [String] its name in the current locale, or the label itself when
  #   it has no translation
  def investment_activity_label_name(label)
    t("transactions.activity_labels.#{label.parameterize(separator: "_")}", default: label)
  end

  # @param filter [Hash] one entry from transaction_search_filters
  # @return [String] the partial that renders that filter's controls
  def get_transaction_search_filter_partial_path(filter)
    "transactions/searches/filters/#{filter[:key]}"
  end

  # @return [Hash] the filter shown when the user has not picked one
  def get_default_transaction_search_filter
    transaction_search_filters[0]
  end

  # Shared between the transactions page and the account activity feed's
  # amount filter badge, so the label doesn't drift out of sync with the
  # options offered in filters/_amount_filter.html.erb.
  # @param operator [String, nil] "equal", "greater" or "less"
  # @return [String] the translated operator label
  def transaction_amount_operator_label(operator)
    case operator
    when "equal" then t("transactions.searches.search.equal_to")
    when "greater" then t("transactions.searches.search.greater_than")
    when "less" then t("transactions.searches.search.less_than")
    else operator.to_s
    end
  end

  # A split child is only folded under its parent when the user asked for
  # grouping and the current view is rendering grouped.
  #
  # @param entry [Entry] the entry being rendered
  # @param params_grouped [String, nil] the grouped param as it arrived
  # @return [Boolean] whether to render this entry inside its split group
  def in_split_group?(entry, params_grouped)
    entry.split_child? && Current.user.show_split_grouped? && params_grouped == "true"
  end

  # Single source of truth for how each reconciled_status renders — used by
  # both the transaction row/detail badge (_reconcile_badge.html.erb) and the
  # bulk-reconcile selection-bar menu (_selection_bar.html.erb), so the two
  # can't silently drift out of sync.
  RECONCILE_STATUS_PRESENTATION = {
    "unreconciled" => { tone: :neutral, icon: "circle", text_class: "text-secondary" },
    "cleared" => { tone: :warning, icon: "circle-dot", text_class: "text-warning" },
    "reconciled" => { tone: :success, icon: "check-circle", text_class: "text-success" }
  }.freeze

  def reconcile_status_tone(status)
    RECONCILE_STATUS_PRESENTATION.fetch(status, RECONCILE_STATUS_PRESENTATION["unreconciled"])[:tone]
  end

  def reconcile_status_icon(status)
    RECONCILE_STATUS_PRESENTATION.fetch(status, RECONCILE_STATUS_PRESENTATION["unreconciled"])[:icon]
  end

  # Foreground token for the compact, icon-only indicator rendered in the
  # transaction list row, where there is no room for a labelled pill.
  def reconcile_status_text_class(status)
    RECONCILE_STATUS_PRESENTATION.fetch(status, RECONCILE_STATUS_PRESENTATION["unreconciled"])[:text_class]
  end

  # Files whose content shapes a cached transaction row; see
  # transaction_row_cache_key.
  TRANSACTION_ROW_SOURCES = %w[
    app/views/transactions/_transaction.html.erb
    app/views/transactions/_transaction_category.html.erb
    app/views/transactions/_transfer_match.html.erb
    app/views/categories/_*.html.erb
    app/views/tags/_*.html.erb
    app/views/investment_activity/_*.html.erb
    app/helpers/transactions_helper.rb
    app/helpers/categories_helper.rb
    app/components/DS/*.{rb,html.erb}
    config/locales/**/*.yml
  ].freeze

  TRANSACTION_ROW_SOURCES_DIGEST = Digest::SHA256.hexdigest(
    TRANSACTION_ROW_SOURCES.flat_map { |pattern| Dir[Rails.root.join(pattern).to_s] }.sort.map { |file| File.read(file) }.join
  ).first(16)

  # Fragment cache key for one row of the transactions list. Everything the
  # row shows or branches on is part of the key, so any change renders the
  # row fresh:
  #
  # - the records it reads (entry, transaction, tags, merchant, transfer and
  #   its other leg, whose kind and category an inflow row depends on, the
  #   security a brokerage activity shows a logo for)
  # - the displayed attributes of the accounts and categories it shows, and
  #   whether an account supports trades (a crypto account's subtype); their
  #   record versions would change on every balance sync or category pick
  # - per-user or per-request state (locale, user, family display settings,
  #   whether the user may annotate the account or see the counterpart,
  #   whether the entry is a split parent, grouped rendering, view context)
  # - a digest of the row's templates, the helpers and DS components it
  #   renders and the locale files (TRANSACTION_ROW_SOURCES), plus the image
  #   build or app version, so a deploy with new markup or translations never
  #   serves old rows, also for source builds without BUILD_COMMIT_SHA; skip_digest is on because the ERB
  #   dependency tracker cannot digest DS::* components (see
  #   account_sidebar_tabs)
  # - the Brandfetch settings that shape logo URLs
  #
  # Add a file to TRANSACTION_ROW_SOURCES when the row starts rendering it.
  def transaction_row_cache_key(entry, view_ctx:, in_split_group:)
    transaction = entry.entryable
    transfer = transaction.transfer
    outflow_leg = transaction.transfer_as_outflow.present?
    counterpart = transfer && (outflow_leg ? transfer.to_account : transfer.from_account)
    other_leg = transfer && (outflow_leg ? transfer.inflow_transaction : transfer.outflow_transaction)
    split_parent = @split_parent_entry_ids ? @split_parent_entry_ids.include?(entry.id) : entry.split_parent?
    account_key = ->(account) { account && [ account.id, account.name, account.accountable_type, account.supports_trades? ] }
    category_key = ->(category) { category && [ category.id, category.name, category.color, category.lucide_icon ] }

    [
      "transaction_row",
      TRANSACTION_ROW_SOURCES_DIGEST,
      ENV["BUILD_COMMIT_SHA"].presence || (@app_version ||= Sure.version.to_s),
      I18n.locale,
      Current.user&.id,
      Current.family&.currency,
      Current.family&.locale,
      view_ctx,
      in_split_group,
      split_parent,
      # The "Transfer?" hint is drawn inside the cached row.
      @transfer_hint_transaction_ids&.include?(transaction.id) || false,
      can_annotate_account?(entry.account),
      Current.family&.manual_reconciliation?,
      can_reconcile_account?(entry.account),
      (manual_account?(entry.account) if transfer.present?),
      counterpart.present? && @accessible_account_ids&.include?(counterpart.id),
      Setting.brand_fetch_logo_size,
      Setting.brand_fetch_client_id.presence&.then { |id| Digest::SHA256.hexdigest(id) },
      entry.cache_key_with_version,
      transaction.cache_key_with_version,
      account_key.(entry.account),
      category_key.(transaction.category),
      transaction.merchant&.cache_key_with_version,
      transaction.tags.map(&:cache_key_with_version).sort,
      transfer&.cache_key_with_version,
      other_leg&.cache_key_with_version,
      account_key.(counterpart),
      (category_key.(other_leg.category) if transfer && !outflow_leg),
      transaction.activity_security&.cache_key_with_version
    ]
  end

  # Name of the category an automatic assignment recorded — falls back to a
  # generic label when that category has since been deleted.
  def category_provenance_category_name(transaction, provenance)
    return transaction.category&.name if provenance.current?

    Current.family.categories.find_by(id: provenance.category_id)&.name ||
      t("transactions.category_provenance.deleted_category")
  end

  # Whether the current user may annotate (e.g. re-tag) entries on this
  # account. Memoized per request so list rows don't query per row.
  def can_annotate_account?(account)
    return false unless Current.user

    @annotatable_account_ids ||= Account.annotatable_by(Current.user).pluck(:id).to_set
    @annotatable_account_ids.include?(account.id)
  end

  # Whether the current user may cycle the manual reconciliation status.
  # TransactionsController#reconcile requires write access (see
  # require_account_permission! in AccountAuthorizable), so the badge must
  # only be offered on accounts the user owns or holds full_control on --
  # otherwise the click is rejected and the status never advances. Matches
  # the "write" predicate rather than the annotate one, since reconciling is
  # not an annotation. Memoized per request so list rows don't query per row.
  def can_reconcile_account?(account)
    return false unless Current.user

    @reconcilable_account_ids ||= Account.writable_by(Current.user).pluck(:id).to_set
    @reconcilable_account_ids.include?(account.id)
  end

  # Memoized per request so reading the row cache key does not run one
  # account-provider query per transfer row.
  def manual_account?(account)
    return false unless account

    @manual_account_cache ||= {}
    @manual_account_cache.fetch(account.id) do
      @manual_account_cache[account.id] = account.manual?
    end
  end

  # A matched transfer cannot be bulk edited like a normal entry: its date,
  # category and merchant belong to the pair or to the outflow leg. The
  # checkbox is offered only where manual reconciliation is available, and
  # Edit then exposes the safe fields (name, notes, tags, reconciliation).
  def bulk_reconcilable_transfer?(entry)
    transaction = entry.entryable

    transaction&.transfer.present? &&
      Current.family&.manual_reconciliation? &&
      manual_account?(entry.account) &&
      can_reconcile_account?(entry.account)
  end

  # The dashboard drill-down filters by account id, so its filter chips name
  # the account rather than print the id. Memoized per request like the above.
  def transaction_filter_account_name(account_id)
    @transaction_filter_account_names ||= Current.user.accessible_accounts.pluck(:id, :name).to_h
    @transaction_filter_account_names.fetch(account_id, account_id)
  end

  # ---- Transaction extra details helpers ----
  # Returns a structured hash describing extra details for a transaction.
  # Input can be a Transaction or an Entry (responds_to :transaction).
  # Structure:
  #   {
  #     kind: :simplefin | :plaid | :raw,
  #     simplefin: { payee:, description:, memo: },
  #     plaid: { original_description:, payment_channel:, transaction_code: },
  #     provider_extras: [ { key:, value:, multiline: } ],
  #       multiline marks values the view should render in a <pre> block
  #       rather than inline opposite their label.
  #     raw: String (pretty JSON) — only set for :raw, where we have no
  #       structured rendering for the provider
  #   }
  def build_transaction_extra_details(obj)
    tx = obj.respond_to?(:transaction) ? obj.transaction : obj
    return nil unless tx.respond_to?(:extra) && tx.extra.present?

    extra = tx.extra

    if extra.is_a?(Hash) && extra["simplefin"].present?
      sf = extra["simplefin"]
      simple = {
        payee: sf.is_a?(Hash) ? sf["payee"].presence : nil,
        description: sf.is_a?(Hash) ? sf["description"].presence : nil,
        memo: sf.is_a?(Hash) ? sf["memo"].presence : nil
      }.compact

      extras = []
      if sf.is_a?(Hash) && sf["extra"].is_a?(Hash) && sf["extra"].present?
        sf["extra"].each do |k, v|
          extras.concat(provider_extra_rows(provider_extra_field_label(k), v))
        end
      end

      # Same rule as the Plaid branch below. SimpleFIN always writes a pending
      # flag, so a transaction carrying nothing else would otherwise open an
      # Additional details section with no details in it.
      return nil if simple.blank? && extras.blank?

      {
        kind: :simplefin,
        simplefin: simple,
        plaid: {},
        provider_extras: extras,
        raw: nil
      }
    elsif extra.is_a?(Hash) && extra["plaid"].present?
      plaid = extra["plaid"]
      simple = {
        original_description: plaid.is_a?(Hash) ? plaid["original_description"].presence : nil,
        payment_channel: plaid.is_a?(Hash) ? plaid["payment_channel"].presence : nil,
        transaction_code: plaid.is_a?(Hash) ? plaid["transaction_code"].presence : nil
      }.compact

      extras = []
      if plaid.is_a?(Hash)
        if plaid["payment_meta"].is_a?(Hash) && plaid["payment_meta"].present?
          plaid["payment_meta"].each do |k, v|
            extras.concat(provider_extra_rows(t("transactions.show.plaid_payment_meta_label", name: provider_extra_field_label(k)), v))
          end
        end

        if plaid["counterparties"].is_a?(Array) && plaid["counterparties"].present?
          plaid["counterparties"].each_with_index do |counterparty, index|
            extras.concat(provider_extra_rows(t("transactions.show.plaid_counterparty_label", index: index + 1), counterparty))
          end
        end
      end

      # Only show Additional details when there is something beyond pending flags
      return nil if simple.blank? && extras.blank?

      {
        kind: :plaid,
        simplefin: {},
        plaid: simple,
        provider_extras: extras,
        # No raw dump: the structured rows above already cover the payload, and
        # the only fields they omit (pending, pending_transaction_id) are what
        # the pending badge communicates.
        raw: nil
      }
    else
      {
        kind: :raw,
        simplefin: {},
        plaid: {},
        provider_extras: [],
        raw: pretty_json(extra)
      }
    end
  end

  # Flatten hashes into labeled rows; pretty-print remaining nested structures.
  #
  # `key` arrives already presentable — localized by the caller, or run through
  # provider_extra_field_label here. Nothing downstream reformats it, because a
  # composed label is part translation and part provider identifier and
  # `humanize` would lowercase the translated half.
  #
  # An empty value yields no row. A row with nothing opposite its label is noise,
  # and it made the extras non-blank, which defeated the guard that keeps an
  # empty Additional details section closed.
  def provider_extra_rows(key, value, depth: 0)
    value = value.reject { |item| blank_provider_extra?(item) } if value.is_a?(Array)
    return [] if blank_provider_extra?(value)

    label = key.to_s

    case value
    when Hash
      value.flat_map do |child_key, child_value|
        child = provider_extra_field_label(child_key)
        child_label = depth.zero? ? "#{label} · #{child}" : "#{label}.#{child}"
        provider_extra_rows(child_label, child_value, depth: depth + 1)
      end
    when Array
      if value.all? { |item| !item.is_a?(Hash) && !item.is_a?(Array) }
        [ provider_extra_row(label, value.join(", ")) ]
      else
        # Pass the raw value — provider_extra_row does the single encode. Handing
        # it a pretty_json string here would re-encode it into an escaped one-liner.
        [ provider_extra_row(label, value, multiline: true) ]
      end
    else
      [ provider_extra_row(label, value) ]
    end
  end

  # Builds one row for the view. The key arrives already presentable and is not
  # reformatted here, since a composed label is part translation and part
  # provider identifier.
  #
  # @param key [String] the label to show
  # @param value [Object] the provider value
  # @param multiline [Boolean] render in a block rather than opposite the label
  # @return [Hash] a row of { key:, value:, multiline: }
  def provider_extra_row(key, value, multiline: false)
    display = if multiline || value.is_a?(Hash) || value.is_a?(Array)
      pretty_json(value)
    else
      value
    end

    {
      key: key.to_s,
      value: display,
      multiline: multiline || value.is_a?(Hash) || value.is_a?(Array)
    }
  end

  # Provider field names are schema identifiers (reference_number,
  # confidence_level), so they get a translation where we know the field and
  # `humanize` otherwise — the set is open-ended and a provider can add to it
  # without us, which is better served by a readable fallback than a missing key.
  #
  # The key becomes part of an i18n lookup, so a blank or dotted one would be read
  # as a scope rather than a field name: "" resolves to the whole
  # provider_extra_fields hash, which then rendered as the label. Those fall back
  # to the humanized key, as does any lookup that comes back as something other
  # than a string.
  def provider_extra_field_label(key)
    fallback = key.to_s.humanize
    return fallback if key.to_s.strip.empty? || key.to_s.include?(".")

    label = t("transactions.show.provider_extra_fields.#{key}", default: fallback)
    label.is_a?(String) ? label : fallback
  end

  # Nothing worth a row: nil, an empty or whitespace-only string, or an empty
  # collection. false and 0 are real values a provider meant to report, so they stay.
  #
  # @param value [Object] a provider value
  # @return [Boolean] whether the value has nothing to show
  def blank_provider_extra?(value)
    case value
    when nil then true
    when String then value.strip.empty?
    when Array, Hash then value.empty?
    else false
    end
  end

  # Provider payloads are arbitrary JSON, so anything that cannot be generated
  # falls back to its string form rather than raising in a view.
  #
  # @param value [Object] any provider value
  # @return [String] indented JSON, or the value's string form
  def pretty_json(value)
    JSON.pretty_generate(value)
  rescue StandardError
    value.to_s
  end

  # Options for the convert-to-trade security picker: label, id and the data
  # its price check reads. That check compares against the price the
  # transaction implies, so only a positive quote converted to `currency`
  # carries data-price-cents. Without a rate the quote is still shown, under its own
  # currency. The securities share one rate lookup per quote currency and day.
  def convert_to_trade_security_options(securities, currency)
    rates = {}
    securities.map do |security|
      price = security.current_price_in(currency, rates: rates)
      shown_price = price || security.current_price
      label = security.ticker.to_s.dup
      label << " (#{format_money(shown_price)})" if shown_price
      label << " - #{security.name.truncate(25)}" if security.name.present?
      # Fractional cents are kept: a converted quote can be worth less than a
      # cent (1 JPY in USD), and a zero would make the check divide by zero.
      price_cents = price_cents_for_check(price)
      [ label, security.id, { "data-price-cents" => price_cents, "data-ticker" => security.ticker } ]
    end
  end

  # @param price [Money, nil] a quote in the transaction's currency
  # @return [Integer, Float, nil] the quote in cents, whole cents as an integer
  def price_cents_for_check(price)
    return unless price&.amount&.positive?

    cents = price.amount.to_d * 100
    cents.frac.zero? ? cents.to_i : cents.to_f
  end

  # A pending transfer match as the viewer may see it from `transaction`'s
  # row. The accounts and transactions pages set @accessible_account_ids;
  # a view that does not, such as the turbo stream that redraws a match,
  # looks the viewer's accessible accounts up once per request.
  def pending_transfer_match(transaction)
    @transfer_match_visible_account_ids ||= (@accessible_account_ids || accessible_accounts.pluck(:id)).to_set
    Transfer::PendingMatch.new(transaction, visible_account_ids: @transfer_match_visible_account_ids)
  end
end