Class: LlmCostTracker::ReconciliationController

Inherits:
ApplicationController show all
Defined in:
app/controllers/llm_cost_tracker/reconciliation_controller.rb

Instance Method Summary collapse

Instance Method Details

#indexObject



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'app/controllers/llm_cost_tracker/reconciliation_controller.rb', line 5

def index
  @reconciliation_enabled = LlmCostTracker::Reconciliation.enabled?
  @reconciliation_installed = LlmCostTracker::ProviderInvoice.table_exists?
  if @reconciliation_enabled && @reconciliation_installed
    @scopes = invoice_scopes
    @sources = @scopes.map { |scope| scope[:source] }.uniq
    @diffs = @scopes.filter_map { |scope| diff_for(scope) }
    @last_imported_at = LlmCostTracker::ProviderInvoice.maximum(:imported_at)
  else
    @scopes = []
    @sources = []
    @diffs = []
    @last_imported_at = nil
  end
  @threshold = LlmCostTracker::Reconciliation::DEFAULT_THRESHOLD_PERCENT
  @configured_importers = @reconciliation_enabled ? configured_importers : {}
end

#trigger_importObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/controllers/llm_cost_tracker/reconciliation_controller.rb', line 23

def trigger_import
  unless LlmCostTracker::Reconciliation.enabled?
    return redirect_to reconciliation_path, alert: "Reconciliation is disabled"
  end

  source = params[:source].to_s
  importer = configured_importers[source.to_sym]
  return redirect_to reconciliation_path, alert: "No importer configured for #{source}" if importer.nil?

  result = importer.call
  if result.respond_to?(:errors) && result.errors.any?
    LlmCostTracker::Logging.warn(
      "Reconciliation import for #{source} returned #{result.errors.size} row error(s)"
    )
    return redirect_to(
      reconciliation_path,
      alert: "Imported #{result.respond_to?(:total_imported) ? result.total_imported : 0} " \
             "#{source} rows with #{result.errors.size} row error(s); see Rails logs for details."
    )
  end
  message = if result.respond_to?(:total_imported)
              "Imported #{result.total_imported} #{source} rows"
            else
              "Triggered #{source} importer"
            end
  redirect_to reconciliation_path, notice: message
rescue StandardError => e
  LlmCostTracker::Logging.warn("Reconciliation import failed for #{source}: #{e.class}: #{e.message}")
  redirect_to reconciliation_path,
              alert: "Import failed (#{e.class.name}); see Rails logs for details."
end