Skip to content

Instantly share code, notes, and snippets.

@iarie
Last active June 8, 2020 13:35
Show Gist options
  • Save iarie/5d7b50a25efaaed2ace0e2cd86217520 to your computer and use it in GitHub Desktop.
Save iarie/5d7b50a25efaaed2ace0e2cd86217520 to your computer and use it in GitHub Desktop.
Find stuck shipments by criteria: shipment should have similar
# May
interval = Date.new(2020, 5, 1).all_month
stock_location_ids = Spree::Supplier.alphabroder.stock_location_ids
order_ids = Spree::Order.joins(:shipments).where(
completed_at: interval,
spree_shipments: {
state: 'processing',
stock_location_id: stock_location_ids
}
).where(
'spree_shipments.deleted_at IS NULL'
).ids.uniq; order_ids.size
orders_and_shipments = Spree::Order.includes(:shipments).find(order_ids).map do |order|
sorted_shipments = order.shipments.map do |s|
{
id: s.id,
state: s.state,
stock_location_id: s.stock_location_id,
delivery_date: s.delivery_date,
shipping_rule_id: s.shipping_rule_id
}
end.sort_by(&:first)
[order.number, sorted_shipments]
end.to_h
# search for "twin" shipment for 'processing' using critera:
# shipment must be from same WH and with same delivery date
pairs = orders_and_shipments.map do |_, shipments|
processing = shipments.find { |x| x[:state] == 'processing' }
twin = shipments.find do |x|
x[:id] != processing[:id] &&
x[:stock_location_id] == processing[:stock_location_id] &&
x[:delivery_date] == processing[:delivery_date]
end
next unless twin
[processing[:id], twin[:state]]
end.compact
# pairs.group_by(&:last).transform_values(&:size)
# => {"shipped"=>723, "picking"=>103, "processing"=>1}
shipments_to_update = pairs.select { |x| x.last == 'shipped' }
# UPDATE DB:
#
# shipments_to_update.map do |x|
# ship = Spree::Shipment.find(x[:id])
# ship.transaction do
# ship.update_column(state: 'shipped')
# ship.supplier_shipments.update_all(status: 'shipped')
# end
# print('.')
# [ship.id]
# end; print('');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment