Class: Dscf::Core::AuditLoggerJob

Inherits:
ApplicationJob show all
Defined in:
app/jobs/dscf/core/audit_logger_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(record_id:, record_type:, before_main:, after_main:, before_associated:, after_associated:, action_name:, controller_name:, actor_id: nil, actor_type: nil, request_uuid: nil, ip_address: nil, user_agent: nil, configs: []) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
54
# File 'app/jobs/dscf/core/audit_logger_job.rb', line 8

def perform(record_id:, record_type:, before_main:, after_main:, before_associated:, after_associated:,
            action_name:, controller_name:, actor_id: nil, actor_type: nil,
            request_uuid: nil, ip_address: nil, user_agent: nil, configs: [])
  # Find the auditable record
  record = record_type.constantize.find_by(id: record_id)
  return unless record

  # Find the actor if present
  actor = actor_id && actor_type ? actor_type.constantize.find_by(id: actor_id) : nil

  # Calculate changes
  all_changes = calculate_changes(
    before_main: before_main,
    after_main: after_main,
    before_associated: before_associated,
    after_associated: after_associated,
    configs: configs
  )

  # Skip if no changes detected
  # Check for empty structured format
  return if all_changes.blank? ||
            (all_changes.is_a?(Hash) &&
             all_changes[:main].blank? &&
             all_changes[:associated].blank?)

  # Resolve action label
  action_label = resolve_action_label(action_name, configs)

  # Create audit log
  record.record_audit!(
    action_label,
    audited_changes: all_changes,
    metadata: {
      controller: controller_name,
      action: action_name,
      request_uuid: request_uuid
    },
    actor: actor,
    request_uuid: request_uuid,
    ip_address: ip_address,
    user_agent: user_agent
  )
rescue StandardError => e
  Rails.logger.error "AuditLoggerJob failed: #{e.message}\n#{e.backtrace.first(5).join("\n")}"
  raise
end