class SpreeWinkelstraat::OrderImporter < Spree::Core::Importer::Order def self.import(user, params) begin 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.associate_user!(user) if user.present? 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) if completed_at = params.delete(:completed_at) order.completed_at = completed_at order.state = 'complete' end params.delete(:user_id) unless user.present? && user.try(:has_spree_role?, "admin") && params.key?(:user_id) order.update_attributes!(params) order.create_proposed_shipments unless shipments_attrs.present? # Really ensure that the order totals & states are correct 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 rescue Exception => e order.destroy if order && order.persisted? raise e.message end end def self.create_payments_from_params(payments_hash, order) return [] unless payments_hash payments_hash.each do |p| begin payment = order.payments.build order: order payment.amount = p.fetch(:amount, order.total) # Order API should be using state as that's the normal payment field. # spree_wombat serializes payment state as status so imported orders should fall back to status field. payment.state = p[:state] || p[:status] || 'completed' payment.created_at = p[:created_at] if p[:created_at] payment.payment_method = Spree::PaymentMethod.find_by_name!(p[:payment_method]) payment.source = create_source_payment_from_params(p[:source], payment) if p[:source] payment.save! rescue Exception => e raise "Order import payments: #{e.message} #{p}" end end end end