Class: UsageCredits::FulfillmentService

Inherits:
Object
  • Object
show all
Defined in:
lib/usage_credits/services/fulfillment_service.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fulfillment) ⇒ FulfillmentService

Returns a new instance of FulfillmentService.



24
25
26
27
# File 'lib/usage_credits/services/fulfillment_service.rb', line 24

def initialize(fulfillment)
  @fulfillment = fulfillment
  validate_fulfillment!
end

Class Method Details

.process_pending_fulfillmentsObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/usage_credits/services/fulfillment_service.rb', line 4

def self.process_pending_fulfillments
  count = 0
  failed = 0

  Fulfillment.due_for_fulfillment.find_each do |fulfillment|
    begin
      new(fulfillment).process
      count += 1
    rescue StandardError => e
      failed += 1
      Rails.logger.error "Failed to process fulfillment #{fulfillment.id}: #{e.message}"
      Rails.logger.error e.backtrace.join("\n")
      next # Continue with next fulfillment
    end
  end

  Rails.logger.info "Processed #{count} fulfillments (#{failed} failed)"
  count
end

Instance Method Details

#processObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/usage_credits/services/fulfillment_service.rb', line 29

def process
  ActiveRecord::Base.transaction do
    @fulfillment.lock! # row lock to avoid double awarding

    # re-check if it's still due, in case time changed or another process already updated it
    return unless @fulfillment.due_for_fulfillment?

    credits = calculate_credits
    give_credits(credits)
    update_fulfillment(credits)
  end
rescue UsageCredits::Error => e
  Rails.logger.error "Usage credits error processing fulfillment #{@fulfillment.id}: #{e.message}"
  raise
rescue StandardError => e
  Rails.logger.error "Unexpected error processing fulfillment #{@fulfillment.id}: #{e.message}"
  raise
end