Class: Cats::Core::LostCommodity

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

Instance Method Summary collapse

Instance Method Details

#set_unitObject



14
15
16
17
18
19
20
# File 'app/models/cats/core/lost_commodity.rb', line 14

def set_unit
  return if unit

  return unless receipt_authorization

  self.unit = receipt_authorization.unit
end

#validate_quantityObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/models/cats/core/lost_commodity.rb', line 22

def validate_quantity
  return unless quantity && unit && receipt_authorization

  total = UnitConversion.convert(receipt_authorization.unit, unit, receipt_authorization.quantity)
  receipts = Receipt.where(receipt_authorization: receipt_authorization)
  losses = LostCommodity.where(receipt_authorization: receipt_authorization)
  used = UnitConversion.harmonized_total(receipts, unit) + UnitConversion.harmonized_total(losses, unit)
  used -= quantity_was if quantity_was

  remaining = total - used
  return unless quantity > remaining

  errors.add(:quantity, "exceeds authorized quantity. Maximum allowed is #{remaining} #{unit.abbreviation}")
end