Class: Cats::Core::Authorization

Inherits:
ApplicationRecord show all
Defined in:
app/models/cats/core/authorization.rb

Direct Known Subclasses

DispatchAuthorization, ReceiptAuthorization

Constant Summary collapse

AUTHORIZED =

Authorization statuses

"Authorized".freeze
CONFIRMED =
"Confirmed".freeze
STATUSES =
[AUTHORIZED, CONFIRMED].freeze

Instance Method Summary collapse

Instance Method Details

#confirmObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'app/models/cats/core/authorization.rb', line 58

def confirm
  if instance_of?(DispatchAuthorization)
    ActiveRecord::Base.transaction do
      raise(StandardError, "Authorization does not have transactions.") if transactions.blank?

      transactions.each(&:commit)
      self.status = CONFIRMED
      save!
      reload
      if dispatch.all_authorizations_confirmed?
        Util.generate_pin(dispatch)
        dispatch.quantity = dispatch.dispatch_transactions.sum(:quantity)
        dispatch.dispatch_status = Dispatch::READY_TO_START
        dispatch.save!
      end
    end
  elsif instance_of?(ReceiptAuthorization)
    raise(StandardError, "Authorization does not have receipts.") unless receipts.count.positive?

    total_received = receipts.sum(:quantity)
    total_lost = lost_commodities.sum(:quantity)
    diff = quantity - (total_received + total_lost)
    raise(StandardError, "A quantity of #{diff} is unaccounted for.") unless diff.zero?

    self.received_quantity = total_received
    self.status = CONFIRMED
    save!
    Util.generate_pin(self)
  end
  self
end

#set_unitObject



30
31
32
33
34
35
36
# File 'app/models/cats/core/authorization.rb', line 30

def set_unit
  return if unit

  return unless dispatch

  self.unit = dispatch.unit
end

#transactionsObject

A convenience method to return dispatch or receipt transactions based on the authorization type.



52
53
54
55
56
# File 'app/models/cats/core/authorization.rb', line 52

def transactions
  return dispatch_transactions if instance_of?(DispatchAuthorization)

  receipt_transactions if instance_of?(ReceiptAuthorization)
end

#validate_dispatch_statusObject



38
39
40
41
42
43
44
45
46
47
48
# File 'app/models/cats/core/authorization.rb', line 38

def validate_dispatch_status
  return unless dispatch

  if instance_of?(DispatchAuthorization)
    errors.add(:dispatch, "is not in draft state.") unless dispatch.dispatch_status == Dispatch::DRAFT
  else
    return if dispatch.dispatch_status == Cats::Core::Dispatch::STARTED

    errors.add(:dispatch, 'should be in "Started" state.')
  end
end