Skip to content

Instantly share code, notes, and snippets.

@cored
Created September 14, 2018 15:16
Show Gist options
  • Save cored/b4c6279e06def49eb89497ff3265a560 to your computer and use it in GitHub Desktop.
Save cored/b4c6279e06def49eb89497ff3265a560 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
module Shipments
class Build
def self.shipments_for(shipments_payload:)
shipments_payload.map do |shipment_payload|
call(payload: shipment_payload)
end
end
def self.call(payload:)
new(params: ActionController::Parameters.new(payload)).call
end
def initialize(params:)
@params = params
end
def call
build_shipment_items(shipment)
shipment
end
private
def shipment
@shipment ||= Shipment.new(shipment_params).tap do |shipment|
shipment.trading_partner_identifier ||= TradingPartnerIdentifier::CASPER_IDENTIFIER
shipment.shipping_address = Address.new(address_params)
shipment.mattress_removal = mattress_removal?
end
end
def build_shipment_items(shipment)
Array(params[:inventory_units]).compact.map do |item|
product = Product.find_by!(sku: item[:product_id])
if variation_skus = ::Product::SPLIT_VARIATION_PRODUCTS[product.sku]
variation_skus.map do |sku|
item[:quantity].times do
shipment.shipment_items
.build(product: product, requested_variation_sku: sku)
end
end
else
item[:quantity].times do
shipment.shipment_items.build(product: product)
end
end
end.flatten
end
def shipment_params
@shipment_params ||= permitted_shipment_params.tap do |shipment_params|
if params[:delivery_preference].present?
shipment_params[:delivery_availability] = params[:delivery_preference].to_json
end
shipment_params[:held_for_review_at] = Time.now.utc if params[:hold_for_review] == true
end
end
def permitted_shipment_params
params.permit(
:number, :order_number, :order_completed_at, :order_admin_notes,
:vip, :email,:signature_required, :special_instructions,
:order_special_instructions, :status, :hold_for_arrival_on,
:shipped_at, :held_for_review_at, :deleted_at, :text_message_number,
:box_sku, :shipping_preference, :selected_slot_window_start,
:selected_slot_window_end, :messaged_ships_by, :shipment_timezone,
:locale, :warehouse_id, :mattress_removal
)
end
def address_params
permitted_address_params.tap do |address_params|
address_params[:zipcode] = address_params[:zipcode].split('-').first
address_params[:address2] ||= ""
address_params[:solidus_address_identifier] = params[:shipping_address][:id]
end
end
def permitted_address_params
params.require(:shipping_address).permit(
:firstname, :lastname, :address1, :address2, :city,
:zipcode, :phone, :state, :company, :country
)
end
def mattress_removal?
params[:mattress_removal].presence || !params.dig("shipping_method", "mattress_removal").nil?
end
attr_reader :params
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment