Class: SolidusImporter::SpreeCoreImporterOrder

Inherits:
Spree::Core::Importer::Order
  • Object
show all
Defined in:
app/models/solidus_importer/spree_core_importer_order.rb

Class Method Summary collapse

Class Method Details

.import(user, params) ⇒ Object



3
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
# File 'app/models/solidus_importer/spree_core_importer_order.rb', line 3

def self.import(user, params)
  params = params.to_h
  ActiveRecord::Base.transaction do
    ensure_country_id_from_params params[:ship_address_attributes]
    ensure_state_id_from_params params[:ship_address_attributes]
    ensure_country_id_from_params params[:bill_address_attributes]
    ensure_state_id_from_params params[:bill_address_attributes]

    create_params = params.slice :currency
    order = Spree::Order.create! create_params
    order.store ||= Spree::Store.default
    order.associate_user!(user)
    order.save!

    shipments_attrs = params.delete(:shipments_attributes)

    create_line_items_from_params(params.delete(:line_items_attributes), order)
    create_shipments_from_params(shipments_attrs, order)
    create_adjustments_from_params(params.delete(:adjustments_attributes), order)
    create_payments_from_params(params.delete(:payments_attributes), order)

    params.delete(:user_id) unless user.try(:has_spree_role?, "admin") && params.key?(:user_id)

    completed_at = params.delete(:completed_at)

    order.update!(params)

    order.create_proposed_shipments unless shipments_attrs.present?

    if completed_at
      order.completed_at = completed_at
      order.state = 'complete'
      order.save!
    end

    # Really ensure that the order totals & states are correct
    updater = SolidusImporter::OrderUpdater.new(order)
    updater.update
    if shipments_attrs.present?
      order.shipments.each_with_index do |shipment, index|
        shipment.update_columns(cost: shipments_attrs[index][:cost].to_f) if shipments_attrs[index][:cost].present?
      end
    end
    order.reload
  end
end