The personal finance app for everyone (by everyone)
Ruby
class InsightsController < ApplicationController
before_action :require_preview_features!
before_action :set_insight, only: %i[acknowledge unacknowledge]
def index
load_feed
@breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("insights.index.title"), nil ] ]
# Viewing the feed is what "read" means here; the New badge for this
# render comes from @unread_ids captured above. Turbo's hover prefetch
# hits this GET before the user actually navigates, so skip the write
# for prefetch requests or badges would clear on hover.
unless prefetch_request?
Current.family.insights.visible.active.update_all(status: "read", read_at: Time.current, updated_at: Time.current)
end
end
def acknowledge
@insight.acknowledge!
# Both surfaces: the response carries streams for the /insights list and the
# dashboard widget, and each page applies only the ones whose targets it has.
# The list (not just the acknowledged card) is reloaded so its empty state
# can take over when the last insight goes.
load_feed
load_widget_feed
respond_to do |format|
format.turbo_stream
format.html { redirect_back_or_to insights_path }
end
end
def unacknowledge
@insight.unacknowledge!
load_feed
load_widget_feed
respond_to do |format|
format.turbo_stream
format.html { redirect_back_or_to insights_path }
end
end
def refresh
GenerateInsightsJob.perform_later(family_id: Current.family.id)
respond_to do |format|
# Swaps the button into its pending state; the job broadcasts the
# refreshed list and the idle button back when it finishes.
format.turbo_stream
format.html { redirect_to insights_path, notice: t("insights.refresh.queued") }
end
end
private
def set_insight
# Not `visible`: unacknowledge targets acknowledged rows. The account
# check still applies, so a hidden row can't be changed by id.
@insight = Current.family.insights.about_shared_accounts.find(params[:id])
end
def load_feed
@insights = Current.family.insights.visible.ordered.to_a
@unread_ids = @insights.select(&:active?).map(&:id).to_set
end
# Acknowledging is reachable from the dashboard widget as well as this page,
# so the response re-renders the widget's top three. Removing a row there
# should promote the next insight into the freed slot, not leave a gap.
def load_widget_feed
@feed_insights = Current.family.insights.visible.ordered.limit(Insight::FEED_LIMIT).to_a
end
# Turbo sends X-Sec-Purpose (the fetch spec forbids setting Sec-Purpose
# from JS) on hover-prefetch requests.
def prefetch_request?
request.headers["X-Sec-Purpose"] == "prefetch" || request.headers["Sec-Purpose"].to_s.include?("prefetch")
end
end