Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
8.8 KB
Raw Blame
class RulesController < ApplicationController
  include StreamExtensions

  before_action :require_non_guest!, except: %i[index]
  before_action :set_rule, only: [  :edit, :update, :destroy, :apply, :confirm ]

  def index
    @rules = Current.family.rules.includes(:actions, conditions: :sub_conditions).ordered.to_a
    Rule.share_option_lists(@rules)
    @layout = Rule::Layout.new(Current.family, rules: @rules)
    @list_filter = Rule::ListFilter.new(@rules)

    # Fetch recent rule runs with pagination
    recent_runs_scope = RuleRun
                          .joins(:rule)
                          .where(rules: { family_id: Current.family.id })
                          .recent
                          .includes(:rule)

    @pagy, @recent_runs = pagy(recent_runs_scope, limit: safe_per_page, page_param: :runs_page)

    render layout: "settings"
  end

  def new
    @rule = Current.family.rules.build(
      resource_type: params[:resource_type].presence_in(Rule::SUPPORTED_RESOURCE_TYPES) || "transaction",
    )

    if params[:name].present?
      @rule.name = params[:name]
      @rule.conditions.build(
        condition_type: "transaction_name",
        operator: "like",
        value: params[:name]
      )
    end

    if params[:action_type].in?(Rule::Action::SUPPORTED_ACTION_TYPES) && params[:action_value].present?
      @rule.actions.build(
        action_type: params[:action_type],
        value: params[:action_value]
      )
    end
  end

  def create
    @rule = Current.family.rules.build(rule_params)

    if save_rule
      redirect_to confirm_rule_path(@rule, reload_on_close: true)
    else
      render_invalid_rule :new
    end
  end

  def apply
    @rule.update!(active: true)

    # The rule stayed off, so running it now would only repeat the slow query.
    if @rule.notification_baseline_timed_out?
      redirect_back_or_to rules_path, alert: t("rules.notification_baseline_timed_out")
      return
    end

    @rule.apply_later(ignore_attribute_locks: true)
    redirect_back_or_to rules_path, notice: "#{@rule.resource_type.humanize} rule activated"
  end

  def confirm
    @active_rules_above_count = @rule.active_rules_above.count
    # Compute provider, model, and cost estimation for auto-categorize actions
    if @rule.actions.any? { |a| a.action_type == "auto_categorize" }
      @selected_model, @estimated_cost = auto_categorize_estimate(@rule)
    end
  end

  def edit
  end

  def update
    @rule.assign_attributes(rule_params)

    if save_rule
      flash_message = if @rule.notification_baseline_timed_out?
        { alert: t("rules.notification_baseline_timed_out") }
      else
        { notice: t(".success") }
      end

      respond_to do |format|
        format.html { redirect_back_or_to rules_path, **flash_message }
        format.turbo_stream { stream_redirect_back_or_to rules_path, **flash_message }
      end
    else
      render_invalid_rule :edit
    end
  end

  def destroy
    @rule.destroy
    redirect_to rules_path, notice: t(".success")
  end

  # Orders the top-level items: groups and rules without a group. The rules
  # inside a group are ordered by RuleGroupsController#reorder.
  def reorder
    Rule::Layout.new(Current.family).reorder!(params.require(:items))
    head :no_content
  rescue ArgumentError
    head :unprocessable_entity
  end

  # Groups go too: without their rules they would be empty folders.
  def destroy_all
    Rule.transaction do
      Current.family.rules.destroy_all
      Current.family.rule_groups.destroy_all
    end
    redirect_to rules_path, notice: t(".success")
  end

  def confirm_all
    @rules = Current.family.rules
    @total_affected_count = Rule.total_affected_resource_count(@rules)

    # Compute AI cost estimation if any rule has auto_categorize action
    if @rules.any? { |r| r.actions.any? { |a| a.action_type == "auto_categorize" } }
      @selected_model, @estimated_cost = auto_categorize_estimate(
        Current.family,
        transaction_count: @total_affected_count
      )
    end
  end

  def apply_all
    ApplyAllRulesJob.perform_later(Current.family)
    redirect_back_or_to rules_path, notice: t("rules.apply_all.success")
  end

  def clear_ai_cache
    enqueue_ai_cache_reset
    redirect_to rules_path, notice: t("rules.clear_ai_cache.success")
  end

  private
    # A group typed into the form may be created by another request at the
    # same moment; the save then rolls back, and saving again finds it.
    def save_rule
      @rule.save
    rescue ActiveRecord::RecordNotUnique
      raise unless @rule.rule_group&.new_record?

      @rule.save
    end

    def render_invalid_rule(template)
      # A native select cannot preserve an invalid option on resubmission. An
      # action marked for destruction is not validated, but is still rendered.
      invalid_selector = @rule.errors[:resource_type].any? ||
        @rule.actions.any? { |action| action.errors[:action_type].any? || !action.action_type.in?(Rule::Action::SUPPORTED_ACTION_TYPES) } ||
        @rule.conditions.any? { |condition| invalid_condition_selector?(condition) }

      if invalid_selector
        render plain: @rule.errors.full_messages.to_sentence, status: :unprocessable_entity
        return
      end

      render template, status: :unprocessable_entity
    end

    def invalid_condition_selector?(condition)
      condition.errors[:condition_type].any? || condition.errors[:operator].any? ||
        condition.sub_conditions.any? { |sub_condition| invalid_condition_selector?(sub_condition) }
    end

    # Names the provider that will actually run, and prices against it.
    #
    # This previously hardcoded :openai, so an Anthropic install was quoted the
    # wrong model and a family on Jev was quoted a provider that would not run
    # at all. LlmUsage has no pricing for Jev, so the cost comes back nil and the
    # view says so rather than inventing a figure.
    def auto_categorize_estimate(scope, transaction_count: nil)
      family = scope.is_a?(Rule) ? scope.family : scope
      count = transaction_count || scope.affected_resource_count
      model = Ai.plan(:categorize, family:)&.model&.name
      return [ nil, nil ] if model.blank?

      cost = LlmUsage.estimate_auto_categorize_cost(
        transaction_count: count,
        category_count: family.categories.count,
        model: model
      )

      [ model, cost ]
    end

    # The reset itself happens in a background job, so an enqueue that never
    # lands looks exactly like a job that ran and found nothing. Logging the
    # request separately from the job's own "started" entry tells those apart.
    def enqueue_ai_cache_reset
      perform_ai_cache_reset_later

      DebugLogEntry.capture(
        category: ClearAiCacheJob::DEBUG_CATEGORY,
        level: "info",
        message: "AI cache reset requested from the rules page",
        source: self.class.name,
        family: Current.family,
        user: Current.user
      )
    end

    # Split out so the rescue below covers only the enqueue it reports on.
    # Anything that runs after the job is safely queued — the request log above,
    # the redirect — is then structurally incapable of being recorded as an
    # enqueue failure and retried, without that resting on the internals of
    # whatever those later steps happen to call.
    def perform_ai_cache_reset_later
      attempted_job = nil
      enqueued = ClearAiCacheJob.perform_later(Current.family) { |job| attempted_job = job }

      # perform_later turns an ActiveJob::EnqueueError — or an enqueue aborted by
      # a callback — into a false return rather than raising it, so the return
      # value is the only signal that the reset never reached the queue. The
      # yielded job carries the underlying error when there was one.
      return if enqueued

      raise attempted_job&.enqueue_error || ActiveJob::EnqueueError.new("ClearAiCacheJob was not enqueued")
    rescue => e
      DebugLogEntry.capture(
        category: ClearAiCacheJob::DEBUG_CATEGORY,
        level: "error",
        message: "AI cache reset could not be enqueued: #{e.class}: #{e.message}",
        source: self.class.name,
        family: Current.family,
        user: Current.user,
        metadata: { error_class: e.class.name, error_message: e.message }
      )
      raise
    end

    def set_rule
      @rule = Current.family.rules.find(params[:id])
    end

    def rule_params
      params.require(:rule).permit(
        :resource_type, :effective_date, :active, :name, :stop_processing, :apply_immediately,
        :rule_group_id, :new_rule_group_name,
        conditions_attributes: [
          :id, :condition_type, :operator, :value, :_destroy,
          sub_conditions_attributes: [ :id, :condition_type, :operator, :value, :_destroy ]
        ],
        actions_attributes: [
          :id, :action_type, :value, :_destroy, { value: [] },
          split_rows: [ :type, :name, :share, :category_id, :merchant_id, tag_ids: [] ]
        ]
      )
    end
end