Class: Shipment
- Inherits:
-
ApplicationRecord
- Object
- ActiveRecord::Base
- ApplicationRecord
- Shipment
- 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 :integer 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 =
%w[awaiting_label label_complete manually_complete].freeze
- PACKED_OR_MEASURED_STATES =
%w[packed awaiting_label label_complete manually_complete].freeze
- TRACKING_STATUS_INCOMPLETE =
%w[not_yet_in_system unknown accepted in_transit exception delivery_attempt].freeze
- 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 =
50.0- MIN_WEIGHT_DELTA_LBS =
3.0- MAX_WEIGHT_DELTA_LBS =
50.0- PALLET_NOMINAL_WEIGHT =
41- CRATE_NOMINAL_WEIGHT =
84- WARNING_WEIGHT =
These thresholds come from Amazon (with some contingency) but are worthwhile across all our shipping, see:
https://go.shipping.amazon.com/n/NzU3LUtQSS00MjgAAAGcTdyhxFO5pv0QxByVWJP_-QoGeuMdXRV7txCh0_giwakJ_UJTZHx2XvzOmjjRSI2Gh4SCs_k=
https://go.shipping.amazon.com/n/NzU3LUtQSS00MjgAAAGcTdyhxHZuGL_tw_8Y4VHGifVkrvJViB3tyeUhibzDwFnJehHZWyCmzdN26qnQGjbeh3JbEBM= 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 =
%w[GLS DPD DHL].freeze
Constants included from Models::Auditable
Models::Auditable::ALWAYS_IGNORED
Instance Attribute Summary collapse
- #actual_total_charges ⇒ Object readonly
-
#assign_sscc ⇒ Object
Returns the value of attribute assign_sscc.
- #carrier ⇒ Object readonly
- #date_shipped ⇒ Object readonly
- #height ⇒ Object readonly
- #length ⇒ Object readonly
-
#manual_container_code ⇒ Object
Returns the value of attribute manual_container_code.
-
#number ⇒ Object
Returns the value of attribute number.
-
#shipments_number ⇒ Object
Returns the value of attribute shipments_number.
- #weight ⇒ Object readonly
- #width ⇒ Object readonly
Belongs to collapse
- #delivery ⇒ Delivery
- #mail_activity ⇒ MailActivity
- #manifest ⇒ Manifest
- #order ⇒ Order
- #parent_shipment ⇒ Shipment
- #standalone_delivery ⇒ StandaloneDelivery
Methods included from Models::Auditable
Has one collapse
Has many collapse
- #child_shipments ⇒ ActiveRecord::Relation<Shipment>
- #line_items ⇒ ActiveRecord::Relation<LineItem>
- #shipment_contents ⇒ ActiveRecord::Relation<ShipmentContent>
- #uploads ⇒ ActiveRecord::Relation<Upload>
Class Method Summary collapse
- .all_carriers_for_select ⇒ Object
-
.awaiting_label ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are awaiting label.
-
.build_gs1_128(serial:, application_identifier: '00', gs1_prefix: GS1_PREFIX) ⇒ Object
Based on An Introduction to the Serial Shipping Container Code (SSCC) https://www.gs1us.org/DesktopModules/Bring2mind/DMX/Download.aspx?Command=Core_Download&EntryId=177 and Check digit calculator https://www.gs1us.org/DesktopModules/Bring2mind/DMX/Download.aspx?Command=Core_Download&EntryId=729&language=en-US&PortalId=0&TabId=134.
-
.carrier_candidates_for_pickup ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are carrier candidates for pickup.
- .carrier_icon(carrier) ⇒ Object
- .carrier_options_for_select(delivery, show_all: false) ⇒ Object
-
.cartons ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are cartons.
-
.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.
-
.completed ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are completed.
- .container_types_for_select ⇒ Object
-
.contentable ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are contentable.
-
.crates ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are crates.
- .custom_carriers_for_select ⇒ Object
-
.fedex_express ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are fedex express.
- .get_next_shipments_serial ⇒ Object
-
.label_complete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are label complete.
-
.label_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are label voided.
-
.line_item_to_content_key(line_item) ⇒ Object
Builds a content key to present a line in our shipment content.
-
.manually_complete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are manually complete.
-
.manually_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are manually voided.
-
.measured ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are measured.
- .next_sscc_for_gs1_128 ⇒ Object
-
.non_pallets ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are non pallets.
-
.non_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are non voided.
- .override_carriers_for_select ⇒ Object
-
.packageable ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packageable.
-
.packed ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packed.
-
.packed_or_awaiting_labels ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packed or awaiting labels.
-
.packed_or_measured ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packed or measured.
-
.palleted_crates ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are palleted crates.
-
.pallets ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are pallets.
- .states_for_select ⇒ Object
-
.suggested ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are suggested.
-
.suggested_packed_or_awaiting_labels ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are suggested packed or awaiting labels.
-
.top_level ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are top level.
- .tracking_link(carrier, tracking_number) ⇒ Object
-
.tracking_status_complete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are tracking status complete.
-
.tracking_status_incomplete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are tracking status incomplete.
-
.voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are voided.
Instance Method Summary collapse
- #amazon_container_code? ⇒ Boolean
- #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
- #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_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
- #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 !.
- #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
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::EventPublishable
Instance Attribute Details
#actual_total_charges ⇒ Object (readonly)
185 |
# File 'app/models/shipment.rb', line 185 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.
146 147 148 |
# File 'app/models/shipment.rb', line 146 def assign_sscc @assign_sscc end |
#carrier ⇒ Object (readonly)
180 |
# File 'app/models/shipment.rb', line 180 validates :carrier, presence: { if: ->(s) { s.label_complete? || s.manually_complete? } } |
#date_shipped ⇒ Object (readonly)
179 |
# File 'app/models/shipment.rb', line 179 validates :date_shipped, presence: { if: :is_legacy } |
#height ⇒ Object (readonly)
182 |
# File 'app/models/shipment.rb', line 182 validates :width, :length, :height, presence: { if: :neither_legacy_nor_service } |
#length ⇒ Object (readonly)
182 |
# File 'app/models/shipment.rb', line 182 validates :width, :length, :height, presence: { if: :neither_legacy_nor_service } |
#manual_container_code ⇒ Object
Returns the value of attribute manual_container_code.
146 147 148 |
# File 'app/models/shipment.rb', line 146 def manual_container_code @manual_container_code end |
#number ⇒ Object
Returns the value of attribute number.
146 147 148 |
# File 'app/models/shipment.rb', line 146 def number @number end |
#shipments_number ⇒ Object
Returns the value of attribute shipments_number.
146 147 148 |
# File 'app/models/shipment.rb', line 146 def shipments_number @shipments_number end |
#weight ⇒ Object (readonly)
181 |
# File 'app/models/shipment.rb', line 181 validates :weight, presence: true |
#width ⇒ Object (readonly)
182 |
# File 'app/models/shipment.rb', line 182 validates :width, :length, :height, presence: { if: :neither_legacy_nor_service } |
Class Method Details
.all_carriers_for_select ⇒ Object
630 631 632 633 634 |
# File 'app/models/shipment.rb', line 630 def self.all_carriers_for_select = SHIPPING_CARRIERS_OPTIONS.values.map { |o| o.map(&:last) }.flatten.uniq.sort += custom_carriers_for_select .compact.uniq end |
.awaiting_label ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are awaiting label. Active Record Scope
191 |
# File 'app/models/shipment.rb', line 191 scope :awaiting_label, -> { where(state: 'awaiting_label') } |
.build_gs1_128(serial:, application_identifier: '00', gs1_prefix: GS1_PREFIX) ⇒ Object
Based on An Introduction to the Serial Shipping Container Code (SSCC) https://www.gs1us.org/DesktopModules/Bring2mind/DMX/Download.aspx?Command=Core_Download&EntryId=177
and Check digit calculator https://www.gs1us.org/DesktopModules/Bring2mind/DMX/Download.aspx?Command=Core_Download&EntryId=729&language=en-US&PortalId=0&TabId=134
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 |
# File 'app/models/shipment.rb', line 996 def self.build_gs1_128(serial:, application_identifier: '00', gs1_prefix: GS1_PREFIX) s = [0] # extension digit s += gs1_prefix.split('') # our gs1 prefix, 7 digits s += serial.to_s.rjust(9, '0').split('') # 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_pickup ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are carrier candidates for pickup. Active Record Scope
219 |
# File 'app/models/shipment.rb', line 219 scope :carrier_candidates_for_pickup, ->(carrier) { top_level.joins(:delivery).label_complete.where('shipments.carrier = :carrier', { carrier: }).where("deliveries.state = 'pending_ship_confirm' or deliveries.state = 'shipped'") } |
.carrier_icon(carrier) ⇒ Object
636 637 638 |
# File 'app/models/shipment.rb', line 636 def self.carrier_icon(carrier) ShipmentCourier.new(carrier).courier_icon_url end |
.carrier_options_for_select(delivery, show_all: false) ⇒ Object
616 617 618 619 620 621 622 623 624 625 626 627 628 |
# File 'app/models/shipment.rb', line 616 def self.(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
211 |
# File 'app/models/shipment.rb', line 211 scope :cartons, -> { where(container_type: 0) } |
.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
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 |
# File 'app/models/shipment.rb', line 656 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 |
.completed ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are completed. Active Record Scope
187 |
# File 'app/models/shipment.rb', line 187 scope :completed, -> { where(state: %w[label_complete manually_complete]) } |
.container_types_for_select ⇒ Object
576 577 578 |
# File 'app/models/shipment.rb', line 576 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
210 |
# File 'app/models/shipment.rb', line 210 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
213 |
# File 'app/models/shipment.rb', line 213 scope :crates, -> { where(container_type: 2) } |
.custom_carriers_for_select ⇒ Object
679 680 681 682 683 684 |
# File 'app/models/shipment.rb', line 679 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).map(&:presence).compact.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
220 |
# File 'app/models/shipment.rb', line 220 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
985 986 987 988 |
# File 'app/models/shipment.rb', line 985 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
197 |
# File 'app/models/shipment.rb', line 197 scope :label_complete, -> { where(state: 'label_complete') } |
.label_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are label voided. Active Record Scope
198 |
# File 'app/models/shipment.rb', line 198 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
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 |
# File 'app/models/shipment.rb', line 774 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_complete ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are manually complete. Active Record Scope
195 |
# File 'app/models/shipment.rb', line 195 scope :manually_complete, -> { where(state: 'manually_complete') } |
.manually_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are manually voided. Active Record Scope
196 |
# File 'app/models/shipment.rb', line 196 scope :manually_voided, -> { where(state: 'manually_voided') } |
.measured ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are measured. Active Record Scope
208 |
# File 'app/models/shipment.rb', line 208 scope :measured, -> { where(state: MEASURED_STATES) } |
.next_sscc_for_gs1_128 ⇒ Object
990 991 992 |
# File 'app/models/shipment.rb', line 990 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
215 |
# File 'app/models/shipment.rb', line 215 scope :non_pallets, -> { where(container_type: [0, 2]) } |
.non_voided ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are non voided. Active Record Scope
209 |
# File 'app/models/shipment.rb', line 209 scope :non_voided, -> { where.not(state: %w[label_voided manually_voided]) } |
.override_carriers_for_select ⇒ Object
675 676 677 |
# File 'app/models/shipment.rb', line 675 def self.override_carriers_for_select [nil, 'Override'] + (ShippingOption.active.pluck('distinct carrier').compact + Shipment.custom_carriers_for_select).uniq.sort end |
.packageable ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packageable. Active Record Scope
207 |
# File 'app/models/shipment.rb', line 207 scope :packageable, -> { where(state: PACKING_STATES) } |
.packed ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are packed. Active Record Scope
190 |
# File 'app/models/shipment.rb', line 190 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
193 |
# File 'app/models/shipment.rb', line 193 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
194 |
# File 'app/models/shipment.rb', line 194 scope :packed_or_measured, -> { where(state: PACKED_OR_MEASURED_STATES) } |
.palleted_crates ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are palleted crates. Active Record Scope
214 |
# File 'app/models/shipment.rb', line 214 scope :palleted_crates, -> { where(container_type: 3) } |
.pallets ⇒ ActiveRecord::Relation<Shipment>
A relation of Shipments that are pallets. Active Record Scope
212 |
# File 'app/models/shipment.rb', line 212 scope :pallets, -> { where(container_type: 1) } |
.states_for_select ⇒ Object
572 573 574 |
# File 'app/models/shipment.rb', line 572 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
189 |
# File 'app/models/shipment.rb', line 189 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
192 |
# File 'app/models/shipment.rb', line 192 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
216 |
# File 'app/models/shipment.rb', line 216 scope :top_level, -> { where(parent_shipment_id: nil) } |
.tracking_link(carrier, tracking_number) ⇒ Object
640 641 642 |
# File 'app/models/shipment.rb', line 640 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
204 205 206 |
# File 'app/models/shipment.rb', line 204 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
199 200 201 202 |
# File 'app/models/shipment.rb', line 199 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
188 |
# File 'app/models/shipment.rb', line 188 scope :voided, -> { where(state: %w[label_voided manually_voided]) } |
Instance Method Details
#amazon_container_code? ⇒ Boolean
730 731 732 |
# File 'app/models/shipment.rb', line 730 def amazon_container_code? container_code&.starts_with?('AMZN') end |
#audit ⇒ Object
916 917 918 919 920 921 922 |
# File 'app/models/shipment.rb', line 916 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_pdf ⇒ Object
564 565 566 |
# File 'app/models/shipment.rb', line 564 def bol_pdf uploads.ship_bol_pdfs.first end |
#bps_barcode(file_path: nil, partner_code: nil) ⇒ Object
717 718 719 720 721 722 723 724 725 726 727 728 |
# File 'app/models/shipment.rb', line 717 def (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() 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
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 |
# File 'app/models/shipment.rb', line 696 def 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
686 687 688 689 690 691 692 693 694 |
# File 'app/models/shipment.rb', line 686 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
374 375 376 |
# File 'app/models/shipment.rb', line 374 def carrier_icon self.class.carrier_icon(sanitized_carrier) end |
#carrier_options_for_select ⇒ Object
608 609 610 611 612 613 614 |
# File 'app/models/shipment.rb', line 608 def = [] = self.class.all_carriers_for_select if delivery # If the current carrier is not in the list add them, could be an override one << carrier unless .compact.detect { |e| e == carrier } .compact.uniq.sort end |
#check_if_oversize ⇒ Object
417 418 419 420 421 |
# File 'app/models/shipment.rb', line 417 def check_if_oversize return false if is_legacy WarehousePackage.check_if_dimensions_oversize([length, width, height], container_type) end |
#child_shipments ⇒ ActiveRecord::Relation<Shipment>
165 |
# File 'app/models/shipment.rb', line 165 has_many :child_shipments, class_name: 'Shipment', foreign_key: 'parent_shipment_id', dependent: :nullify |
#complete? ⇒ Boolean
568 569 570 |
# File 'app/models/shipment.rb', line 568 def complete? manually_complete? || label_complete? end |
#compute_item_declared_value ⇒ Object
1066 1067 1068 1069 1070 |
# File 'app/models/shipment.rb', line 1066 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).map { |sc| sc.line_item.unit_value_for_commercial_invoice * sc.quantity.to_f }.sum end |
#compute_item_weight ⇒ Object
1037 1038 1039 1040 |
# File 'app/models/shipment.rb', line 1037 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 shipment_contents.map { |sc| sc.line_item.item.base_weight.to_f * sc.quantity.to_i }.sum end |
#compute_shipment_declared_value(skip_carrier_guard: false) ⇒ Object
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 |
# File 'app/models/shipment.rb', line 1072 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? { |cs| cs.shipment_contents.joins(:line_item).where.not(line_items: { parent_id: nil }).exists? } 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_weight ⇒ Object
1060 1061 1062 1063 1064 |
# File 'app/models/shipment.rb', line 1060 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
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 |
# File 'app/models/shipment.rb', line 1042 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_type ⇒ Object
738 739 740 741 742 743 744 745 746 747 748 |
# File 'app/models/shipment.rb', line 738 def container_code_type return unless container_code.present? if amazon_container_code? 'Amazon Container Code' elsif sscc_code? 'Serial Shipping Container Code (SSCC)' else 'Container Code' end end |
#deep_dup ⇒ Object
123 124 125 |
# File 'app/models/shipment.rb', line 123 def deep_dup deep_clone(except: %i[container_code tracking_number]) end |
#delivery ⇒ Delivery
Validations:
- Presence ({ if: ->(s) { s.neither_legacy_nor_service && s.mail_activity_id.nil? && s.standalone_delivery.nil? } })
154 |
# File 'app/models/shipment.rb', line 154 belongs_to :delivery, optional: true |
#delivery_or_mail_activity ⇒ Object
312 313 314 |
# File 'app/models/shipment.rb', line 312 def delivery_or_mail_activity delivery || mail_activity end |
#dimensions_changed? ⇒ Boolean
886 887 888 |
# File 'app/models/shipment.rb', line 886 def dimensions_changed? length_changed? || width_changed? || height_changed? || weight_changed? end |
#dimensions_text(display_units: false) ⇒ Object
595 596 597 598 |
# File 'app/models/shipment.rb', line 595 def dimensions_text(display_units: false) dims = [length, width, height].compact.map(&:round) s = dims.map { |sd| display_units ? "#{sd} in" : sd }.join(' x ') end |
#dimensions_text_converted(unit: 'in', precision: 0, display_units: false) ⇒ Object
1163 1164 1165 1166 |
# File 'app/models/shipment.rb', line 1163 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
396 397 398 |
# File 'app/models/shipment.rb', line 396 def editable? suggested? || packed? || (awaiting_label? && delivery&.is_rma_return?) || is_legacy || (is_manual && !part_of_a_locked_delivery?) end |
#effective_nmfc_code ⇒ Object
453 454 455 456 457 458 459 460 461 |
# File 'app/models/shipment.rb', line 453 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.sort_by { |h| h[:voting_weight] }.first || {})[:nmfc_code] || ProductCategoryConstants::FALLBACK_NMFC_CODE end |
#entered_and_computed_weights_are_close? ⇒ Boolean
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 |
# File 'app/models/shipment.rb', line 1115 def entered_and_computed_weights_are_close? if pallet? # be more exacting with pallets 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 # 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
974 975 976 |
# File 'app/models/shipment.rb', line 974 def final? delivery&.invoiced? || order&.invoiced? || mail_activity&.complete? end |
#freight_class ⇒ Object
439 440 441 442 443 444 445 446 447 448 449 450 451 |
# File 'app/models/shipment.rb', line 439 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
386 387 388 389 390 |
# File 'app/models/shipment.rb', line 386 def freight_shipment? dels = [delivery] dels += order.present? ? order.deliveries : [] dels.compact.uniq.any?(&:ships_ltl_freight?) end |
#full_dimension_text(metric: false) ⇒ Object
587 588 589 590 591 592 593 |
# File 'app/models/shipment.rb', line 587 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
851 852 853 854 855 856 857 858 859 860 861 862 863 |
# File 'app/models/shipment.rb', line 851 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
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# File 'app/models/shipment.rb', line 489 def generate_letter_ship_label_pdf(ship_label_tmp_path, carrier) self.carrier = carrier # Check if we need to merge with existing ship_label_pdf for these carriers should_merge_pdfs = carrier.to_s.downcase.match?(/speedeedelivery|canadapost|canpar/) # generate the pdf file_name = get_file_name('letter') ship_label_pdf_path = Upload.temp_location(file_name) so = delivery.rma_for_return ? delivery.rma_for_return.shipping_option : nil 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 we need to merge with existing ship_label_pdf and it exists if should_merge_pdfs && ship_label_pdf&.&.path combined_pdf = PdfCombinator.new # Add the letter format PDF combined_pdf << pdf # Add the existing ship_label_pdf first combined_pdf << PdfCombinator.load(ship_label_pdf..path) # Save the combined PDF combined_pdf.save(ship_label_pdf_path) else # Save the letter PDF alone (original behavior) File.open(ship_label_pdf_path, 'wb') do |file| file.write pdf file.flush file.fsync end 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) ⇒ Object
475 476 477 478 479 480 481 482 483 484 485 486 487 |
# File 'app/models/shipment.rb', line 475 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 = {}) ⇒ 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
545 546 547 548 549 550 551 |
# File 'app/models/shipment.rb', line 545 def generate_speedee_label_pdf( = {}) res = Pdf::Label::Speedee.call(self, ) 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
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 |
# File 'app/models/shipment.rb', line 750 def (file_path = nil) raise 'Container code is invalid' unless container_code.present? # 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 'barby' require 'barby/barcode/code_128' require 'barby/outputter/png_outputter' sscc_string = "#{Barby::Code128::FNC1}#{container_code}" = Barby::Code128.new(sscc_string) png = .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
463 464 465 466 467 468 469 470 471 472 473 |
# File 'app/models/shipment.rb', line 463 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
882 883 884 |
# File 'app/models/shipment.rb', line 882 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
1140 1141 1142 1143 1144 |
# File 'app/models/shipment.rb', line 1140 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
939 940 941 942 943 944 945 946 947 |
# File 'app/models/shipment.rb', line 939 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
409 410 411 |
# File 'app/models/shipment.rb', line 409 def is_rma_return? delivery&.is_rma_return? end |
#is_service? ⇒ Boolean
413 414 415 |
# File 'app/models/shipment.rb', line 413 def is_service? state.in?(%w[service_redemption_code_sent service_fulfilled]) || delivery&.is_service_only? end |
#is_speedee_oversize? ⇒ Boolean
423 424 425 |
# File 'app/models/shipment.rb', line 423 def is_speedee_oversize? (length + (2.0 * (width + height))) >= Shipping::SpeedeeDelivery::HIGH_DIMENSIONAL_LENGTH_THRESHOLD end |
#length_converted(unit: 'in', precision: 0) ⇒ Object
1128 1129 1130 1131 1132 |
# File 'app/models/shipment.rb', line 1128 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>
164 |
# File 'app/models/shipment.rb', line 164 has_many :line_items, through: :shipment_contents |
#locked_for_fba? ⇒ Boolean
1168 1169 1170 |
# File 'app/models/shipment.rb', line 1168 def locked_for_fba? container_code =~ CustomerConstants::AMAZON_FBA_ID_REGEX && (packed? || awaiting_label?) end |
#mail_activity ⇒ MailActivity
156 |
# File 'app/models/shipment.rb', line 156 belongs_to :mail_activity, optional: true |
#manifest ⇒ Manifest
158 |
# File 'app/models/shipment.rb', line 158 belongs_to :manifest, optional: true |
#manual_shipment ⇒ Object
382 383 384 |
# File 'app/models/shipment.rb', line 382 def manual_shipment is_manual end |
#need_to_audit? ⇒ Boolean
966 967 968 |
# File 'app/models/shipment.rb', line 966 def need_to_audit? dimensions_changed? || container_type_changed? || !audited end |
#neither_legacy_nor_service ⇒ Object
378 379 380 |
# File 'app/models/shipment.rb', line 378 def neither_legacy_nor_service !(is_legacy || is_service?) end |
#non_freight_shipment? ⇒ Boolean
392 393 394 |
# File 'app/models/shipment.rb', line 392 def non_freight_shipment? !freight_shipment? end |
#ok_to_delete_with_mail_activity? ⇒ Boolean
600 601 602 |
# File 'app/models/shipment.rb', line 600 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
604 605 606 |
# File 'app/models/shipment.rb', line 604 def ok_to_delete_with_standalone_delivery? suggested? or label_voided? or manually_voided? or packed? end |
#order ⇒ Order
Validations:
- Presence ({ if: ->(s) { s.delivery.present? && !(s.delivery.quoting? || s.delivery.pre_pack? || s.delivery.is_rma_return?) } })
155 |
# File 'app/models/shipment.rb', line 155 belongs_to :order, optional: true |
#packed_or_pre_packed? ⇒ Boolean
924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
# File 'app/models/shipment.rb', line 924 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 |
#parent_shipment ⇒ Shipment
160 |
# File 'app/models/shipment.rb', line 160 belongs_to :parent_shipment, class_name: 'Shipment', optional: true |
#part_of_a_locked_delivery? ⇒ Boolean
400 401 402 403 404 405 406 407 |
# File 'app/models/shipment.rb', line 400 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
370 371 372 |
# File 'app/models/shipment.rb', line 370 def qualifies_for_tracking_api? label_complete? && carrier != 'SpeedeeDelivery' && container_type == 'carton' end |
#ready_to_manually_complete? ⇒ Boolean
978 979 980 981 982 983 |
# File 'app/models/shipment.rb', line 978 def ready_to_manually_complete? tracking_ok = true tracking_ok = false if non_freight_shipment? && parent_shipment_id.nil? && !tracking_number.present? 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
316 317 318 |
# File 'app/models/shipment.rb', line 316 def reference_number container_code.presence || "PD#{id}" end |
#resource_reference_and_shipment_number ⇒ Object Also known as: order_reference_and_shipment_number
324 325 326 327 |
# File 'app/models/shipment.rb', line 324 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_dimensions ⇒ Object
902 903 904 905 906 907 908 909 910 |
# File 'app/models/shipment.rb', line 902 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) ⇒ Object
949 950 951 952 953 954 955 956 957 958 959 960 |
# File 'app/models/shipment.rb', line 949 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
354 355 356 357 358 359 |
# File 'app/models/shipment.rb', line 354 def sanitized_carrier valid_carriers = (SHIPPING_CARRIERS_OPTIONS[(delivery&.country&.iso3 || 'USA').to_sym] || []).map { |a| a.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.detect { |c| carrier.downcase.index(c.downcase).present? } || carrier end |
#set_carrier(carrier_override = nil) ⇒ Object
870 871 872 873 874 875 876 877 878 879 880 |
# File 'app/models/shipment.rb', line 870 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_number ⇒ Object
865 866 867 868 |
# File 'app/models/shipment.rb', line 865 def set_default_number self.number ||= 1 self.order = delivery.order if delivery&.order end |
#set_default_pallet_dimensions ⇒ Object
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 |
# File 'app/models/shipment.rb', line 1023 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_weight ⇒ Object
When warehouse just wants to use the item shipping_weight
1111 1112 1113 |
# File 'app/models/shipment.rb', line 1111 def set_default_shipment_weight self.weight ||= compute_shipment_weight end |
#set_sscc ⇒ Object
1019 1020 1021 |
# File 'app/models/shipment.rb', line 1019 def set_sscc self.container_code ||= self.class.next_sscc_for_gs1_128 end |
#ship_label_pdf(letter_format = false) ⇒ Object
553 554 555 556 557 |
# File 'app/models/shipment.rb', line 553 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
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 |
# File 'app/models/shipment.rb', line 798 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 component_quantity = 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_label ⇒ Object
832 833 834 835 836 837 838 839 840 841 842 843 844 845 |
# File 'app/models/shipment.rb', line 832 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
847 848 849 |
# File 'app/models/shipment.rb', line 847 def shipment_content_quantity shipment_contents.sum(:quantity) end |
#shipment_contents ⇒ ActiveRecord::Relation<ShipmentContent>
163 |
# File 'app/models/shipment.rb', line 163 has_many :shipment_contents, dependent: :destroy |
#shipment_index ⇒ Object
320 321 322 |
# File 'app/models/shipment.rb', line 320 def shipment_index (delivery&.shipment_ids || mail_activity&.shipment_ids || order&.direct_shipment_ids)&.index(id) || 0 end |
#shipment_position ⇒ Object
346 347 348 |
# File 'app/models/shipment.rb', line 346 def shipment_position similar_shipment_ids.index(id) + 1 end |
#shipment_total ⇒ Object
350 351 352 |
# File 'app/models/shipment.rb', line 350 def shipment_total similar_shipment_ids.size end |
#shipment_tracking_number ⇒ Object
Initialize a shipment tracking number object
560 561 562 |
# File 'app/models/shipment.rb', line 560 def shipment_tracking_number ShipmentTrackingNumber.new(tracking_number, courier_code: carrier) end |
#shipping_insurance_link ⇒ Object
1176 1177 1178 |
# File 'app/models/shipment.rb', line 1176 def shipping_insurance_link Shipping::ShippingInsurance.new.get_shipping_insurance_link_for_shipment(self) end |
#shipping_insurance_record_id ⇒ Object
1172 1173 1174 |
# File 'app/models/shipment.rb', line 1172 def shipping_insurance_record_id shipping_insurance_data&.dig('shipping_insurance_record_id') end |
#signature_confirmation? ⇒ Boolean
1180 1181 1182 |
# File 'app/models/shipment.rb', line 1180 def signature_confirmation? delivery&.signature_confirmation&.to_b end |
#similar_shipment_ids ⇒ Object
334 335 336 337 338 339 340 341 342 343 344 |
# File 'app/models/shipment.rb', line 334 def similar_shipment_ids shipment_ids = if carton? delivery_or_mail_activity.shipments.cartons.order(:id).pluck(:id) elsif pallet? delivery_or_mail_activity.shipments.pallets.order(:id).pluck(:id) elsif crate? delivery_or_mail_activity.shipments.crates.order(:id).pluck(:id) elsif palleted_crate? delivery_or_mail_activity.shipments.palleted_crates.order(:id).pluck(:id) end end |
#skip_audit? ⇒ Boolean
962 963 964 |
# File 'app/models/shipment.rb', line 962 def skip_audit? final? || service_redemption_code_sent? || service_fulfilled? || manually_voided? || label_voided? end |
#sort_dimensions ⇒ Object
895 896 897 898 899 900 |
# File 'app/models/shipment.rb', line 895 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_string ⇒ Object
330 331 332 |
# File 'app/models/shipment.rb', line 330 def sort_string [parent_shipment&.reference_number, reference_number].compact.join end |
#speedee_manifest_shipment ⇒ SpeedeeManifestShipment
159 |
# File 'app/models/shipment.rb', line 159 has_one :speedee_manifest_shipment |
#sscc_code? ⇒ Boolean
734 735 736 |
# File 'app/models/shipment.rb', line 734 def sscc_code? !amazon_container_code? && container_code.size == 20 end |
#standalone_delivery ⇒ StandaloneDelivery
157 |
# File 'app/models/shipment.rb', line 157 belongs_to :standalone_delivery, optional: true |
#surface_sqin ⇒ Object
1104 1105 1106 1107 1108 |
# File 'app/models/shipment.rb', line 1104 def surface_sqin return unless length && height && width 2 * ((length * height) + (length * width) + (width * height)) end |
#to_package ⇒ Object
912 913 914 |
# File 'app/models/shipment.rb', line 912 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 !
891 892 893 |
# File 'app/models/shipment.rb', line 891 def to_packdims [length.round(1).to_f, width.round(1).to_f, height.round(1).to_f, weight.round(4).to_f, Shipment.container_types[container_type]] end |
#to_s ⇒ Object
580 581 582 583 584 585 |
# File 'app/models/shipment.rb', line 580 def to_s s = [reference_number] s << carrier s << tracking_number s.compact.join(' | ') end |
#tracking_link ⇒ Object
361 362 363 364 365 366 367 368 |
# File 'app/models/shipment.rb', line 361 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>
162 |
# File 'app/models/shipment.rb', line 162 has_many :uploads, as: :resource, dependent: :destroy |
#voided? ⇒ Boolean
970 971 972 |
# File 'app/models/shipment.rb', line 970 def voided? label_voided? || manually_voided? end |
#volume ⇒ Object
427 428 429 430 431 |
# File 'app/models/shipment.rb', line 427 def volume res = nil res = length * width * height if length.present? && width.present? && height.present? res end |
#volume_in_cubic_feet ⇒ Object
433 434 435 436 437 |
# File 'app/models/shipment.rb', line 433 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
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 |
# File 'app/models/shipment.rb', line 1146 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
1134 1135 1136 1137 1138 |
# File 'app/models/shipment.rb', line 1134 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 |