Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
67.5 KB
Raw Blame
class ReportsController < ApplicationController
  include Periodable

  SIGN_AGNOSTIC_EXPENSE_KINDS = %w[loan_payment investment_contribution].freeze

  # Bump when the body's markup changes, so a deploy never serves the old one.
  REPORT_BODY_CACHE_VERSION = 6
  # Every parameter the body is built from, as a background rebuild repeats
  # it and as part of the cache key: the period, the tag and entry filters,
  # the breakdown's sort and the trend chart's selection.
  REPORT_BODY_PARAMS = %i[
    period_type start_date end_date sort_by sort_direction filter_category_id filter_account_id
    filter_amount_min filter_amount_max filter_date_start filter_date_end trend_granularity
  ].freeze
  # The views warmed after each sync, as their URLs carry them.
  WARMED_PERIOD_TYPES = %i[monthly quarterly ytd last_6_months all_time].freeze

  # Allow API key authentication for exports (for Google Sheets integration)
  # Note: We run authentication_for_export which handles both session and API key auth
  skip_authentication only: :export_transactions
  before_action :authenticate_for_export, only: :export_transactions

  helper_method :filter_tags

  # The report body is served from PageCache: at once when a build exists, even
  # one from before the latest data (it is rebuilt in the background then), and
  # built while the member waits only the first time or on `refresh`.
  def index
    setup_report_period(show_flash: true)
    refresh = params[:refresh].present?
    served = PageCache.serve(
      report_body_cache_key,
      version: report_body_version,
      family: Current.family,
      user: Current.user,
      refresh: refresh,
      rebuild_later: -> { RebuildReportJob.perform_later(Current.user, report_query, I18n.locale.to_s) }
    ) { render_report_body }
    # A refresh is rebuilt above; drop it from the URL so reloading doesn't
    # rebuild again. A page too big to keep is shown as built instead, since
    # the redirect would only build it a second time.
    return redirect_to(reports_path(request.query_parameters.except("refresh"))) if refresh && served.kept

    @report = served.body
    @report_built_at = served.built_at
    @report_stale = served.stale
    @reports_sections = order_reports_sections(@report[:sections])

    @breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.reports"), nil ] ]
  end

  def print
    # The print view does not render the chart, so skip its bucket queries.
    setup_report_data(show_flash: false, include_trend: false)

    render layout: "print"
  end

  # Builds and caches the report body for `user` outside a request, so a
  # background job can have it ready before anyone opens Reports. `query` is
  # what the page's URL would carry (period_type, start_date, end_date,
  # filter_tag_ids). Returns whether it had to build the body: one already
  # built from the current data is left alone.
  # `locale` is the one the cached build was made in, when a request chose it
  # (a ?locale= or the browser's language); without it the member's own applies.
  def self.warm_body_cache(user:, query: {}, locale: nil)
    controller = new
    url_query = locale.present? ? query.merge(locale: locale) : query
    request = ActionDispatch::Request.new(Rack::MockRequest.env_for("/reports?#{url_query.to_query}"))
    request.routes = _routes
    controller.set_request!(request)
    controller.set_response!(make_response!(request))

    # Current memoizes the member's accounts, and Current.set doesn't clear
    # that, so it is reset around each member: a job warming several members
    # must never build one member's report from another's accounts. Only call
    # this outside a request.
    Current.reset
    Current.session = Session.new(user: user)
    # The member's locale and time zone, chosen as a request would choose them.
    controller.send(:switch_locale) do
      controller.send(:switch_timezone) { controller.send(:warm_report_body) }
    end
  ensure
    Current.reset
  end

  def update_preferences
    # `require` passes a scalar through, and indexing a String by key raises,
    # so a body whose `preferences` is not an object is refused here.
    return head :bad_request unless params[:preferences].is_a?(ActionController::Parameters)

    if Current.user.update_reports_preferences(preferences_params)
      head :ok
    else
      head :unprocessable_entity
    end
  end

  def export_transactions
    @period_type = requested_period_type
    @start_date = parse_date_param(:start_date) || default_start_date
    @end_date = parse_date_param(:end_date) || default_end_date

    # Validate and fix date range if end_date is before start_date
    # Don't show flash message since we're returning CSV data
    validate_and_fix_date_range(show_flash: false)

    @period = Period.custom(start_date: @start_date, end_date: @end_date)

    # Build monthly breakdown data for export
    @export_data = build_monthly_breakdown_for_export

    respond_to do |format|
      format.csv do
        csv_data = generate_transactions_csv
        send_data csv_data,
                  filename: "transactions_breakdown_#{@start_date.strftime('%Y%m%d')}_to_#{@end_date.strftime('%Y%m%d')}.csv",
                  type: "text/csv"
      end

      # Excel and PDF exports require additional gems (caxlsx and prawn)
      # Uncomment and install gems if needed:
      #
      # format.xlsx do
      #   xlsx_data = generate_transactions_xlsx
      #   send_data xlsx_data,
      #             filename: "transactions_breakdown_#{@start_date.strftime('%Y%m%d')}_to_#{@end_date.strftime('%Y%m%d')}.xlsx",
      #             type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      # end
      #
      # format.pdf do
      #   pdf_data = generate_transactions_pdf
      #   send_data pdf_data,
      #             filename: "transactions_breakdown_#{@start_date.strftime('%Y%m%d')}_to_#{@end_date.strftime('%Y%m%d')}.pdf",
      #             type: "application/pdf"
      # end
    end
  end

  def google_sheets_instructions
    # Re-build the params needed for the export URL
    base_params = {
      period_type: params[:period_type],
      start_date: params[:start_date],
      end_date: params[:end_date],
      sort_by: params[:sort_by],
      sort_direction: params[:sort_direction],
      filter_tag_ids: filter_tags.map(&:id).presence
    }.compact

    # The CSV URL the instructions tell people to add their API key to
    @csv_url = export_transactions_reports_url(base_params.merge(format: :csv))

    # This action will render `app/views/reports/google_sheets_instructions.html.erb`
    # It will render *inside* the modal frame.
  end

  def picker
    @period_type = requested_period_type
    @start_date = parse_date_param(:start_date) || Date.current.beginning_of_month
    @category_selection = category_selection
    @trend_granularity = trend_granularity
    render partial: "reports/period_picker", locals: {
      period_type: @period_type,
      start_date: @start_date
    }
  end

  private
    # A blank period_type (`?period_type=`) means the default, as report_query keys it.
    def requested_period_type
      params[:period_type].presence&.to_sym || :monthly
    end

    def setup_report_period(show_flash: false)
      @period_type = requested_period_type
      @start_date = parse_date_param(:start_date) || default_start_date
      @end_date = parse_date_param(:end_date) || default_end_date

      # Validate and fix date range if end_date is before start_date
      validate_and_fix_date_range(show_flash: show_flash)

      # Build the period
      @period = Period.custom(start_date: @start_date, end_date: @end_date)
      @previous_period = build_previous_period

      @tags = Current.family.tags.alphabetically
      @filter_tags = filter_tags

      # Trend chart selection. It scopes the chart only, not the report totals.
      # The page header draws it too, so it is read before the body is served.
      @category_selection = category_selection
      @trend_granularity = trend_granularity

      # Build navigation links for period switching
      @nav = build_period_navigation
    end

    def setup_report_data(show_flash: false, include_trend: true)
      setup_report_period(show_flash: show_flash)

      # Get aggregated data
      @income_statement = Current.family.income_statement(user: Current.user)
      @current_income_totals = @income_statement.income_totals(period: @period)
      @current_expense_totals = @income_statement.expense_totals(period: @period)

      @previous_income_totals = @income_statement.income_totals(period: @previous_period)
      @previous_expense_totals = @income_statement.expense_totals(period: @previous_period)

      # Calculate summary metrics
      @summary_metrics = build_summary_metrics

      # Build trend data (last 6 months)
      @trends_data = build_trends_data(income_statement: @income_statement)

      # Net worth metrics
      @net_worth_metrics = build_net_worth_metrics

      # Transactions breakdown
      @transactions = build_transactions_breakdown
      @category_trend = include_trend ? build_category_trend : nil

      @biggest_expenses_limit = Current.user.reports_biggest_expenses_limit
      @biggest_expenses = build_biggest_expenses(@biggest_expenses_limit)

      # Investment metrics
      @investment_metrics = build_investment_metrics

      # Spending vs normal (preview): this period against the year before it
      @spending_comparison = build_spending_comparison

      # Investment flows (contributions/withdrawals)
      @investment_flows = InvestmentFlowStatement.new(Current.family, user: Current.user).period_totals(period: @period)

      # Flags for view rendering
      @has_accounts = accessible_accounts.any?
    end

    # The report's figures, rendered: the exchange rate notes, the summary and
    # each section's content. Section order, which are collapsed and the
    # section frames are drawn when the page is served, so arranging the page
    # never invalidates it.
    def render_report_body
      setup_report_data(show_flash: false)
      html = ->(partial, locals) { render_to_string(partial: partial, locals: locals, formats: [ :html ]) }

      {
        notes: html.call("shared/exchange_rate_notes", { family: Current.family }),
        has_transactions: Current.family.transactions.any?,
        summary: html.call("reports/summary_dashboard", { metrics: @summary_metrics, period_type: @period_type }),
        sections: build_reports_sections.map do |section|
          section.except(:partial, :locals).merge(html: (html.call(section[:partial], section[:locals]) if section[:visible]))
        end
      }
    end

    def warm_report_body
      setup_report_period(show_flash: false)
      key = report_body_cache_key
      version = report_body_version
      return false if PageCache.current?(key, version: version, family: Current.family, user: Current.user)

      started_at = Time.current
      PageCache.write(key, render_report_body, version: version, family: Current.family, user: Current.user, started_at: started_at)
      true
    end

    def report_query
      query = params.permit(*REPORT_BODY_PARAMS, filter_tag_ids: [], trend_category_ids: []).to_h.symbolize_keys
      query[:filter_tag_ids] = filter_tags.map(&:id).sort if filter_tags.any?
      query.except!(:filter_tag_ids) if filter_tags.none?
      query[:trend_category_ids] = Array(query[:trend_category_ids]).sort if query[:trend_category_ids].present?
      query.except!(:trend_category_ids) if query[:trend_category_ids].blank?
      # The page opens on this month when no period is given; naming it keeps one
      # key for /reports and its warmed ?period_type=monthly build.
      query[:period_type] = "monthly" if query[:period_type].blank?
      query.compact_blank.sort.to_h
    end

    # Names the report whatever data it is built from: whose it is (family and
    # member: PageCache also enforces both on every read), the
    # member's settings that change its figures, and the period and filters as
    # the URL gave them. A default period ("this year") keeps its key from one
    # day to the next, so yesterday's build is served while today's is made.
    #
    # The accounts the member may see are part of the name, not the version: a
    # build from before a change of access is never served, even stale, so a
    # report can't show an account the member has just lost.
    def report_body_cache_key
      [
        "reports_body", REPORT_BODY_CACHE_VERSION, Current.family.id, Current.user.id, report_member_version,
        report_family_settings_version, I18n.locale,
        report_access_digest, Digest::SHA256.hexdigest(report_query.to_query),
        report_period_start_key
      ].join("/")
    end

    # A default period starts afresh each month, quarter or year, and the new
    # one is a different report, not a stale copy of the last, so its start is
    # part of the name. The end date isn't, so "this year" keeps its build from
    # one day to the next. All time's start moves whenever older history
    # arrives; that build is replaced in the background, not while the member
    # waits, so it's left out.
    def report_period_start_key
      @start_date unless @period_type == :all_time
    end

    def report_access_digest
      Digest::SHA256.hexdigest([
        accessible_accounts.map(&:id).sort.join(","),
        Current.user.finance_accounts.pluck(:id).sort.join(",")
      ].join("|"))
    end

    # The family's settings that change a report's figures or how it reads.
    # Part of the key, not the version: a build made under other settings is
    # never served, even while its replacement is still being built.
    def report_family_settings_version
      family = Current.family
      Digest::SHA256.hexdigest([
        family.currency, family.investment_contributions_as_spending, family.month_start_day, family.date_format,
        family.household_budget_enabled, family.personal_budgets, family.moniker
      ].join("|"))
    end

    # The member's settings that change a report's figures. Section order and
    # collapse state are left out: they are applied when the page is served.
    def report_member_version
      user = Current.user
      [ user.reports_biggest_expenses_limit, user.preview_features_enabled?, user.role ].join(",")
    end

    # Everything the body is drawn from: the family's data (a completed sync,
    # any entry, category, tag or tagging, account or budget change), exchange
    # rates, the dates the period resolves to and today's date. A build from a
    # different version is served stale and rebuilt.
    def report_body_version
      family = Current.family
      Digest::SHA256.hexdigest([
        family.build_cache_key("reports_body", invalidate_on_data_updates: true),
        family.entries_version,
        family.tags_version,
        family.holdings_version,
        ExchangeRate.updated_at_version,
        family.budgets.maximum(:updated_at)&.to_f,
        BudgetCategory.joins(:budget).where(budgets: { family_id: family.id }).maximum(:updated_at)&.to_f,
        accessible_accounts.map(&:updated_at).max&.to_f,
        @start_date, @end_date, Date.current
      ].join("|"))
    end

    def preferences_params
      # Only the reports keys are passed on; User#update_reports_preferences
      # drops any value that is not an array of keys, a hash of flags or an
      # offered limit.
      prefs = params.require(:preferences)
      {
        "reports_collapsed_sections" => prefs[:reports_collapsed_sections],
        "reports_section_order" => prefs[:reports_section_order],
        "reports_biggest_expenses_limit" => prefs[:reports_biggest_expenses_limit]
      }
    end

    def build_reports_sections
      all_sections = [
        {
          key: "net_worth",
          title: "reports.net_worth.title",
          partial: "reports/net_worth",
          locals: { net_worth_metrics: @net_worth_metrics },
          visible: accessible_accounts.any?,
          collapsible: true
        },
        {
          key: "trends_insights",
          title: "reports.trends.title",
          partial: "reports/trends_insights",
          locals: trend_section_locals,
          visible: @has_accounts,
          collapsible: true
        },
        {
          key: "spending_vs_normal",
          title: "reports.spending_vs_normal.title",
          partial: "reports/spending_vs_normal",
          locals: { comparison: @spending_comparison, start_date: @start_date, end_date: @end_date },
          visible: @has_accounts && @spending_comparison.present?,
          collapsible: true,
          preview: true
        },
        {
          key: "investment_performance",
          title: "reports.investment_performance.title",
          partial: "reports/investment_performance",
          locals: { investment_metrics: @investment_metrics },
          visible: @investment_metrics[:has_investments],
          collapsible: true
        },
        {
          key: "investment_flows",
          title: "reports.investment_flows.title",
          partial: "reports/investment_flows",
          locals: { investment_flows: @investment_flows },
          visible: @investment_metrics[:has_investments] && (@investment_flows.contributions.amount > 0 || @investment_flows.withdrawals.amount > 0),
          collapsible: true
        },
        {
          key: "transactions_breakdown",
          title: "reports.transactions_breakdown.title",
          partial: "reports/transactions_breakdown",
          locals: {
            transactions: @transactions,
            period_type: @period_type,
            start_date: @start_date,
            end_date: @end_date,
            filter_tags: filter_tags
          },
          visible: @has_accounts,
          collapsible: true
        },
        {
          key: "biggest_expenses",
          title: "reports.biggest_expenses.title",
          partial: "reports/biggest_expenses",
          locals: { expenses: @biggest_expenses },
          header_partial: "reports/biggest_expenses_limit",
          header_locals: { limit: @biggest_expenses_limit },
          visible: @has_accounts && @biggest_expenses.any?,
          collapsible: true
        }
      ]

      order_reports_sections(all_sections)
    end

    # Puts sections in the member's saved order. Kept apart from building them,
    # so a cached report is reordered when served rather than rebuilt.
    def order_reports_sections(all_sections)
      section_order = Current.user.reports_section_order
      ordered_sections = section_order.map do |key|
        all_sections.find { |s| s[:key] == key }
      end.compact

      # Add any new sections that aren't in the saved order (future-proofing)
      all_sections.each do |section|
        ordered_sections << section unless ordered_sections.include?(section)
      end

      ordered_sections
    end

    def validate_and_fix_date_range(show_flash: false)
      return unless @start_date > @end_date

      # Swap the dates to maintain user's intended date range
      @start_date, @end_date = @end_date, @start_date
      flash.now[:alert] = t("reports.invalid_date_range") if show_flash
    end

    def ensure_money(value)
      return value if value.is_a?(Money)
      # Value is numeric (BigDecimal or Integer) in dollars - pass directly to Money.new
      Money.new(value, Current.family.currency)
    end

    def parse_date_param(param_name)
      date_string = params[param_name]
      return nil if date_string.blank?

      Date.parse(date_string)
    rescue Date::Error
      nil
    end

    def default_start_date
      case @period_type
      when :monthly
        Date.current.beginning_of_month.to_date
      when :quarterly
        Date.current.beginning_of_quarter.to_date
      when :ytd
        Date.current.beginning_of_year.to_date
      when :last_6_months
        (Date.current.end_of_month + 1.day - 6.months).beginning_of_month.to_date
      when :last_12_months
        (Date.current.end_of_month + 1.day - 12.months).beginning_of_month.to_date
      when :all_time
        earliest_report_activity_date || Date.current.beginning_of_month.to_date
      when :custom
        1.month.ago.to_date
      else
        Date.current.beginning_of_month.to_date
      end
    end

    # The first transaction or trade in the accounts this member's reports read
    # (their finance accounts, as IncomeStatement uses), never a scheduled one.
    # An older entry in an account they can't see must not start All time: its
    # date would show in the label and the URLs built from it.
    def earliest_report_activity_date
      Entry.where(account_id: Current.user.finance_accounts.select(:id), entryable_type: %w[Transaction Trade])
        .excluding_scheduled
        .minimum(:date)
    end

    def default_end_date
      case @period_type
      when :monthly, :last_6_months, :last_12_months
        Date.current.end_of_month.to_date
      when :quarterly
        Date.current.end_of_quarter.to_date
      when :ytd, :all_time, :custom
        Date.current
      else
        Date.current.end_of_month.to_date
      end
    end

    def build_previous_period
      duration = (@end_date - @start_date).to_i
      previous_end = @start_date - 1.day
      previous_start = previous_end - duration.days

      Period.custom(start_date: previous_start, end_date: previous_end)
    end

    def build_summary_metrics
      # Ensure we always have Money objects
      if filter_tags.any?
        current = @income_statement.totals_for(@period, tag_ids: filter_tags.map(&:id))
        previous = @income_statement.totals_for(@previous_period, tag_ids: filter_tags.map(&:id))
        current_income, current_expenses = current.income_money, current.expense_money
        previous_income, previous_expenses = previous.income_money, previous.expense_money
      else
        current_income = ensure_money(@current_income_totals.total)
        current_expenses = ensure_money(@current_expense_totals.total)
        previous_income = ensure_money(@previous_income_totals.total)
        previous_expenses = ensure_money(@previous_expense_totals.total)
      end
      net_savings = current_income - current_expenses

      # Calculate percentage changes. All time has no period before it to compare with.
      unless @period_type == :all_time
        income_change = calculate_percentage_change(previous_income, current_income)
        expense_change = calculate_percentage_change(previous_expenses, current_expenses)
      end

      # Get budget performance for current period
      budget_percent = calculate_budget_performance

      {
        current_income: current_income,
        income_change: income_change,
        current_expenses: current_expenses,
        expense_change: expense_change,
        net_savings: net_savings,
        budget_percent: budget_percent
      }
    end

    def calculate_percentage_change(previous_value, current_value)
      return 0 if previous_value.zero?

      ((current_value - previous_value) / previous_value * 100).round(1)
    end

    def calculate_budget_performance
      # Only calculate if we're looking at current month
      return nil unless @period_type == :monthly && @start_date.beginning_of_month.to_date == Date.current.beginning_of_month.to_date

      budget = Budget.find_or_bootstrap(Current.family, start_date: @start_date.beginning_of_month.to_date, user: Current.user)
      return 0 if budget.nil? || budget.allocated_spending.zero?

      (budget.actual_spending / budget.allocated_spending * 100).round(1)
    rescue StandardError
      nil
    end

    def build_spending_comparison
      return nil unless preview_features_enabled?

      IncomeStatement::SpendingComparison.new(
        @income_statement,
        period: @period,
        history_start: IncomeStatement::SpendingComparison.history_start(@income_statement)
      )
    end

    def build_trends_data(income_statement:)
      # Month-by-month data based on the current period filter, fetched with a
      # single month-grouped totals query instead of two queries per month.
      trends = []

      current_month = @start_date.beginning_of_month
      end_of_period = @end_date.end_of_month

      monthly_totals = if filter_tags.empty?
        income_statement.monthly_income_expense_totals(
          period: Period.custom(start_date: current_month, end_date: @end_date)
        )
      end

      while current_month <= end_of_period
        if filter_tags.any?
          month_end = [ current_month.end_of_month, @end_date ].min
          period = Period.custom(start_date: current_month, end_date: month_end)
          totals = income_statement.totals_for(period, tag_ids: filter_tags.map(&:id))
          income = totals.income_money.amount
          expenses = totals.expense_money.amount
        else
          totals = monthly_totals[current_month] || { income: 0.to_d, expense: 0.to_d }
          income = totals[:income]
          expenses = totals[:expense]
        end

        trends << {
          month: current_month.strftime("%b %Y"),
          calendar_month: current_month,
          is_current_month: (current_month.month == Date.current.month && current_month.year == Date.current.year),
          income: income,
          expenses: expenses,
          net: income - expenses
        }

        current_month = current_month.next_month
      end

      trends
    end

    # An entry's amount in family currency at the rate the summary totals use:
    # ExchangeRate.rate_sql, the stored rate nearest the entry's date, however
    # old, as IncomeStatement::ScopedTransactionsQuery reads it. Nil when there
    # is none, so the entry is left out, as the summary leaves it out, rather
    # than counted at 1. No provider is called.
    def report_amount_converter(family_currency)
      rates = {}
      rate_query = "SELECT #{ExchangeRate.rate_sql(from: ':from', to: ':to', on: 'CAST(:on AS date)')}"
      lambda do |entry|
        amount = entry.amount.abs
        next amount if entry.currency == family_currency

        key = [ entry.date, entry.currency ]
        unless rates.key?(key)
          sql = ExchangeRate.sanitize_sql_array([ rate_query, { from: entry.currency, to: family_currency, on: entry.date } ])
          value = ExchangeRate.connection.select_value(sql)
          rates[key] = value && BigDecimal(value.to_s)
        end
        rates[key] && amount * rates[key]
      end
    end

    # The period's reportable transactions with every Reports filter applied
    # (finance account scoping, tax-advantaged exclusion, tags, ...).
    def report_transactions_scope(excluded_kinds:)
      transactions = Transaction
        .joins(:entry)
        .joins(entry: :account)
        .where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] })
        .merge(Account.included_in_reports)
        .where(entries: { entryable_type: "Transaction", excluded: false, date: @period.date_range })
        .where.not(kind: excluded_kinds)
        .includes(entry: :account, category: :parent)
      transactions = exclude_tax_advantaged_accounts(transactions)

      apply_transaction_filters(transactions)
    end

    # The period's largest expenses in the family currency, largest first.
    # Unlike the breakdown it keeps one-time expenses (the view marks them):
    # a one-off is exactly what this list is for. Trades are left out, as in
    # the income statement.
    def build_biggest_expenses(limit)
      family_currency = Current.family.currency
      # Loan payments and investment contributions are expenses whatever their
      # sign (some importers store them negative), as in the income statement.
      expenses = report_transactions_scope(excluded_kinds: Current.family.analytics_excluded_kinds - [ "one_time" ])
        .where("entries.amount > 0 OR (entries.amount < 0 AND transactions.kind IN (?))", SIGN_AGNOSTIC_EXPENSE_KINDS)
      expense_amount_sql = Arel.sql(ActiveRecord::Base.sanitize_sql_array([
        "CASE WHEN transactions.kind IN (?) THEN ABS(entries.amount) ELSE entries.amount END DESC", SIGN_AGNOSTIC_EXPENSE_KINDS
      ]))

      # The overall top `limit` is always among the top `limit` in the family
      # currency plus the foreign-currency rows, so only those get loaded.
      candidates = expenses.where(entries: { currency: family_currency }).order(expense_amount_sql).limit(limit).to_a +
        expenses.where.not(entries: { currency: family_currency }).to_a

      convert = report_amount_converter(family_currency)
      candidates.filter_map do |transaction|
        amount = convert.call(transaction.entry)
        { transaction: transaction, entry: transaction.entry, amount: Money.new(amount, family_currency) } if amount
      end.sort_by { |expense| -expense[:amount].amount }.first(limit)
    end

    def build_transactions_breakdown
      # Exclude transfers, one-time, and CC payments (matching income_statement logic)
      transactions = report_transactions_scope(excluded_kinds: Current.family.analytics_excluded_kinds)

      # Get trades in the period (matching income_statement logic)
      trades = Trade
        .joins(:entry)
        .joins(entry: :account)
        .where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] })
        .merge(Account.included_in_reports)
        # Buys/sells move value between cash and holdings; keep cash income and fees, decided by label as Portfolio::FlowClassifier does.
        # A qty-0 trade also stays unless its label marks it as a movement (internal, external or transfer).
        .where(
          "trades.investment_activity_label IN (?) OR (trades.qty = 0 AND (trades.investment_activity_label IS NULL OR trades.investment_activity_label NOT IN (?)))",
          Portfolio::FlowClassifier::INCOME_LABELS + Portfolio::FlowClassifier::FEE_LABELS,
          Portfolio::FlowClassifier::INTERNAL_LABELS + Portfolio::FlowClassifier::EXTERNAL_LABELS + [ Portfolio::FlowClassifier::TRANSFER_LABEL ]
        )
        .where(entries: { entryable_type: "Trade", excluded: false, date: @period.date_range })
        .includes(entry: :account, category: :parent)
      trades = exclude_tax_advantaged_accounts(trades)

      trades = apply_entry_filters(trades)

      # Get sort parameters
      sort_by = %w[amount count].include?(params[:sort_by]) ? params[:sort_by] : "amount"
      sort_direction = %w[asc desc].include?(params[:sort_direction]) ? params[:sort_direction] : "desc"
      sort_logic = ->(item) do
        value = (sort_by == "count") ? item[:count] : item[:total]
        sort_direction == "asc" ? (value || 0) : -(value || 0)
      end

      # Group by category (tracking parent relationship) and type
      # Structure: { [parent_category_id, type] => { parent_data, subcategories: { subcategory_id => data } } }
      grouped_data = {}
      family_currency = Current.family.currency

      # Helper to initialize a category group hash
      init_category_group = ->(id, name, color, icon, type, filter_value) do
        {
          category_id: id,
          category_name: name,
          category_filter_value: filter_value,
          category_color: color,
          category_icon: icon,
          type: type,
          total: 0,
          count: 0,
          has_transactions: false,
          subcategories: {}
        }
      end

      # Helper to initialize a subcategory hash
      init_subcategory = ->(category) do
        {
          category_id: category.id,
          category_name: category.name,
          category_filter_value: category.filter_value,
          category_color: category.color,
          category_icon: category.lucide_icon,
          total: 0,
          count: 0,
          has_transactions: false
        }
      end

      # Helper to process an entry (transaction or trade)
      convert = report_amount_converter(family_currency)
      process_entry = ->(category, entry, is_trade) do
        # No money moved (e.g. a 0.00 card authorisation): neither income nor expense
        next if entry.amount.zero?

        type = entry.amount > 0 ? "expense" : "income"
        converted_amount = convert.call(entry)
        next if converted_amount.nil?

        if category.nil?
          # Uncategorized or Other Investments (for trades)
          if is_trade
            parent_key = [ :other_investments, type ]
            grouped_data[parent_key] ||= init_category_group.call(:other_investments, Category.other_investments.name, Category.other_investments.color, Category.other_investments.lucide_icon, type, Category.other_investments.name)
          else
            parent_key = [ :uncategorized, type ]
            grouped_data[parent_key] ||= init_category_group.call(:uncategorized, Category.uncategorized.name, Category.uncategorized.color, Category.uncategorized.lucide_icon, type, Category.uncategorized.filter_value)
          end
        elsif category.parent_id.present?
          # This is a subcategory - group under parent
          parent = category.parent
          parent_key = [ parent.id, type ]
          grouped_data[parent_key] ||= init_category_group.call(parent.id, parent.name, parent.color || Category::UNCATEGORIZED_COLOR, parent.lucide_icon, type, parent.filter_value)

          # Add to subcategory
          grouped_data[parent_key][:subcategories][category.id] ||= init_subcategory.call(category)
          grouped_data[parent_key][:subcategories][category.id][:count] += 1
          grouped_data[parent_key][:subcategories][category.id][:total] += converted_amount
          grouped_data[parent_key][:subcategories][category.id][:has_transactions] = true unless is_trade
        else
          # This is a root category (no parent)
          parent_key = [ category.id, type ]
          grouped_data[parent_key] ||= init_category_group.call(category.id, category.name, category.color || Category::UNCATEGORIZED_COLOR, category.lucide_icon, type, category.filter_value)
        end

        grouped_data[parent_key][:count] += 1
        grouped_data[parent_key][:total] += converted_amount
        grouped_data[parent_key][:has_transactions] = true unless is_trade
      end

      # Process transactions
      transactions.each do |transaction|
        process_entry.call(transaction.category, transaction.entry, false)
      end

      # Process trades
      trades.each do |trade|
        process_entry.call(trade.category, trade.entry, true)
      end

      # Convert to array and sort subcategories
      result = grouped_data.values.map do |parent_data|
        subcategories = parent_data[:subcategories].values.sort_by(&sort_logic)
        parent_data.merge(subcategories: subcategories)
      end

      # Sort by the chosen key with the specified direction
      result.sort_by(&sort_logic)
    end

    def category_selection
      @category_selection ||= Reports::CategorySelection.new(Current.family, params[:trend_category_ids])
    end

    def trend_granularity
      @trend_granularity ||= begin
        requested = params[:trend_granularity]
        if %w[month year].include?(requested)
          requested
        else
          long_period? ? "year" : "month"
        end
      end
    end

    # Two years of monthly points is still readable. Longer ranges default to
    # years, and the user can override the choice.
    def long_period?
      @start_date.present? && @end_date.present? && @start_date.advance(months: 24) < @end_date
    end

    # Category trends are a preview. The model scopes only the chart; the
    # report totals and tables stay unfiltered.
    def build_category_trend
      return nil unless preview_features_enabled?

      Reports::CategoryTrend.new(
        @income_statement,
        period: @period,
        selection: category_selection,
        granularity: trend_granularity,
        tag_ids: filter_tags.map(&:id)
      )
    end

    # Preview users get the trend locals. Building the category options for
    # everyone costs a query and objects that the view never renders.
    def trend_section_locals
      locals = {
        trends_data: @trends_data,
        period_type: @period_type,
        start_date: @start_date,
        end_date: @end_date,
        trend_granularity: trend_granularity
      }
      return locals unless @category_trend

      locals.merge(
        category_trend: @category_trend,
        category_options: category_selection.options,
        selected_category_values: category_selection.selected_values,
        selected_category_count: category_selection.selected_count
      )
    end

    def build_investment_metrics
      investment_statement = Current.family.investment_statement
      investment_accounts = investment_statement.investment_accounts

      # Shown when there is something to show: an investment account in scope,
      # or a disposal in the period for the realised-gains half. That half reads
      # every account included in reports, disabled ones too, while
      # `investment_accounts` is visible accounts only -- so a family whose only
      # brokerage account is closed used to get no card at all.
      return { has_investments: false } unless investment_accounts.any? || period_sell_trades.exists?

      period_totals = investment_statement.totals(period: @period)
      {
        has_investments: true,
        portfolio_value: investment_statement.portfolio_value_money,
        unrealized_trend: investment_statement.unrealized_gains_trend,
        period_return_trend: investment_statement.period_return_trend(period: @period),
        period_contributions: period_totals.contributions,
        period_withdrawals: period_totals.withdrawals,
        top_holdings: investment_statement.top_holdings(limit: 5),
        accounts: investment_accounts.to_a,
        gains_by_tax_treatment: build_gains_by_tax_treatment(investment_statement)
      }
    end

    def build_gains_by_tax_treatment(investment_statement)
      currency = Current.family.currency
      # The card's holdings, average costs already read in one query (the trends
      # below would otherwise run them per holding), plus each account's
      # accountable for its tax treatment.
      current_holdings = investment_statement.holdings_with_avg_costs
      ActiveRecord::Associations::Preloader.new(records: current_holdings, associations: { account: :accountable }).call

      # Group holdings by tax treatment (from account)
      holdings_by_treatment = current_holdings.group_by { |h| h.account.tax_treatment || :taxable }

      # Get sell trades in period with realized gains
      # Eager-load security, account, and accountable to avoid N+1
      sell_trades = period_sell_trades
        .includes(:security, entry: { account: :accountable })
        .to_a

      # Each sale's basis position in one query, before the rates: the rate
      # preload keys on the currency that position is carried in.
      Trade.preload_basis_holdings(sell_trades)

      # What each fifo sale took from which lot, read once for the whole set.
      lot_disposals = HoldingLotDisposal.readable_by_sale(sell_trades)
      sell_trades.each { |trade| trade.preloaded_lot_disposals = lot_disposals[trade.entry.id] }

      # The rates the proceeds conversion needs, in one query rather than one
      # per foreign disposal.
      Trade.preload_exchange_rates(sell_trades)

      trades_by_treatment = sell_trades.group_by { |t| t.entry.account.tax_treatment || :taxable }

      # Unwrap helper: Trend#value / realized_gain_loss#value are Money objects,
      # and this codebase's Money keeps the source currency through `*` and
      # through `Money.new(money, _)`. Unwrapping to BigDecimal first keeps sums
      # and the final Money.new(..., currency) correctly labeled in family currency.
      to_numeric = ->(value) { value.is_a?(Money) ? value.amount : value }

      # Unrealized gains mark holdings to market, so convert at today's FX.
      # Both conversions return nil when there is no rate, since converting
      # at 1 would report a ¥1,000,000 gain as $1,000,000. A figure that
      # cannot be converted is left out of the total and counted, so the card
      # can say the total is partial.
      foreign_holding_currencies = current_holdings.map(&:currency).compact.uniq.reject { |c| c == currency }
      holding_rates = ExchangeRate.rates_for(foreign_holding_currencies, to: currency, date: Date.current)
      convert_current = ->(amount, from) {
        numeric = to_numeric.call(amount)
        next numeric if from == currency

        rate = holding_rates[from]
        rate && numeric * rate
      }

      # Realized gains are locked at trade time, so convert each at its own
      # entry-date FX. Mirrors InvestmentStatement::Totals, which also uses
      # entry-date rates for contributions/withdrawals on this same card.
      # A realised figure arrives in the currency the POSITION is held in, not
      # the one the disposal was priced in: Trade#realized_gain_loss converts
      # the proceeds into the basis's currency before subtracting, so that the
      # two sides are comparable. All three sets are needed -- the accounts',
      # which is what a gain usually carries, the trades' own, and the
      # holdings', for a position carried in a third currency.
      foreign_trade_currencies = (
        sell_trades.map(&:currency) +
        sell_trades.map { |t| t.entry.account.currency } +
        sell_trades.map(&:preloaded_basis_currency)
      ).compact.uniq.reject { |c| c == currency }
      rates_by_trade_date = sell_trades.map { |t| t.entry.date }.uniq.each_with_object({}) do |date, memo|
        memo[date] = ExchangeRate.rates_for(foreign_trade_currencies, to: currency, date: date)
      end
      convert_trade = ->(amount, from, date) {
        numeric = to_numeric.call(amount)
        next numeric if from == currency

        rate = rates_by_trade_date.dig(date, from)
        rate && numeric * rate
      }

      # Build metrics per treatment
      %i[taxable tax_deferred tax_exempt tax_advantaged].each_with_object({}) do |treatment, hash|
        holdings = holdings_by_treatment[treatment] || []
        trades = trades_by_treatment[treatment] || []

        # Sum unrealized gains from holdings (only those with known cost basis
        # and a rate into family currency)
        unconverted = 0
        unrealized_by_holding = {}
        unrealized = holdings.sum do |h|
          trend = h.trend
          next 0 unless trend

          converted = convert_current.call(trend.value, h.currency)
          unconverted += 1 if converted.nil?
          unrealized_by_holding[h.id] = Money.new(converted, currency) if converted
          converted || 0
        end

        # Sum realized gains from sell trades, each converted from the currency
        # its own figure carries.
        realized_by_trade = trades.each_with_object({}) do |t, memo|
          gain = t.realized_gain_loss
          if gain.nil?
            # A sale with no rate between its own two currencies is left out
            # too, and counted; one with no cost basis never had a figure.
            unconverted += 1 if t.realized_gain_unconvertible?
            next
          end

          converted = convert_trade.call(gain.value, gain.value.currency.iso_code, t.entry.date)
          if converted.nil?
            unconverted += 1
            next
          end

          memo[t.id] = Money.new(converted, currency)
        end

        realized = realized_by_trade.values.sum(Money.new(0, currency)).amount

        # Only include treatment groups that have some activity
        next if holdings.empty? && trades.empty?

        hash[treatment] = {
          holdings: holdings,
          sell_trades: trades,
          unrealized_gain: Money.new(unrealized, currency),
          realized_gain: Money.new(realized, currency),
          # Per-trade figures in family currency, so the lines under the card
          # and the card's own total are the same arithmetic. The partial used
          # to re-label `gain.value` as family currency without converting it.
          realized_gain_by_trade: realized_by_trade,
          # The same for each holding's unrealised gain; one with no rate has
          # no entry, and its line says so.
          unrealized_gain_by_holding: unrealized_by_holding,
          # Holdings and sells left out of the totals for want of a rate.
          unconverted_count: unconverted,
          total_gain: Money.new(unrealized + realized, currency)
        }
      end
    end

    # The period's disposals, as the realised-gains half of the investment
    # card lists them. The card's gate asks the same relation, so the two
    # cannot disagree about what counts as a disposal. Scoped to the accounts
    # this user includes in their finances -- the per-user scope
    # `investment_accounts` applies -- so another member's unshared account
    # is neither listed nor opens the card.
    def period_sell_trades
      Current.family.trades
        .joins(entry: :account)
        # An excluded trade is left out of reports, as InvestmentStatement::Totals
        # leaves it out of the same card's contributions and withdrawals.
        .where(entries: { date: @period.date_range, excluded: false })
        .where(entries: { account_id: Current.user.finance_accounts.select(:id) })
        .merge(Account.included_in_reports)
        .where("trades.qty < 0")
        # A transfer out has the same negative quantity as a sale and would be
        # counted and listed as one. Nothing was sold, so it belongs in neither.
        .where(
          "trades.investment_activity_label IS NULL OR trades.investment_activity_label NOT IN (?)",
          Trade::INTERNAL_MOVEMENT_LABELS
        )
    end

    def build_net_worth_metrics
      balance_sheet = Current.family.balance_sheet
      currency = Current.family.currency

      # Current net worth
      current_net_worth = balance_sheet.net_worth
      total_assets = balance_sheet.assets.total
      total_liabilities = balance_sheet.liabilities.total

      # Get net worth series for the period to calculate change
      # The series.trend gives us the change from first to last value in the period
      net_worth_series = balance_sheet.net_worth_series(period: @period)
      trend = net_worth_series&.trend

      # Get asset and liability groups for breakdown
      asset_groups = balance_sheet.assets.account_groups.map do |group|
        { name: group.name, total: Money.new(group.total, currency) }
      end.reject { |g| g[:total].zero? }

      liability_groups = balance_sheet.liabilities.account_groups.map do |group|
        { name: group.name, total: Money.new(group.total, currency) }
      end.reject { |g| g[:total].zero? }

      # Monthly net worth series with per-account-group breakdown for the chart
      breakdown_series = BalanceSheet::NetWorthBreakdownSeriesBuilder
        .new(Current.family, user: Current.user)
        .breakdown_series(period: @period)

      {
        current_net_worth: Money.new(current_net_worth, currency),
        total_assets: Money.new(total_assets, currency),
        total_liabilities: Money.new(total_liabilities, currency),
        trend: trend,
        asset_groups: asset_groups,
        liability_groups: liability_groups,
        breakdown_series: breakdown_series
      }
    end

    def apply_transaction_filters(scope)
      scope = apply_entry_filters(scope)

      scope = scope.with_any_tag(filter_tags.map(&:id)) if filter_tags.any?

      scope
    end

    def filter_tag_ids
      @filter_tag_ids ||= params[:filter_tag_ids].is_a?(Array) ? params[:filter_tag_ids].grep(String).compact_blank : []
    end

    # The family's tags among filter_tag_ids. Ids that match none of them
    # (another family's tag, a deleted one) are ignored.
    def filter_tags
      @filter_tags ||= filter_tag_ids.any? ? Current.family.tags.where(id: filter_tag_ids).alphabetically.to_a : []
    end

    def exclude_tax_advantaged_accounts(scope)
      tax_advantaged_account_ids = Current.family.tax_advantaged_account_ids
      return scope if tax_advantaged_account_ids.blank?

      scope.where.not(accounts: { id: tax_advantaged_account_ids })
    end

    # Filters applicable to both transactions and trades (entry-level + category)
    def apply_entry_filters(scope)
      # Scope to user's finance accounts
      finance_account_ids = Current.user&.finance_accounts&.pluck(:id) || []
      scope = scope.where(entries: { account_id: finance_account_ids })

      # Filter by category (including subcategories)
      if params[:filter_category_id].present?
        category_id = params[:filter_category_id]
        # Scope to family's categories to prevent cross-family data access
        subcategory_ids = Current.family.categories.where(parent_id: category_id).pluck(:id)
        all_category_ids = [ category_id ] + subcategory_ids
        # Trades have no category, so a category filter leaves them out.
        scope = scope.model == Trade ? scope.none : scope.where(category_id: all_category_ids)
      end

      # Trades carry no tags, so a tag filter leaves them out.
      scope = scope.none if scope.model == Trade && filter_tags.any?

      # Filter by account
      if params[:filter_account_id].present?
        scope = scope.where(entries: { account_id: params[:filter_account_id] })
      end

      # Filter by amount range
      if params[:filter_amount_min].present?
        scope = scope.where("ABS(entries.amount) >= ?", params[:filter_amount_min].to_f)
      end

      if params[:filter_amount_max].present?
        scope = scope.where("ABS(entries.amount) <= ?", params[:filter_amount_max].to_f)
      end

      # Filter by date range (within the period)
      if params[:filter_date_start].present?
        filter_start = Date.parse(params[:filter_date_start])
        scope = scope.where("entries.date >= ?", filter_start) if filter_start >= @start_date
      end

      if params[:filter_date_end].present?
        filter_end = Date.parse(params[:filter_date_end])
        scope = scope.where("entries.date <= ?", filter_end) if filter_end <= @end_date
      end

      scope
    rescue Date::Error
      scope
    end

    def build_monthly_breakdown_for_export
      # Generate list of months in the period
      months = []
      current_month = @start_date.beginning_of_month
      end_of_period = @end_date.end_of_month

      while current_month <= end_of_period
        months << current_month
        current_month = current_month.next_month
      end

      # Get all transactions in the period
      # Exclude transfers, one-time, and CC payments (matching income_statement logic)
      transactions = Transaction
        .joins(:entry)
        .joins(entry: :account)
        .where(accounts: { family_id: Current.family.id, status: [ "draft", "active" ] })
        .merge(Account.included_in_reports)
        .where(entries: { entryable_type: "Transaction", excluded: false, date: @period.date_range })
        .where.not(kind: Current.family.analytics_excluded_kinds)
        .includes(entry: :account, category: [])
      transactions = exclude_tax_advantaged_accounts(transactions)

      transactions = apply_transaction_filters(transactions)

      # Group by category, type, and month
      breakdown = {}
      family_currency = Current.family.currency
      convert = report_amount_converter(family_currency)

      # Process transactions
      transactions.each do |transaction|
        entry = transaction.entry
        next if entry.amount.zero? # neither income nor expense
        is_expense = entry.amount > 0
        type = is_expense ? "expense" : "income"
        category_name = transaction.category&.name || "Uncategorized"
        month_key = entry.date.beginning_of_month

        # Convert to family currency, leaving out what has no rate
        converted_amount = convert.call(entry)
        next if converted_amount.nil?

        key = [ category_name, type ]
        breakdown[key] ||= { category: category_name, type: type, months: {}, total: 0 }
        breakdown[key][:months][month_key] ||= 0
        breakdown[key][:months][month_key] += converted_amount
        breakdown[key][:total] += converted_amount
      end

      # Convert to array and sort by type and total (descending)
      result = breakdown.map do |key, data|
        {
          category: data[:category],
          type: data[:type],
          months: data[:months],
          total: data[:total]
        }
      end

      # Separate and sort income and expenses
      income_data = result.select { |r| r[:type] == "income" }.sort_by { |r| -r[:total] }
      expense_data = result.select { |r| r[:type] == "expense" }.sort_by { |r| -r[:total] }

      {
        months: months,
        income: income_data,
        expenses: expense_data
      }
    end

    def generate_transactions_csv
      require "csv"

      # Category names are user-supplied and this is the export the app points
      # at Google Sheets, so the cells that carry them are escaped against
      # formula injection (CWE-1236). Only that column: the amount cells are
      # formatted money such as "-$42.00", which the escape would turn to text.
      CSV.generate(force_quotes: true) do |csv|
        # Build header row: Category + Month columns + Total
        month_headers = @export_data[:months].map { |m| m.strftime("%b %Y") }
        header_row = [ "Category" ] + month_headers + [ "Total" ]
        csv << header_row

        # Income section
        if @export_data[:income].any?
          csv << [ "INCOME" ] + Array.new(month_headers.length + 1, "")

          @export_data[:income].each do |category_data|
            row = [ CsvSanitizer.sanitize(category_data[:category]) ]

            # Add amounts for each month
            @export_data[:months].each do |month|
              amount = category_data[:months][month] || 0
              row << Money.new(amount, Current.family.currency).format
            end

            # Add row total
            row << Money.new(category_data[:total], Current.family.currency).format
            csv << row
          end

          # Income totals row
          totals_row = [ "TOTAL INCOME" ]
          @export_data[:months].each do |month|
            month_total = @export_data[:income].sum { |c| c[:months][month] || 0 }
            totals_row << Money.new(month_total, Current.family.currency).format
          end
          grand_income_total = @export_data[:income].sum { |c| c[:total] }
          totals_row << Money.new(grand_income_total, Current.family.currency).format
          csv << totals_row

          # Blank row
          csv << []
        end

        # Expenses section
        if @export_data[:expenses].any?
          csv << [ "EXPENSES" ] + Array.new(month_headers.length + 1, "")

          @export_data[:expenses].each do |category_data|
            row = [ CsvSanitizer.sanitize(category_data[:category]) ]

            # Add amounts for each month
            @export_data[:months].each do |month|
              amount = category_data[:months][month] || 0
              row << Money.new(amount, Current.family.currency).format
            end

            # Add row total
            row << Money.new(category_data[:total], Current.family.currency).format
            csv << row
          end

          # Expenses totals row
          totals_row = [ "TOTAL EXPENSES" ]
          @export_data[:months].each do |month|
            month_total = @export_data[:expenses].sum { |c| c[:months][month] || 0 }
            totals_row << Money.new(month_total, Current.family.currency).format
          end
          grand_expenses_total = @export_data[:expenses].sum { |c| c[:total] }
          totals_row << Money.new(grand_expenses_total, Current.family.currency).format
          csv << totals_row
        end
      end
    end

    def generate_transactions_xlsx
      require "caxlsx"

      package = Axlsx::Package.new
      workbook = package.workbook
      bold_style = workbook.styles.add_style(b: true)

      workbook.add_worksheet(name: "Breakdown") do |sheet|
        # Build header row: Category + Month columns + Total
        month_headers = @export_data[:months].map { |m| m.strftime("%b %Y") }
        header_row = [ "Category" ] + month_headers + [ "Total" ]
        sheet.add_row header_row, style: bold_style

        # Income section
        if @export_data[:income].any?
          sheet.add_row [ "INCOME" ] + Array.new(month_headers.length + 1, ""), style: bold_style

          @export_data[:income].each do |category_data|
            row = [ category_data[:category] ]

            # Add amounts for each month
            @export_data[:months].each do |month|
              amount = category_data[:months][month] || 0
              row << Money.new(amount, Current.family.currency).format
            end

            # Add row total
            row << Money.new(category_data[:total], Current.family.currency).format
            sheet.add_row row
          end

          # Income totals row
          totals_row = [ "TOTAL INCOME" ]
          @export_data[:months].each do |month|
            month_total = @export_data[:income].sum { |c| c[:months][month] || 0 }
            totals_row << Money.new(month_total, Current.family.currency).format
          end
          grand_income_total = @export_data[:income].sum { |c| c[:total] }
          totals_row << Money.new(grand_income_total, Current.family.currency).format
          sheet.add_row totals_row, style: bold_style

          # Blank row
          sheet.add_row []
        end

        # Expenses section
        if @export_data[:expenses].any?
          sheet.add_row [ "EXPENSES" ] + Array.new(month_headers.length + 1, ""), style: bold_style

          @export_data[:expenses].each do |category_data|
            row = [ category_data[:category] ]

            # Add amounts for each month
            @export_data[:months].each do |month|
              amount = category_data[:months][month] || 0
              row << Money.new(amount, Current.family.currency).format
            end

            # Add row total
            row << Money.new(category_data[:total], Current.family.currency).format
            sheet.add_row row
          end

          # Expenses totals row
          totals_row = [ "TOTAL EXPENSES" ]
          @export_data[:months].each do |month|
            month_total = @export_data[:expenses].sum { |c| c[:months][month] || 0 }
            totals_row << Money.new(month_total, Current.family.currency).format
          end
          grand_expenses_total = @export_data[:expenses].sum { |c| c[:total] }
          totals_row << Money.new(grand_expenses_total, Current.family.currency).format
          sheet.add_row totals_row, style: bold_style
        end
      end

      package.to_stream.read
    end

    def generate_transactions_pdf
      require "prawn"

      Prawn::Document.new(page_layout: :landscape) do |pdf|
        pdf.text "Transaction Breakdown Report", size: 20, style: :bold
        pdf.text "Period: #{@start_date.strftime('%b %-d, %Y')} to #{@end_date.strftime('%b %-d, %Y')}", size: 12
        pdf.move_down 20

        if @export_data[:income].any? || @export_data[:expenses].any?
          # Build header row
          month_headers = @export_data[:months].map { |m| m.strftime("%b %Y") }
          header_row = [ "Category" ] + month_headers + [ "Total" ]

          # Income section
          if @export_data[:income].any?
            pdf.text "INCOME", size: 14, style: :bold
            pdf.move_down 10

            income_table_data = [ header_row ]

            @export_data[:income].each do |category_data|
              row = [ category_data[:category] ]

              @export_data[:months].each do |month|
                amount = category_data[:months][month] || 0
                row << Money.new(amount, Current.family.currency).format
              end

              row << Money.new(category_data[:total], Current.family.currency).format
              income_table_data << row
            end

            # Income totals row
            totals_row = [ "TOTAL INCOME" ]
            @export_data[:months].each do |month|
              month_total = @export_data[:income].sum { |c| c[:months][month] || 0 }
              totals_row << Money.new(month_total, Current.family.currency).format
            end
            grand_income_total = @export_data[:income].sum { |c| c[:total] }
            totals_row << Money.new(grand_income_total, Current.family.currency).format
            income_table_data << totals_row

            pdf.table(income_table_data, header: true, width: pdf.bounds.width, cell_style: { size: 8 }) do
              row(0).font_style = :bold
              row(0).background_color = "CCFFCC"
              row(-1).font_style = :bold
              row(-1).background_color = "99FF99"
              columns(0).align = :left
              columns(1..-1).align = :right
              self.row_colors = [ "FFFFFF", "F9F9F9" ]
            end

            pdf.move_down 20
          end

          # Expenses section
          if @export_data[:expenses].any?
            pdf.text "EXPENSES", size: 14, style: :bold
            pdf.move_down 10

            expenses_table_data = [ header_row ]

            @export_data[:expenses].each do |category_data|
              row = [ category_data[:category] ]

              @export_data[:months].each do |month|
                amount = category_data[:months][month] || 0
                row << Money.new(amount, Current.family.currency).format
              end

              row << Money.new(category_data[:total], Current.family.currency).format
              expenses_table_data << row
            end

            # Expenses totals row
            totals_row = [ "TOTAL EXPENSES" ]
            @export_data[:months].each do |month|
              month_total = @export_data[:expenses].sum { |c| c[:months][month] || 0 }
              totals_row << Money.new(month_total, Current.family.currency).format
            end
            grand_expenses_total = @export_data[:expenses].sum { |c| c[:total] }
            totals_row << Money.new(grand_expenses_total, Current.family.currency).format
            expenses_table_data << totals_row

            pdf.table(expenses_table_data, header: true, width: pdf.bounds.width, cell_style: { size: 8 }) do
              row(0).font_style = :bold
              row(0).background_color = "FFCCCC"
              row(-1).font_style = :bold
              row(-1).background_color = "FF9999"
              columns(0).align = :left
              columns(1..-1).align = :right
              self.row_colors = [ "FFFFFF", "F9F9F9" ]
            end
          end
        else
          pdf.text "No transactions found for this period.", size: 12
        end
      end.render
    end

    # Export Authentication - handles both session and API key auth
    def authenticate_for_export
      if api_key_present?
        # Use API key authentication
        authenticate_with_api_key
      else
        # Use normal session authentication
        authenticate_user!
      end
    end

    # API Key Authentication Methods
    def api_key_present?
      params[:api_key].present? || request.headers["X-Api-Key"].present?
    end

    def authenticate_with_api_key
      api_key_value = params[:api_key] || request.headers["X-Api-Key"]

      unless api_key_value
        render plain: "API key is required", status: :unauthorized
        return false
      end

      @api_key = ApiKey.find_by_value(api_key_value)

      unless @api_key && @api_key.active?
        render plain: "Invalid or expired API key", status: :unauthorized
        return false
      end

      # Check if API key has read permissions
      unless @api_key.scopes&.include?("read") || @api_key.scopes&.include?("read_write")
        render plain: "API key does not have read permission", status: :forbidden
        return false
      end

      # Set up the current user and session context
      @current_user = @api_key.user
      @api_key.update_last_used!

      # Set up Current context for API requests (similar to Api::V1::BaseController)
      # Return false if setup fails to halt the filter chain
      return false unless setup_current_context_for_api_key

      true
    end

    def setup_current_context_for_api_key
      unless @current_user
        render plain: "User not found for API key", status: :internal_server_error
        return false
      end

      unless @current_user.active?
        render plain: "Invalid or expired API key", status: :unauthorized
        return false
      end

      # Build a fresh unsaved session so API key exports never reuse an existing
      # web session that may already carry impersonation state.
      Current.session = @current_user.sessions.build(
        user_agent: request.user_agent,
        ip_address: request.ip
      )
      Current.session.active_impersonator_session = nil

      # Verify the delegation chain works
      unless Current.user
        render plain: "Failed to establish user context", status: :internal_server_error
        return false
      end

      # Ensure we have a valid family context
      unless Current.family
        render plain: "User does not have an associated family", status: :internal_server_error
        return false
      end

      true
    end

    def build_period_navigation
      # Called at the end of setup_report_data, so @start_date and @end_date are guaranteed to be set.
      case @period_type
      when :monthly
        prev_start = @start_date.beginning_of_month - 1.month
        prev_end   = prev_start.end_of_month
        next_start = @start_date.beginning_of_month + 1.month
        next_end   = next_start.end_of_month
        at_latest  = @start_date.beginning_of_month >= Date.current.beginning_of_month
      when :quarterly
        prev_start = (@start_date.beginning_of_quarter - 1.day).beginning_of_quarter
        prev_end   = prev_start.end_of_quarter
        next_start = @end_date.end_of_quarter + 1.day
        next_end   = next_start.end_of_quarter
        at_latest  = @start_date.beginning_of_quarter >= Date.current.beginning_of_quarter
      when :ytd
        prev_year  = @start_date.year - 1
        prev_start = Date.new(prev_year, 1, 1)
        prev_end   = Date.new(prev_year, 12, 31)
        next_year  = @start_date.year + 1
        next_start = Date.new(next_year, 1, 1)
        next_end   = next_year == Date.current.year ? Date.current : Date.new(next_year, 12, 31)
        at_latest  = @start_date.year >= Date.current.year
      when :last_6_months
        prev_start = @start_date.beginning_of_month - 6.months
        prev_end   = prev_start + 6.months - 1.day
        candidate_start = @start_date.beginning_of_month + 6.months
        if candidate_start + 6.months >= Date.current.beginning_of_month
          next_end   = Date.current.end_of_month
          next_start = (next_end + 1.day - 6.months).beginning_of_month
        else
          next_start = candidate_start
          next_end   = next_start + 6.months - 1.day
        end
        at_latest  = @end_date >= Date.current.end_of_month
      when :last_12_months
        prev_start = @start_date.beginning_of_month - 12.months
        prev_end   = prev_start + 12.months - 1.day
        candidate_start = @start_date.beginning_of_month + 12.months
        if candidate_start + 12.months >= Date.current.beginning_of_month
          next_end   = Date.current.end_of_month
          next_start = (next_end + 1.day - 12.months).beginning_of_month
        else
          next_start = candidate_start
          next_end   = next_start + 12.months - 1.day
        end
        at_latest  = @end_date >= Date.current.end_of_month
      else
        return nil
      end

      { prev_start: prev_start, prev_end: prev_end, next_start: next_start, next_end: next_end, at_latest: at_latest, label: period_label }
    end

    def period_label
      case @period_type
      when :monthly
        I18n.l(@start_date, format: :month_year)
      when :quarterly
        t("reports.index.period_label.quarterly", quarter: @start_date.quarter, year: @start_date.year)
      when :ytd
        if @start_date.year == Date.current.year
          t("reports.index.period_label.ytd", year: @start_date.year)
        else
          t("reports.index.period_label.past_year", year: @start_date.year)
        end
      when :last_6_months
        t("reports.index.period_label.last_6_months",
          start: I18n.l(@start_date, format: :short_month_year),
          end: I18n.l(@end_date, format: :short_month_year))
      when :last_12_months
        t("reports.index.period_label.last_12_months",
          start: I18n.l(@start_date, format: :short_month_year),
          end: I18n.l(@end_date, format: :short_month_year))
      end
    end
end