Class: SpreeCmCommissioner::Imports::Orders::Update

Inherits:
Base
  • Object
show all
Defined in:
app/services/spree_cm_commissioner/imports/orders/update.rb

Constant Summary collapse

BATCH_SIZE =
ENV.fetch('IMPORT_ORDERS_BATCH_SIZE', '50').to_i

Instance Attribute Summary

Attributes inherited from Base

#fail_row_numbers, #import_order_id

Instance Method Summary collapse

Methods inherited from Base

#call, #cleaned_value, #fetch_content, #import_order, #initialize, #record_failure, #save_fail_rows, #update_import_status_when_finish, #update_import_status_when_start

Constructor Details

This class inherits a constructor from SpreeCmCommissioner::Imports::Orders::Base

Instance Method Details

#import_ordersObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/services/spree_cm_commissioner/imports/orders/update.rb', line 7

def import_orders
  file_path = fetch_content
  batch = []

  begin
    CSV.foreach(file_path, headers: true).with_index(2) do |row, index|
      batch << [row, index]

      if batch.size >= BATCH_SIZE
        process_batch(batch)
        batch = []
      end
    end

    process_batch(batch) unless batch.empty?
  ensure
    FileUtils.rm_f(file_path)
  end
end

#process_batch(batch) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'app/services/spree_cm_commissioner/imports/orders/update.rb', line 27

def process_batch(batch)
  batch.each do |row, index|
    ActiveRecord::Base.transaction do
      process_row(row, index)
    rescue StandardError
      record_failure(index)
    end
  end
end

#process_row(row, index) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'app/services/spree_cm_commissioner/imports/orders/update.rb', line 37

def process_row(row, index)
  order_number = cleaned_value(row['order_number'])
  order = Spree::Order.find_by(number: order_number)

  unless order
    record_failure(index)
    return
  end

  guest_id = cleaned_value(row['guest_id'])
  seat_number = cleaned_value(row['seat_number'])

  guest =
    order.guests.find_by(seat_number: seat_number) ||
    order.guests.find_by(id: guest_id)

  unless guest
    record_failure(index)
    return
  end

  guest_data = row.to_hash
                  .symbolize_keys
                  .slice(*SpreeCmCommissioner::Guest.csv_importable_columns)

  guest_data.compact_blank!

  if guest.update(guest_data)
    recalculate_order(order)
  else
    record_failure(index)
  end
end

#recalculate_order(order) ⇒ Object



71
72
73
# File 'app/services/spree_cm_commissioner/imports/orders/update.rb', line 71

def recalculate_order(order)
  order.update_with_updater!
end