Class: Spree::Shipment

Inherits:
Base
  • Object
show all
Extended by:
DisplayMoney
Includes:
NumberAsParam
Defined in:
app/models/spree/shipment.rb

Defined Under Namespace

Classes: ManifestItem

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DisplayMoney

money_methods

Methods included from NumberAsParam

#to_param

Methods inherited from Base

belongs_to_required_by_default, page, spree_base_scopes

Methods included from Preferences::Preferable

#clear_preferences, #default_preferences, #defined_preferences, #get_preference, #has_preference!, #has_preference?, #preference_default, #preference_type, #set_preference

Instance Attribute Details

#special_instructionsObject

Returns the value of attribute special_instructions.



31
32
33
# File 'app/models/spree/shipment.rb', line 31

def special_instructions
  @special_instructions
end

Instance Method Details

#add_shipping_method(shipping_method, selected = false) ⇒ Object



90
91
92
# File 'app/models/spree/shipment.rb', line 90

def add_shipping_method(shipping_method, selected = false)
  shipping_rates.create(shipping_method: shipping_method, selected: selected, cost: cost)
end

#after_cancelObject



94
95
96
# File 'app/models/spree/shipment.rb', line 94

def after_cancel
  manifest.each { |item| manifest_restock(item) }
end

#after_resumeObject



98
99
100
# File 'app/models/spree/shipment.rb', line 98

def after_resume
  manifest.each { |item| manifest_unstock(item) }
end

#backordered?Boolean

Returns:

  • (Boolean)


102
103
104
# File 'app/models/spree/shipment.rb', line 102

def backordered?
  inventory_units.any?(&:backordered?)
end

#currencyObject



106
107
108
# File 'app/models/spree/shipment.rb', line 106

def currency
  order ? order.currency : Spree::Config[:currency]
end

#determine_state(order) ⇒ Object

Determines the appropriate state according to the following logic:

pending unless order is complete and order.payment_state is paid shipped if already shipped (ie. does not change the state) ready all other cases



115
116
117
118
119
120
121
# File 'app/models/spree/shipment.rb', line 115

def determine_state(order)
  return 'canceled' if order.canceled?
  return 'pending' unless order.can_ship?
  return 'pending' if inventory_units.any? &:backordered?
  return 'shipped' if shipped?
  order.paid? || Spree::Config[:auto_capture_on_dispatch] ? 'ready' : 'pending'
end

#discounted_costObject Also known as: discounted_amount



123
124
125
# File 'app/models/spree/shipment.rb', line 123

def discounted_cost
  cost + promo_total
end

#final_priceObject



128
129
130
# File 'app/models/spree/shipment.rb', line 128

def final_price
  cost + adjustment_total
end

#final_price_with_itemsObject



132
133
134
# File 'app/models/spree/shipment.rb', line 132

def final_price_with_items
  item_cost + final_price
end

#finalize!Object



136
137
138
139
# File 'app/models/spree/shipment.rb', line 136

def finalize!
  inventory_units.finalize_units!
  after_resume
end

#include?(variant) ⇒ Boolean

Returns:

  • (Boolean)


141
142
143
# File 'app/models/spree/shipment.rb', line 141

def include?(variant)
  inventory_units_for(variant).present?
end

#inventory_units_for(variant) ⇒ Object



145
146
147
# File 'app/models/spree/shipment.rb', line 145

def inventory_units_for(variant)
  inventory_units.where(variant_id: variant.id)
end

#inventory_units_for_item(line_item, variant = nil) ⇒ Object



149
150
151
# File 'app/models/spree/shipment.rb', line 149

def inventory_units_for_item(line_item, variant = nil)
  inventory_units.where(line_item_id: line_item.id, variant_id: line_item.variant_id || variant.id)
end

#item_costObject



153
154
155
# File 'app/models/spree/shipment.rb', line 153

def item_cost
  manifest.map { |m| (m.line_item.price + (m.line_item.adjustment_total / m.line_item.quantity)) * m.quantity }.sum
end

#line_itemsObject



157
158
159
# File 'app/models/spree/shipment.rb', line 157

def line_items
  inventory_units.includes(:line_item).map(&:line_item).uniq
end

#manifestObject



163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'app/models/spree/shipment.rb', line 163

def manifest
  # Grouping by the ID means that we don't have to call out to the association accessor
  # This makes the grouping by faster because it results in less SQL cache hits.
  inventory_units.group_by(&:variant_id).map do |_variant_id, units|
    units.group_by(&:line_item_id).map do |_line_item_id, units|
      states = {}
      units.group_by(&:state).each { |state, iu| states[state] = iu.sum(&:quantity) }

      line_item = units.first.line_item
      variant = units.first.variant
      ManifestItem.new(line_item, variant, units.sum(&:quantity), states)
    end
  end.flatten
end

#process_order_paymentsObject



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'app/models/spree/shipment.rb', line 178

def process_order_payments
  pending_payments = order.pending_payments.
                     sort_by(&:uncaptured_amount).reverse

  shipment_to_pay = final_price_with_items
  payments_amount = 0

  payments_pool = pending_payments.each_with_object([]) do |payment, pool|
    break if payments_amount >= shipment_to_pay
    payments_amount += payment.uncaptured_amount
    pool << payment
  end

  payments_pool.each do |payment|
    capturable_amount = if payment.amount >= shipment_to_pay
                          shipment_to_pay
                        else
                          payment.amount
                        end

    cents = (capturable_amount * 100).to_i
    payment.capture!(cents)
    shipment_to_pay -= capturable_amount
  end
end

#ready_or_pending?Boolean

Returns:

  • (Boolean)


204
205
206
# File 'app/models/spree/shipment.rb', line 204

def ready_or_pending?
  ready? || pending?
end

#refresh_rates(shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'app/models/spree/shipment.rb', line 208

def refresh_rates(shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END)
  return shipping_rates if shipped?
  return [] unless can_get_rates?

  # StockEstimator.new assigment below will replace the current shipping_method
  original_shipping_method_id = shipping_method.try(:id)

  self.shipping_rates = Stock::Estimator.new(order).
                        shipping_rates(to_package, shipping_method_filter)

  if shipping_method
    selected_rate = shipping_rates.detect do |rate|
      rate.shipping_method_id == original_shipping_method_id
    end
    self.selected_shipping_rate_id = selected_rate.id if selected_rate
  end

  shipping_rates
end

#selected_shipping_rate_idObject



228
229
230
# File 'app/models/spree/shipment.rb', line 228

def selected_shipping_rate_id
  selected_shipping_rate.try(:id)
end

#selected_shipping_rate_id=(id) ⇒ Object



232
233
234
235
236
# File 'app/models/spree/shipment.rb', line 232

def selected_shipping_rate_id=(id)
  shipping_rates.update_all(selected: false)
  shipping_rates.update(id, selected: true)
  save!
end

#set_up_inventory(state, variant, order, line_item) ⇒ Object



238
239
240
241
242
243
244
245
# File 'app/models/spree/shipment.rb', line 238

def set_up_inventory(state, variant, order, line_item)
  inventory_units.create(
    state: state,
    variant_id: variant.id,
    order_id: order.id,
    line_item_id: line_item.id
  )
end

#shipped=(value) ⇒ Object



247
248
249
250
# File 'app/models/spree/shipment.rb', line 247

def shipped=(value)
  return unless value == '1' && shipped_at.nil?
  self.shipped_at = Time.current
end

#shipping_methodObject



252
253
254
# File 'app/models/spree/shipment.rb', line 252

def shipping_method
  selected_shipping_rate.try(:shipping_method) || shipping_rates.first.try(:shipping_method)
end

#tax_categoryObject



256
257
258
# File 'app/models/spree/shipment.rb', line 256

def tax_category
  selected_shipping_rate.try(:tax_rate).try(:tax_category)
end

#tax_totalObject

Only one of either included_tax_total or additional_tax_total is set This method returns the total of the two. Saves having to check if tax is included or additional.



263
264
265
# File 'app/models/spree/shipment.rb', line 263

def tax_total
  included_tax_total + additional_tax_total
end

#to_packageObject



267
268
269
270
271
272
273
# File 'app/models/spree/shipment.rb', line 267

def to_package
  package = Stock::Package.new(stock_location)
  inventory_units.includes(:variant).joins(:variant).group_by(&:state).each do |state, state_inventory_units|
    package.add_multiple state_inventory_units, state.to_sym
  end
  package
end

#tracking_urlObject



275
276
277
# File 'app/models/spree/shipment.rb', line 275

def tracking_url
  @tracking_url ||= shipping_method.build_tracking_url(tracking)
end

#transfer_to_location(variant, quantity, stock_location) ⇒ Object

Raises:

  • (ArgumentError)


332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'app/models/spree/shipment.rb', line 332

def transfer_to_location(variant, quantity, stock_location)
  raise ArgumentError if quantity <= 0

  transaction do
    new_shipment = order.shipments.create!(stock_location: stock_location)

    order.contents.remove(variant, quantity, shipment: self)
    order.contents.add(variant, quantity, shipment: new_shipment)

    refresh_rates
    save!
    new_shipment.save!
  end
end

#transfer_to_shipment(variant, quantity, shipment_to_transfer_to) ⇒ Object

Raises:

  • (ArgumentError)


347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'app/models/spree/shipment.rb', line 347

def transfer_to_shipment(variant, quantity, shipment_to_transfer_to)
  quantity_already_shipment_to_transfer_to = shipment_to_transfer_to.manifest.find do |mi|
    mi.line_item.variant == variant
  end.try(:quantity) || 0
  final_quantity = quantity + quantity_already_shipment_to_transfer_to

  raise ArgumentError if quantity <= 0 || self == shipment_to_transfer_to

  transaction do
    order.contents.remove(variant, quantity, shipment: self)
    order.contents.add(variant, quantity, shipment: shipment_to_transfer_to)

    refresh_rates
    save!
    shipment_to_transfer_to.refresh_rates
    shipment_to_transfer_to.save!
  end
end

#update!(order) ⇒ Object

Updates various aspects of the Shipment while bypassing any callbacks. Note that this method takes an explicit reference to the Order object. This is necessary because the association actually has a stale (and unsaved) copy of the Order and so it will not yield the correct results.



322
323
324
325
326
327
328
329
330
# File 'app/models/spree/shipment.rb', line 322

def update!(order)
  old_state = state
  new_state = determine_state(order)
  update_columns(
    state: new_state,
    updated_at: Time.current
  )
  after_ship if new_state == 'shipped' && old_state != 'shipped'
end

#update_amountsObject



279
280
281
282
283
284
285
286
287
# File 'app/models/spree/shipment.rb', line 279

def update_amounts
  if selected_shipping_rate
    update_columns(
      cost: selected_shipping_rate.cost,
      adjustment_total: adjustments.additional.map(&:update!).compact.sum,
      updated_at: Time.current
    )
  end
end

#update_attributes_and_order(params = {}) ⇒ Object

Update Shipment and make sure Order states follow the shipment changes



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'app/models/spree/shipment.rb', line 290

def update_attributes_and_order(params = {})
  if update_attributes params
    if params.key? :selected_shipping_rate_id
      # Changing the selected Shipping Rate won't update the cost (for now)
      # so we persist the Shipment#cost before calculating order shipment
      # total and updating payment state (given a change in shipment cost
      # might change the Order#payment_state)
      update_amounts

      order.updater.update_shipment_total
      order.updater.update_payment_state

      # Update shipment state only after order total is updated because it
      # (via Order#paid?) affects the shipment state (YAY)
      update_columns(
        state: determine_state(order),
        updated_at: Time.current
      )

      # And then it's time to update shipment states and finally persist
      # order changes
      order.updater.update_shipment_state
      order.updater.persist_totals
    end

    true
  end
end