Class: Cats::Core::StackTransaction

Inherits:
Transaction show all
Defined in:
app/models/cats/core/stack_transaction.rb

Constant Summary

Constants inherited from Transaction

Transaction::COMMITTED, Transaction::DRAFT, Transaction::STATUSES

Instance Method Summary collapse

Methods inherited from Transaction

#set_status

Instance Method Details

#commitObject



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

def commit
  StackTransaction.transaction do
    self.status = COMMITTED
    save!
    source.quantity -= UnitConversion.convert(unit, source.unit, quantity)
    source.save!
    destination.quantity += UnitConversion.convert(unit, destination.unit, quantity)
    destination.stack_status = Stack::ALLOCATED if destination.stack_status == Stack::RESERVED
    destination.save!
  end
end

#validate_commodityObject



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

def validate_commodity
  return unless source && destination

  return if source.commodity.batch_no == destination.commodity.batch_no

  errors.add(:commodity, "batch number should be the same.")
end

#validate_quantityObject



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

def validate_quantity
  return unless quantity.present? && source.present?

  dispatched = StackTransaction.where(source: source, status: DRAFT)
  total_dispatched = dispatched.reduce(0) do |_sum, rec|
    UnitConversion.convert(source.unit, Cats::Core::UnitOfMeasure.find(rec.unit_id), rec.quantity)
  end
  available = source.quantity - total_dispatched
  available += UnitConversion.convert(source.unit, unit, quantity_was) if quantity_was

  converted_quantity = UnitConversion.convert(source.unit, Cats::Core::UnitOfMeasure.find(unit_id), quantity)

  errors.add(:quantity, "total is higher than source quantity (Max = #{available}).") if converted_quantity > available
end