Class: DeliveriesController

Inherits:
CrmController show all
Includes:
Controllers::WarehouseStreamActions, Controllers::Workflowable
Defined in:
app/controllers/deliveries_controller.rb

Overview

Controller: deliveries.

Constant Summary collapse

COMPLETE_PICKING_SUBMIT =

Complete picking submit.

'Save and complete picking'
COMPLETE_PRE_PACKING_SUBMIT =

Complete pre packing submit.

'Save and complete packaging estimate'
GENERATE_LABELS =

Generate labels.

'Generate Labels'
MANUAL_LABELS =

Manual labels.

'Manual Labels'
DELETE_ALL_SHIPMENTS =

Delete all shipments.

'Delete all shipments'
'Print carton labels'

Constants included from Controllers::WarehouseStreamActions

Controllers::WarehouseStreamActions::WAREHOUSE_TAB_CONTENT_FRAME

Constants included from Controllers::ReferenceFindable

Controllers::ReferenceFindable::ID_EMBEDDED_PATTERNS

Constants included from Controllers::AnalyticsEvents

Controllers::AnalyticsEvents::MAX_QUEUED_EVENTS, Controllers::AnalyticsEvents::SESSION_KEY

Constants included from Controllers::ErrorRendering

Controllers::ErrorRendering::NON_CONTENT_PATH_PREFIXES

Constants included from Www::SeoHelper

Www::SeoHelper::AWARDS, Www::SeoHelper::CA_ADDRESS, Www::SeoHelper::CA_BUSINESS_HOURS, Www::SeoHelper::CA_CONTACT_POINT, Www::SeoHelper::CA_CURRENCIES, Www::SeoHelper::CA_DESCRIPTION, Www::SeoHelper::CA_FOUNDING_DATE, Www::SeoHelper::CA_GLOBAL_LOCATION_NUMBER, Www::SeoHelper::CA_LEGAL_NAME, Www::SeoHelper::CA_LOCAL_BUSINESS, Www::SeoHelper::CA_ONLINE_STORE, Www::SeoHelper::CA_RETURN_POLICY, Www::SeoHelper::CA_SALES_DEPARTMENT, Www::SeoHelper::CA_SERVICE_AREA, Www::SeoHelper::CA_URL, Www::SeoHelper::CA_VAT_ID, Www::SeoHelper::CA_WAREHOUSE_DEPARTMENT, Www::SeoHelper::CA_WAREHOUSE_HOURS, Www::SeoHelper::COMPANY_EMAIL, Www::SeoHelper::COMPANY_LOGO, Www::SeoHelper::COMPANY_NAME, Www::SeoHelper::COMPANY_SLOGAN, Www::SeoHelper::EXPERTISE, Www::SeoHelper::FAX_NUMBER, Www::SeoHelper::GS1_COMPANY_PREFIX, Www::SeoHelper::ISO6523_CODE, Www::SeoHelper::PAYMENT_METHODS, Www::SeoHelper::PHONE_NUMBER, Www::SeoHelper::PRIMARY_NAICS, Www::SeoHelper::REFUND_TYPE, Www::SeoHelper::RETURN_FEES, Www::SeoHelper::RETURN_METHOD, Www::SeoHelper::RETURN_POLICY_CATEGORY, Www::SeoHelper::SECONDARY_NAICS, Www::SeoHelper::SOCIAL_PROFILES, Www::SeoHelper::US_ADDRESS, Www::SeoHelper::US_BUSINESS_HOURS, Www::SeoHelper::US_CONTACT_POINT, Www::SeoHelper::US_CURRENCIES, Www::SeoHelper::US_DESCRIPTION, Www::SeoHelper::US_FOUNDING_DATE, Www::SeoHelper::US_GLOBAL_LOCATION_NUMBER, Www::SeoHelper::US_IMAGE, Www::SeoHelper::US_LEGAL_NAME, Www::SeoHelper::US_LOCAL_BUSINESS, Www::SeoHelper::US_ONLINE_STORE, Www::SeoHelper::US_RETURN_POLICY, Www::SeoHelper::US_SALES_DEPARTMENT, Www::SeoHelper::US_SERVICE_AREA, Www::SeoHelper::US_TAX_ID, Www::SeoHelper::US_URL, Www::SeoHelper::US_WAREHOUSE_DEPARTMENT, Www::SeoHelper::US_WAREHOUSE_HOURS

Constants included from IconHelper

IconHelper::CUSTOM_ICON_MAP, IconHelper::CUSTOM_SVG_DIR, IconHelper::DEFAULT_FAMILY

Instance Method Summary collapse

Methods included from Controllers::WarehouseStreamActions

#redirect_to

Methods included from FileDownloadPresenter

#file_download_entry

Methods included from Controllers::Workflowable

#render_workflow_error_stream, #render_workflow_success_stream, #workflow_action, #workflow_action_complete

Methods inherited from CrmController

#access_denied, #context_id, #context_object, #crm_home_path, #current_ability, #default_url_options, #download_temp, #get_tempfile_path_for_download, #init_status_job_collector, #initialize_crm_lazy_chunks, #persist_enqueued_status_jobs, #record_not_found, #redirect_to_job_or_fallback, #render_edit_action, #set_context, #set_download_path, #stash_file_for_temp_download, #sync_admin_presence_cookie

Methods inherited from ApplicationController

#account_impersonated?, #add_to_flash, #after_sign_in_path_for, #bypass_forgery_protection?, #chat_enabled?, #cloudflare_cleared?, #default_catalog, #default_url_options, #enable_turbo_frames, #find_publication, #fix_invalid_accept_header, #init_js_utils, #is_globals_call?, #layout_by_resource, #locale_store, #redirect_to, #require_employee_for_crm, #set_base_host, #set_real_ip, #set_report_errors_for, #should_render_layout?, #stamp_impersonation_context, #warmlyyours_canada_ip?, #warmlyyours_ip?, #y

Methods included from Controllers::ReturnPathHandling

#check_for_return_path, #redirect_to_return_path_or_default

Methods included from Controllers::AnalyticsEvents

#consume_queued_analytics_events, #track_event

Methods included from Controllers::DeviceDetection

#device_detector, #is_ie?

Methods included from Controllers::SubdomainDetection

#is_crm_request?, #is_www_request?, #json_request?

Methods included from Controllers::TurboSafeRedirect

#redirect_to

Methods included from Controllers::TrackingDetection

#bot_request?, #gdpr_country?, #gdpr_country_data, #prevent_bots, #set_tracking_cookie, #track_visitor?

Methods included from Controllers::AcceleratedFileSending

#send_file_accelerated, #send_upload_accelerated

Methods included from Controllers::ErrorRendering

#excp_string, #mail_to_for_error_reporting, #render_400, #render_404, #render_406, #render_410, #render_500, #render_invalid_authenticity_token, #render_ip_spoof_error, #render_unpermitted_parameters, #safe_referer_or_fallback

Methods included from Controllers::TurnstileVerification

#load_turnstile_script_tag, #turnstile_lazy_widget, #turnstile_script_tag, #turnstile_widget, #validate_turnstile!

Methods included from Controllers::CloudflareCaching

edge_cached, #edge_cached_action?, #reset_cloudflare_cache, #set_cloudflare_cache, #skip_edge_cache!, #skip_session

Methods included from Controllers::Webpackable

#preload_webpack_fonts, #webpack_css_include, #webpack_css_url, #webpack_js_include, #wpd_is_running?

Methods included from Controllers::Localizable

#cloudflare_country_locale, #determine_request_locale, #geocoder_locale, #guest_user_locale_check, #locale_optional_www_auth_path?, #param_locale, #set_locale, #set_request_locale, #skip_localization?, #warmlyyours_ip_locale

Methods included from Controllers::Authenticable

#access_denied, #authenticate_account, #authenticate_account!, #authenticate_account_from_login_token!, #check_is_a_manager, #check_is_a_sales_manager, #check_is_an_admin, #check_is_an_employee, #check_party, #clear_mismatched_guest_user, #create_guest_user, #credentials?, #current_or_guest_user, #current_or_guest_user_id_read_only, #current_user, #devise_mapping, #fully_logged_in?, #generate_bot_id, #guest_user, #identifiable?, #init_current_user, #initialize_guest, #load_context_user, #logging_in, #resource, #resource_name, #restrict_access_for_non_employees, #scrubbed_request_path, #user_object, #warn_on_session_guest_id_leak

Methods included from ApplicationHelper

#better_number_to_currency, #check_force_logout, #check_or_cross, #check_or_times, #embedded_tab_frame_id, #error_messages, #general_disclaimer_on_product_installation_and_local_codes, #gridjs_from_html_table, #gridjs_table, #is_wy_ip, #line_break, #parent_layout, #pass_or_fail, #render_error_messages_list, #render_video_card, #resolved_auth_form_turbo_frame, #return_path_or, #safe_css_color, #set_return_path_if_present, #set_section_if_present, #tab_frame_id, #to_underscore, #track_page?, #turbo_section_wrapper, #turbo_tabs_request?, #url_on_same_domain_as_request, #widget_index_daily_focus_index_path, #working_hours?, #yes_or_no, #yes_or_no_highlighted, #yes_or_no_with_check_or_cross, #youtube_video

Methods included from UppyUploaderHelper

#file_uploader, #image_uploader, #large_file_uploader_s3, #lead_sketch_uploader, #rma_image_uploader, #rma_image_uploader_s3, #uppy_uploader, #video_uploader

Methods included from Www::ImagesHelper

#image_asset_tag, #image_asset_url

Methods included from Www::SeoHelper

#add_page_schema, #add_webpage_schema, #canada?, #company_social_links, #ensure_context_json, #json_ld_script_tag, #local_business_schema, #online_store_id, #online_store_schema, #page_main_entity, #page_main_entity_json, #render_auto_collection_page_schema, #render_collection_page_schema, #render_local_business_schema, #render_online_store_schema, #render_page_schemas, #render_page_video_schemas, #render_webpage_schema, #render_webpage_schema_with_collections, #usa?

Methods included from UrlsHelper

#catalog_breadcrumb_links, #catalog_link, #catalog_link_for_product_line, #catalog_link_for_sku, #cms_link, #delocalized_path, #path_to_sales_product_sku, #path_to_sales_product_sku_for_product_line, #path_to_sales_product_sku_for_product_line_slug, #product_line_from_catalog_link, #protocol_neutral_url, #sanitize_external_url, #valid_external_url?

Methods included from IconHelper

#account_nav_icon, #fa_icon, #star_rating_html

Instance Method Details

#bolObject



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
# File 'app/controllers/deliveries_controller.rb', line 822

def bol
  @delivery = Delivery.find(params[:id])

  respond_to do |format|
    format.html do
      render layout: 'pdf/bol', locals: {
        delivery: @delivery
      }
    end
    format.pdf do
      result = Shipping::BolGenerator.new.process(@delivery)
      send_data result.pdf,
                filename: result.file_name,
                type: 'application/pdf',
                disposition: 'inline'
    end
  end
end

#cancel_cod_checkObject



392
393
394
395
396
397
398
# File 'app/controllers/deliveries_controller.rb', line 392

def cancel_cod_check
  @ship_quotable.cod_collection_type = nil
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true), flash: { error: err_msg }
end

#cancel_cod_no_checkObject



481
482
483
484
485
486
487
# File 'app/controllers/deliveries_controller.rb', line 481

def cancel_cod_no_check
  @ship_quotable.cod_collection_type = nil
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true), flash: { error: err_msg }
end

#cancel_ltl_freightObject



326
327
328
329
330
331
332
333
334
335
# File 'app/controllers/deliveries_controller.rb', line 326

def cancel_ltl_freight
  @delivery.ltl_freight = false
  res = @delivery.retrieve_shipping_costs
  @ship_quotable.do_not_detect_shipping = true
  @delivery.save
  @ship_quotable.save
  err_msg = nil
  err_msg = res[:message] unless res[:code] == :ok
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true), flash: { error: err_msg }
end

#cancel_ltl_freight_guaranteedObject



372
373
374
375
376
377
378
379
380
381
382
# File 'app/controllers/deliveries_controller.rb', line 372

def cancel_ltl_freight_guaranteed
  @delivery.ltl_freight = true
  @delivery.ltl_freight_guaranteed = false
  res = @delivery.retrieve_shipping_costs
  @ship_quotable.do_not_detect_shipping = true
  @delivery.save
  @ship_quotable.save
  err_msg = nil
  err_msg = res[:message] unless res[:code] == :ok
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true), flash: { error: err_msg }
end

#cancel_ltl_freight_prepackObject



349
350
351
352
353
354
355
356
357
358
# File 'app/controllers/deliveries_controller.rb', line 349

def cancel_ltl_freight_prepack
  @delivery.ltl_freight = false
  res = @delivery.retrieve_shipping_costs
  @ship_quotable.do_not_detect_shipping = true
  @delivery.save
  @ship_quotable.save
  err_msg = nil
  err_msg = res[:message] unless res[:code] == :ok
  redirect_to picked_delivery_path(@delivery, return_path: @return_path), flash: { error: err_msg }
end

#cancel_pickupObject



648
649
650
651
# File 'app/controllers/deliveries_controller.rb', line 648

def cancel_pickup
  @delivery.cancel_pickup
  redirect_to_return_path_or_default delivery_path(@delivery)
end

#cancel_saturday_deliveryObject



290
291
292
293
294
295
296
# File 'app/controllers/deliveries_controller.rb', line 290

def cancel_saturday_delivery
  @ship_quotable.saturday_delivery = false
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true), flash: { error: err_msg }
end

#cancel_signature_confirmationObject



306
307
308
309
310
311
312
# File 'app/controllers/deliveries_controller.rb', line 306

def cancel_signature_confirmation
  @ship_quotable.signature_confirmation = false
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true), flash: { error: err_msg }
end

#check_if_ships_freight_and_address_freight_readyObject



489
490
491
492
493
494
# File 'app/controllers/deliveries_controller.rb', line 489

def check_if_ships_freight_and_address_freight_ready
  return unless @ship_quotable.ships_freight_but_address_not_freight_ready? || (@ship_quotable.is_override? && @ship_quotable.should_ship_freight_but_address_not_freight_ready?)

  redirect_to edit_address_path(@ship_quotable.shipping_address, ships_freight: 'true', return_path: polymorphic_path(@ship_quotable, action: :shipping)),
              flash: { error: "Please complete selecting freight related fields on the shipping address, so we can calculate freight on this #{@ship_quotable.class.to_s.downcase}." }
end

#choose_ships_economy_carrierObject



901
# File 'app/controllers/deliveries_controller.rb', line 901

def choose_ships_economy_carrier; end

#ciObject



841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'app/controllers/deliveries_controller.rb', line 841

def ci
  @delivery = Delivery.find(params[:id])

  respond_to do |format|
    format.html do
      render layout: 'pdf/ci', locals: {
        delivery: @delivery
      }
    end
    format.pdf do
      pdf_data = Pdf::Document::CommercialInvoice.new(@delivery).call.pdf
      send_data pdf_data,
                filename: "#{@delivery.reference_number}_CI.pdf",
                type: 'application/pdf',
                disposition: 'inline'
    end
  end
end

#ci_legacyObject



860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
# File 'app/controllers/deliveries_controller.rb', line 860

def ci_legacy
  @delivery = Delivery.find(params[:id])

  respond_to do |format|
    format.html do
      render layout: 'pdf/ci', locals: {
        delivery: @delivery
      }
    end
    format.pdf do
      pdf_data = Pdf::Document::CommercialInvoice.new(@delivery).call.pdf
      usmca_cert_uploads = Upload.where(category: 'usmca_certificate').joins(items: :line_items).merge(@delivery.line_items)
      if usmca_cert_uploads.present?
        combined = PdfCombinator.new
        combined << pdf_data
        usmca_cert_uploads.each do |upload|
          combined << upload.attachment.data if upload.attachment&.data.present?
        rescue StandardError
          nil
        end
        pdf_data = combined.to_pdf
      end
      send_data pdf_data,
                filename: "#{@delivery.reference_number}_CI.pdf",
                type: 'application/pdf',
                disposition: 'inline'
    end
  end
end

#cod_checkObject



384
385
386
387
388
389
390
# File 'app/controllers/deliveries_controller.rb', line 384

def cod_check
  @ship_quotable.cod_collection_type = 'check'
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true, shipping_update_type: 'cod_check'), flash: { error: err_msg }
end

#cod_no_checkObject



473
474
475
476
477
478
479
# File 'app/controllers/deliveries_controller.rb', line 473

def cod_no_check
  @ship_quotable.cod_collection_type = 'no_check'
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true, shipping_update_type: 'cod_no_check'), flash: { error: err_msg }
end

#complete_asynch_print_bolObject



753
754
755
756
757
758
759
# File 'app/controllers/deliveries_controller.rb', line 753

def complete_asynch_print_bol
  print_uploads = []
  @delivery.generate_asynch_labels
  print_uploads << @delivery.all_labels_pdf unless @order.is_rma_return?
  handle_print_uploads([], print_uploads.compact)
  redirect_to_return_path_or_default warehouse_path(@order.store, tab: 'pending_ship_labels')
end

#complete_palletizationObject



45
46
47
48
49
50
51
52
# File 'app/controllers/deliveries_controller.rb', line 45

def complete_palletization
  if @delivery.update(params[:delivery] || {}) & @delivery.pallet_weight_matching
    complete_picked_action
  else
    flash.now[:error] = @delivery.errors_to_s.presence || 'Pallet weights do not match shipment weights.'
    render :palletization, status: :unprocessable_content
  end
end

#complete_pickedObject



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'app/controllers/deliveries_controller.rb', line 54

def complete_picked
  if params[:commit] == DELETE_ALL_SHIPMENTS
    @delivery.shipments.destroy_all
    flash[:info] = 'All shipments were deleted'
    render_picked_action
  elsif @delivery.update(params[:delivery] || {})
    if @delivery.shipments.pallets.present? && (@delivery.shipments.cartons.present? || @delivery.shipments.crates.present?)
      redirect_to palletization_delivery_path(@delivery)
    else
      complete_picked_action
    end
  else
    render_picked_action
  end
end

#complete_ship_labelObject



655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
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
728
729
730
731
732
733
734
# File 'app/controllers/deliveries_controller.rb', line 655

def complete_ship_label
  # `has_many :shipments` declares an order(:created_at), which find_each
  # silently dropped on Rails 7 and warns about on Rails 8 (it paginates by
  # id internally). The iteration here doesn't care about ordering — make
  # that explicit with reorder(nil) to suppress the warning.
  @delivery.shipments.where(state: %w[packed]).reorder(nil).find_each(&:ready_for_label)
  @shipments = @delivery.shipments.awaiting_label

  print_uploads = []
  if params[:commit] == GENERATE_LABELS
    # Push the delivery carrier down
    @shipments.each { |s| s.update(carrier: @delivery.carrier, is_manual: false) }

    result = @delivery.generate_labels
    if result[:status_code] != :ok
      @delivery.errors.add(:base, result[:status_message] || 'Unable to print ship labels, please contact a member of the IT team for assistance')
      render :ship_label, status: :unprocessable_content
    elsif result[:status_code] == :ok
      if @delivery.carrier == 'Freightquote' && @delivery.pending_carrier_confirm?
        job_id = GetFreightquoteLoadNumber.perform_async({ delivery_id: @delivery.id,
                                                           current_user_id: @context_user.id }.deep_stringify_keys)
        if job_id
          redirect_to job_path(job_id)
        else
          @delivery.errors.add(:base, result[:status_message] || 'Unable to schedule FreightQuote load number monitor, please contact a member of the IT team for assistance')
          render :ship_label, status: :unprocessable_content
        end
      else
        label_pdf = @delivery.all_labels_pdf
        print_uploads << label_pdf if label_pdf && !@order.is_rma_return?
        handle_print_uploads(@shipments, print_uploads)
        set_pickup_confirmation_flash(@delivery)
        if @delivery.requires_manual_pickup?
          contact = @delivery.manual_pickup_contact
          flash[:error] = "<strong>Manual Pickup Required</strong> &mdash; " \
                          "<strong>#{ERB::Util.html_escape(contact[:name])}</strong> " \
                          "(#{ERB::Util.html_escape(contact[:location])}) does not support automated pickup. " \
                          "Warehouse staff <strong>MUST</strong> arrange pickup: " \
                          "<a href=\"tel:#{ERB::Util.html_escape(contact[:phone].gsub(/[^\d+]/, ''))}\">#{ERB::Util.html_escape(contact[:phone])}</a>" \
                          " | <a href=\"mailto:#{ERB::Util.html_escape(contact[:email])}\">#{ERB::Util.html_escape(contact[:email])}</a>" \
                          " | <a href=\"#{ERB::Util.html_escape(contact[:url])}\" target=\"_blank\" rel=\"noopener\"><strong>Schedule Quick Pickup</strong></a>"
          Mailer.manual_pickup_required_email(@delivery).deliver_later
        end
        redirect_to_return_path_or_default warehouse_path(@order.store, tab: 'pending_ship_labels')
      end
    end
  elsif params[:commit] == MANUAL_LABELS && params[:delivery].present?
    override_carrier = params[:delivery].delete(:override_carrier)
    @delivery.attributes = params[:delivery]
    @delivery.shipments.select(&:awaiting_label?).each do |shp|
      shp.carrier = override_carrier if (shp.carrier.blank? || shp.carrier.to_s.downcase.include?('override')) && override_carrier.present?
      shp.tracking_number ||= @delivery.master_tracking_number
      shp.is_manual = true
    end
    if @delivery.save && @delivery.shipments.awaiting_label.all?(&:manually_complete)
      @delivery.reload.ship_labeled!
      @shipments = @delivery.shipments.manually_complete
      handle_print_uploads(@shipments, print_uploads)
      redirect_to_return_path_or_default delivery_path(@delivery, tab: 'shipping')
    else
      @delivery.errors.add(:base, 'Cannot complete manual shipment.  A carrier and tracking number, PRO number, or BOL number must be specified')
      render :ship_label, status: :unprocessable_content
    end
  elsif params[:commit] == PRINT_CARTON_LABELS
    flash[:info] = 'Carton Labels sent to printer'
    # The "Print carton labels" submit means the user explicitly wants carton
    # (SSCC) labels. The `print[:container_label]` checkbox in handle_print_uploads
    # is only rendered when the store has a current_shipping_label_print_profile
    # (see ship_label.html.erb), so for users without one the button silently did
    # nothing. Force the flag here -- the click itself is the intent.
    handle_print_uploads(@shipments, generate_carton_labels: true)
    redirect_to_return_path_or_default ship_label_delivery_path(@delivery)
  elsif @delivery.update(params[:delivery])
    flash[:info] = "Delivery #{view_context.link_to(@delivery.reference_number, delivery_path(@delivery))} saved"
    redirect_to_return_path_or_default warehouse_path(@order.store, tab: 'pending_ship_labels')
  else
    flash.now[:error] = @delivery.errors_to_s.presence || 'Could not save delivery.'
    render :ship_label, status: :unprocessable_content
  end
end

#createObject

POST /deliveries
POST /deliveries.xml



579
580
581
582
583
584
585
586
587
588
589
590
591
# File 'app/controllers/deliveries_controller.rb', line 579

def create
  @delivery = Delivery.new(params[:delivery])

  respond_to do |format|
    if @delivery.save
      format.html { redirect_to(@delivery, notice: 'Delivery was successfully created.') }
      format.xml  { render xml: @delivery, status: :created, location: @delivery }
    else
      format.html { render action: 'new', status: :unprocessable_content }
      format.xml  { render xml: @delivery.errors, status: :unprocessable_content }
    end
  end
end

#editObject

GET /deliveries/1/edit



546
547
548
# File 'app/controllers/deliveries_controller.rb', line 546

def edit
  @delivery = Delivery.find(params[:id])
end

#edit_release_dateObject



550
# File 'app/controllers/deliveries_controller.rb', line 550

def edit_release_date; end

#edit_shipment_contentsObject



818
819
820
# File 'app/controllers/deliveries_controller.rb', line 818

def edit_shipment_contents
  @delivery = Delivery.find(params[:id])
end

#edit_trackingObject



70
# File 'app/controllers/deliveries_controller.rb', line 70

def edit_tracking; end

#export_shipments_contents_to_csvObject



913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
# File 'app/controllers/deliveries_controller.rb', line 913

def export_shipments_contents_to_csv
  csv_string = CSV.generate do |csv|
    # header row
    csv << ['Container Code', 'Weight', 'Dimensions', 'Contents']

    # data rows
    @delivery.shipments.each do |s|
      csv << [s.container_code.to_s, "#{s.weight.ceil} lbs", s.dimensions_text(display_units: true), s.shipment_contents.map { |sc| "#{sc.quantity} x #{sc.line_item.sku}" }.join(', ')]
    end
  end

  # send it to the browsah
  send_data csv_string,
            type: 'text/csv; charset=iso-8859-1; header=present',
            disposition: "attachment; filename=#{@delivery.name}.csv"
end

#finish_void_shipmentsObject



763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'app/controllers/deliveries_controller.rb', line 763

def finish_void_shipments
  note = params.dig(:note, :content).presence || 'none given'
  Delivery.transaction do
    @delivery.quick_note("VOIDing shipments, reason: #{note}")
    result = @delivery.void_shipments
    if result[:status_code] == :error
      flash.now[:error] = "#{view_context.link_to @delivery.name, delivery_path(@delivery)} #{result[:status_message]}"
      render :void_shipments, status: :unprocessable_content
    else
      flash[:info] = "#{view_context.link_to @delivery.name, delivery_path(@delivery)} #{result[:status_message]}"
      # Move delivery back tp pending ship label
      @delivery.cancel_shipments! if @delivery.can_cancel_shipments?
      redirect_to_return_path_or_default warehouse_path(@order.store)
    end
  end
end

#holdObject Also known as: cancel_picking



628
629
630
631
632
633
634
635
636
637
638
639
# File 'app/controllers/deliveries_controller.rb', line 628

def hold
  @order.cr_hold if @order.can_cr_hold?(current_user)
  unless @order.in_cr_hold?
    # here we use select form to pass current_user to each delivery's cancelable? method
    flash[:error] = "Delivery/order could not be held: some deliveries in the order are not cancelable: #{@order.deliveries.active.reject { |d| d.cancelable?(current_user) }.map { |d| "#{d.name(true)}: #{d.state}" }.inspect}"
  end
  if @order.in_cr_hold? && (params[:reserve_stock] == '1')
    redirect_to pick_lines_inventory_commits_path(resource_type: 'Order', resource_id: @order.id), notice: 'Order is on hold, please select which items you would like to reserve and click Save'
  else
    redirect_to_return_path_or_default order_path(@order)
  end
end

#indexObject

These are actions for deliveries PAST the quoting stage, ie at_warehouse or beyond



498
499
500
501
502
# File 'app/controllers/deliveries_controller.rb', line 498

def index
  @q = Delivery.ransack(params[:q])
  @q.sorts = 'created_at DESC' if @q.sorts.blank?
  @pagy, @deliveries = pagy(:countish, @q.result)
end

#ltl_freightObject



314
315
316
317
318
319
320
321
322
323
324
# File 'app/controllers/deliveries_controller.rb', line 314

def ltl_freight
  @delivery.ltl_freight = true
  @delivery.ltl_freight_guaranteed = false
  res = @delivery.retrieve_shipping_costs
  @ship_quotable.do_not_detect_shipping = true
  @delivery.save
  @ship_quotable.save
  err_msg = nil
  err_msg = res[:message] unless res[:code] == :ok
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true, shipping_update_type: 'ltl_freight'), flash: { error: err_msg }
end

#ltl_freight_guaranteedObject



360
361
362
363
364
365
366
367
368
369
370
# File 'app/controllers/deliveries_controller.rb', line 360

def ltl_freight_guaranteed
  @delivery.ltl_freight = false
  @delivery.ltl_freight_guaranteed = true
  res = @delivery.retrieve_shipping_costs
  @ship_quotable.do_not_detect_shipping = true
  @delivery.save
  @ship_quotable.save
  err_msg = nil
  err_msg = res[:message] unless res[:code] == :ok
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true, shipping_update_type: 'ltl_freight_guaranteed'), flash: { error: err_msg }
end

#ltl_freight_prepackObject



337
338
339
340
341
342
343
344
345
346
347
# File 'app/controllers/deliveries_controller.rb', line 337

def ltl_freight_prepack
  @delivery.ltl_freight = true
  @delivery.ltl_freight_guaranteed = false
  res = @delivery.retrieve_shipping_costs
  @ship_quotable.do_not_detect_shipping = true
  @delivery.save
  @ship_quotable.save
  err_msg = nil
  err_msg = res[:message] unless res[:code] == :ok
  redirect_to picked_delivery_path(@delivery, return_path: @return_path), flash: { error: err_msg }
end

#multiple_originObject



167
168
169
170
171
# File 'app/controllers/deliveries_controller.rb', line 167

def multiple_origin
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.update(ltl_freight: false, ltl_freight_guaranteed: false, single_origin: false)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true)
end

#newObject

GET /deliveries/new
GET /deliveries/new.xml



536
537
538
539
540
541
542
543
# File 'app/controllers/deliveries_controller.rb', line 536

def new
  @delivery = Delivery.new

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render xml: @delivery }
  end
end

#palletizationObject



41
42
43
# File 'app/controllers/deliveries_controller.rb', line 41

def palletization
  flash[:info] = 'Pallets and other containers detected, please confirm assignment. Pallets can contain items but also other non-pallet containers.'
end

#pending_confirmObject



788
789
790
791
# File 'app/controllers/deliveries_controller.rb', line 788

def pending_confirm
  @delivery.pending_confirm! if @delivery.shipped?
  redirect_to_return_path_or_default delivery_path(@delivery)
end

#pick_slipObject



518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# File 'app/controllers/deliveries_controller.rb', line 518

def pick_slip
  @delivery = Delivery.find(params[:id])
  split_kits = params[:split_kits].to_b

  respond_to do |format|
    format.pdf do
      pdf_generator = Pdf::Document::PackingSlip.new(@delivery, { split_kits: split_kits, skip_plans: false })
      pdf_data = pdf_generator.call
      send_data pdf_data,
                filename: @delivery.pick_slip_file_name,
                type: 'application/pdf',
                disposition: 'inline'
    end
  end
end

#pickedObject



30
31
32
33
34
35
36
37
38
39
# File 'app/controllers/deliveries_controller.rb', line 30

def picked
  if @delivery.locked_for_fba?
    complete_picked_action(true) # just go to pending_ship_label and skip picking since we must be packed already
  else
    @delivery.repick if @delivery.can_repick?
    zero_out_shipment_weight = false
    zero_out_shipment_weight = true if @delivery&.order&.awaiting_deliveries? # here we want to force warehouse to enter *measured* weight when ship labeling, though not pre-packing
    render_picked_action(zero_out_shipment_weight)
  end
end

GET /customers/1/orders/1/print_pick_slip



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'app/controllers/deliveries_controller.rb', line 610

def print_pick_slip
  @delivery.picking
  split_kits = params[:split_kits].to_b
  pdf = @delivery.generate_pick_slip_pdf(split_kits)
  if (print_profile = PrintProfile.where(id: params[:print_profile_id]).first)
    jid = print_profile.print_upload(pdf)
    flash[:info] = "Print Job #{jid} submitted to #{print_profile.name} [#{print_profile.id}]"
  else
    session[:download_path] = upload_url(pdf.id)
    session[:download_disposition] = :inline
  end
  if @delivery.should_print_heating_element_labels?
    redirect_to generate_barcodes_path(delivery_id: @delivery.id, heating_elements_only: true, return_path: @return_path)
  else
    redirect_to_return_path_or_default delivery_path(@delivery, tab: 'shipping')
  end
end


802
803
804
805
# File 'app/controllers/deliveries_controller.rb', line 802

def print_serial_numbers
  pdf = @delivery.generate_serial_numbers_pdf
  redirect_to upload_path(pdf)
end

#purchase_marketplace_labelObject

Eager purchase of marketplace labels (Walmart, Amazon, etc.) before warehouse picks the order
This allows reporting tracking to marketplaces earlier



402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'app/controllers/deliveries_controller.rb', line 402

def purchase_marketplace_label
  # Check if this delivery supports marketplace label purchasing
  purchaser_class = Edi::MarketplaceLabelPurchaser.for_delivery(@delivery)

  unless purchaser_class
    flash[:error] = 'This delivery does not support marketplace label purchasing'
    redirect_to polymorphic_path(@ship_quotable, action: :shipping) and return
  end

  marketplace_name = Edi::MarketplaceLabelPurchaser.marketplace_name(@order)

  unless Edi::MarketplaceLabelPurchaser.marketplace_carrier?(@delivery.carrier)
    flash[:error] = "Please select a #{marketplace_name} shipping method first"
    redirect_to polymorphic_path(@ship_quotable, action: :shipping) and return
  end

  # Create shipments if they don't exist
  if @delivery.shipments.empty?
    Shipping::CreateSuggestedShipment.new.process(@delivery)
    @delivery.reload
  end

  # Get shipments that don't already have labels
  shipments_to_label = @delivery.shipments.reject { |s| s.tracking_number.present? }

  if shipments_to_label.empty?
    flash[:info] = 'All shipments already have labels'
    redirect_to polymorphic_path(@ship_quotable, action: :shipping) and return
  end

  # Get the rate data from selected shipping cost
  selected_shipping_cost = @delivery.selected_shipping_cost
  if selected_shipping_cost&.rate_data.blank?
    flash[:error] = "No #{marketplace_name} rate selected"
    redirect_to polymorphic_path(@ship_quotable, action: :shipping) and return
  end

  # Build marketplace-agnostic rate hash from rate_data
  rate_data = selected_shipping_cost.rate_data.with_indifferent_access
  rate = build_marketplace_rate(rate_data)

  success_count = 0
  error_messages = []

  shipments_to_label.each do |shipment|
    purchaser = purchaser_class.new(shipment)
    result = purchaser.purchase_label(rate)

    if result.success
      success_count += 1
      shipment.label_generated! if shipment.can_label_generated?
    else
      error_messages << "Shipment #{shipment.id}: #{result.error}"
    end
  rescue StandardError => e
    error_messages << "Shipment #{shipment.id}: #{e.message}"
    ErrorReporting.error(e, shipment_id: shipment.id, delivery_id: @delivery.id)
  end

  if success_count > 0
    flash[:info] = "Purchased #{success_count} #{marketplace_name} label(s) successfully"
    # Update delivery with tracking info from first shipment
    first_labeled = @delivery.shipments.find { |s| s.tracking_number.present? }
    @delivery.update(master_tracking_number: first_labeled.tracking_number) if first_labeled
  end

  flash[:error] = error_messages.join('; ') if error_messages.any?

  redirect_to polymorphic_path(@ship_quotable, action: :shipping)
end

#recalculate_shippingObject



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'app/controllers/deliveries_controller.rb', line 93

def recalculate_shipping
  # Save deadline dates if provided in params (only for non-marketplace orders)
  # IMPORTANT: Do not overwrite dates for marketplace/EDI orders - these are retailer-provided
  is_marketplace_order = @ship_quotable.try(:edi_orchestrator_partner).present?
  unless is_marketplace_order
    if params[:requested_ship_before].present? || params[:requested_deliver_by].present?
      @ship_quotable.requested_ship_before = params[:requested_ship_before] if params[:requested_ship_before].present?
      @ship_quotable.requested_deliver_by = params[:requested_deliver_by] if params[:requested_deliver_by].present?
      @ship_quotable.save
    end
  end

  # Ensure delivery is in quoting state before retrieving costs
  if @delivery.state != 'quoting'
    Rails.logger.warn("[RecalculateShipping] Delivery #{@delivery.id} is in state '#{@delivery.state}', transitioning to 'quoting'")
    @delivery.back_to_quoting! if @delivery.can_back_to_quoting?
  end

  # Parse rate_ship_date if provided (user can override the ship date for rate calculation)
  rate_ship_date = nil
  if params[:rate_ship_date].present?
    rate_ship_date = begin
      Date.parse(params[:rate_ship_date])
    rescue StandardError
      nil
    end
    # Ensure it's not in the past
    rate_ship_date = nil if rate_ship_date && rate_ship_date < Date.current
  end

  result = @delivery.retrieve_shipping_costs(rate_ship_date: rate_ship_date)
  Rails.logger.info("[RecalculateShipping] Delivery #{@delivery.id} retrieve_shipping_costs result: #{result.inspect}")

  @ship_quotable.do_not_detect_shipping = true
  @ship_quotable.last_shipping_rate_request_result = @ship_quotable.deliveries.where(state: 'quoting').map(&:last_shipping_rate_request_result)
  @ship_quotable.save
  # puts "recalculate_shipping test end time: #{Time.current}"
  # puts "recalculate_shipping test processing time = #{Time.current - start}"
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true)
end

#recalculate_shipping_allObject



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'app/controllers/deliveries_controller.rb', line 134

def recalculate_shipping_all
  # Save deadline dates if provided in params (only for non-marketplace orders)
  # IMPORTANT: Do not overwrite dates for marketplace/EDI orders - these are retailer-provided
  if @ship_quotable.try(:edi_orchestrator_partner).blank?
    if params[:requested_ship_before].present? || params[:requested_deliver_by].present?
      @ship_quotable.requested_ship_before = params[:requested_ship_before] if params[:requested_ship_before].present?
      @ship_quotable.requested_deliver_by = params[:requested_deliver_by] if params[:requested_deliver_by].present?
      @ship_quotable.save
    end
  end

  # Parse rate_ship_date if provided (user can override the ship date for rate calculation)
  rate_ship_date = nil
  if params[:rate_ship_date].present?
    rate_ship_date = begin
      Date.parse(params[:rate_ship_date])
    rescue StandardError
      nil
    end
    # Ensure it's not in the past
    rate_ship_date = nil if rate_ship_date && rate_ship_date < Date.current
  end

  @ship_quotable.retrieve_shipping_costs(rate_ship_date: rate_ship_date)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true)
end

#releaseObject



642
643
644
645
646
# File 'app/controllers/deliveries_controller.rb', line 642

def release
  @delivery.override_future_release_date = '1'
  @delivery.release!
  redirect_to_return_path_or_default delivery_path(@delivery)
end

#request_estimated_packagingObject



890
891
892
893
894
895
896
897
898
899
# File 'app/controllers/deliveries_controller.rb', line 890

def request_estimated_packaging
  @delivery.prepack_requester = current_user
  if @delivery.update(params[:delivery] || {}) && (@delivery.quote || @delivery).request_estimated_packaging # quote needs to go to pre_pack, order has separate flows for pre_pack to carrier assignment etc and we only set the order delivery to be in pre_pack
    flash[:info] = "Status updated to #{@delivery.human_state_name}"
    redirect_to_return_path_or_default delivery_path(@delivery)
  else
    flash[:error] = @delivery.errors_to_s
    redirect_to_return_path_or_default delivery_path(@delivery)
  end
end

#retry_asynch_carrier_confirmObject



736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'app/controllers/deliveries_controller.rb', line 736

def retry_asynch_carrier_confirm
  @return_path = delivery_path(@delivery)
  if @delivery.carrier == 'Freightquote' && @delivery.pending_carrier_confirm?
    job_id = GetFreightquoteLoadNumber.perform_async({ delivery_id: @delivery.id,
                                                       current_user_id: @context_user.id }.deep_stringify_keys)
    if job_id
      redirect_to job_path(job_id)
    else
      @delivery.errors.add(:base, 'Unable to retry asynchronous carrier confirm, please contact a member of the IT team for assistance')
      redirect_to_return_path_or_default delivery_path(@delivery)
    end
  else
    flash[:info] = "Delivery #{view_context.link_to(@delivery.reference_number, delivery_path(@delivery))} does not need asynchronous carrier confirmation"
    redirect_to_return_path_or_default delivery_path(@delivery)
  end
end

#saturday_deliveryObject



282
283
284
285
286
287
288
# File 'app/controllers/deliveries_controller.rb', line 282

def saturday_delivery
  @ship_quotable.saturday_delivery = true
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true, shipping_update_type: 'saturday_delivery'), flash: { error: err_msg }
end

#selected_shipping_account_number_id_from_paramsString?

Extract the submitted shipping_account_number_id for the shipping_cost
row identified by params[:shipping_cost_id] out of the nested
deliveries/shipping_costs attributes.

Returns:

  • (String, nil)

    "" when de-selected, the id when selected, nil when absent



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'app/controllers/deliveries_controller.rb', line 195

def 
  return nil unless @ship_quotable

  root = params[@ship_quotable.model_name.param_key]
  return nil unless root.respond_to?(:to_unsafe_h)

  deliveries = root.to_unsafe_h[:deliveries_attributes]
  return nil unless deliveries.respond_to?(:each_value)

  target = params[:shipping_cost_id].to_s
  deliveries.each_value do |delivery_attrs|
    scs = delivery_attrs.is_a?(Hash) ? delivery_attrs[:shipping_costs_attributes] : nil
    next unless scs.respond_to?(:each_value)

    scs.each_value do |sc_attrs|
      next unless sc_attrs.is_a?(Hash)
      return sc_attrs[:shipping_account_number_id].to_s if sc_attrs[:id].to_s == target
    end
  end
  nil
end

#serial_numbersObject



807
808
809
810
811
812
# File 'app/controllers/deliveries_controller.rb', line 807

def serial_numbers
  @delivery = Delivery.find(params[:id])
  serial_numbers = @delivery.serial_numbers_to_print
  result = Pdf::Label::SerialNumber.call(serial_numbers)
  send_data result.pdf, filename: 'serial_numbers.pdf', type: 'application/pdf', disposition: 'inline'
end

#ship_labelObject



653
# File 'app/controllers/deliveries_controller.rb', line 653

def ship_label; end

#shippedObject



780
781
782
783
784
785
786
# File 'app/controllers/deliveries_controller.rb', line 780

def shipped
  flash[:error] = 'Delivery could not be marked shipped: perhaps no PRO/tracking numbers?' unless @delivery.shipped
  redirect_to_return_path_or_default delivery_path(@delivery)
rescue RuntimeError => e
  flash[:error] = e.message
  redirect_to_return_path_or_default delivery_path(@delivery)
end

#showObject

GET /deliveries/1
GET /deliveries/1.xml



506
507
508
509
510
511
512
513
514
515
516
# File 'app/controllers/deliveries_controller.rb', line 506

def show
  @delivery = Delivery.includes(line_items: [:item]).find(params[:id])
  if @delivery.nil?
    redirect_to(@delivery.resource, notice: 'Delivery was cancelled, please see order or quote.')
  else
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render xml: @delivery }
    end
  end
end

#show_shipment_contentObject



814
815
816
# File 'app/controllers/deliveries_controller.rb', line 814

def show_shipment_content
  @delivery = Delivery.find(params[:id])
end

#signature_confirmationObject



298
299
300
301
302
303
304
# File 'app/controllers/deliveries_controller.rb', line 298

def signature_confirmation
  @ship_quotable.signature_confirmation = true
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.save!
  err_msg = MessagingLog.last_shipping_rate_message_error(@delivery.messaging_logs)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true, shipping_update_type: 'signature_confirmation'), flash: { error: err_msg }
end

#single_originObject



161
162
163
164
165
# File 'app/controllers/deliveries_controller.rb', line 161

def single_origin
  @ship_quotable.need_to_recalculate_shipping
  @ship_quotable.update(ltl_freight: false, ltl_freight_guaranteed: false, single_origin: true)
  redirect_to polymorphic_path(@ship_quotable, action: :shipping, shipping_updated: true)
end

#switch_ships_economy_carrierObject



903
904
905
906
907
908
909
910
911
# File 'app/controllers/deliveries_controller.rb', line 903

def switch_ships_economy_carrier
  if @delivery.update(params[:delivery] || {})
    @delivery.apply_shipping_match_for_economy_shipping
    redirect_to ship_label_delivery_path(@delivery)
  else
    flash.now[:error] = @delivery.errors_to_s.presence || 'Could not switch shipping economy carrier.'
    render :choose_ships_economy_carrier, status: :unprocessable_content
  end
end

#tab_account_ledgerObject



975
976
977
978
979
980
981
# File 'app/controllers/deliveries_controller.rb', line 975

def 
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_freight_eventsObject



991
992
993
994
995
996
997
# File 'app/controllers/deliveries_controller.rb', line 991

def tab_freight_events
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_invoicesObject



959
960
961
962
963
964
965
# File 'app/controllers/deliveries_controller.rb', line 959

def tab_invoices
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_item_ledgerObject



967
968
969
970
971
972
973
# File 'app/controllers/deliveries_controller.rb', line 967

def tab_item_ledger
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_line_itemsObject



951
952
953
954
955
956
957
# File 'app/controllers/deliveries_controller.rb', line 951

def tab_line_items
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_mainObject

Tab actions for turbo-tabs lazy loading.
Streamed pattern (PR #903) — every tab serves both formats so in-pane
interactions can target tab_frame_id via turbo_stream.update without
falling through to the empty-shell handler in turbo_stream_actions.js.



934
935
936
937
938
939
940
941
# File 'app/controllers/deliveries_controller.rb', line 934

def tab_main
  authorize!(:read, @delivery)
  @delivery_presenter = DeliveryPresenter.new(@delivery, view_context)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_shippingObject



943
944
945
946
947
948
949
# File 'app/controllers/deliveries_controller.rb', line 943

def tab_shipping
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_shipping_api_logObject



983
984
985
986
987
988
989
# File 'app/controllers/deliveries_controller.rb', line 983

def tab_shipping_api_log
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_tracking_eventsObject



999
1000
1001
1002
1003
1004
1005
# File 'app/controllers/deliveries_controller.rb', line 999

def tab_tracking_events
  authorize!(:read, @delivery)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#trigger_invoicedObject



793
794
795
796
797
798
799
800
# File 'app/controllers/deliveries_controller.rb', line 793

def trigger_invoiced
  # Advisory locking is handled by CreateInvoiceFromDelivery service
  @delivery.trigger_invoiced! if @delivery.shipped?
rescue StandardError => e
  flash[:error] = "Could not create invoice: #{e.message}"
ensure
  redirect_to_return_path_or_default delivery_path(@delivery)
end

#updateObject

PUT /deliveries/1
PUT /deliveries/1.xml



595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'app/controllers/deliveries_controller.rb', line 595

def update
  @delivery = Delivery.find(params[:id])

  respond_to do |format|
    if @delivery.update(params[:delivery])
      format.html { redirect_to(@delivery, notice: 'Delivery was successfully updated.') }
      format.xml  { head :ok }
    else
      format.html { render action: 'edit', status: :unprocessable_content }
      format.xml  { render xml: @delivery.errors, status: :unprocessable_content }
    end
  end
end

#update_release_dateObject

TODO



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'app/controllers/deliveries_controller.rb', line 553

def update_release_date
  @delivery.future_release_date = params[:delivery][:future_release_date]
  @delivery.manual_release_only = params[:delivery][:manual_release_only]
  @delivery.do_not_reserve_stock = params[:delivery][:do_not_reserve_stock]
  if @delivery.save
    unless (@order.future_release_date == @delivery.future_release_date) && (@order.manual_release_only == @delivery.manual_release_only) && (@order.do_not_reserve_stock == @delivery.do_not_reserve_stock)
      @order.update(
        future_release_date: @delivery.future_release_date,
        manual_release_only: @delivery.manual_release_only,
        do_not_reserve_stock: @delivery.do_not_reserve_stock
      )
    end
    @delivery.schedule_for_future_release! if @delivery.can_schedule_for_future_release?
    if @delivery.do_not_reserve_stock? && @delivery.order.has_committed_line_items?
      @delivery.uncommit_catalog_items
    elsif !@delivery.do_not_reserve_stock? && !@delivery.order.has_committed_line_items?
      @delivery.commit_catalog_items
    end
    redirect_to_return_path_or_default delivery_path(@delivery)
  else
    render action: 'edit_release_date', status: :unprocessable_content
  end
end

#update_shipping_costObject



173
174
175
# File 'app/controllers/deliveries_controller.rb', line 173

def update_shipping_cost
  update_shipping_cost_data
end

#update_shipping_cost_account_numberObject



177
178
179
180
181
182
183
184
185
186
187
188
# File 'app/controllers/deliveries_controller.rb', line 177

def 
  # The SAN <select> is a NESTED field
  # (<itemizable>[deliveries_attributes][i][shipping_costs_attributes][j][shipping_account_number_id]).
  # The observe-field Stimulus controller submits the WHOLE form, so the
  # changed value never arrives as top-level `params[:shipping_account_number_id]`
  # — it's nested under the row that fired the change. Pull it out by
  # matching the shipping_cost id. Returns "" for the blank
  # "<store> <carrier> account" de-select option, the id when one is
  # selected, or nil if the row isn't in the payload (leave SAN untouched).
  san_id = 
  update_shipping_cost_data(!san_id.nil?, san_id)
end

#update_shipping_cost_data(force_shipping_account_number = false, shipping_account_number_id = nil) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'app/controllers/deliveries_controller.rb', line 217

def update_shipping_cost_data( = false,  = nil)
  @updated = false
  @shipping_cost = @delivery.shipping_costs.find { |sc| sc.id == params[:shipping_cost_id].to_i }
  if @shipping_cost
    if WyShipping::AMAZON_BUY_SHIPPING_ADMIN_ONLY && @shipping_cost.is_amzbs? && !&.is_admin?
      flash.now[:error] = 'Only administrators can select Amazon Buy Shipping rates.'
      return true
    end

    # Apply the account-number selection from the rate screen. The
    # selector's blank option ("<store> <carrier> account") DE-selects the
    # SAN — back to prepaid on our account — so we must assign even when
    # blank (→ nil), not only when present; otherwise de-selecting left the
    # SAN attached and the shipping line stuck at $0 (calculated_cost
    # zeroes on an attached SAN). Assign the ASSOCIATION (not the bare _id)
    # so the in-memory object — and the re-rendered cost cell — reflect the
    # change without a stale association cache. Saving fires
    # ShippingCost#set_line_items_price, which re-prices any shipping line
    # owned by THIS cost from the now-current calculated_cost.
    if 
      san = .presence && ShippingAccountNumber.find_by(id: )
      @shipping_cost. = san || nil
      @shipping_cost.save

      # Changing the account on a NON-selected option must only update that
      # option's quoted-cost display — it must NOT switch the order's chosen
      # shipping method. update_from_shipping_cost SELECTS whatever cost it's
      # given, so only run it when this cost is already the selected one.
      # (set_line_items_price above is a no-op for a non-selected cost — it
      # owns no shipping line items — so the order line/total are untouched.)
      unless @shipping_cost.id == @delivery.selected_shipping_cost_id
        @updated = true
        @shipping_cost.reload
        return true
      end

      # Account changed on the SELECTED option: keep it selected, but
      # re-price its order line + recompute totals below.
      @delivery.update_column(:shipping_account_number_id, san&.id)
    end

    # Use the service to handle the complete shipping update flow
    # This captures the old method BEFORE making changes, then handles consequences AFTER
    result = Shipping::UpdateShippingMethod.new.update_from_shipping_cost(@delivery, @shipping_cost, @ship_quotable)

    if result.success?
      @updated = true
      # Render the streamed cell + totals from freshly persisted state. The
      # service only reloads the itemizable when the SELECTED option id
      # changes; changing the SAN on the already-selected option still
      # re-prices the shipping line, so reload here regardless.
      @shipping_cost.reload
      @ship_quotable&.reload
      result.messages.each do |msg|
        flash.now[:info] = msg
      end
    else
      flash.now[:error] = result.errors
    end
  else
    flash.now[:error] = "Could not update shipping cost. Shipping cost #{params[:shipping_cost_id]} not found."
  end
  true
end

#update_trackingObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'app/controllers/deliveries_controller.rb', line 72

def update_tracking
  if (tn = params.dig(:master_tracking, :tracking_number)).present?
    @delivery.shipments.completed.each do |s|
      s.update_attribute!(:tracking_number, tn)
    end
    flash[:info] = "Delivery #{delivery_link} tracking updated for all completed shipments"
    redirect_to_return_path_or_default delivery_path(@delivery)
  elsif @delivery.update(params[:delivery] || {})
    sending_commercial_invoice = false
    if @delivery.ships_ltl_freight? && @delivery.ltl_pro_number_changed? && @delivery.invoiced?
      # This is the scenario where the LTL PRO number was provided by the LTL truck driver and populated by warehouse staff after the load pickup, so now send_commercial_invoice_to_carrier (if it should be done) now that we have the PRO and the delivery's after_transition to invoiced did not send it.
      @delivery.send_commercial_invoice_to_carrier if @delivery.should_send_commercial_invoice_to_carrier?
      sending_commercial_invoice = true if @delivery.should_send_commercial_invoice_to_carrier?
    end
    flash[:info] = "Delivery #{delivery_link} tracking updated#{', attempting to send commercial invoice to carrier!' if sending_commercial_invoice}"
    redirect_to_return_path_or_default delivery_path(@delivery)
  else
    render :edit_tracking, status: :unprocessable_content
  end
end

#void_shipmentsObject



761
# File 'app/controllers/deliveries_controller.rb', line 761

def void_shipments; end