Class: Shipment

Inherits:
ApplicationRecord show all
Includes:
Memery, Models::Auditable, Models::LiquidMethods
Defined in:
app/models/shipment.rb

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 =

Pallet nominal weight.

41
CRATE_NOMINAL_WEIGHT =

Crate nominal weight.

84
WARNING_WEIGHT =
42.0
ALERT_WEIGHT =

Alert weight.

50.0
WARNING_LENGTH =

Warning length.

32.0
ALERT_LENGTH =

Alert length.

36.0
WARNING_WIDTH =

Warning width.

26.0
ALERT_WIDTH =

Alert width.

29.0
WARNING_HEIGHT =

Warning height.

21.0
ALERT_HEIGHT =

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

Constants included from Models::Auditable

Models::Auditable::ALWAYS_IGNORED

Constants included from Models::Schedulable

Models::Schedulable::SIMPLE_FORM_OPTIONS

Instance Attribute Summary collapse

Belongs to collapse

Methods included from Models::Auditable

#creator, #updater

Has one collapse

Has many collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Models::Auditable

#all_skipped_columns, #audit_reference_data, #should_not_save_version, #stamp_record

Methods inherited from ApplicationRecord

ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation

Methods included from Models::Schedulable

config

Methods included from Models::AfterCommittable

#after_commit

Methods included from Models::EventPublishable

#publish_event

Instance Attribute Details

#actual_total_chargesObject (readonly)

Actual charges must be non-negative when present.

Validations:

  • Numericality ({ greater_than_or_equal_to: 0.0, if: :actual_total_charges })


286
# File 'app/models/shipment.rb', line 286

validates :actual_total_charges, numericality: { greater_than_or_equal_to: 0.0, if: :actual_total_charges }

#assign_ssccObject

Returns the value of attribute assign_sscc.



163
164
165
# File 'app/models/shipment.rb', line 163

def assign_sscc
  @assign_sscc
end

#carrierObject (readonly)

Carrier required once the label is complete.

Validations:

  • Presence ({ if: ->(s) { s.label_complete? || s.manually_complete? } })


272
# File 'app/models/shipment.rb', line 272

validates :carrier, presence: { if: ->(s) { s.label_complete? || s.manually_complete? } }

#date_shippedObject (readonly)

Ship date required for legacy shipments.

Validations:



270
# File 'app/models/shipment.rb', line 270

validates :date_shipped, presence: { if: :is_legacy }

#heightObject (readonly)

Dimensions required for non-legacy, non-service shipments.

Validations:

  • Presence ({ if: :neither_legacy_nor_service })
  • Numericality ({ greater_than: 0.0, if: :neither_legacy_nor_service })


281
# File 'app/models/shipment.rb', line 281

validates :width, :length, :height, presence: { if: :neither_legacy_nor_service }

#lengthObject (readonly)

Dimensions required for non-legacy, non-service shipments.

Validations:

  • Presence ({ if: :neither_legacy_nor_service })
  • Numericality ({ greater_than: 0.0, if: :neither_legacy_nor_service })


281
# File 'app/models/shipment.rb', line 281

validates :width, :length, :height, presence: { if: :neither_legacy_nor_service }

#numberObject

Returns the value of attribute number.



163
164
165
# File 'app/models/shipment.rb', line 163

def number
  @number
end

#shipments_numberObject

Returns the value of attribute shipments_number.



163
164
165
# File 'app/models/shipment.rb', line 163

def shipments_number
  @shipments_number
end

#skip_tracking_number_validationObject

Returns the value of attribute skip_tracking_number_validation.



163
164
165
# File 'app/models/shipment.rb', line 163

def skip_tracking_number_validation
  @skip_tracking_number_validation
end

#tracking_numberObject (readonly)

Catches hand-keyed numbers that can't belong to the carrier they were
entered against (the wrong Canpar barcode, a truncated UPS number).
Only fires when tracking_number is changing, and only for parcel
carriers with a published barcode spec. @see TrackingNumberFormatValidator

Validations:

  • Tracking_number_format ({ carrier_method: :carrier })


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

validates :tracking_number, tracking_number_format: { carrier_method: :carrier }

#weightObject (readonly)

Weight is always required.

Validations:



279
# File 'app/models/shipment.rb', line 279

validates :weight, presence: true

#widthObject (readonly)

Dimensions required for non-legacy, non-service shipments.

Validations:

  • Presence ({ if: :neither_legacy_nor_service })
  • Numericality ({ greater_than: 0.0, if: :neither_legacy_nor_service })


281
# File 'app/models/shipment.rb', line 281

validates :width, :length, :height, presence: { if: :neither_legacy_nor_service }

Class Method Details

.all_carriers_for_selectArray<String>

All known carriers as select options.

Returns:

  • (Array<String>)


909
910
911
912
913
# File 'app/models/shipment.rb', line 909

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_labelActiveRecord::Relation<Shipment>

A relation of Shipments that are awaiting label. Active Record Scope

Returns:

See Also:



292
# File 'app/models/shipment.rb', line 292

scope :awaiting_label, -> { where(state: 'awaiting_label') }

.build_gs1_128(serial:, application_identifier: '00', gs1_prefix: GS1_PREFIX) ⇒ String

Parameters:

  • serial (Integer)

    serial component

  • application_identifier (String) (defaults to: '00')

    GS1 AI prefix

  • gs1_prefix (String) (defaults to: GS1_PREFIX)

    company GS1 prefix

Returns:

  • (String)

    the SSCC code



1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
# File 'app/models/shipment.rb', line 1397

def self.build_gs1_128(serial:, application_identifier: '00', gs1_prefix: GS1_PREFIX)
  s = [0] # extension digit
  s += gs1_prefix.chars # our gs1 prefix, 7 digits
  s += serial.to_s.rjust(9, '0').chars # serial code 9 digits zero padded

  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 # round to the next ten
  s << (check_ceil - check_sum)
  "#{application_identifier}#{s.join}"
end

.carrier_candidates_for_pickupActiveRecord::Relation<Shipment>

A relation of Shipments that are carrier candidates for pickup. Active Record Scope

Returns:

See Also:



326
# File 'app/models/shipment.rb', line 326

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) ⇒ String

Icon URL for a carrier.

Parameters:

  • carrier (String)

    carrier name

Returns:

  • (String)


918
919
920
# File 'app/models/shipment.rb', line 918

def self.carrier_icon(carrier)
  ShipmentCourier.new(carrier).courier_icon_url
end

.carrier_options_for_select(delivery, show_all: false) ⇒ Array

Carrier choices for a delivery's destination country.

Parameters:

  • delivery (Delivery)

    the delivery being shipped

  • show_all (Boolean) (defaults to: false)

    include every country's carriers

Returns:

  • (Array)


893
894
895
896
897
898
899
900
901
902
903
904
905
# File 'app/models/shipment.rb', line 893

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

.cartonsActiveRecord::Relation<Shipment>

A relation of Shipments that are cartons. Active Record Scope

Returns:

See Also:



312
# File 'app/models/shipment.rb', line 312

scope :cartons, -> { where(container_type: 'carton') }

.choose_carrier_pickup_date_time(carrier, store) ⇒ Time?

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
Next pickup date/time for a carrier at a store, honoring cut-off times.

Parameters:

  • carrier (String)

    carrier name

  • store (Store)

    pickup store

Returns:

  • (Time, nil)


945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
# File 'app/models/shipment.rb', line 945

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 # WY Canada is Eastern Time, Wy US is Central
    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

.completedActiveRecord::Relation<Shipment>

A relation of Shipments that are completed. Active Record Scope

Returns:

See Also:



288
# File 'app/models/shipment.rb', line 288

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.

Parameters:

  • int (Integer, String, nil)

    packdim 5th-element value;
    coerced via to_i so nil / non-numeric inputs map to 0 and
    resolve to 'carton'.

Returns:

  • (String, nil)

    enum label, or nil if the integer falls
    outside the known set (currently > 3).



202
203
204
# File 'app/models/shipment.rb', line 202

def self.container_type_from_packdim_int(int)
  PACKDIM_CONTAINER_INTS.invert[int.to_i]
end

.container_types_for_selectArray<Array(String, String)>

Container types as [humanized label, key] select options.

Returns:

  • (Array<Array(String, String)>)


835
836
837
# File 'app/models/shipment.rb', line 835

def self.container_types_for_select
  Shipment.container_types.keys.map { |ct| [ct.humanize, ct] }
end

.contentableActiveRecord::Relation<Shipment>

A relation of Shipments that are contentable. Active Record Scope

Returns:

See Also:



311
# File 'app/models/shipment.rb', line 311

scope :contentable, -> { where.not(state: %w[label_voided manually_voided suggested]) }

.cratesActiveRecord::Relation<Shipment>

A relation of Shipments that are crates. Active Record Scope

Returns:

See Also:



314
# File 'app/models/shipment.rb', line 314

scope :crates, -> { where(container_type: 'crate') }

.custom_carriers_for_selectArray<String>

Custom (description-override) carriers for select boxes (cached).

Returns:

  • (Array<String>)


972
973
974
975
976
977
# File 'app/models/shipment.rb', line 972

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_expressActiveRecord::Relation<Shipment>

A relation of Shipments that are fedex express. Active Record Scope

Returns:

See Also:



327
# File 'app/models/shipment.rb', line 327

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_serialInteger

Next serial from the shipments sequence.

Returns:

  • (Integer)


1380
1381
1382
1383
# File 'app/models/shipment.rb', line 1380

def self.get_next_shipments_serial
  seq = Shipment.find_by_sql("SELECT nextval('shipments_serial') AS shipment_serial")
  seq[0].shipment_serial
end

.label_completeActiveRecord::Relation<Shipment>

A relation of Shipments that are label complete. Active Record Scope

Returns:

See Also:



298
# File 'app/models/shipment.rb', line 298

scope :label_complete, -> { where(state: 'label_complete') }

.label_voidedActiveRecord::Relation<Shipment>

A relation of Shipments that are label voided. Active Record Scope

Returns:

See Also:



299
# File 'app/models/shipment.rb', line 299

scope :label_voided, -> { where(state: 'label_voided') }

.line_item_to_content_key(line_item) ⇒ Hash

Builds a content key to present a line in our shipment content

Parameters:

  • line_item (LineItem)

    the line item

Returns:

  • (Hash)

    composite content key



1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
# File 'app/models/shipment.rb', line 1095

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
  # need this information for EDI shipment information when dealing with kits
  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_completeActiveRecord::Relation<Shipment>

A relation of Shipments that are manually complete. Active Record Scope

Returns:

See Also:



296
# File 'app/models/shipment.rb', line 296

scope :manually_complete, -> { where(state: 'manually_complete') }

.manually_voidedActiveRecord::Relation<Shipment>

A relation of Shipments that are manually voided. Active Record Scope

Returns:

See Also:



297
# File 'app/models/shipment.rb', line 297

scope :manually_voided, -> { where(state: 'manually_voided') }

.measuredActiveRecord::Relation<Shipment>

A relation of Shipments that are measured. Active Record Scope

Returns:

See Also:



309
# File 'app/models/shipment.rb', line 309

scope :measured, -> { where(state: MEASURED_STATES) }

.next_sscc_for_gs1_128String

Next SSCC in GS1-128 format.

Returns:

  • (String)


1387
1388
1389
# File 'app/models/shipment.rb', line 1387

def self.next_sscc_for_gs1_128
  build_gs1_128(serial: get_next_shipments_serial)
end

.non_freight_deliveryActiveRecord::Relation<Shipment>

A relation of Shipments that are non freight delivery. Active Record Scope

Returns:

See Also:



322
# File 'app/models/shipment.rb', line 322

scope :non_freight_delivery, -> { where(delivery: Delivery.not_ltl_freight) }

.non_palletsActiveRecord::Relation<Shipment>

A relation of Shipments that are non pallets. Active Record Scope

Returns:

See Also:



316
# File 'app/models/shipment.rb', line 316

scope :non_pallets, -> { where(container_type: %w[carton crate]) }

.non_voidedActiveRecord::Relation<Shipment>

A relation of Shipments that are non voided. Active Record Scope

Returns:

See Also:



310
# File 'app/models/shipment.rb', line 310

scope :non_voided, -> { where.not(state: %w[label_voided manually_voided]) }

.override_carriers_for_selectArray

Override carrier choices for select boxes.

Returns:

  • (Array)


966
967
968
# File 'app/models/shipment.rb', line 966

def self.override_carriers_for_select
  [nil, 'Override'] + (ShippingOption.active.pluck('distinct carrier').compact + Shipment.custom_carriers_for_select).uniq.sort
end

.packageableActiveRecord::Relation<Shipment>

A relation of Shipments that are packageable. Active Record Scope

Returns:

See Also:



308
# File 'app/models/shipment.rb', line 308

scope :packageable, -> { where(state: PACKING_STATES) }

.packedActiveRecord::Relation<Shipment>

A relation of Shipments that are packed. Active Record Scope

Returns:

See Also:



291
# File 'app/models/shipment.rb', line 291

scope :packed, -> { where(state: 'packed') }

.packed_or_awaiting_labelsActiveRecord::Relation<Shipment>

A relation of Shipments that are packed or awaiting labels. Active Record Scope

Returns:

See Also:



294
# File 'app/models/shipment.rb', line 294

scope :packed_or_awaiting_labels, -> { where(state: %w[packed awaiting_label]) }

.packed_or_measuredActiveRecord::Relation<Shipment>

A relation of Shipments that are packed or measured. Active Record Scope

Returns:

See Also:



295
# File 'app/models/shipment.rb', line 295

scope :packed_or_measured, -> { where(state: PACKED_OR_MEASURED_STATES) }

.palleted_cratesActiveRecord::Relation<Shipment>

A relation of Shipments that are palleted crates. Active Record Scope

Returns:

See Also:



315
# File 'app/models/shipment.rb', line 315

scope :palleted_crates, -> { where(container_type: 'palleted_crate') }

.palletsActiveRecord::Relation<Shipment>

A relation of Shipments that are pallets. Active Record Scope

Returns:

See Also:



313
# File 'app/models/shipment.rb', line 313

scope :pallets, -> { where(container_type: 'pallet') }

.states_for_selectArray<Array(String, String)>

Shipment states as [titleized human name, value] select options.

Returns:

  • (Array<Array(String, String)>)


829
830
831
# File 'app/models/shipment.rb', line 829

def self.states_for_select
  state_machines[:state].states.map { |s| [s.human_name.titleize, s.value] }
end

.suggestedActiveRecord::Relation<Shipment>

A relation of Shipments that are suggested. Active Record Scope

Returns:

See Also:



290
# File 'app/models/shipment.rb', line 290

scope :suggested, -> { where(state: 'suggested') }

.suggested_packed_or_awaiting_labelsActiveRecord::Relation<Shipment>

A relation of Shipments that are suggested packed or awaiting labels. Active Record Scope

Returns:

See Also:



293
# File 'app/models/shipment.rb', line 293

scope :suggested_packed_or_awaiting_labels, -> { where(state: %w[suggested packed awaiting_label]) }

.top_levelActiveRecord::Relation<Shipment>

A relation of Shipments that are top level. Active Record Scope

Returns:

See Also:



323
# File 'app/models/shipment.rb', line 323

scope :top_level, -> { where(parent_shipment_id: nil) }

Carrier tracking URL for a tracking number.

Parameters:

  • carrier (String)

    carrier name

  • tracking_number (String)

    tracking number

Returns:

  • (String, nil)


926
927
928
# File 'app/models/shipment.rb', line 926

def self.tracking_link(carrier, tracking_number)
  ShipmentTrackingNumber.new(tracking_number, courier_code: carrier).tracking_url
end

.tracking_status_completeActiveRecord::Relation<Shipment>

A relation of Shipments that are tracking status complete. Active Record Scope

Returns:

See Also:



305
306
307
# File 'app/models/shipment.rb', line 305

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_incompleteActiveRecord::Relation<Shipment>

A relation of Shipments that are tracking status incomplete. Active Record Scope

Returns:

See Also:



300
301
302
303
# File 'app/models/shipment.rb', line 300

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, ''])
}

.valid_sscc?(code) ⇒ Boolean

True when code is a well-formed SSCC: AI (00) + 17 data digits + the
correct mod-10 check digit (same math as build_gs1_128 above).

Parameters:

  • code (String)

    candidate SSCC

Returns:

  • (Boolean)


1416
1417
1418
1419
1420
1421
1422
# File 'app/models/shipment.rb', line 1416

def self.valid_sscc?(code)
  match = /\A00(\d{17})(\d)\z/.match(code.to_s)
  return false unless match

  sum = match[1].chars.each_with_index.sum { |d, i| d.to_i * (i.even? ? 3 : 1) }
  (((sum * 0.1).ceil * 10) - sum) == match[2].to_i
end

.voidedActiveRecord::Relation<Shipment>

A relation of Shipments that are voided. Active Record Scope

Returns:

See Also:



289
# File 'app/models/shipment.rb', line 289

scope :voided, -> { where(state: %w[label_voided manually_voided]) }

Instance Method Details

#amazon_container_code?Boolean?

Whether the container code is an Amazon (AMZN-prefixed) code.

Returns:

  • (Boolean, nil)


1033
1034
1035
# File 'app/models/shipment.rb', line 1033

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.

Parameters:

  • qr_png_tmp_path (String)

    path to the downloaded QR PNG

  • instructions (String, nil)

    carrier-supplied counter instructions

  • handoff_code (String, nil)

    optional kiosk PIN

Returns:

  • (Upload)

    the persisted PNG upload

Raises:

  • (RuntimeError)

    if the upload couldn't be created



787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'app/models/shipment.rb', line 787

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

  # Set unconditionally (presence => nil) so a regenerated label can't leave
  # stale instructions/handoff code behind; save! so a persistence failure
  # surfaces instead of being silently dropped.
  self.paperless_instructions = instructions.presence
  self.paperless_handoff_code = handoff_code.presence
  save!

  uploads << upload
end

#auditHash

Runs the package auditor against this shipment's container.

Returns:

  • (Hash)

    audit issues keyed by carrier



1264
1265
1266
1267
1268
1269
1270
# File 'app/models/shipment.rb', line 1264

def audit
  box = to_package
  Shipping::PackageAuditor.new.process(box, carriers: [carrier].compact.presence, shipment: self)
rescue Shipping::Container::InvalidPackageDimensions => e
  Rails.logger.error "Shipping auditor failed to run #{e} on shipment id #{id}"
  {}
end

#bol_pdfUpload?

Latest BOL upload for this shipment.

Returns:



817
818
819
# File 'app/models/shipment.rb', line 817

def bol_pdf
  uploads.ship_bol_pdfs.first
end

#bps_barcode(file_path: nil, _partner_code: nil) ⇒ String, Object

QR barcode image for the BPS barcode string.

Parameters:

  • file_path (String, nil) (defaults to: nil)

    save to this path instead of returning the image

  • _partner_code (String, nil) (defaults to: nil)

    unused

Returns:

  • (String, Object)

    file path or image



1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
# File 'app/models/shipment.rb', line 1018

def bps_barcode(file_path: nil, _partner_code: nil)
  # file_path ||= Rails.root.join(Rails.application.config.x.temp_storage_path.to_s, "bps-#{id}-#{Time.current.to_i}#{rand(1000)}.png")
  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_stringString

BPS barcode payload string (partner prefix, PO, contents).

Returns:

  • (String)


993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
# File 'app/models/shipment.rb', line 993

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_prefixString?

BPS partner code prefix (AMZN for Amazon, else the customer reference).

Returns:

  • (String, nil)


981
982
983
984
985
986
987
988
989
# File 'app/models/shipment.rb', line 981

def bps_partner_code_prefix
  return unless (customer = delivery&.customer)

  if customer.report_grouping == 'Amazon'
    'AMZN'
  else
    customer.reference_number
  end
end

#carrier_iconString

Icon name for the sanitized carrier.

Returns:

  • (String)


527
528
529
# File 'app/models/shipment.rb', line 527

def carrier_icon
  self.class.carrier_icon(sanitized_carrier)
end

#carrier_options_for_selectArray<String>

Carrier choices for this shipment (including any override carrier).

Returns:

  • (Array<String>)


881
882
883
884
885
886
887
# File 'app/models/shipment.rb', line 881

def carrier_options_for_select
  options = []
  options = self.class.all_carriers_for_select if delivery
  # If the current carrier is not in the list add them, could be an override one
  options << carrier unless options.compact.find { |e| e == carrier }
  options.compact.uniq.sort
end

#check_if_oversizeBoolean

Whether the dimensions are oversize for the container type.

Returns:

  • (Boolean)


588
589
590
591
592
# File 'app/models/shipment.rb', line 588

def check_if_oversize
  return false if is_legacy

  WarehousePackage.check_if_dimensions_oversize([length, width, height], container_type)
end

#child_shipmentsActiveRecord::Relation<Shipment>

Child shipments in a multi-piece shipment.

Returns:

See Also:



243
# File 'app/models/shipment.rb', line 243

has_many :child_shipments, class_name: 'Shipment', foreign_key: 'parent_shipment_id', dependent: :nullify

#complete?Boolean

Whether the shipment is complete (manually or via label).

Returns:

  • (Boolean)


823
824
825
# File 'app/models/shipment.rb', line 823

def complete?
  manually_complete? || label_complete?
end

#compute_item_declared_valueFloat

Declared customs value of the packed items.

Returns:

  • (Float)


1497
1498
1499
1500
1501
# File 'app/models/shipment.rb', line 1497

def compute_item_declared_value
  # Use includes(:line_item) to preload the belongs_to in one batch query instead of
  # firing a separate SELECT per ShipmentContent row.
  shipment_contents.includes(:line_item).sum { |sc| sc.line_item.unit_value_for_commercial_invoice * sc.quantity.to_f }
end

#compute_item_weightFloat

Net weight of the packed items.

Returns:

  • (Float)


1461
1462
1463
1464
1465
# File 'app/models/shipment.rb', line 1461

def compute_item_weight
  # important: item.base_weight is the better quality number and means Net Weight so the correct number to use when calculating item weight because tare weight (of the box, pallet, crate etc) is added after
  # reject marked_for_destruction so in-memory recomputes (pre-pack weight autoset) don't count lines being removed
  shipment_contents.reject(&:marked_for_destruction?).sum { |sc| sc.line_item.item.base_weight.to_f * sc.quantity.to_i }
end

#compute_shipment_declared_value(skip_carrier_guard: false) ⇒ Float

Declared customs value for the whole shipment, falling back to an even
split of the delivery's declared value.

Parameters:

  • skip_carrier_guard (Boolean) (defaults to: false)

    bypass the carrier do-not-insure guard

Returns:

  • (Float)


1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
# File 'app/models/shipment.rb', line 1507

def compute_shipment_declared_value(skip_carrier_guard: false)
  # skip_carrier_guard: true is used by Shipsurance itself to get the real insured value.
  # Without it we'd create a circular zero: do_not_ship_insure_via_carrier? returns true
  # for Shipsurance-qualified deliveries, causing the API to receive declaredValue "0.0".
  # Standalone CRM shipments have standalone_delivery but no delivery (AppSignal #4550).
  return 0.0 if !skip_carrier_guard && delivery&.do_not_ship_insure_via_carrier?

  # if the shipment has no shipment_contents or if any of the shipment's or child shipments'
  # shipment_contents have kit components, use the delivery subtotal method because we store
  # only kit component line items in shipment_contents (not kit parent line items) and their
  # price/cogs are $0.
  # Use a single EXISTS+JOIN query per shipment instead of per-row sc.line_item loads.
  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) # one source of truth here, let delivery decide total declared value
  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_weightInteger?

Total shipment weight: child items + own items + tare, rounded up.

Returns:

  • (Integer, nil)


1489
1490
1491
1492
1493
# File 'app/models/shipment.rb', line 1489

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_weightFloat?

Tare (container) weight by container type.

Returns:

  • (Float, nil)


1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
# File 'app/models/shipment.rb', line 1469

def compute_tare_weight
  if carton?
    if (sqin = surface_sqin) # made up formula, a weight per sq.in of container
      [(0.0007 * sqin), 1].max
    else
      0.25
    end
  elsif pallet? || palleted_crate?
    PALLET_NOMINAL_WEIGHT # typical GMA pallet is 33-48 lbs
  elsif crate?
    if (sqin = surface_sqin) # made up formula, a weight per sq.in of container, see: https://www.uline.com/BL_427/Standard-Wood-Crates
      [(0.00875 * sqin), 1].max
    else
      CRATE_NOMINAL_WEIGHT
    end
  end
end

#container_code_typeString?

Human-readable classification of the container code.

Returns:

  • (String, nil)


1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
# File 'app/models/shipment.rb', line 1045

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_dupShipment

Duplicates this shipment without container code or tracking number.

Returns:



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

def deep_dup
  deep_clone(except: %i[container_code tracking_number])
end

#deliveryDelivery

Delivery this shipment belongs to.

Returns:

See Also:

Validations:

  • Presence ({ if: ->(s) { s.neither_legacy_nor_service && s.mail_activity_id.nil? && s.standalone_delivery.nil? } })


222
# File 'app/models/shipment.rb', line 222

belongs_to :delivery, optional: true

#delivery_or_mail_activityDelivery, ...

The resource this shipment is attached to (delivery or mail activity).

Returns:



421
422
423
# File 'app/models/shipment.rb', line 421

def delivery_or_mail_activity
  delivery || mail_activity
end

#dimensions_changed?Boolean

Whether any dimension or weight changed.

Returns:

  • (Boolean)


1224
1225
1226
# File 'app/models/shipment.rb', line 1224

def dimensions_changed?
  length_changed? || width_changed? || height_changed? || weight_changed?
end

#dimensions_text(display_units: false) ⇒ String

Rounded dimensions joined as "L x W x H".

Parameters:

  • display_units (Boolean) (defaults to: false)

    append "in" to each dimension

Returns:

  • (String)


862
863
864
865
# File 'app/models/shipment.rb', line 862

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) ⇒ String

Dimensions converted to another unit, joined as "L x W x H".

Parameters:

  • unit (String) (defaults to: 'in')

    target unit

  • precision (Integer) (defaults to: 0)

    decimal places

  • display_units (Boolean) (defaults to: false)

    append the unit label

Returns:

  • (String)


1631
1632
1633
1634
# File 'app/models/shipment.rb', line 1631

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

#display_tracking_numberObject

The tracking number to display for this shipment. For ShipEngine LTL freight
that's the delivery-level PRO (ltl_pro_number) — the per-pallet
tracking_number is blank or a non-trackable booking number.



507
508
509
510
511
# File 'app/models/shipment.rb', line 507

def display_tracking_number
  return delivery.ltl_pro_number.presence || tracking_number if shipengine_ltl?

  tracking_number
end

#editable?Boolean

Whether the shipment can still be edited.

Returns:

  • (Boolean)


559
560
561
# File 'app/models/shipment.rb', line 559

def editable?
  suggested? || packed? || (awaiting_label? && delivery&.is_rma_return?) || is_legacy || (is_manual && !part_of_a_locked_delivery?)
end

#effective_nmfc_codeString

NMFC code voted by contents weighted on quantity, weight, and volume.

Returns:

  • (String)


634
635
636
637
638
639
640
641
642
# File 'app/models/shipment.rb', line 634

def effective_nmfc_code
  # just count the occurrences of item effective NMFC codes from the shipment contents, with voting weighted by quantity, shipping weight and volume and take the top one
  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_neededObject

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.



1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
# File 'app/models/shipment.rb', line 1357

def enqueue_tracking_registration_if_needed
  return unless saved_change_to_tracking_number?
  return if tracking_number.blank?

  # Resolve a canonical carrier from the free-form `shipments.carrier`
  # column, falling back to the tracking number's format pattern when
  # the carrier string is a placeholder ("Override", "Standard",
  # "Shipping override, please confirm") or unrecognised service-level
  # name. Catches the long tail of manually-entered shipments that
  # would otherwise silently skip registration.
  normalized = Heatwave::Normalizers.resolve_shipping_carrier(carrier, tracking_number: tracking_number)
  return unless PARCEL_CARRIER_INTERNAL_TO_SHIPENGINE_CODE.key?(normalized)

  # Tracking number changed — clear any prior registration stamp so the
  # worker re-registers with SE for the new number. update_columns
  # skips callbacks so this doesn't trigger another after_commit.
  update_columns(tracking_registered_at: nil) if tracking_registered_at.present?

  ShipmentTrackingRegistrationWorker.perform_async(id)
end

#entered_and_computed_weights_are_close?Boolean

Whether the entered weight is close to the computed weight (pallets only).

Returns:

  • (Boolean)


1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
# File 'app/models/shipment.rb', line 1561

def entered_and_computed_weights_are_close?
  if pallet? # be more exacting with pallets
    delta_percent = 100.0 * (weight.to_f - compute_shipment_weight.to_f).abs / (compute_shipment_weight || 1).to_f
    delta_lbs = (weight.to_f - compute_shipment_weight.to_f).abs
    return true if delta_lbs <= MIN_WEIGHT_DELTA_LBS # first test that we're at least a few lbs over before going on, to eliminate cables/screws etc.

    (delta_percent <= MAX_WEIGHT_DELTA_PERCENT) &&
      (delta_lbs <= MAX_WEIGHT_DELTA_LBS)
  else
    true # non-pallets, let it go
  end
end

#final?Boolean?

Whether the parent resource is final (invoiced/complete).

Returns:

  • (Boolean, nil)


1338
1339
1340
# File 'app/models/shipment.rb', line 1338

def final?
  delivery&.invoiced? || order&.invoiced? || mail_activity&.complete?
end

#freight_classInteger?

Freight class derived from density (weight per cubic foot).

Returns:

  • (Integer, nil)


618
619
620
621
622
623
624
625
626
627
628
629
630
# File 'app/models/shipment.rb', line 618

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

Whether this shipment (or a sibling on the order) ships LTL freight.

Returns:

  • (Boolean)


545
546
547
548
549
# File 'app/models/shipment.rb', line 545

def freight_shipment?
  dels = [delivery]
  dels += order.present? ? order.deliveries : []
  dels.compact.uniq.any?(&:ships_ltl_freight?)
end

#full_dimension_text(metric: false) ⇒ String

Dimensions and weight as display text.

Parameters:

  • metric (Boolean) (defaults to: false)

    render in cm/kg instead of in/lbs

Returns:

  • (String)


851
852
853
854
855
856
857
# File 'app/models/shipment.rb', line 851

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) ⇒ Upload?

Generates (or reuses) the SSCC container label upload.

Parameters:

  • return_existing (Boolean) (defaults to: false)

    reuse the existing label when present

Returns:



1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
# File 'app/models/shipment.rb', line 1179

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) ⇒ Array<Upload>

Generates and attaches the letter-format ship-label PDF.

Parameters:

  • ship_label_tmp_path (String)

    path to the carrier label file

  • carrier (String)

    carrier name

Returns:



697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'app/models/shipment.rb', line 697

def generate_letter_ship_label_pdf(ship_label_tmp_path, carrier)
  self.carrier = carrier

  # For these carriers the label comes back as its own PDF (no PNG to
  # rotate in), so embed its pages into the letter PDF instead of merging
  # the raw file — LetterShip composites each label page at native size on
  # a letter page, keeping the printed label at true 4x6 under any
  # "fit to page" print setting.
  merge_carriers = carrier.to_s.downcase.match?(/speedeedelivery|canadapost|canpar/)
  label_pdf_path = merge_carriers ? ship_label_pdf&.attachment&.path : nil

  # generate the pdf
  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, label_pdf_path: label_pdf_path).pdf
  File.open(ship_label_pdf_path, 'wb') do |file|
    file.write pdf
    file.flush
    file.fsync
  end
  save

  # attach the finished ship label and delete temp files
  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) ⇒ Array<Upload>

Generates and attaches the parcel ship-label PDF.

Parameters:

  • ship_label_tmp_path (String)

    path to the carrier label PDF

  • carrier_to_use (String)

    carrier name

  • is_return (Boolean) (defaults to: false)

    whether this is a return label

Returns:



679
680
681
682
683
684
685
686
687
688
689
690
691
# File 'app/models/shipment.rb', line 679

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) # we need to do this copy to get the correct file extension and mime type for browser handling
  # attach the finished ship label
  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 = {}) ⇒ Array<Upload>

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

Generates the Speedee Delivery ship label PDF and attaches it as an
upload in the 'ship_label_pdf' category.

Parameters:

Options Hash (options):

  • sort_code (String) — default: '00'

    Speedee sort code

  • signature_confirmation (Boolean)

    request AOD
    signature service

Returns:



754
755
756
757
758
759
760
# File 'app/models/shipment.rb', line 754

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) ⇒ String

Generates a GS1-128 (or Code 128 fallback) barcode PNG for the SSCC.

Parameters:

  • file_path (String, nil) (defaults to: nil)

    save to this path instead of returning data

Returns:

  • (String)

    file path or PNG data



1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
# File 'app/models/shipment.rb', line 1060

def generate_sscc_barcode(file_path = nil)
  raise 'Container code is invalid' if container_code.blank?

  # file_path ||= Rails.root.join(Rails.application.config.x.temp_storage_path.to_s, "gs1-128-#{id}-#{Time.current.to_i}#{rand(1000)}.png")
  require 'zint'
  # container_code carries the leading AI (00); zint's GS1 mode wants the AI
  # bracketed and prepends FNC1 itself (barby needed a literal FNC1 byte).
  # Manually entered container codes may not be valid GS1 SSCCs (right shape
  # but wrong check digit, or not SSCC-shaped at all) — fall back to a plain
  # Code 128 rather than printing a GS1 symbol scanners will reject.
  value, symbology =
    if self.class.valid_sscc?(container_code)
      ["[#{container_code[0, 2]}]#{container_code[2..]}", Zint::Constants::Symbologies::BARCODE_GS1_128]
    else
      [container_code, Zint::Constants::Symbologies::BARCODE_CODE128]
    end
  barcode = Zint::Barcode.new(value:, symbology:)
  barcode.show_hrt = 0 # barby rendered bars only; keep it that way
  png = barcode.to_memory_file(extension: '.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) ⇒ String

Timestamped PDF file name for a generated document of the given type.

Parameters:

  • file_type (String)

    document type (package, letter, bol, ...)

Returns:

  • (String)


647
648
649
650
651
652
653
654
655
656
657
# File 'app/models/shipment.rb', line 647

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

Whether length, width, height, and weight are all present and positive.

Returns:

  • (Boolean)


1218
1219
1220
# File 'app/models/shipment.rb', line 1218

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) ⇒ Float?

Height converted to another unit.

Parameters:

  • unit (String) (defaults to: 'in')

    target unit

  • precision (Integer) (defaults to: 0)

    decimal places (ceil-rounded)

Returns:

  • (Float, nil)


1598
1599
1600
1601
1602
# File 'app/models/shipment.rb', line 1598

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

Audits and records whether the shipment incurs an oversized penalty.

Returns:

  • (Boolean)


1291
1292
1293
1294
1295
1296
1297
1298
1299
# File 'app/models/shipment.rb', line 1291

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?

Whether this shipment is an RMA return.

Returns:

  • (Boolean, nil)


576
577
578
# File 'app/models/shipment.rb', line 576

def is_rma_return?
  delivery&.is_rma_return?
end

#is_service?Boolean?

Whether this is a service (non-physical) shipment.

Returns:

  • (Boolean, nil)


582
583
584
# File 'app/models/shipment.rb', line 582

def is_service?
  state.in?(%w[service_redemption_code_sent service_fulfilled]) || delivery&.is_service_only?
end

#is_speedee_oversize?Boolean

Whether girth exceeds Speedee's dimensional threshold.

Returns:

  • (Boolean)


596
597
598
# File 'app/models/shipment.rb', line 596

def is_speedee_oversize?
  (length + (2.0 * (width + height))) >= Shipping::SpeedeeDelivery::HIGH_DIMENSIONAL_LENGTH_THRESHOLD
end

#length_converted(unit: 'in', precision: 0) ⇒ Float?

Length converted to another unit.

Parameters:

  • unit (String) (defaults to: 'in')

    target unit

  • precision (Integer) (defaults to: 0)

    decimal places (ceil-rounded)

Returns:

  • (Float, nil)


1578
1579
1580
1581
1582
# File 'app/models/shipment.rb', line 1578

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_itemsActiveRecord::Relation<LineItem>

Line items packed in this shipment.

Returns:

See Also:



241
# File 'app/models/shipment.rb', line 241

has_many :line_items, through: :shipment_contents

#locked_for_fba?Boolean?

Whether this shipment is locked as an Amazon FBA container.

Returns:

  • (Boolean, nil)


1638
1639
1640
# File 'app/models/shipment.rb', line 1638

def locked_for_fba?
  container_code =~ CustomerConstants::AMAZON_FBA_ID_REGEX && (packed? || awaiting_label?)
end

#mail_activityMailActivity

Mail activity backing this shipment (letter shipments).



226
# File 'app/models/shipment.rb', line 226

belongs_to :mail_activity, optional: true

#manifestManifest

Manifest this shipment is part of.

Returns:

See Also:



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

belongs_to :manifest, optional: true

#manual_container_codeString?

Form accessor for the container code.

Returns:

  • (String, nil)


1426
1427
1428
# File 'app/models/shipment.rb', line 1426

def manual_container_code
  container_code
end

#manual_container_code=(code) ⇒ void

This method returns an undefined value.

Form setter for the container code (ignores blanks).

Parameters:

  • code (String)

    container code



1433
1434
1435
# File 'app/models/shipment.rb', line 1433

def manual_container_code=(code)
  self.container_code = code if code.present?
end

#manual_shipmentBoolean

Whether this is a manual shipment.

Returns:

  • (Boolean)


539
540
541
# File 'app/models/shipment.rb', line 539

def manual_shipment
  is_manual
end

#need_to_audit?Boolean

Whether an audit is needed (dimensions/container changed or never audited).

Returns:

  • (Boolean)


1326
1327
1328
# File 'app/models/shipment.rb', line 1326

def need_to_audit?
  dimensions_changed? || container_type_changed? || !audited
end

#neither_legacy_nor_serviceBoolean

Whether this is neither a legacy nor a service shipment.

Returns:

  • (Boolean)


533
534
535
# File 'app/models/shipment.rb', line 533

def neither_legacy_nor_service
  !(is_legacy || is_service?)
end

#non_freight_shipment?Boolean

Whether this shipment does not ship LTL freight.

Returns:

  • (Boolean)


553
554
555
# File 'app/models/shipment.rb', line 553

def non_freight_shipment?
  !freight_shipment?
end

#ok_to_delete_with_mail_activity?Boolean

Whether a mail-activity shipment can be deleted in its current state.

Returns:

  • (Boolean)


869
870
871
# File 'app/models/shipment.rb', line 869

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

Whether a standalone-delivery shipment can be deleted in its current state.

Returns:

  • (Boolean)


875
876
877
# File 'app/models/shipment.rb', line 875

def ok_to_delete_with_standalone_delivery?
  suggested? or label_voided? or manually_voided? or packed?
end

#orderOrder

Order this shipment fulfills.

Returns:

See Also:

Validations:

  • Presence ({ if: ->(s) { s.delivery.present? && !(s.delivery.quoting? || s.delivery.pre_pack? || s.delivery.is_rma_return?) } })


224
# File 'app/models/shipment.rb', line 224

belongs_to :order, optional: true

#packed_or_pre_packed?Boolean

Whether the shipment is packed or has a definitive packing solution.

Returns:

  • (Boolean)


1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
# File 'app/models/shipment.rb', line 1274

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_nameObject

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.



662
663
664
665
666
667
668
669
670
671
672
# File 'app/models/shipment.rb', line 662

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_pngUpload?

The paperless QR/barcode PNG attached to this shipment, if any.

Returns:



806
807
808
# File 'app/models/shipment.rb', line 806

def paperless_qr_png
  uploads.in_category('paperless_qr_png').first
end

#parent_shipmentShipment

Parent shipment when this is part of a multi-piece shipment.

Returns:

See Also:



234
# File 'app/models/shipment.rb', line 234

belongs_to :parent_shipment, class_name: 'Shipment', optional: true

#part_of_a_locked_delivery?Boolean

Whether the parent delivery is locked (ship-confirmed, shipped, or invoiced).

Returns:

  • (Boolean)


565
566
567
568
569
570
571
572
# File 'app/models/shipment.rb', line 565

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

Whether this shipment qualifies for the carrier tracking API.

Returns:

  • (Boolean)


521
522
523
# File 'app/models/shipment.rb', line 521

def qualifies_for_tracking_api?
  label_complete? && carrier != 'SpeedeeDelivery' && container_type == 'carton'
end

#ready_to_manually_complete?Boolean

Whether the shipment has the carrier/tracking info needed to complete manually.

Returns:

  • (Boolean)


1344
1345
1346
1347
1348
1349
# File 'app/models/shipment.rb', line 1344

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_numberString

Reference number (container code or PD-prefixed id).

Returns:

  • (String)


427
428
429
# File 'app/models/shipment.rb', line 427

def reference_number
  container_code.presence || "PD#{id}"
end

#resource_reference_and_shipment_numberString Also known as: order_reference_and_shipment_number

Reference combining the parent's reference number and shipment position.

Returns:

  • (String)


439
440
441
442
# File 'app/models/shipment.rb', line 439

def resource_reference_and_shipment_number
  # a handy reference number for the shipment without a layer of container_code etc.
  "#{delivery&.resource&.reference_number}_#{shipment_index + 1}"
end

#round_dimensionsvoid

This method returns an undefined value.

Rounds dimensions to 1 decimal and weight to 4.



1246
1247
1248
1249
1250
1251
1252
1253
1254
# File 'app/models/shipment.rb', line 1246

def round_dimensions
  # 1 decimal place is all we want for dims but 4 for weight to handle small items
  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) ⇒ void

This method returns an undefined value.

Runs the package audit before save unless skipped.

Parameters:

  • force (Boolean) (defaults to: false)

    run even when skip/need checks fail



1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
# File 'app/models/shipment.rb', line 1304

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_carrierString?

Carrier name normalized to a known carrier for the destination country.

Returns:

  • (String, nil)


479
480
481
482
483
484
# File 'app/models/shipment.rb', line 479

def sanitized_carrier
  valid_carriers = (SHIPPING_CARRIERS_OPTIONS[(delivery&.country&.iso3 || 'USA').to_sym] || []).map(&:first) + ['Amazon'] # we need to also add Amazon here as a valid carrier pending integration into Heatwave
  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) ⇒ void

This method returns an undefined value.

Sets the carrier from an override, tracking-number detection, or the
parent's reported carrier.

Parameters:

  • carrier_override (String, nil) (defaults to: nil)

    explicit carrier



1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
# File 'app/models/shipment.rb', line 1204

def set_carrier(carrier_override = nil)
  if carrier_override.present?
    self.carrier = carrier_override
  else
    if tracking_number_changed? && tracking_number.present?
      # Attempt to auto detect and match
      self.carrier ||= ShipmentTrackingNumber.new(tracking_number).courier_name
    end
    self.carrier ||= delivery_or_mail_activity&.reported_carrier
  end
end

#set_default_numbervoid

This method returns an undefined value.

Defaults the shipment number and links the delivery's order.



1195
1196
1197
1198
# File 'app/models/shipment.rb', line 1195

def set_default_number
  self.number ||= 1
  self.order = delivery.order if delivery&.order
end

#set_default_pallet_dimensionsvoid

This method returns an undefined value.

Defaults dimensions/weight for incomplete pallets.



1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
# File 'app/models/shipment.rb', line 1445

def set_default_pallet_dimensions
  return unless pallet?
  return if complete?

  self.length ||= 48
  self.width ||= 40
  self.height ||= 78 # 6.5' typical height
  self.weight ||= compute_tare_weight
  # Hard to compute this effectively right now
  # if self.weight.nil? && (cartons = container&.shipments.carton).present?
  #   self.weight = cartons.sum(:weight) + compute_tare_weight # typical GMA pallet is 33-48 lbs
  # end
end

#set_default_shipment_weightObject

When warehouse just wants to use the item shipping_weight.
During pre-pack the weight field is read-only in the UI and estimated
weights are authoritative-by-calculation: always overwrite from contents.
Measured weights are entered manually at ship-label time (delivery no
longer pre_pack), where the ||= default preserves what warehouse typed.



1551
1552
1553
1554
1555
1556
1557
# File 'app/models/shipment.rb', line 1551

def set_default_shipment_weight
  if delivery&.pre_pack? && (suggested? || packed?)
    self.weight = compute_shipment_weight || weight
  else
    self.weight ||= compute_shipment_weight
  end
end

#set_ssccvoid

This method returns an undefined value.

Assigns a generated SSCC when no container code is set.



1439
1440
1441
# File 'app/models/shipment.rb', line 1439

def set_sscc
  self.container_code ||= self.class.next_sscc_for_gs1_128
end

#ship_label_pdf(letter_format = false) ⇒ Upload?

Latest ship-label upload for this shipment.

Parameters:

  • letter_format (Boolean) (defaults to: false)

    use the letter-format label category

Returns:



765
766
767
768
769
# File 'app/models/shipment.rb', line 765

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

#shipengine_ltl?Boolean

True when this shipment belongs to a ShipEngine LTL freight delivery, whose
tracking is keyed on the delivery PRO rather than the shipment.

Returns:

  • (Boolean)


515
516
517
# File 'app/models/shipment.rb', line 515

def shipengine_ltl?
  delivery&.shipping_option&.is_shipengine_ltl? || false
end

#shipment_content_grouped_content_keyObject

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



1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
# File 'app/models/shipment.rb', line 1119

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
        # We need to determine the ratio of this shipment content quantity in relation to the
        # parent item, then from the shipment content quantity determine to the best of our
        # ability what the parent quantity would be.
        parent_quantity_factor = sc.line_item.parent_quantity_factor
        sc.quantity
        parent_quantity = (sc.quantity / parent_quantity_factor).ceil
        contents[content_key] += parent_quantity
        # we need to keep track that we counted this parent otherwise the next kit component
        # will inflate the count
        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_labelString

Label describing the packed contents (single SKU/ASIN/UPC or "Mixed Skus").

Returns:

  • (String)


1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File 'app/models/shipment.rb', line 1155

def 
  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_quantityInteger

Total quantity packed in this shipment.

Returns:

  • (Integer)


1172
1173
1174
# File 'app/models/shipment.rb', line 1172

def shipment_content_quantity
  shipment_contents.sum(:quantity)
end

#shipment_contentsActiveRecord::Relation<ShipmentContent>

Contents packed in this shipment.

Returns:

See Also:



239
# File 'app/models/shipment.rb', line 239

has_many :shipment_contents, dependent: :destroy

#shipment_eventsActiveRecord::Relation<ShipmentEvent>

Tracking events for this shipment.

Returns:

See Also:



245
# File 'app/models/shipment.rb', line 245

has_many :shipment_events, dependent: :nullify, inverse_of: :shipment

#shipment_indexInteger

Zero-based position of this shipment among its parent's shipments.

Returns:

  • (Integer)


433
434
435
# File 'app/models/shipment.rb', line 433

def shipment_index
  (delivery&.shipment_ids || mail_activity&.shipment_ids || order&.direct_shipment_ids)&.index(id) || 0
end

#shipment_positionInteger

1-based position among similar shipments.

Returns:

  • (Integer)


467
468
469
# File 'app/models/shipment.rb', line 467

def shipment_position
  similar_shipment_ids.index(id) + 1
end

#shipment_totalInteger

Count of similar shipments on the same parent.

Returns:

  • (Integer)


473
474
475
# File 'app/models/shipment.rb', line 473

def shipment_total
  similar_shipment_ids.size
end

#shipment_tracking_numberObject

Initialize a shipment tracking number object



811
812
813
# File 'app/models/shipment.rb', line 811

def shipment_tracking_number
  ShipmentTrackingNumber.new(tracking_number, courier_code: carrier)
end

URL to the Shipsurance record for this shipment.

Returns:

  • (String, nil)


1650
1651
1652
# File 'app/models/shipment.rb', line 1650

def shipping_insurance_link
  Shipping::ShippingInsurance.new.get_shipping_insurance_link_for_shipment(self)
end

#shipping_insurance_record_idString?

Shipsurance record id from the stored insurance data.

Returns:

  • (String, nil)


1644
1645
1646
# File 'app/models/shipment.rb', line 1644

def shipping_insurance_record_id
  shipping_insurance_data&.dig('shipping_insurance_record_id')
end

#signature_confirmation?Boolean?

Whether the delivery requests signature confirmation.

Returns:

  • (Boolean, nil)


1656
1657
1658
# File 'app/models/shipment.rb', line 1656

def signature_confirmation?
  delivery&.signature_confirmation&.to_b
end

#similar_shipment_idsArray<Integer>?

Ids of shipments of the same container type on the same parent.

Returns:

  • (Array<Integer>, nil)


453
454
455
456
457
458
459
460
461
462
463
# File 'app/models/shipment.rb', line 453

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?

Whether the audit can be skipped (final, voided, service, or LTL).

Returns:

  • (Boolean, nil)


1319
1320
1321
1322
# File 'app/models/shipment.rb', line 1319

def skip_audit?
  final? || service_redemption_code_sent? || service_fulfilled? || manually_voided? || label_voided? ||
    delivery&.ships_ltl_freight?
end

#sort_dimensionsvoid

This method returns an undefined value.

Sorts carton dimensions longest-first.



1237
1238
1239
1240
1241
1242
# File 'app/models/shipment.rb', line 1237

def sort_dimensions
  return unless has_dimensions?
  return unless carton? # do NOT sort if pallet, crate, etc, only cartons use this convention

  self.length, self.width, self.height = [length, width, height].sort.reverse
end

#sort_stringString

Sort key grouping child shipments under their parent.

Returns:

  • (String)


447
448
449
# File 'app/models/shipment.rb', line 447

def sort_string
  [parent_shipment&.reference_number, reference_number].compact.join
end

#speedee_manifest_shipmentSpeedeeManifestShipment

Speedee manifest join record for this shipment.



232
# File 'app/models/shipment.rb', line 232

has_one :speedee_manifest_shipment

#sscc_code?Boolean

Whether the container code is a 20-digit SSCC.

Returns:

  • (Boolean)


1039
1040
1041
# File 'app/models/shipment.rb', line 1039

def sscc_code?
  !amazon_container_code? && container_code.size == 20
end

#standalone_deliveryStandaloneDelivery

Standalone (non-order) delivery backing this shipment.



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

belongs_to :standalone_delivery, optional: true

#surface_sqinFloat?

Surface area of the container in square inches.

Returns:

  • (Float, nil)


1540
1541
1542
1543
1544
# File 'app/models/shipment.rb', line 1540

def surface_sqin
  return unless length && height && width

  2 * ((length * height) + (length * width) + (width * height))
end

#to_packageShipping::Container

Shipping::Container value object for this shipment.

Returns:



1258
1259
1260
# File 'app/models/shipment.rb', line 1258

def to_package
  Shipping::Container.new(length:, width:, height:, weight:, container_type:, flat_rate_package_type:)
end

#to_packdimsObject

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.



1231
1232
1233
# File 'app/models/shipment.rb', line 1231

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_sString

String representation: reference number, carrier, tracking number.

Returns:

  • (String)


841
842
843
844
845
846
# File 'app/models/shipment.rb', line 841

def to_s
  s = [reference_number]
  s << carrier
  s << tracking_number
  s.compact.join(' | ')
end

Carrier tracking URL for this shipment, resolving marketplace and LTL
carriers to their real carrier.

Returns:

  • (String, nil)


489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'app/models/shipment.rb', line 489

def tracking_link
  # ShipEngine LTL freight is tracked at the delivery level by its PRO
  # (delivery.ltl_pro_number), which arrives asynchronously and is NOT stored
  # on the per-pallet shipment's tracking_number. Route the link through the
  # delivery PRO so every pallet resolves to the carrier's LTL tracking page.
  return self.class.tracking_link(carrier, delivery.ltl_pro_number) if shipengine_ltl?

  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

#uploadsActiveRecord::Relation<Upload>

File uploads (labels, documents) for this shipment.

Returns:

  • (ActiveRecord::Relation<Upload>)

See Also:



237
# File 'app/models/shipment.rb', line 237

has_many :uploads, as: :resource, dependent: :destroy

#voided?Boolean

Whether the shipment is voided.

Returns:

  • (Boolean)


1332
1333
1334
# File 'app/models/shipment.rb', line 1332

def voided?
  label_voided? || manually_voided?
end

#volumeFloat?

Volume in cubic inches.

Returns:

  • (Float, nil)


602
603
604
605
606
# File 'app/models/shipment.rb', line 602

def volume
  res = nil
  res = length * width * height if length.present? && width.present? && height.present?
  res
end

#volume_in_cubic_feetFloat?

Volume in cubic feet.

Returns:

  • (Float, nil)


610
611
612
613
614
# File 'app/models/shipment.rb', line 610

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) ⇒ Float, ...

Weight converted to another unit.

Parameters:

  • unit (String) (defaults to: 'lbs')

    target unit

  • precision (Integer, nil) (defaults to: nil)

    decimal places (ceil-rounded)

  • display_units (Boolean) (defaults to: false)

    append the unit label

Returns:

  • (Float, String, nil)


1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
# File 'app/models/shipment.rb', line 1609

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) ⇒ Float?

Width converted to another unit.

Parameters:

  • unit (String) (defaults to: 'in')

    target unit

  • precision (Integer) (defaults to: 0)

    decimal places (ceil-rounded)

Returns:

  • (Float, nil)


1588
1589
1590
1591
1592
# File 'app/models/shipment.rb', line 1588

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