Class: Shipment
Overview
== Schema Information
Table name: shipments
Database name: primary
id :integer not null, primary key
actual_delivery_date :date
actual_total_charges :decimal(8, 2)
amz_metadata :jsonb
audit_result :jsonb
audited :boolean default(FALSE), not null
carrier :string(255)
carrier_package_type :string(255)
container_code :string
container_type :enum default("carton"), not null
date_shipped :date
estimated_delivery_date :date
flat_rate_package_type :string
height :decimal(6, 1)
is_legacy :boolean default(FALSE), not null
is_manual :boolean
is_return :boolean default(FALSE), not null
is_ship_insured :boolean default(FALSE), not null
issues_count :integer default(0)
length :decimal(6, 1)
shipping_insurance_data :jsonb
state :string(255) default("manually_complete"), not null
sww_metadata :jsonb
tracking_carrier_description :string
tracking_carrier_status :string
tracking_description :string
tracking_number :string(255)
tracking_state :string default("not_yet_in_system")
tracking_status :string
uploads_count :integer default(0)
weight :decimal(10, 4)
width :decimal(6, 1)
created_at :datetime
updated_at :datetime
amz_shipment_id :string
delivery_id :integer
legacy_ep_carrier_account_id :string
legacy_ep_shipment_id :string
legacy_shipping_insurance_record_id :string
mail_activity_id :integer
manifest_id :integer
order_id :integer
order_shipment_id :integer
parent_shipment_id :integer
shipengine_label_id :string
standalone_delivery_id :integer
sww_label_id :string
Indexes
by_car_did (carrier,delivery_id)
by_delivery_id_w (delivery_id) WHERE (parent_shipment_id IS NULL)
by_st_did_w (state,delivery_id) WHERE (parent_shipment_id IS NULL)
idx_delivery_id_container_type (delivery_id,container_type)
idx_delivery_id_state_cont_type (delivery_id,state,container_type)
idx_state_delivery_id_order_id (state,delivery_id,order_id)
index_shipments_on_amz_shipment_id (amz_shipment_id) WHERE (amz_shipment_id IS NOT NULL)
index_shipments_on_container_code (container_code) UNIQUE
index_shipments_on_flat_rate_package_type (flat_rate_package_type)
index_shipments_on_legacy_ep_carrier_account_id (legacy_ep_carrier_account_id)
index_shipments_on_legacy_ep_shipment_id (legacy_ep_shipment_id)
index_shipments_on_mail_activity_id (mail_activity_id)
index_shipments_on_manifest_id (manifest_id)
index_shipments_on_parent_shipment_id (parent_shipment_id)
index_shipments_on_sww_label_id (sww_label_id) WHERE (sww_label_id IS NOT NULL)
index_shipments_on_tracking_state (tracking_state)
shipments_order_id_index (order_id)
Foreign Keys
fk_rails_... (delivery_id => deliveries.id) ON DELETE => cascade
fk_rails_... (parent_shipment_id => shipments.id) ON DELETE => nullify
Defined Under Namespace
Classes: AuditForm
Constant Summary
collapse
- PACKING_STATES =
Which shipments can be packed and get their content specified?
%w[suggested packed awaiting_label manually_complete].freeze
- MEASURED_STATES =
Recognised measured states.
%w[awaiting_label label_complete manually_complete].freeze
- PACKED_OR_MEASURED_STATES =
Recognised packed or measured states.
%w[packed awaiting_label label_complete manually_complete].freeze
- TRACKING_STATUS_INCOMPLETE =
Tracking status incomplete.
%w[not_yet_in_system unknown accepted in_transit exception delivery_attempt].freeze
- TRACKING_STATUS_COMPLETE =
Tracking status complete.
%w[delivered delivered_to_collection_location].freeze
- TRACKING_LOOKBACK_DAYS =
No need to collect hundreds of tracking calls on old unused labels. Give it a month then buh bye.
30
- GS1_PREFIX =
TRACKING_LOOKBACK_DAYS = 87 if Rails.env.development?
'0881308'
- MAX_WEIGHT_DELTA_PERCENT =
Maximum weight delta percent.
50.0
- MIN_WEIGHT_DELTA_LBS =
Minimum weight delta lbs.
3.0
- MAX_WEIGHT_DELTA_LBS =
Maximum weight delta lbs.
50.0
- PALLET_NOMINAL_WEIGHT =
41
- CRATE_NOMINAL_WEIGHT =
84
- WARNING_WEIGHT =
42.0
- ALERT_WEIGHT =
50.0
- WARNING_LENGTH =
32.0
- ALERT_LENGTH =
36.0
- WARNING_WIDTH =
26.0
- ALERT_WIDTH =
29.0
- WARNING_HEIGHT =
21.0
- ALERT_HEIGHT =
23.0
- ADDITIONAL_CARRIERS_TO_INCLUDE =
Additional carriers to include.
%w[GLS DPD DHL].freeze
- PACKDIM_CONTAINER_INTS =
Wire-format mapping used by #to_packdims / Item#to_packdims to keep the
5th element of every packdim row an integer. The packdims JSONB column
is the input to MD5-based packing dedup (see Shipping::Md5HashItem and
Packing.format_packdim_contents) — historic rows store the integer code,
so the enum-to-integer mapping is preserved here as a wire artifact even
though the column itself is now a Postgres enum.
{ 'carton' => 0, 'pallet' => 1, 'crate' => 2, 'palleted_crate' => 3 }.freeze
Models::Auditable::ALWAYS_IGNORED
Constants included
from Schedulable
Schedulable::SIMPLE_FORM_OPTIONS
Instance Attribute Summary collapse
#creator, #updater
Class Method Summary
collapse
Instance Method Summary
collapse
-
#amazon_container_code? ⇒ Boolean
-
#attach_paperless_qr(qr_png_tmp_path, instructions, handoff_code) ⇒ Upload
Attaches the paperless QR/barcode PNG that ShipEngine returned for this shipment under its dedicated upload category, and persists the carrier- supplied counter instructions and (optional) handoff PIN to the shipment so the return-instructions PDF can render them without re-fetching from ShipEngine.
-
#audit ⇒ Object
-
#bol_pdf ⇒ Object
-
#bps_barcode(file_path: nil, _partner_code: nil) ⇒ Object
-
#bps_barcode_string ⇒ Object
-
#bps_partner_code_prefix ⇒ Object
-
#carrier_icon ⇒ Object
-
#carrier_options_for_select ⇒ Object
-
#check_if_oversize ⇒ Object
-
#complete? ⇒ Boolean
-
#compute_item_declared_value ⇒ Object
-
#compute_item_weight ⇒ Object
-
#compute_shipment_declared_value(skip_carrier_guard: false) ⇒ Object
-
#compute_shipment_weight ⇒ Object
-
#compute_tare_weight ⇒ Object
-
#container_code_type ⇒ Object
-
#deep_dup ⇒ Object
-
#delivery_or_mail_activity ⇒ Object
-
#dimensions_changed? ⇒ Boolean
-
#dimensions_text(display_units: false) ⇒ Object
-
#dimensions_text_converted(unit: 'in', precision: 0, display_units: false) ⇒ Object
-
#editable? ⇒ Boolean
-
#effective_nmfc_code ⇒ Object
-
#enqueue_tracking_registration_if_needed ⇒ Object
after_commit hook: enqueue ShipmentTrackingRegistrationWorker whenever the shipment has just landed a (new) tracking_number for a carrier we can resolve to a ShipEngine carrier_code.
-
#entered_and_computed_weights_are_close? ⇒ Boolean
-
#final? ⇒ Boolean
-
#freight_class ⇒ Object
-
#freight_shipment? ⇒ Boolean
-
#full_dimension_text(metric: false) ⇒ Object
-
#generate_and_attach_sscc_label(return_existing: false) ⇒ Object
-
#generate_letter_ship_label_pdf(ship_label_tmp_path, carrier) ⇒ Object
-
#generate_ship_label_pdf(ship_label_tmp_path, carrier_to_use, is_return = false) ⇒ Object
-
#generate_speedee_label_pdf(options = {}) ⇒ Object
def generate_bol_pdf(ship_bol_tmp_path=nil) # if we have carrier generated BOL, use that if ship_bol_tmp_path # generate the pdf from the file path file_name = get_file_name('bol') ship_bol_pdf_path = Upload.temp_location(file_name) FileUtils.cp(ship_bol_tmp_path, ship_bol_pdf_path) # attach the finished bol pdf upload = Upload.uploadify(ship_bol_pdf_path, 'ship_bol_pdf') else # otherwise try to generate it using our template from scratch res = Shipping::BolGenerator.new.process(self.delivery) upload = Upload.uploadify_from_data(file_name: res.file_name, data: res.pdf, category: 'ship_bol_pdf', resource: self) end raise "BOL PDF was not generated" unless upload return self.uploads << upload end.
-
#generate_sscc_barcode(file_path = nil) ⇒ Object
-
#get_file_name(file_type) ⇒ Object
-
#has_dimensions? ⇒ Boolean
-
#height_converted(unit: 'in', precision: 0) ⇒ Object
-
#incurs_oversized_penalty? ⇒ Boolean
-
#is_rma_return? ⇒ Boolean
-
#is_service? ⇒ Boolean
-
#is_speedee_oversize? ⇒ Boolean
-
#length_converted(unit: 'in', precision: 0) ⇒ Object
-
#locked_for_fba? ⇒ Boolean
-
#manual_container_code ⇒ Object
-
#manual_container_code=(code) ⇒ Object
-
#manual_shipment ⇒ Object
-
#need_to_audit? ⇒ Boolean
-
#neither_legacy_nor_service ⇒ Object
-
#non_freight_shipment? ⇒ Boolean
-
#ok_to_delete_with_mail_activity? ⇒ Boolean
-
#ok_to_delete_with_standalone_delivery? ⇒ Boolean
-
#packed_or_pre_packed? ⇒ Boolean
-
#paperless_qr_file_name ⇒ Object
Filename for the paperless QR/barcode PNG attachment.
-
#paperless_qr_png ⇒ Upload?
The paperless QR/barcode PNG attached to this shipment, if any.
-
#part_of_a_locked_delivery? ⇒ Boolean
-
#qualifies_for_tracking_api? ⇒ Boolean
-
#ready_to_manually_complete? ⇒ Boolean
-
#reference_number ⇒ Object
-
#resource_reference_and_shipment_number ⇒ Object
(also: #order_reference_and_shipment_number)
-
#round_dimensions ⇒ Object
-
#run_audit(force = false) ⇒ Object
-
#sanitized_carrier ⇒ Object
-
#set_carrier(carrier_override = nil) ⇒ Object
-
#set_default_number ⇒ Object
-
#set_default_pallet_dimensions ⇒ Object
-
#set_default_shipment_weight ⇒ Object
When warehouse just wants to use the item shipping_weight.
-
#set_sscc ⇒ Object
-
#ship_label_pdf(letter_format = false) ⇒ Object
-
#shipment_content_grouped_content_key ⇒ Object
Creates a hash, key is a composite key with asin, sku, upc value is total quantity of that item If line item is a kit component, only kit parent is taken into account.
-
#shipment_content_label ⇒ Object
-
#shipment_content_quantity ⇒ Object
-
#shipment_index ⇒ Object
-
#shipment_position ⇒ Object
-
#shipment_total ⇒ Object
-
#shipment_tracking_number ⇒ Object
Initialize a shipment tracking number object.
-
#shipping_insurance_link ⇒ Object
-
#shipping_insurance_record_id ⇒ Object
-
#signature_confirmation? ⇒ Boolean
-
#similar_shipment_ids ⇒ Object
-
#skip_audit? ⇒ Boolean
-
#sort_dimensions ⇒ Object
-
#sort_string ⇒ Object
-
#sscc_code? ⇒ Boolean
-
#surface_sqin ⇒ Object
-
#to_package ⇒ Object
-
#to_packdims ⇒ Object
Only floats will serialize properly to json which is necessary in packing.rb, so don't remove .to_f ! The 5th element is intentionally the integer wire-format code (see PACKDIM_CONTAINER_INTS above) so MD5 hashes keep matching historic rows.
-
#to_s ⇒ Object
-
#tracking_link ⇒ Object
-
#voided? ⇒ Boolean
-
#volume ⇒ Object
-
#volume_in_cubic_feet ⇒ Object
-
#weight_converted(unit: 'lbs', precision: nil, display_units: false) ⇒ Object
-
#width_converted(unit: 'in', precision: 0) ⇒ Object
#all_skipped_columns, #audit_reference_data, #should_not_save_version, #stamp_record
ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation
config
#after_commit
#publish_event
Instance Attribute Details
#actual_total_charges ⇒ Object
259
|
# File 'app/models/shipment.rb', line 259
validates :actual_total_charges, numericality: { greater_than_or_equal_to: 0.0, if: :actual_total_charges }
|
#assign_sscc ⇒ Object
Returns the value of attribute assign_sscc.
164
165
166
|
# File 'app/models/shipment.rb', line 164
def assign_sscc
@assign_sscc
end
|
#carrier ⇒ Object
254
|
# File 'app/models/shipment.rb', line 254
validates :carrier, presence: { if: ->(s) { s.label_complete? || s.manually_complete? } }
|
#date_shipped ⇒ Object
253
|
# File 'app/models/shipment.rb', line 253
validates :date_shipped, presence: { if: :is_legacy }
|
#height ⇒ Object
256
|
# File 'app/models/shipment.rb', line 256
validates :width, :length, :height, presence: { if: :neither_legacy_nor_service }
|
#length ⇒ Object
256
|
# File 'app/models/shipment.rb', line 256
validates :width, :length, :height, presence: { if: :neither_legacy_nor_service }
|
#number ⇒ Object
Returns the value of attribute number.
164
165
166
|
# File 'app/models/shipment.rb', line 164
def number
@number
end
|
#shipments_number ⇒ Object
Returns the value of attribute shipments_number.
164
165
166
|
# File 'app/models/shipment.rb', line 164
def shipments_number
@shipments_number
end
|
#weight ⇒ Object
255
|
# File 'app/models/shipment.rb', line 255
validates :weight, presence: true
|
#width ⇒ Object
256
|
# File 'app/models/shipment.rb', line 256
validates :width, :length, :height, presence: { if: :neither_legacy_nor_service }
|
Class Method Details
.all_carriers_for_select ⇒ Object
758
759
760
761
762
|
# File 'app/models/shipment.rb', line 758
def self.all_carriers_for_select
options = SHIPPING_CARRIERS_OPTIONS.values.map { |o| o.map(&:last) }.flatten.uniq.sort
options += custom_carriers_for_select
options.compact.uniq
end
|
.awaiting_label ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are awaiting label. Active Record Scope
265
|
# File 'app/models/shipment.rb', line 265
scope :awaiting_label, -> { where(state: 'awaiting_label') }
|
.build_gs1_128(serial:, application_identifier: '00', gs1_prefix: GS1_PREFIX) ⇒ Object
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
|
# File 'app/models/shipment.rb', line 1153
def self.build_gs1_128(serial:, application_identifier: '00', gs1_prefix: GS1_PREFIX)
s = [0] s += gs1_prefix.chars s += serial.to_s.rjust(9, '0').chars
check_sum = 0
s.each_with_index do |digit, i|
factor = (i.modulo(2).zero? ? 3 : 1)
check_sum += digit.to_i * factor
end
check_ceil = (check_sum.to_f * 0.1).ceil * 10 s << (check_ceil - check_sum)
"#{application_identifier}#{s.join}"
end
|
.carrier_candidates_for_pickup ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are carrier candidates for pickup. Active Record Scope
293
|
# File 'app/models/shipment.rb', line 293
scope :carrier_candidates_for_pickup, ->(carrier) { top_level.joins(:delivery).label_complete.where(shipments: { carrier: carrier }).where("deliveries.state = 'pending_ship_confirm' or deliveries.state = 'shipped'") }
|
.carrier_icon(carrier) ⇒ Object
.carrier_options_for_select(delivery, show_all: false) ⇒ Object
744
745
746
747
748
749
750
751
752
753
754
755
756
|
# File 'app/models/shipment.rb', line 744
def self.carrier_options_for_select(delivery, show_all: false)
country_sym = (delivery.country&.iso3 || 'USA').to_sym
carriers = []
if show_all
SHIPPING_CARRIERS_OPTIONS.sort_by { |country_iso3, _carriers| country_iso3 == country_sym ? 0 : 1 }.each do |_country_iso3, country_carriers|
carriers += country_carriers
end
else
carriers = SHIPPING_CARRIERS_OPTIONS[country_sym]
end
carriers ||= OVERRIDE_OPTION
carriers.compact.uniq
end
|
.cartons ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are cartons. Active Record Scope
285
|
# File 'app/models/shipment.rb', line 285
scope :cartons, -> { where(container_type: 'carton') }
|
.choose_carrier_pickup_date_time(carrier, store) ⇒ Object
def self.choose_saia_pickup_date_time
datetime = Time.current
tz = 'America/Chicago'
Time.use_zone(tz) do
datetime = [Time.current, Time.zone.parse("2:00pm")].max
if datetime > Time.zone.parse("2:00pm")
datetime = 1.working.day.since(Time.zone.parse("10:00:00"))
end
end
datetime
end
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
|
# File 'app/models/shipment.rb', line 784
def self.choose_carrier_pickup_date_time(carrier, store)
pickup_date = ''
pickup_time = ''
pickup_date_time = nil
Time.use_zone(store.time_zone_string) do today_cut_off_time = Time.zone.parse('2:00pm')
today_cut_off_time = Time.zone.parse(Store::CARRIER_PICKUP_CUT_OFF_TIMES[store.name][carrier]) if Store::CARRIER_PICKUP_CUT_OFF_TIMES[store.name] && Store::CARRIER_PICKUP_CUT_OFF_TIMES[store.name][carrier]
if Time.current >= today_cut_off_time
pickup_date = 1.working.day.since(today_cut_off_time).strftime('%Y-%m-%d')
pickup_time = '9:00'
else
pickup_date = today_cut_off_time.strftime('%Y-%m-%d')
pickup_time = Time.current.strftime('%R:%S')
end
pickup_date_time = Time.zone.parse("#{pickup_date} #{pickup_time}")
end
pickup_date_time
end
|
.completed ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are completed. Active Record Scope
261
|
# File 'app/models/shipment.rb', line 261
scope :completed, -> { where(state: %w[label_complete manually_complete]) }
|
.container_type_from_packdim_int(int) ⇒ String?
Note:
nil and non-numeric input both decode to 'carton' via
to_i returning 0. That is intentional — historic rows that
pre-date the wire-format column default to carton.
Decode the wire-format integer at packdim[4] back into the
container_type enum string label. Use this anywhere the packdim
5th element is being read; Shipment.container_types.invert no
longer round-trips because container_type is now a Postgres enum
whose key/value are both the same string.
Logic Details
PACKDIM_CONTAINER_INTS ('carton' => 0, 'pallet' => 1, 'crate' => 2, 'palleted_crate' => 3) is the canonical wire format preserved for
MD5 dedup of historic packdim rows. .invert[int.to_i] looks up
the label by integer code.
203
204
205
|
# File 'app/models/shipment.rb', line 203
def self.container_type_from_packdim_int(int)
PACKDIM_CONTAINER_INTS.invert[int.to_i]
end
|
.container_types_for_select ⇒ Object
704
705
706
|
# File 'app/models/shipment.rb', line 704
def self.container_types_for_select
Shipment.container_types.keys.map { |ct| [ct.humanize, ct] }
end
|
.contentable ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are contentable. Active Record Scope
284
|
# File 'app/models/shipment.rb', line 284
scope :contentable, -> { where.not(state: %w[label_voided manually_voided suggested]) }
|
.crates ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are crates. Active Record Scope
287
|
# File 'app/models/shipment.rb', line 287
scope :crates, -> { where(container_type: 'crate') }
|
.custom_carriers_for_select ⇒ Object
807
808
809
810
811
812
|
# File 'app/models/shipment.rb', line 807
def self.custom_carriers_for_select
carriers = ADDITIONAL_CARRIERS_TO_INCLUDE
carriers + Rails.cache.fetch(:custom_carrier_for_select, expires_in: 1.day) do
ShippingCost.where.not(description_override: nil).pluck('distinct description_override'.sql_safe).filter_map(&:presence).map(&:squish).map { |d| d[0..45].titleize }.uniq.sort
end
end
|
.fedex_express ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are fedex express. Active Record Scope
294
|
# File 'app/models/shipment.rb', line 294
scope :fedex_express, -> { where(carrier: 'FedEx').joins(delivery: :selected_shipping_cost).where.not(shipping_costs: { shipping_option_id: Delivery::FEDEX_GROUND_SHIPPING_OPTION_IDS }) }
|
.get_next_shipments_serial ⇒ Object
1142
1143
1144
1145
|
# File 'app/models/shipment.rb', line 1142
def self.get_next_shipments_serial
seq = Shipment.find_by_sql("SELECT nextval('shipments_serial') AS shipment_serial")
seq[0].shipment_serial
end
|
.label_complete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are label complete. Active Record Scope
271
|
# File 'app/models/shipment.rb', line 271
scope :label_complete, -> { where(state: 'label_complete') }
|
.label_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are label voided. Active Record Scope
272
|
# File 'app/models/shipment.rb', line 272
scope :label_voided, -> { where(state: 'label_voided') }
|
.line_item_to_content_key(line_item) ⇒ Object
Builds a content key to present a line in our shipment content
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
|
# File 'app/models/shipment.rb', line 902
def self.line_item_to_content_key(line_item)
content_key = { sku: line_item.item.sku }
if (asin = line_item.catalog_item.amazon_asin)
content_key[:asin] = asin
end
if (upc = line_item.item.upc.presence)
content_key[:upc] = upc
end
if (edi_line_number = line_item.edi_line_number.presence)
content_key[:edi_line_number] = edi_line_number
end
if (edi_reference = line_item.edi_reference.presence)
content_key[:edi_reference] = edi_reference
end
if (third_party_part_number = line_item.catalog_item.third_party_part_number.presence)
content_key[:third_party_part_number] = third_party_part_number
end
content_key
end
|
.manually_complete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are manually complete. Active Record Scope
269
|
# File 'app/models/shipment.rb', line 269
scope :manually_complete, -> { where(state: 'manually_complete') }
|
.manually_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are manually voided. Active Record Scope
270
|
# File 'app/models/shipment.rb', line 270
scope :manually_voided, -> { where(state: 'manually_voided') }
|
.measured ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are measured. Active Record Scope
282
|
# File 'app/models/shipment.rb', line 282
scope :measured, -> { where(state: MEASURED_STATES) }
|
.next_sscc_for_gs1_128 ⇒ Object
1147
1148
1149
|
# File 'app/models/shipment.rb', line 1147
def self.next_sscc_for_gs1_128
build_gs1_128(serial: get_next_shipments_serial)
end
|
.non_pallets ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are non pallets. Active Record Scope
289
|
# File 'app/models/shipment.rb', line 289
scope :non_pallets, -> { where(container_type: %w[carton crate]) }
|
.non_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are non voided. Active Record Scope
283
|
# File 'app/models/shipment.rb', line 283
scope :non_voided, -> { where.not(state: %w[label_voided manually_voided]) }
|
.override_carriers_for_select ⇒ Object
.packageable ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packageable. Active Record Scope
281
|
# File 'app/models/shipment.rb', line 281
scope :packageable, -> { where(state: PACKING_STATES) }
|
.packed ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packed. Active Record Scope
264
|
# File 'app/models/shipment.rb', line 264
scope :packed, -> { where(state: 'packed') }
|
.packed_or_awaiting_labels ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packed or awaiting labels. Active Record Scope
267
|
# File 'app/models/shipment.rb', line 267
scope :packed_or_awaiting_labels, -> { where(state: %w[packed awaiting_label]) }
|
.packed_or_measured ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packed or measured. Active Record Scope
.palleted_crates ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are palleted crates. Active Record Scope
288
|
# File 'app/models/shipment.rb', line 288
scope :palleted_crates, -> { where(container_type: 'palleted_crate') }
|
.pallets ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are pallets. Active Record Scope
286
|
# File 'app/models/shipment.rb', line 286
scope :pallets, -> { where(container_type: 'pallet') }
|
.states_for_select ⇒ Object
700
701
702
|
# File 'app/models/shipment.rb', line 700
def self.states_for_select
state_machines[:state].states.map { |s| [s.human_name.titleize, s.value] }
end
|
.suggested ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are suggested. Active Record Scope
263
|
# File 'app/models/shipment.rb', line 263
scope :suggested, -> { where(state: 'suggested') }
|
.suggested_packed_or_awaiting_labels ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are suggested packed or awaiting labels. Active Record Scope
266
|
# File 'app/models/shipment.rb', line 266
scope :suggested_packed_or_awaiting_labels, -> { where(state: %w[suggested packed awaiting_label]) }
|
.top_level ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are top level. Active Record Scope
290
|
# File 'app/models/shipment.rb', line 290
scope :top_level, -> { where(parent_shipment_id: nil) }
|
.tracking_link(carrier, tracking_number) ⇒ Object
768
769
770
|
# File 'app/models/shipment.rb', line 768
def self.tracking_link(carrier, tracking_number)
ShipmentTrackingNumber.new(tracking_number, courier_code: carrier).tracking_url
end
|
.tracking_status_complete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are tracking status complete. Active Record Scope
278
279
280
|
# File 'app/models/shipment.rb', line 278
scope :tracking_status_complete, -> {
where.not(carrier: 'SpeedeeDelivery').where.not(delivery: nil).where(tracking_state: TRACKING_STATUS_COMPLETE).where(date_shipped: TRACKING_LOOKBACK_DAYS.days.ago..)
}
|
.tracking_status_incomplete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are tracking status incomplete. Active Record Scope
273
274
275
276
|
# File 'app/models/shipment.rb', line 273
scope :tracking_status_incomplete, -> {
where.not(carrier: 'SpeedeeDelivery').where.not(delivery: nil).where(tracking_state: TRACKING_STATUS_INCOMPLETE).where(date_shipped: TRACKING_LOOKBACK_DAYS.days.ago..)
.where.not(tracking_number: [nil, ''])
}
|
.voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are voided. Active Record Scope
262
|
# File 'app/models/shipment.rb', line 262
scope :voided, -> { where(state: %w[label_voided manually_voided]) }
|
Instance Method Details
#amazon_container_code? ⇒ Boolean
858
859
860
|
# File 'app/models/shipment.rb', line 858
def amazon_container_code?
container_code&.starts_with?('AMZN')
end
|
#attach_paperless_qr(qr_png_tmp_path, instructions, handoff_code) ⇒ Upload
Attaches the paperless QR/barcode PNG that ShipEngine returned for this
shipment under its dedicated upload category, and persists the carrier-
supplied counter instructions and (optional) handoff PIN to the
shipment so the return-instructions PDF can render them without
re-fetching from ShipEngine.
Called from Delivery#generate_labels for each return shipment whose
ShipEngine response carried a usable paperless_download.href. Mirrors
generate_ship_label_pdf in shape — copies a tempfile to a stable
upload location and stores it through the Upload model.
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
|
# File 'app/models/shipment.rb', line 664
def attach_paperless_qr(qr_png_tmp_path, instructions, handoff_code)
file_name = paperless_qr_file_name
qr_png_path = Upload.temp_location(file_name)
FileUtils.cp(qr_png_tmp_path, qr_png_path)
upload = Upload.uploadify(qr_png_path, 'paperless_qr_png')
raise 'Paperless QR PNG was not generated' unless upload
self.paperless_instructions = instructions.presence
self.paperless_handoff_code = handoff_code.presence
save!
uploads << upload
end
|
#bol_pdf ⇒ Object
692
693
694
|
# File 'app/models/shipment.rb', line 692
def bol_pdf
uploads.ship_bol_pdfs.first
end
|
#bps_barcode(file_path: nil, _partner_code: nil) ⇒ Object
845
846
847
848
849
850
851
852
853
854
855
856
|
# File 'app/models/shipment.rb', line 845
def bps_barcode(file_path: nil, _partner_code: nil)
require 'rqrcode'
qrcode = RQRCode::QRCode.new(bps_barcode_string)
image = qrcode.as_png.resize(150, 150).crop(20, 20, 110, 110)
if file_path
image.save(file_path)
file_path
else
image
end
end
|
#bps_barcode_string ⇒ Object
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
|
# File 'app/models/shipment.rb', line 824
def bps_barcode_string
s = [bps_partner_code_prefix]
if delivery&.customer&.report_grouping == 'Amazon' && (ref_nbr = delivery&.order&.shipment_reference_number).present?
s << "PO:#{ref_nbr}"
elsif delivery.po_number.present?
s << "PO:#{delivery.po_number}"
end
shipment_content_grouped_content_key.each do |content_key, quantity|
s << if (asin = content_key[:asin])
"ASIN:#{asin}"
elsif (upc = content_key[:upc])
"UPC:#{upc}"
else
"SKU:#{content_key[:sku]}"
end
s << "QTY:#{quantity}"
end
s.map(&:squish).join(',')
end
|
#bps_partner_code_prefix ⇒ Object
814
815
816
817
818
819
820
821
822
|
# File 'app/models/shipment.rb', line 814
def bps_partner_code_prefix
return unless (customer = delivery&.customer)
if customer.report_grouping == 'Amazon'
'AMZN'
else
customer.reference_number
end
end
|
#carrier_icon ⇒ Object
448
449
450
|
# File 'app/models/shipment.rb', line 448
def carrier_icon
self.class.carrier_icon(sanitized_carrier)
end
|
#carrier_options_for_select ⇒ Object
736
737
738
739
740
741
742
|
# File 'app/models/shipment.rb', line 736
def carrier_options_for_select
options = []
options = self.class.all_carriers_for_select if delivery
options << carrier unless options.compact.find { |e| e == carrier }
options.compact.uniq.sort
end
|
#check_if_oversize ⇒ Object
#child_shipments ⇒ ActiveRecord::Relation<Shipment>
228
|
# File 'app/models/shipment.rb', line 228
has_many :child_shipments, class_name: 'Shipment', foreign_key: 'parent_shipment_id', dependent: :nullify
|
#complete? ⇒ Boolean
696
697
698
|
# File 'app/models/shipment.rb', line 696
def complete?
manually_complete? || label_complete?
end
|
#compute_item_declared_value ⇒ Object
1223
1224
1225
1226
1227
|
# File 'app/models/shipment.rb', line 1223
def compute_item_declared_value
shipment_contents.includes(:line_item).sum { |sc| sc.line_item.unit_value_for_commercial_invoice * sc.quantity.to_f }
end
|
#compute_item_weight ⇒ Object
1194
1195
1196
1197
|
# File 'app/models/shipment.rb', line 1194
def compute_item_weight
shipment_contents.sum { |sc| sc.line_item.item.base_weight.to_f * sc.quantity.to_i }
end
|
#compute_shipment_declared_value(skip_carrier_guard: false) ⇒ Object
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
|
# File 'app/models/shipment.rb', line 1229
def compute_shipment_declared_value(skip_carrier_guard: false)
return 0.0 if !skip_carrier_guard && delivery&.do_not_ship_insure_via_carrier?
no_kit_components = !shipment_contents.joins(:line_item).where.not(line_items: { parent_id: nil }).exists?
no_child_kit_components = child_shipments.none? do |cs|
cs.shipment_contents.joins(:line_item).where.not(line_items: { parent_id: nil }).exists?
end
if (shipment_contents.present? || child_shipments.present?) &&
no_kit_components &&
no_child_kit_components &&
(compute_item_declared_value > 0.0 || child_shipments.to_a.any? { |s| s.compute_item_declared_value > 0.0 })
(child_shipments.to_a.sum(&:compute_item_declared_value) + compute_item_declared_value).to_f
elsif delivery.present?
(delivery.calculate_declared_value.to_f.abs / [delivery.shipments.size, 1].max).round(2) elsif standalone_delivery.present?
(standalone_delivery.calculate_declared_value.to_f.abs / [standalone_delivery.shipments.size, 1].max).round(2)
else
0.0
end
end
|
#compute_shipment_weight ⇒ Object
1217
1218
1219
1220
1221
|
# File 'app/models/shipment.rb', line 1217
def compute_shipment_weight
return unless shipment_contents.present? || child_shipments.present?
(child_shipments.to_a.sum(&:compute_item_weight) + compute_item_weight + compute_tare_weight).ceil
end
|
#compute_tare_weight ⇒ Object
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
|
# File 'app/models/shipment.rb', line 1199
def compute_tare_weight
if carton?
if (sqin = surface_sqin) [(0.0007 * sqin), 1].max
else
0.25
end
elsif pallet? || palleted_crate?
PALLET_NOMINAL_WEIGHT elsif crate?
if (sqin = surface_sqin) [(0.00875 * sqin), 1].max
else
CRATE_NOMINAL_WEIGHT
end
end
end
|
#container_code_type ⇒ Object
866
867
868
869
870
871
872
873
874
875
876
|
# File 'app/models/shipment.rb', line 866
def container_code_type
return if container_code.blank?
if amazon_container_code?
'Amazon Container Code'
elsif sscc_code?
'Serial Shipping Container Code (SSCC)'
else
'Container Code'
end
end
|
#deep_dup ⇒ Object
141
142
143
|
# File 'app/models/shipment.rb', line 141
def deep_dup
deep_clone(except: %i[container_code tracking_number])
end
|
Validations:
-
Presence
({ if: ->(s) { s.neither_legacy_nor_service && s.mail_activity_id.nil? && s.standalone_delivery.nil? } })
217
|
# File 'app/models/shipment.rb', line 217
belongs_to :delivery, optional: true
|
#delivery_or_mail_activity ⇒ Object
386
387
388
|
# File 'app/models/shipment.rb', line 386
def delivery_or_mail_activity
delivery || mail_activity
end
|
#dimensions_changed? ⇒ Boolean
1014
1015
1016
|
# File 'app/models/shipment.rb', line 1014
def dimensions_changed?
length_changed? || width_changed? || height_changed? || weight_changed?
end
|
#dimensions_text(display_units: false) ⇒ Object
723
724
725
726
|
# File 'app/models/shipment.rb', line 723
def dimensions_text(display_units: false)
dims = [length, width, height].compact.map(&:round)
dims.map { |sd| display_units ? "#{sd} in" : sd }.join(' x ')
end
|
#dimensions_text_converted(unit: 'in', precision: 0, display_units: false) ⇒ Object
1319
1320
1321
1322
|
# File 'app/models/shipment.rb', line 1319
def dimensions_text_converted(unit: 'in', precision: 0, display_units: false)
dims = [length_converted(unit:, precision:), width_converted(unit:, precision:), height_converted(unit:, precision:)].compact
dims.map { |sd| display_units ? "#{sd} #{unit}" : sd }.join(' x ')
end
|
#editable? ⇒ Boolean
470
471
472
|
# File 'app/models/shipment.rb', line 470
def editable?
suggested? || packed? || (awaiting_label? && delivery&.is_rma_return?) || is_legacy || (is_manual && !part_of_a_locked_delivery?)
end
|
#effective_nmfc_code ⇒ Object
527
528
529
530
531
532
533
534
535
|
# File 'app/models/shipment.rb', line 527
def effective_nmfc_code
nmfc_code_arr = []
shipment_content_grouped_content_key.each do |content_key, quantity|
it = Item.where(sku: content_key[:sku]).first
nmfc_code_arr << { nmfc_code: it.effective_nmfc_code, voting_weight: quantity * it.base_weight * it.shipping_volume } if it
end
(nmfc_code_arr.min_by { |h| h[:voting_weight] } || {})[:nmfc_code] || ProductCategoryConstants::FALLBACK_NMFC_CODE
end
|
#enqueue_tracking_registration_if_needed ⇒ Object
after_commit hook: enqueue ShipmentTrackingRegistrationWorker whenever
the shipment has just landed a (new) tracking_number for a carrier we
can resolve to a ShipEngine carrier_code. Idempotent — the worker
itself short-circuits when tracking_registered_at is already set, and
we use update_columns to clear the stamp when tracking_number changes
so a re-issued label (after a void+regen) re-registers cleanly.
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
|
# File 'app/models/shipment.rb', line 1122
def enqueue_tracking_registration_if_needed
return unless saved_change_to_tracking_number?
return if tracking_number.blank?
normalized = Heatwave::Normalizers.resolve_shipping_carrier(carrier, tracking_number: tracking_number)
return unless PARCEL_CARRIER_INTERNAL_TO_SHIPENGINE_CODE.key?(normalized)
update_columns(tracking_registered_at: nil) if tracking_registered_at.present?
ShipmentTrackingRegistrationWorker.perform_async(id)
end
|
#entered_and_computed_weights_are_close? ⇒ Boolean
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
|
# File 'app/models/shipment.rb', line 1271
def entered_and_computed_weights_are_close?
if pallet? delta_percent = 100.0 * (self.weight.to_f - compute_shipment_weight.to_f).abs / (compute_shipment_weight || 1).to_f
delta_lbs = (self.weight.to_f - compute_shipment_weight.to_f).abs
return true if delta_lbs <= MIN_WEIGHT_DELTA_LBS
(delta_percent <= MAX_WEIGHT_DELTA_PERCENT) &&
(delta_lbs <= MAX_WEIGHT_DELTA_LBS)
else
true end
end
|
#final? ⇒ Boolean
1105
1106
1107
|
# File 'app/models/shipment.rb', line 1105
def final?
delivery&.invoiced? || order&.invoiced? || mail_activity&.complete?
end
|
#freight_class ⇒ Object
513
514
515
516
517
518
519
520
521
522
523
524
525
|
# File 'app/models/shipment.rb', line 513
def freight_class
freight_class = nil
if weight.present? && volume_in_cubic_feet.present?
pcf = weight / volume_in_cubic_feet
Shipping::UpsFreight::FREIGHT_CLASS_BY_PCF.each do |fc, pcf_limits|
if pcf >= pcf_limits[:lower] && pcf < pcf_limits[:upper]
freight_class = fc.to_i
break
end
end
end
freight_class
end
|
#freight_shipment? ⇒ Boolean
460
461
462
463
464
|
# File 'app/models/shipment.rb', line 460
def freight_shipment?
dels = [delivery]
dels += order.present? ? order.deliveries : []
dels.compact.uniq.any?(&:ships_ltl_freight?)
end
|
#full_dimension_text(metric: false) ⇒ Object
715
716
717
718
719
720
721
|
# File 'app/models/shipment.rb', line 715
def full_dimension_text(metric: false)
if metric
"#{dimensions_text_converted(unit: 'cm', display_units: true)} - #{weight_converted(unit: 'kg', display_units: true)}"
else
"#{dimensions_text(display_units: true)} - #{weight.ceil} lbs"
end
end
|
#generate_and_attach_sscc_label(return_existing: false) ⇒ Object
979
980
981
982
983
984
985
986
987
988
989
990
991
|
# File 'app/models/shipment.rb', line 979
def generate_and_attach_sscc_label(return_existing: false)
container_labels = uploads.where(category: 'container_label')
if return_existing
upload = container_labels.first
else
container_labels.destroy_all
end
if upload.nil?
res = Shipping::CartonLabelGenerator.new.process(self)
upload = Upload.uploadify_from_data(file_name: res.file_name, data: res.pdf, category: 'container_label', resource: self)
end
upload
end
|
#generate_letter_ship_label_pdf(ship_label_tmp_path, carrier) ⇒ Object
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
|
# File 'app/models/shipment.rb', line 578
def generate_letter_ship_label_pdf(ship_label_tmp_path, carrier)
self.carrier = carrier
should_merge_pdfs = carrier.to_s.downcase.match?(/speedeedelivery|canadapost|canpar/)
file_name = get_file_name('letter')
ship_label_pdf_path = Upload.temp_location(file_name)
so = delivery.rma_for_return&.shipping_option
dropoff_url = so.present? ? Rma::URLS.dig(so&.country, so&.carrier) : nil
pdf = Pdf::Label::LetterShip.call(self, ship_label_tmp_path, dropoff_url: dropoff_url).pdf
if should_merge_pdfs && ship_label_pdf&.attachment&.path
combined_pdf = PdfCombinator.new
combined_pdf << pdf
combined_pdf << PdfCombinator.load(ship_label_pdf.attachment.path)
combined_pdf.save(ship_label_pdf_path)
else
File.open(ship_label_pdf_path, 'wb') do |file|
file.write pdf
file.flush
file.fsync
end
end
save
upload = Upload.uploadify(ship_label_pdf_path, 'letter_ship_label_pdf')
raise 'Finished letter ship label was not generated' unless upload
uploads << upload
end
|
#generate_ship_label_pdf(ship_label_tmp_path, carrier_to_use, is_return = false) ⇒ Object
564
565
566
567
568
569
570
571
572
573
574
575
576
|
# File 'app/models/shipment.rb', line 564
def generate_ship_label_pdf(ship_label_tmp_path, carrier_to_use, is_return = false)
self.carrier = carrier_to_use
self.is_return = is_return
file_name = get_file_name('package')
ship_label_pdf_path = Upload.temp_location(file_name)
FileUtils.cp(ship_label_tmp_path, ship_label_pdf_path) Rails.logger.debug { "Shipping generate_ship_label_pdf: ship_label_tmp_path: #{ship_label_tmp_path}, ship_label_pdf_path: #{ship_label_pdf_path}, carrier_to_use: #{carrier_to_use}, is_return: #{is_return}, on shipment id #{id}" }
upload = Upload.uploadify(ship_label_pdf_path, 'ship_label_pdf')
raise 'Finished ship label was not generated' unless upload
uploads << upload
end
|
#generate_speedee_label_pdf(options = {}) ⇒ Object
def generate_bol_pdf(ship_bol_tmp_path=nil)
if we have carrier generated BOL, use that
if ship_bol_tmp_path
# generate the pdf from the file path
file_name = get_file_name('bol')
ship_bol_pdf_path = Upload.temp_location(file_name)
FileUtils.cp(ship_bol_tmp_path, ship_bol_pdf_path)
# attach the finished bol pdf
upload = Upload.uploadify(ship_bol_pdf_path, 'ship_bol_pdf')
else # otherwise try to generate it using our template from scratch
res = Shipping::BolGenerator.new.process(self.delivery)
upload = Upload.uploadify_from_data(file_name: res.file_name, data: res.pdf, category: 'ship_bol_pdf', resource: self)
end
raise "BOL PDF was not generated" unless upload
return self.uploads << upload
end
634
635
636
637
638
639
640
|
# File 'app/models/shipment.rb', line 634
def generate_speedee_label_pdf(options = {})
res = Pdf::Label::Speedee.call(self, options)
upload = Upload.uploadify_from_data(file_name: res.file_name, data: res.pdf, category: 'ship_label_pdf', resource: self)
raise 'Speedee Delivery ship label PDF was not generated' unless upload
uploads << upload
end
|
#generate_sscc_barcode(file_path = nil) ⇒ Object
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
|
# File 'app/models/shipment.rb', line 878
def generate_sscc_barcode(file_path = nil)
raise 'Container code is invalid' if container_code.blank?
require 'barby'
require 'barby/barcode/code_128'
require 'barby/outputter/png_outputter'
sscc_string = "#{Barby::Code128::FNC1}#{container_code}"
barcode = Barby::Code128.new(sscc_string)
png = barcode.to_png
if file_path
File.open(file_path, 'wb') do |file|
file.write(png)
file.flush
file.fsync
end
file_path
else
png
end
end
|
#get_file_name(file_type) ⇒ Object
537
538
539
540
541
542
543
544
545
546
547
|
# File 'app/models/shipment.rb', line 537
def get_file_name(file_type)
base_name = ''
if delivery
delivery.name(false, true).to_s
elsif mail_activity
mail_activity.name.to_s
elsif order
base_name = order.name.to_s
end
"#{base_name}_#{file_type}_#{shipment_index + 1}_#{Time.current.strftime('%m_%d_%Y_%I_%M%p')}.pdf".downcase
end
|
#has_dimensions? ⇒ Boolean
1010
1011
1012
|
# File 'app/models/shipment.rb', line 1010
def has_dimensions?
length.to_f.positive? && width.to_f.positive? && height.to_f.positive? && weight.to_f > 0
end
|
#height_converted(unit: 'in', precision: 0) ⇒ Object
1296
1297
1298
1299
1300
|
# File 'app/models/shipment.rb', line 1296
def height_converted(unit: 'in', precision: 0)
return unless height
RubyUnits::Unit.new("#{height} in").convert_to(unit.to_s).scalar.to_f.ceil(precision)
end
|
#incurs_oversized_penalty? ⇒ Boolean
1069
1070
1071
1072
1073
1074
1075
1076
1077
|
# File 'app/models/shipment.rb', line 1069
def incurs_oversized_penalty?
ar = audit
self.audited = true
self.audit_result = ar
self.issues_count = ar.size
res = false
res = true if PACKED_OR_MEASURED_STATES.include?(state) && (delivery&.ships_ltl_freight? != true) && (delivery&.is_warehouse_pickup? != true) && (audit_result.keys.any? { |k| k.to_s.index('penalty') } || container_type == 'pallet')
res
end
|
#is_rma_return? ⇒ Boolean
483
484
485
|
# File 'app/models/shipment.rb', line 483
def is_rma_return?
delivery&.is_rma_return?
end
|
#is_service? ⇒ Boolean
487
488
489
|
# File 'app/models/shipment.rb', line 487
def is_service?
state.in?(%w[service_redemption_code_sent service_fulfilled]) || delivery&.is_service_only?
end
|
#is_speedee_oversize? ⇒ Boolean
#length_converted(unit: 'in', precision: 0) ⇒ Object
1284
1285
1286
1287
1288
|
# File 'app/models/shipment.rb', line 1284
def length_converted(unit: 'in', precision: 0)
return unless length
RubyUnits::Unit.new("#{length} in").convert_to(unit.to_s).scalar.to_f.ceil(precision)
end
|
#line_items ⇒ ActiveRecord::Relation<LineItem>
227
|
# File 'app/models/shipment.rb', line 227
has_many :line_items, through: :shipment_contents
|
#locked_for_fba? ⇒ Boolean
1324
1325
1326
|
# File 'app/models/shipment.rb', line 1324
def locked_for_fba?
container_code =~ CustomerConstants::AMAZON_FBA_ID_REGEX && (packed? || awaiting_label?)
end
|
219
|
# File 'app/models/shipment.rb', line 219
belongs_to :mail_activity, optional: true
|
221
|
# File 'app/models/shipment.rb', line 221
belongs_to :manifest, optional: true
|
#manual_container_code ⇒ Object
1168
1169
1170
|
# File 'app/models/shipment.rb', line 1168
def manual_container_code
container_code
end
|
#manual_container_code=(code) ⇒ Object
1172
1173
1174
|
# File 'app/models/shipment.rb', line 1172
def manual_container_code=(code)
self.container_code = code if code.present?
end
|
#manual_shipment ⇒ Object
456
457
458
|
# File 'app/models/shipment.rb', line 456
def manual_shipment
is_manual
end
|
#need_to_audit? ⇒ Boolean
1097
1098
1099
|
# File 'app/models/shipment.rb', line 1097
def need_to_audit?
dimensions_changed? || container_type_changed? || !audited
end
|
#neither_legacy_nor_service ⇒ Object
452
453
454
|
# File 'app/models/shipment.rb', line 452
def neither_legacy_nor_service
!(is_legacy || is_service?)
end
|
#non_freight_shipment? ⇒ Boolean
466
467
468
|
# File 'app/models/shipment.rb', line 466
def non_freight_shipment?
!freight_shipment?
end
|
#ok_to_delete_with_mail_activity? ⇒ Boolean
728
729
730
|
# File 'app/models/shipment.rb', line 728
def ok_to_delete_with_mail_activity?
suggested? or label_voided? or manually_voided? or awaiting_label? or packed?
end
|
#ok_to_delete_with_standalone_delivery? ⇒ Boolean
732
733
734
|
# File 'app/models/shipment.rb', line 732
def ok_to_delete_with_standalone_delivery?
suggested? or label_voided? or manually_voided? or packed?
end
|
Validations:
-
Presence
({ if: ->(s) { s.delivery.present? && !(s.delivery.quoting? || s.delivery.pre_pack? || s.delivery.is_rma_return?) } })
218
|
# File 'app/models/shipment.rb', line 218
belongs_to :order, optional: true
|
#packed_or_pre_packed? ⇒ Boolean
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
|
# File 'app/models/shipment.rb', line 1054
def packed_or_pre_packed?
return true if packed?
res = false
if suggested?
packing_solution = Shipping::DeterminePackaging.new.process(
delivery:,
is_freight: delivery.ships_ltl_freight?,
skip_calculator: true
)
res = true if %w[from_delivery from_item from_manual_entry].include?(packing_solution.source_type.to_s)
end
res
end
|
#paperless_qr_file_name ⇒ Object
Filename for the paperless QR/barcode PNG attachment. Mirrors
get_file_name but emits .png instead of .pdf because the QR
arrives as a raster image from ShipEngine.
552
553
554
555
556
557
558
559
560
561
562
|
# File 'app/models/shipment.rb', line 552
def paperless_qr_file_name
base_name = ''
if delivery
base_name = delivery.name(false, true).to_s
elsif mail_activity
base_name = mail_activity.name.to_s
elsif order
base_name = order.name.to_s
end
"#{base_name}_paperless_qr_#{shipment_index + 1}_#{Time.current.strftime('%m_%d_%Y_%I_%M%p')}.png".downcase
end
|
#paperless_qr_png ⇒ Upload?
The paperless QR/barcode PNG attached to this shipment, if any.
683
684
685
|
# File 'app/models/shipment.rb', line 683
def paperless_qr_png
uploads.in_category('paperless_qr_png').first
end
|
#parent_shipment ⇒ Shipment
223
|
# File 'app/models/shipment.rb', line 223
belongs_to :parent_shipment, class_name: 'Shipment', optional: true
|
#part_of_a_locked_delivery? ⇒ Boolean
474
475
476
477
478
479
480
481
|
# File 'app/models/shipment.rb', line 474
def part_of_a_locked_delivery?
return false unless delivery
delivery.pending_ship_confirm? ||
delivery.shipped? ||
delivery.invoiced? ||
delivery.incorrectly_packaged_ups_canada_order
end
|
#qualifies_for_tracking_api? ⇒ Boolean
444
445
446
|
# File 'app/models/shipment.rb', line 444
def qualifies_for_tracking_api?
label_complete? && carrier != 'SpeedeeDelivery' && container_type == 'carton'
end
|
#ready_to_manually_complete? ⇒ Boolean
1109
1110
1111
1112
1113
1114
|
# File 'app/models/shipment.rb', line 1109
def ready_to_manually_complete?
tracking_ok = true
tracking_ok = false if non_freight_shipment? && parent_shipment_id.nil? && tracking_number.blank?
tracking_ok = false if freight_shipment? && parent_shipment_id.nil? && delivery&.carrier_bol.blank? && delivery&.master_tracking_number.blank? && tracking_number.blank?
carrier.present? && tracking_ok
end
|
#reference_number ⇒ Object
390
391
392
|
# File 'app/models/shipment.rb', line 390
def reference_number
container_code.presence || "PD#{id}"
end
|
#resource_reference_and_shipment_number ⇒ Object
Also known as:
order_reference_and_shipment_number
398
399
400
401
|
# File 'app/models/shipment.rb', line 398
def resource_reference_and_shipment_number
"#{delivery&.resource&.reference_number}_#{shipment_index + 1}"
end
|
#round_dimensions ⇒ Object
1032
1033
1034
1035
1036
1037
1038
1039
1040
|
# File 'app/models/shipment.rb', line 1032
def round_dimensions
return unless has_dimensions?
self.length = length.round(1)
self.width = width.round(1)
self.height = height.round(1)
self.weight = weight.round(4)
end
|
#run_audit(force = false) ⇒ Object
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
|
# File 'app/models/shipment.rb', line 1079
def run_audit(force = false)
unless force
return if skip_audit?
return unless need_to_audit?
end
Rails.logger.info "Auditing shipment #{id}"
ar = audit
self.audited = true
self.audit_result = ar
self.issues_count = ar.size
end
|
#sanitized_carrier ⇒ Object
428
429
430
431
432
433
|
# File 'app/models/shipment.rb', line 428
def sanitized_carrier
valid_carriers = (SHIPPING_CARRIERS_OPTIONS[(delivery&.country&.iso3 || 'USA').to_sym] || []).map(&:first) + ['Amazon'] return carrier if valid_carriers.include?(carrier) || carrier.nil?
valid_carriers.find { |c| carrier.downcase.index(c.downcase).present? } || carrier
end
|
#set_carrier(carrier_override = nil) ⇒ Object
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
|
# File 'app/models/shipment.rb', line 998
def set_carrier(carrier_override = nil)
if carrier_override.present?
self.carrier = carrier_override
else
if tracking_number_changed? && tracking_number.present?
self.carrier ||= ShipmentTrackingNumber.new(tracking_number).courier_name
end
self.carrier ||= delivery_or_mail_activity&.reported_carrier
end
end
|
#set_default_number ⇒ Object
993
994
995
996
|
# File 'app/models/shipment.rb', line 993
def set_default_number
self.number ||= 1
self.order = delivery.order if delivery&.order
end
|
#set_default_pallet_dimensions ⇒ Object
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
|
# File 'app/models/shipment.rb', line 1180
def set_default_pallet_dimensions
return unless pallet?
return if complete?
self.length ||= 48
self.width ||= 40
self.height ||= 78 self.weight ||= compute_tare_weight
end
|
#set_default_shipment_weight ⇒ Object
When warehouse just wants to use the item shipping_weight
1267
1268
1269
|
# File 'app/models/shipment.rb', line 1267
def set_default_shipment_weight
self.weight ||= compute_shipment_weight
end
|
#set_sscc ⇒ Object
1176
1177
1178
|
# File 'app/models/shipment.rb', line 1176
def set_sscc
self.container_code ||= self.class.next_sscc_for_gs1_128
end
|
#ship_label_pdf(letter_format = false) ⇒ Object
642
643
644
645
646
|
# File 'app/models/shipment.rb', line 642
def ship_label_pdf(letter_format = false)
category = 'ship_label_pdf'
category = 'letter_ship_label_pdf' if letter_format
uploads.in_category(category).first
end
|
#shipment_content_grouped_content_key ⇒ Object
Creates a hash, key is a composite key with asin, sku, upc
value is total quantity of that item
If line item is a kit component, only kit parent is taken into account
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
|
# File 'app/models/shipment.rb', line 926
def shipment_content_grouped_content_key
contents = {}
counted_parent_ids = []
sc_sorted = if shipment_contents.any? { |sc| sc.line_item.edi_line_number.present? }
shipment_contents.eager_load(:line_item).sort_by { |sc| sc.line_item.edi_line_number.to_s }
else
shipment_contents.eager_load(:line_item)
end
sc_sorted.each do |sc|
if (parent_line = sc.line_item.parent)
unless counted_parent_ids.include?(parent_line.id)
content_key = self.class.line_item_to_content_key(parent_line)
contents[content_key] ||= 0
parent_quantity_factor = sc.line_item.parent_quantity_factor
sc.quantity
parent_quantity = (sc.quantity / parent_quantity_factor).ceil
contents[content_key] += parent_quantity
counted_parent_ids << parent_line.id
end
else
content_key = self.class.line_item_to_content_key(sc.line_item)
contents[content_key] ||= 0
contents[content_key] += sc.quantity
end
end
contents
end
|
#shipment_content_label ⇒ Object
960
961
962
963
964
965
966
967
968
969
970
971
972
973
|
# File 'app/models/shipment.rb', line 960
def shipment_content_label
if shipment_content_grouped_content_key.size == 1
content_key = shipment_content_grouped_content_key.keys.first
if (asin = content_key[:asin])
"ASIN:#{asin}"
elsif (upc = content_key[:upc])
"UPC:#{upc}"
else
"SKU:#{content_key[:sku]}"
end
else
'Mixed Skus'
end
end
|
#shipment_content_quantity ⇒ Object
975
976
977
|
# File 'app/models/shipment.rb', line 975
def shipment_content_quantity
shipment_contents.sum(:quantity)
end
|
#shipment_contents ⇒ ActiveRecord::Relation<ShipmentContent>
226
|
# File 'app/models/shipment.rb', line 226
has_many :shipment_contents, dependent: :destroy
|
#shipment_events ⇒ ActiveRecord::Relation<ShipmentEvent>
229
|
# File 'app/models/shipment.rb', line 229
has_many :shipment_events, dependent: :nullify, inverse_of: :shipment
|
#shipment_index ⇒ Object
394
395
396
|
# File 'app/models/shipment.rb', line 394
def shipment_index
(delivery&.shipment_ids || mail_activity&.shipment_ids || order&.direct_shipment_ids)&.index(id) || 0
end
|
#shipment_position ⇒ Object
420
421
422
|
# File 'app/models/shipment.rb', line 420
def shipment_position
similar_shipment_ids.index(id) + 1
end
|
#shipment_total ⇒ Object
424
425
426
|
# File 'app/models/shipment.rb', line 424
def shipment_total
similar_shipment_ids.size
end
|
#shipment_tracking_number ⇒ Object
Initialize a shipment tracking number object
688
689
690
|
# File 'app/models/shipment.rb', line 688
def shipment_tracking_number
ShipmentTrackingNumber.new(tracking_number, courier_code: carrier)
end
|
#shipping_insurance_link ⇒ Object
#shipping_insurance_record_id ⇒ Object
1328
1329
1330
|
# File 'app/models/shipment.rb', line 1328
def shipping_insurance_record_id
shipping_insurance_data&.dig('shipping_insurance_record_id')
end
|
#signature_confirmation? ⇒ Boolean
1336
1337
1338
|
# File 'app/models/shipment.rb', line 1336
def signature_confirmation?
delivery&.signature_confirmation&.to_b
end
|
#similar_shipment_ids ⇒ Object
408
409
410
411
412
413
414
415
416
417
418
|
# File 'app/models/shipment.rb', line 408
def similar_shipment_ids
if carton?
delivery_or_mail_activity.shipments.cartons.order(:id).ids
elsif pallet?
delivery_or_mail_activity.shipments.pallets.order(:id).ids
elsif crate?
delivery_or_mail_activity.shipments.crates.order(:id).ids
elsif palleted_crate?
delivery_or_mail_activity.shipments.palleted_crates.order(:id).ids
end
end
|
#skip_audit? ⇒ Boolean
1092
1093
1094
1095
|
# File 'app/models/shipment.rb', line 1092
def skip_audit?
final? || service_redemption_code_sent? || service_fulfilled? || manually_voided? || label_voided? ||
delivery&.ships_ltl_freight?
end
|
#sort_dimensions ⇒ Object
1025
1026
1027
1028
1029
1030
|
# File 'app/models/shipment.rb', line 1025
def sort_dimensions
return unless has_dimensions?
return unless carton?
self.length, self.width, self.height = [length, width, height].sort.reverse
end
|
#sort_string ⇒ Object
404
405
406
|
# File 'app/models/shipment.rb', line 404
def sort_string
[parent_shipment&.reference_number, reference_number].compact.join
end
|
222
|
# File 'app/models/shipment.rb', line 222
has_one :speedee_manifest_shipment
|
#sscc_code? ⇒ Boolean
862
863
864
|
# File 'app/models/shipment.rb', line 862
def sscc_code?
!amazon_container_code? && container_code.size == 20
end
|
220
|
# File 'app/models/shipment.rb', line 220
belongs_to :standalone_delivery, optional: true
|
#surface_sqin ⇒ Object
1260
1261
1262
1263
1264
|
# File 'app/models/shipment.rb', line 1260
def surface_sqin
return unless length && height && width
2 * ((length * height) + (length * width) + (width * height))
end
|
#to_package ⇒ Object
1042
1043
1044
|
# File 'app/models/shipment.rb', line 1042
def to_package
Shipping::Container.new(length:, width:, height:, weight:, container_type:, flat_rate_package_type:)
end
|
#to_packdims ⇒ Object
Only floats will serialize properly to json which is necessary in packing.rb, so don't remove .to_f !
The 5th element is intentionally the integer wire-format code (see
PACKDIM_CONTAINER_INTS above) so MD5 hashes keep matching historic rows.
1021
1022
1023
|
# File 'app/models/shipment.rb', line 1021
def to_packdims
[length.round(1).to_f, width.round(1).to_f, height.round(1).to_f, weight.round(4).to_f, PACKDIM_CONTAINER_INTS[container_type]]
end
|
#to_s ⇒ Object
708
709
710
711
712
713
|
# File 'app/models/shipment.rb', line 708
def to_s
s = [reference_number]
s << carrier
s << tracking_number
s.compact.join(' | ')
end
|
#tracking_link ⇒ Object
435
436
437
438
439
440
441
442
|
# File 'app/models/shipment.rb', line 435
def tracking_link
resolved_carrier = case carrier
when 'AmazonSeller' then amz_carrier.presence || sanitized_carrier
when 'WalmartSeller' then sww_carrier.presence || sanitized_carrier
else sanitized_carrier
end
self.class.tracking_link(resolved_carrier, tracking_number)
end
|
#uploads ⇒ ActiveRecord::Relation<Upload>
225
|
# File 'app/models/shipment.rb', line 225
has_many :uploads, as: :resource, dependent: :destroy
|
#voided? ⇒ Boolean
1101
1102
1103
|
# File 'app/models/shipment.rb', line 1101
def voided?
label_voided? || manually_voided?
end
|
#volume ⇒ Object
501
502
503
504
505
|
# File 'app/models/shipment.rb', line 501
def volume
res = nil
res = length * width * height if length.present? && width.present? && height.present?
res
end
|
#volume_in_cubic_feet ⇒ Object
507
508
509
510
511
|
# File 'app/models/shipment.rb', line 507
def volume_in_cubic_feet
res = nil
res = volume / 1728.0 if volume.present?
res
end
|
#weight_converted(unit: 'lbs', precision: nil, display_units: false) ⇒ Object
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
|
# File 'app/models/shipment.rb', line 1302
def weight_converted(unit: 'lbs', precision: nil, display_units: false)
return unless weight
precision ||= case unit
when 'lbs', 'kg'
2
when 'g'
0
else
2
end
d = RubyUnits::Unit.new("#{weight} lbs")
n = d.convert_to(unit.to_s).scalar.to_f.ceil(precision)
display_units ? "#{n} #{unit}" : n
end
|
#width_converted(unit: 'in', precision: 0) ⇒ Object
1290
1291
1292
1293
1294
|
# File 'app/models/shipment.rb', line 1290
def width_converted(unit: 'in', precision: 0)
return unless width
RubyUnits::Unit.new("#{width} in").convert_to(unit.to_s).scalar.to_f.ceil(precision)
end
|