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, total_amount: 0, 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
|