Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
11.9 KB
Raw Blame
module InsightsHelper
  INSIGHT_ICONS = {
    "spending_anomaly" => "activity",
    "cash_flow_warning" => "alert-triangle",
    "net_worth_milestone" => "trophy",
    "subscription_audit" => "repeat",
    "savings_rate_change" => "piggy-bank",
    "idle_cash" => "wallet",
    "budget_at_risk" => "alert-triangle",
    "budget_on_track" => "circle-check",
    # Same shield the reserve panel uses on the goal page, so the two read as
    # the same object seen from two places.
    "maintained_goal_depleted" => "shield-alert",
    "bill_not_covered" => "calendar-x",
    "loan_payment_change" => "landmark",
    "bank_fees" => "receipt",
    "fixed_commitments_ratio" => "scale"
  }.freeze

  def insight_icon_key(insight)
    INSIGHT_ICONS.fetch(insight.insight_type, "lightbulb")
  end

  # Matches the numeric fragments inside insight prose: currency amounts
  # ("€288.59", "1 234,56 €"), percentages ("142%"), and bare counts. Digit
  # groups may be separated by ".", ",", or the (narrow) no-break spaces some
  # locales format with, but must start and end on a digit so sentence
  # punctuation stays outside the match.
  INSIGHT_NUMERIC_FRAGMENT = /
    (?:\p{Sc}[\s\u00A0\u202F]?)?          # currency symbol prefix
    \d(?:[\d.,\s\u00A0\u202F]*\d)?        # digits with grouping separators
    (?:[\s\u00A0\u202F]?(?:%|\p{Sc}))?    # percent or currency symbol suffix
  /x

  # Insight titles and bodies are stored as finished prose with the amounts
  # already interpolated by the i18n template, so unlike
  # the rest of the app the figures can't be tagged where they're formatted.
  # This wraps each numeric fragment in a privacy-sensitive span at render
  # time so privacy mode blurs the numbers but the sentence stays readable.
  def insight_privacy_text(text)
    safe_join(
      text.to_s.split(/(#{INSIGHT_NUMERIC_FRAGMENT})/o).map.with_index do |part, index|
        index.odd? ? tag.span(part, class: "privacy-sensitive") : part
      end
    )
  end

  # "Savings rate · June" / "Cash flow · Next 30 days" — the card's meta line.
  # Uses the insight's stored period; falls back to the subject (account or
  # merchant name from facts) for insights without one.
  def insight_meta_line(insight)
    parts = [ t("insights.types.#{insight.insight_type}", default: insight.insight_type.humanize) ]
    parts << insight_period_label(insight)
    parts.compact.join(" · ")
  end

  # [value, caption] for the card's right-aligned key figure, from the display
  # facts stored on the row. Nil (no figure) for rows written before facts
  # were persisted — they backfill on the next nightly run.
  def insight_key_figure(insight)
    facts = insight.facts || {}
    return nil if facts.blank?

    case insight.insight_type
    when "savings_rate_change"
      return nil unless facts["change_pp"]
      sign = insight_sentiment(insight) == :positive ? "+" : "−"
      [ "#{sign}#{facts["change_pp"]} pp", t("insights.figures.vs_previous_three_months") ]
    when "net_worth_milestone"
      facts["net_worth"] && [ facts["net_worth"], t("insights.figures.today") ]
    when "spending_anomaly"
      facts["projected_spend"] && [ facts["projected_spend"], t("insights.figures.on_pace") ]
    when "cash_flow_warning"
      facts["projected_low"] && [ facts["projected_low"], facts["projected_low_date"] ]
    when "subscription_audit"
      facts["amount"] && [ facts["amount"], t("insights.figures.days_overdue", count: facts["days_overdue"].to_i) ]
    when "idle_cash"
      facts["balance"] && [ facts["balance"], t("insights.figures.idle_days", count: facts["idle_days"].to_i) ]
    when "budget_at_risk"
      # Not budget_spent_pct: this card's headline is "N categories need
      # attention", and total consumption ("14% of budget") reads as reassurance
      # next to it — a focal figure arguing against its own card. The flagged
      # count is what the card is actually about.
      facts["count"] && [ facts["count"].to_s, t("insights.figures.need_attention") ]
    when "budget_on_track"
      # Still the right figure here, where overall usage *is* the subject.
      facts["budget_spent_pct"] && [ "#{facts["budget_spent_pct"]}%", t("insights.figures.of_budget") ]
    when "bill_not_covered"
      facts["shortfall"] && [ facts["shortfall"], t("insights.figures.short_on", date: facts["due_on"]) ]
    when "loan_payment_change"
      facts["new_payment"] && [ facts["new_payment"], facts["effective_on"] ]
    when "bank_fees"
      facts["amount"] && [ facts["amount"], t("insights.figures.fee_charges", count: facts["count"].to_i) ]
    when "fixed_commitments_ratio"
      facts["current_ratio"] && [ "#{facts["current_ratio"]}%", t("insights.figures.of_income") ]
    end
  end

  # The contextual action for a card, built from the subject ids each
  # generator stores in metadata. Returns nil when the subject no longer
  # resolves (deleted category/account) — the card renders without a link.
  # Looks up through insight.family, not Current, so broadcast renders work.
  def insight_action(insight)
    metadata = insight.metadata || {}

    case insight.insight_type
    when "spending_anomaly"
      category = insight.family.categories.find_by(id: metadata["category_id"])
      category && {
        text: t("insights.actions.spending_anomaly", category: category.name),
        href: transactions_path(q: { categories: [ category.name ] })
      }
    when "idle_cash", "bill_not_covered", "loan_payment_change"
      account = insight_account(insight)
      account && { text: t("insights.actions.#{insight.insight_type}"), href: account_path(account) }
    when "bank_fees"
      account = insight_account(insight)
      fee_names = insight.family.categories.fees.pluck(:name)
      return nil unless account && fee_names.any? && insight.period_start && insight.period_end
      { text: t("insights.actions.bank_fees"),
        href: transactions_path(q: { account_ids: [ account.id ], categories: fee_names, status: [ "confirmed" ], types: [ "expense", "income" ],
                                     start_date: insight.period_start.to_s, end_date: insight.period_end.to_s }) }
    when "subscription_audit"
      { text: t("insights.actions.subscription_audit"), href: recurring_transactions_path }
    when "cash_flow_warning", "fixed_commitments_ratio"
      { text: t("insights.actions.#{insight.insight_type}"), href: recurring_transactions_path }
    when "savings_rate_change"
      return nil unless insight.period_start && insight.period_end
      { text: t("insights.actions.savings_rate_change"),
        href: transactions_path(q: { start_date: insight.period_start.to_s, end_date: insight.period_end.to_s }) }
    when "net_worth_milestone"
      { text: t("insights.actions.net_worth_milestone"), href: reports_path }
    when "budget_at_risk", "budget_on_track"
      return nil unless insight.period_start
      { text: t("insights.actions.budget"), href: budget_path(Budget.date_to_param(insight.period_start)) }
    when "maintained_goal_depleted"
      goal = insight.family.goals.find_by(id: metadata["goal_id"])
      goal && { text: t("insights.actions.maintained_goal_depleted"), href: goal_path(goal) }
    end
  end

  # "Dig in with AI" opens a chat about the insight (#4031). Gated per family,
  # not per user, because cards are also rendered in broadcasts without a
  # Current.user; chats#new asks a user without AI consent to opt in.
  def insight_dig_in_available?(insight)
    family = insight.family
    return false unless family.assistant_enabled?

    family.effective_assistant_type == "external" ? Assistant::External.configured? : Provider::Registry.preferred_llm_provider.present?
  end

  # Fills only these placeholders, so a mistyped one in an override stays as typed.
  def insight_dig_in_prompt(insight)
    values = {
      "title" => insight.title,
      "body" => insight.body,
      "period" => insight.period_start && insight.period_end ? "#{l(insight.period_start)} – #{l(insight.period_end)}" : "–",
      "facts" => (insight.facts || {}).map { |key, value| "- #{key.to_s.humanize}: #{value}" }.join("\n")
    }
    template = insight.family.ai_prompt(:insight_dig_in) || t("insights.dig_in.prompt")

    template.gsub(/%\{(#{values.keys.join("|")})\}/) { values[$1] }
  end

  # Sentiment picks the color; priority only orders the feed. The two are
  # orthogonal — a big savings-rate improvement is high priority AND good news,
  # and must not render red. Red is reserved for a projected-negative balance,
  # matching the app's wider rule that even negative amounts aren't red.
  def insight_icon_color(insight)
    case insight_sentiment(insight)
    when :positive then "success"
    when :negative then "destructive"
    when :warning then "warning"
    else "default"
    end
  end

  # CSS color for the tinted icon circle (FilledIcon-style, color-mix'd to a
  # 10% tint) — CSS variables so dark mode retunes automatically.
  def insight_icon_css_color(insight)
    case insight_sentiment(insight)
    when :positive then "var(--color-success)"
    when :negative then "var(--color-destructive)"
    when :warning then "var(--color-warning)"
    else "var(--color-gray-500)"
    end
  end

  # Derived from type + the direction already stored in metadata, so rows
  # written before a metadata-shape change degrade to :warning, never :negative.
  def insight_sentiment(insight)
    metadata = insight.metadata || {}

    case insight.insight_type
    when "net_worth_milestone", "budget_on_track"
      :positive
    when "savings_rate_change"
      metadata["current_rate"].to_f >= metadata["previous_rate"].to_f ? :positive : :warning
    when "spending_anomaly"
      metadata["direction"] == "below" ? :positive : :warning
    when "cash_flow_warning"
      metadata["negative"] ? :negative : :warning
    when "bill_not_covered"
      # Paying the bill would take the account below zero.
      :negative
    when "loan_payment_change"
      metadata["new_payment"].to_f < metadata["previous_payment"].to_f ? :positive : :warning
    when "budget_at_risk", "maintained_goal_depleted", "bank_fees", "fixed_commitments_ratio"
      # Warning, not negative: the reserve is short, not overdrawn, and red is
      # reserved here for money actually going the wrong side of zero.
      :warning
    else
      :neutral
    end
  end

  private
    def insight_account(insight)
      insight.family.accounts.visible.find_by(id: (insight.metadata || {})["account_id"])
    end

    # "June" for month-aligned periods, "Next 30 days" / "Last 30 days" for
    # rolling windows, an explicit range otherwise; subject name (account,
    # merchant) for insights without a period.
    def insight_period_label(insight)
      start_date = insight.period_start
      end_date = insight.period_end

      if start_date.nil? || end_date.nil?
        facts = insight.facts || {}
        return facts["account"] || facts["name"]
      end

      days = (end_date - start_date).to_i
      if rolling_period_insight?(insight) && start_date >= Date.current - 1
        t("insights.meta.next_n_days", count: days)
      elsif rolling_period_insight?(insight) && end_date >= Date.current - 1
        t("insights.meta.last_n_days", count: days)
      elsif start_date == start_date.beginning_of_month && end_date == start_date.end_of_month
        insight_month_name(start_date)
      elsif start_date == start_date.beginning_of_month && end_date == end_date.end_of_month
        t("insights.meta.date_range", from: insight_month_name(start_date), to: insight_month_name(end_date))
      elsif start_date >= Date.current - 1
        t("insights.meta.next_n_days", count: days)
      elsif end_date >= Date.current - 1
        t("insights.meta.last_n_days", count: days)
      else
        t("insights.meta.date_range", from: I18n.l(start_date, format: :short), to: I18n.l(end_date, format: :short))
      end
    end

    def insight_month_name(date)
      I18n.l(date, format: date.year == Date.current.year ? "%B" : "%B %Y")
    end

    def rolling_period_insight?(insight)
      insight.insight_type.in?(%w[cash_flow_warning net_worth_milestone])
    end
end