Class: Cats::Core::DispatchAuthorization

Inherits:
Authorization show all
Defined in:
app/models/cats/core/dispatch_authorization.rb

Constant Summary

Constants inherited from Authorization

Authorization::AUTHORIZED, Authorization::CONFIRMED, Authorization::STATUSES

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Authorization

#confirm, #set_unit, #transactions

Class Method Details

.ransackable_associations(_auth_object = nil) ⇒ Object



51
52
53
# File 'app/models/cats/core/dispatch_authorization.rb', line 51

def self.ransackable_associations(_auth_object = nil)
  %w[dispatch_transactions]
end

.ransackable_attributes(_auth_object = nil) ⇒ Object



47
48
49
# File 'app/models/cats/core/dispatch_authorization.rb', line 47

def self.ransackable_attributes(_auth_object = nil)
  %w[authorized_by_id dispatch_id quantity status store_id unit_id]
end

Instance Method Details

#validate_commodity_availability_in_storeObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/models/cats/core/dispatch_authorization.rb', line 27

def validate_commodity_availability_in_store
  return if status == CONFIRMED

  return unless dispatch && store && quantity && unit

  commodity = dispatch.dispatch_plan_item.commodity
  stacks = Stack.where(store: store, commodity: commodity)
  if stacks.count.zero?
    errors.add(:store, "does not contain commodity #{commodity.batch_no}.")
    return
  end
  stack_quantity = stacks.map { |s| UnitConversion.convert(s.unit, unit, s.quantity) }.sum
  authorizations = DispatchAuthorization.where(dispatch: dispatch, store: store)
  authorized = authorizations.map { |a| UnitConversion.convert(a.unit, unit, a.quantity) }.sum
  authorized -= quantity_was if persisted?

  diff = quantity + authorized - stack_quantity
  errors.add(:quantity, "exceeds available quantity in store by #{diff} #{unit.abbreviation}.") if diff.positive?
end

#validate_dispatch_plan_item_quantityObject



14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/models/cats/core/dispatch_authorization.rb', line 14

def validate_dispatch_plan_item_quantity
  return if status == CONFIRMED

  return unless dispatch && quantity && unit

  authorizations = DispatchAuthorization.joins(:dispatch).where(
    dispatch: {dispatch_plan_item_id: dispatch.dispatch_plan_item_id}
  )
  quantity_attribs = %w[dispatch_plan_item quantity]
  unit_attribs = %w[dispatch_plan_item unit]
  ValidationUtil.validate_quantity(self, "dispatch", authorizations, "allocated", quantity_attribs, unit_attribs)
end

#validate_dispatch_statusObject



8
9
10
11
12
# File 'app/models/cats/core/dispatch_authorization.rb', line 8

def validate_dispatch_status
  return unless dispatch

  errors.add(:dispatch, "is not in draft state.") unless dispatch.dispatch_status == Dispatch::DRAFT
end