Class: Comee::Core::GoodsReceivedNoteService

Inherits:
Object
  • Object
show all
Defined in:
app/services/comee/core/goods_received_note_service.rb

Instance Method Summary collapse

Instance Method Details

#calculate_grn_total_price(goods_received_note) ⇒ Object



64
65
66
# File 'app/services/comee/core/goods_received_note_service.rb', line 64

def calculate_grn_total_price(goods_received_note)
  goods_received_note.received_items.sum(:total_price)
end

#calculate_grn_total_quantity(goods_received_note) ⇒ Object



60
61
62
# File 'app/services/comee/core/goods_received_note_service.rb', line 60

def calculate_grn_total_quantity(goods_received_note)
  goods_received_note.received_items.sum(:quantity_received)
end

#check_grn_existence(purchase_order) ⇒ Object

Raises:

  • (StandardError)


54
55
56
57
58
# File 'app/services/comee/core/goods_received_note_service.rb', line 54

def check_grn_existence(purchase_order)
  return unless GoodsReceivedNote.exists?(purchase_order_id: purchase_order.id)

  raise(StandardError, "Goods Received Note already exists for this purchase order")
end

#generate_received_note(id) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'app/services/comee/core/goods_received_note_service.rb', line 4

def generate_received_note(id)
  goods_received_note = nil

  begin
    purchase_order = PurchaseOrder.find(id)
  rescue ActiveRecord::RecordNotFound
    raise StandardError, "Purchase Order does not exist."
  end

  if GoodsReceivedNote.exists?(purchase_order: purchase_order)
    raise StandardError, "Goods Received Note already exists for this purchase order"
  end

  GoodsReceivedNote.transaction do
    purchase_order_items = PurchaseOrderItem.where(purchase_order_id: purchase_order.id)

    goods_received_note = GoodsReceivedNote.create!(
      date_of_receipt: Date.current,
      total_quantity: 0, # set initial quantity
      total_amount: 0, # set initial amount
      received_condition: "",
      comments: "",
      purchase_order_id: purchase_order.id
    )

    begin
      ReceivedItem.insert_all(
        purchase_order_items.map do |poi|
          {
            purchase_order_item_id: poi.id,
            goods_received_note_id: goods_received_note.id,
            unit_price: poi.price,
            total_price: poi.total_price,
            quantity_ordered: poi.quantity,
            quantity_received: 0
          }
        end
      )
    rescue StandardError => e
      raise StandardError, "Failed to generate received note items: #{e.message}"
    end
    total_quantity = calculate_grn_total_quantity(goods_received_note)
    total_price = calculate_grn_total_price(goods_received_note)
    goods_received_note.update!(total_amount: total_price, total_quantity: total_quantity)
  end
  goods_received_note
rescue StandardError
  raise
end