Class: DeliveriesController

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

Constant Summary collapse

COMPLETE_PICKING_SUBMIT =
'Save and complete picking'
COMPLETE_PRE_PACKING_SUBMIT =
'Save and complete packaging estimate'
GENERATE_LABELS =
'Generate Labels'
MANUAL_LABELS =
'Manual Labels'
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, #initialize_crm_lazy_chunks, #record_not_found, #redirect_to_job_or_fallback, #render_edit_action, #set_context, #set_download_path, #stash_file_for_temp_download

Methods inherited from ApplicationController

#account_impersonated?, #add_to_flash, #append_token, #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::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, #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_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!, #authenticate_account_from_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, #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, #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



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

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



319
320
321
322
323
324
325
# File 'app/controllers/deliveries_controller.rb', line 319

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



408
409
410
411
412
413
414
# File 'app/controllers/deliveries_controller.rb', line 408

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



253
254
255
256
257
258
259
260
261
262
# File 'app/controllers/deliveries_controller.rb', line 253

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



299
300
301
302
303
304
305
306
307
308
309
# File 'app/controllers/deliveries_controller.rb', line 299

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



276
277
278
279
280
281
282
283
284
285
# File 'app/controllers/deliveries_controller.rb', line 276

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



575
576
577
578
# File 'app/controllers/deliveries_controller.rb', line 575

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

#cancel_saturday_deliveryObject



217
218
219
220
221
222
223
# File 'app/controllers/deliveries_controller.rb', line 217

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



233
234
235
236
237
238
239
# File 'app/controllers/deliveries_controller.rb', line 233

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



416
417
418
419
420
421
# File 'app/controllers/deliveries_controller.rb', line 416

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



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

def choose_ships_economy_carrier; end

#ciObject



752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# File 'app/controllers/deliveries_controller.rb', line 752

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



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
# File 'app/controllers/deliveries_controller.rb', line 771

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



311
312
313
314
315
316
317
# File 'app/controllers/deliveries_controller.rb', line 311

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



400
401
402
403
404
405
406
# File 'app/controllers/deliveries_controller.rb', line 400

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



664
665
666
667
668
669
670
# File 'app/controllers/deliveries_controller.rb', line 664

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



38
39
40
41
42
43
44
45
# File 'app/controllers/deliveries_controller.rb', line 38

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_entity
  end
end

#complete_pickedObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/controllers/deliveries_controller.rb', line 47

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



582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'app/controllers/deliveries_controller.rb', line 582

def complete_ship_label
  @delivery.shipments.where(state: %w[packed]).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_entity
    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_entity
        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)
        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_entity
    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_entity
  end
end

#createObject

POST /deliveries
POST /deliveries.xml



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

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_entity }
      format.xml  { render xml: @delivery.errors, status: :unprocessable_entity }
    end
  end
end

#editObject

GET /deliveries/1/edit



473
474
475
# File 'app/controllers/deliveries_controller.rb', line 473

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

#edit_release_dateObject



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

def edit_release_date; end

#edit_shipment_contentsObject



729
730
731
# File 'app/controllers/deliveries_controller.rb', line 729

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

#edit_trackingObject



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

def edit_tracking; end

#export_shipments_contents_to_csvObject



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

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}", "#{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



674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# File 'app/controllers/deliveries_controller.rb', line 674

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_entity
    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



555
556
557
558
559
560
561
562
563
564
565
566
# File 'app/controllers/deliveries_controller.rb', line 555

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



425
426
427
428
429
# File 'app/controllers/deliveries_controller.rb', line 425

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



241
242
243
244
245
246
247
248
249
250
251
# File 'app/controllers/deliveries_controller.rb', line 241

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



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

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



264
265
266
267
268
269
270
271
272
273
274
# File 'app/controllers/deliveries_controller.rb', line 264

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



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

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



463
464
465
466
467
468
469
470
# File 'app/controllers/deliveries_controller.rb', line 463

def new
  @delivery = Delivery.new

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

#palletizationObject



34
35
36
# File 'app/controllers/deliveries_controller.rb', line 34

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



699
700
701
702
# File 'app/controllers/deliveries_controller.rb', line 699

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

#pick_slipObject



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'app/controllers/deliveries_controller.rb', line 445

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



23
24
25
26
27
28
29
30
31
32
# File 'app/controllers/deliveries_controller.rb', line 23

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



537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'app/controllers/deliveries_controller.rb', line 537

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


713
714
715
716
# File 'app/controllers/deliveries_controller.rb', line 713

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



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'app/controllers/deliveries_controller.rb', line 329

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
  unless selected_shipping_cost&.rate_data.present?
    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



86
87
88
89
90
91
92
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
# File 'app/controllers/deliveries_controller.rb', line 86

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



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'app/controllers/deliveries_controller.rb', line 127

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
  unless @ship_quotable.try(:edi_orchestrator_partner).present?
    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



569
570
571
572
573
# File 'app/controllers/deliveries_controller.rb', line 569

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

#request_estimated_packagingObject



801
802
803
804
805
806
807
808
809
810
# File 'app/controllers/deliveries_controller.rb', line 801

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



647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
# File 'app/controllers/deliveries_controller.rb', line 647

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



209
210
211
212
213
214
215
# File 'app/controllers/deliveries_controller.rb', line 209

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

#serial_numbersObject



718
719
720
721
722
723
# File 'app/controllers/deliveries_controller.rb', line 718

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



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

def ship_label; end

#shippedObject



691
692
693
694
695
696
697
# File 'app/controllers/deliveries_controller.rb', line 691

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



433
434
435
436
437
438
439
440
441
442
443
# File 'app/controllers/deliveries_controller.rb', line 433

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



725
726
727
# File 'app/controllers/deliveries_controller.rb', line 725

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

#signature_confirmationObject



225
226
227
228
229
230
231
# File 'app/controllers/deliveries_controller.rb', line 225

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



154
155
156
157
158
# File 'app/controllers/deliveries_controller.rb', line 154

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



814
815
816
817
818
819
820
821
822
# File 'app/controllers/deliveries_controller.rb', line 814

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_entity
  end
end

#tab_account_ledgerObject



868
869
870
871
# File 'app/controllers/deliveries_controller.rb', line 868

def 
  authorize!(:read, @delivery)
  render layout: should_render_layout?
end

#tab_invoicesObject



858
859
860
861
# File 'app/controllers/deliveries_controller.rb', line 858

def tab_invoices
  authorize!(:read, @delivery)
  render layout: should_render_layout?
end

#tab_item_ledgerObject



863
864
865
866
# File 'app/controllers/deliveries_controller.rb', line 863

def tab_item_ledger
  authorize!(:read, @delivery)
  render layout: should_render_layout?
end

#tab_line_itemsObject



853
854
855
856
# File 'app/controllers/deliveries_controller.rb', line 853

def tab_line_items
  authorize!(:read, @delivery)
  render layout: should_render_layout?
end

#tab_mainObject

Tab actions for turbo-tabs lazy loading



842
843
844
845
846
# File 'app/controllers/deliveries_controller.rb', line 842

def tab_main
  authorize!(:read, @delivery)
  @delivery_presenter = DeliveryPresenter.new(@delivery, view_context)
  render layout: should_render_layout?
end

#tab_shippingObject



848
849
850
851
# File 'app/controllers/deliveries_controller.rb', line 848

def tab_shipping
  authorize!(:read, @delivery)
  render layout: should_render_layout?
end

#trigger_invoicedObject



704
705
706
707
708
709
710
711
# File 'app/controllers/deliveries_controller.rb', line 704

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



522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'app/controllers/deliveries_controller.rb', line 522

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_entity }
      format.xml  { render xml: @delivery.errors, status: :unprocessable_entity }
    end
  end
end

#update_release_dateObject

TODO



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'app/controllers/deliveries_controller.rb', line 480

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_entity
  end
end

#update_shipping_costObject



166
167
168
# File 'app/controllers/deliveries_controller.rb', line 166

def update_shipping_cost
  update_shipping_cost_data
end

#update_shipping_cost_account_numberObject



170
171
172
173
# File 'app/controllers/deliveries_controller.rb', line 170

def 
  # The updated update_shipping_cost_data handles account numbers via the service
  update_shipping_cost_data(true, params[:shipping_account_number_id])
end

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



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'app/controllers/deliveries_controller.rb', line 175

def update_shipping_cost_data( = false,  = nil)
  @updated = false
  @shipping_cost = @delivery.shipping_costs.detect { |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

    # Handle account number override if needed
    if  && .present?
      @shipping_cost. = 
      @delivery. = 
      @shipping_cost.save
    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
      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



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'app/controllers/deliveries_controller.rb', line 65

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_entity
  end
end

#void_shipmentsObject



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

def void_shipments; end