Class: RmasController

Inherits:
CrmController show all
Includes:
Controllers::Attachable, Controllers::Destroyable, Controllers::RequireTurboFrame, Controllers::Workflowable
Defined in:
app/controllers/rmas_controller.rb

Overview

== Schema Information

Table name: rmas

id :integer not null, primary key
rma_number :string(255)
company_id :integer
original_order_id :integer
customer_id :integer
return_shipping_address_id :integer
customer_reference :string(255)
original_po_number :string(255)
contact_name :string(255)
description :string(255)
creator_id :integer
updater_id :integer
created_at :datetime
updated_at :datetime
payment_method :string(255)
state :string(255)
uploads_count :integer
transmission_state :string(255)
legacy_transmission_email :string(255)
legacy_transmission_fax :string(255)
return_label_required :boolean not null
ship_from_address_id :integer
delivery_id :integer
transmission_email :string(255) default([]), is an Array
transmission_fax :string(255) default([]), is an Array
serial_number_state :string

Constant Summary collapse

TAB_ACTIONS =

Tab fragments never render standalone — non-frame hits redirect to show ?tab=.

%i[tab_main tab_rma_items tab_return_labels tab_attachments].freeze
REPLACEMENT_ORDER_TYPE_CHOICES =

Order types that can be picked when a replacement order is created from
the "choose replacement order type" screen. Kept intentionally narrower
than +Rma.replacement_order_types+ -- CO/SS/ST are configured on the RMA
itself via the Add Items form but cannot be selected here.

%w[SO TO MO].freeze

Constants included from Controllers::Attachable

Controllers::Attachable::PUBLICATIONS_PER_PAGE

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

Instance Method Summary collapse

Methods included from Controllers::Workflowable

#render_workflow_error_stream, #render_workflow_success_stream, #workflow_action, #workflow_action_complete

Methods included from Controllers::Destroyable

#destroy, #perform_destroy

Methods included from Controllers::RequireTurboFrame

require_in_pane_tab_frames, require_turbo_frame

Methods included from Controllers::Attachable

#attach, #publication_modal, #remove_attachment, #search_library

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, #touch_employee_last_seen

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?, #skip_layout_for_turbo_frame?, #stamp_impersonation_context, #tab_frame_breakout_request?, #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, #registration_lead_type, #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 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?

Instance Method Details

#add_itemsvoid

This method returns an undefined value.

Renders the form for adding items to an editable RMA.



172
173
174
175
176
177
178
179
180
181
# File 'app/controllers/rmas_controller.rb', line 172

def add_items
  @rma = Rma.includes(rma_items: [:returned_item, { returned_line_item: { item: :kit_target_item_relations } }]).find(params.expect(:id))
  authorize! :update, @rma
  unless @rma.can_be_edited?
    redirect_to(@rma,
                error: "Cannot add items to RMA in state #{@rma.human_state_name}") && return
  end

  set_vars_for_edit_item
end

#add_multiple_imagesvoid

This method returns an undefined value.

Renders the form for attaching multiple photos directly to the RMA.



650
651
652
653
654
# File 'app/controllers/rmas_controller.rb', line 650

def add_multiple_images
  @rma = Rma.find(params.expect(:id))
  @original_invoice = @rma.original_invoice
  @customer = @original_invoice&.customer
end

#bulk_add_itemsvoid

This method returns an undefined value.

Adds every not-yet-returned line item from the RMA's original invoice as
an RMA item in one submission (GET renders the bulk-add form, POST applies it).



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'app/controllers/rmas_controller.rb', line 262

def bulk_add_items
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  redirect_to(@rma, error: "Cannot add items to RMA in state #{@rma.human_state_name}") && return unless @rma.can_be_edited?

  redirect_to(add_items_rma_path(@rma), error: 'RMA must be linked to an invoice to bulk add items') && return if @rma.original_invoice.blank?

  if request.post?
    # Process the bulk add
    returned_reason = params[:returned_reason]
    restocking_reason = params[:restocking_reason]
    replacement_required = params[:replacement_required] == '1'
    will_not_be_returned = params[:will_not_be_returned] == '1'

    if returned_reason.blank?
      flash.now[:error] = 'Primary Return Reason is required'
      prepare_bulk_add_items_form
      render_bulk_add_items_unprocessable and return
    end

    added_count = 0
    errors = []

    @rma.original_invoice.line_items.non_shipping.parents_only.includes(:item, children: :item).find_each do |line_item|
      # Skip if already returned
      already_returned = @rma.rma_items.active.where(returned_line_item_id: line_item.id).sum(:returned_item_quantity)
      next if already_returned >= line_item.quantity

      remaining_qty = line_item.quantity - already_returned
      next if remaining_qty <= 0

      # Create RMA item
      rma_item = @rma.rma_items.build(
        returned_item_id: line_item.get_item_id,
        returned_line_item_id: line_item.id,
        returned_item_description: line_item.name,
        original_qty: line_item.quantity,
        returned_item_quantity: remaining_qty,
        returned_reason: returned_reason,
        restocking_reason: restocking_reason.presence,
        replacement_required: replacement_required,
        will_not_be_returned: will_not_be_returned,
        returned_item_location: 'AVAILABLE'
      )

      if rma_item.valid?
        added_count += 1
      else
        errors << "#{line_item.sku}: #{rma_item.errors.full_messages.join(', ')}"
      end
    end

    if errors.any?
      flash.now[:error] = "Some items could not be added: #{errors.join('; ')}"
      @rma.reload
      prepare_bulk_add_items_form
      render_bulk_add_items_unprocessable and return
    end

    added_items = @rma.rma_items.select(&:new_record?)

    if @rma.save
      @rma.rma_items.reject(&:child?).select { |ri| ri.returned_item&.is_kit? }.each(&:expand_kit_components!)
      @rma.create_documents
      @rma.publish_event(Events::RmaItemsAdded, data: { rma_id: @rma.id, added_rma_item_ids: added_items.map(&:id) })
      @rma.awaiting_return if @rma.requested?
      flash[:warning] = replacement_order_tracking_email_warning
      if will_not_be_returned
        flash[:info] = "Successfully added #{added_count} items to the RMA."
        redirect_to rma_path(@rma)
      else
        flash[:info] = "Successfully added #{added_count} items to the RMA. Configure return labels next."
        redirect_to edit_return_labels_rma_path(@rma)
      end
    else
      flash.now[:error] = 'Failed to save RMA items'
      @rma.reload
      prepare_bulk_add_items_form
      render_bulk_add_items_unprocessable
    end
  else
    prepare_bulk_add_items_form
  end
end

#calculate_shipping_costsvoid

This method returns an undefined value.

Renders shipping cost/rate options for the RMA's return delivery,
refreshing rates when the shipments or line items have changed since the
last quote.



1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
# File 'app/controllers/rmas_controller.rb', line 1013

def calculate_shipping_costs
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  @return_delivery = @rma.return_delivery

  if @return_delivery
    # Preload associations to avoid N+1 in the view
    @return_delivery.shipments.includes(shipment_contents: { line_item: :item }).load
    @return_delivery.line_items.includes(:item).load

    # Get all available shipping options for the country
    @country_iso = @rma.customer.store.country.iso
    @all_shipping_options = ShippingOption.supported_carrier_options_for_rmas(@country_iso)

    # Decide if we need to refresh rates (TTL or data changed)
    last_rate_at = @return_delivery.shipping_costs.maximum(:updated_at)
    newest_data_at = [
      @return_delivery.shipments.maximum(:updated_at),
      @return_delivery.line_items.maximum(:updated_at)
    ].compact.max

    needs_recalc = @return_delivery.shipping_costs.supported.none? ||
                   last_rate_at.nil? ||
                   (newest_data_at && last_rate_at < newest_data_at) ||
                   last_rate_at < 30.minutes.ago

    @return_delivery.retrieve_shipping_costs if needs_recalc

    costs = @return_delivery.shipping_costs.to_a
    # Mirror each paperless option's quote from its standard sibling (paperless
    # rows share carrier + service_code but get no quote of their own).
    @all_shipping_costs = ShippingOption.with_mirrored_paperless_costs(
      @all_shipping_options.map(&:last), costs.index_by(&:shipping_option_id)
    )

    @shipping_costs = costs

    @suggested_packaging = @return_delivery.suggested_packaging_text
    @estimated_cost = @return_delivery.actual_shipping_cost
  else
    @shipping_costs = []
    @all_shipping_costs = {}
    @all_shipping_options = []
  end
end

#choose_replacement_order_typeObject

GET /rmas/1/choose_replacement_order_type
Rendered after update_items detects items flagged for replacement that
haven't been linked to a replacement order yet. Shows a modal asking the
user to confirm the order type to use for the replacement order.



395
396
397
398
399
400
401
402
403
404
405
406
# File 'app/controllers/rmas_controller.rb', line 395

def choose_replacement_order_type
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  redirect_to(@rma, error: "Cannot create replacement order in state #{@rma.human_state_name}") && return unless @rma.can_be_edited?

  @pending_replacement_items = pending_replacement_rma_items(@rma).includes(:returned_item)
  redirect_to(rma_path(@rma), info: 'No items are pending replacement.') && return if @pending_replacement_items.none?

  @rma.replacement_order_type ||= Rma::DEFAULT_ORDER_REPLACEMENT_TYPE
  @replacement_order_type_choices = replacement_order_type_choices
end

#createObject

POST /rmas



143
144
145
146
147
148
149
150
151
152
153
154
# File 'app/controllers/rmas_controller.rb', line 143

def create
  @rma = Rma.new(params[:rma])
  authorize!(:create, Rma)
  if @rma.save
    redirect_to add_items_rma_path(@rma)
  else
    @original_invoice = @rma.original_invoice
    @customer = @rma.customer
    set_addresses
    render action: 'new', status: :unprocessable_content
  end
end

#create_itemsvoid

This method returns an undefined value.

Saves the items submitted on add_items, validating each returned item
exists in the customer's catalog before saving.



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
# File 'app/controllers/rmas_controller.rb', line 187

def create_items
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma
  @rma.assign_attributes(params[:rma])
  items = @rma.rma_items

  redirect_to(rma_path(@rma)) and return if items.empty?

  customer = @rma.customer
  errors = []

  returned_item_ids = items.filter_map(&:returned_item_id).uniq

  if returned_item_ids.any?
    if customer&.catalog
      existing_item_ids = customer.catalog.catalog_items
                                  .joins(:store_item)
                                  .where(store_items: { item_id: returned_item_ids })
                                  .pluck('store_items.item_id')
      existing_index = existing_item_ids.index_with(true)
      missing_ids = returned_item_ids - existing_index.keys

      if missing_ids.any?
        skus_by_id = Item.where(id: missing_ids).pluck(:id, :sku).to_h
        items.each do |rma_item|
          rid = rma_item.returned_item_id
          next if rid.blank? || existing_index.key?(rid)

          sku = skus_by_id[rid] || rid
          errors << "Can't find matching CatalogItem for sku <b>#{sku}</b><br>"
        end
      end
    else
      # No catalog configured: mark all returned items as missing
      skus_by_id = Item.where(id: returned_item_ids).pluck(:id, :sku).to_h
      items.each do |rma_item|
        rid = rma_item.returned_item_id
        next if rid.blank?

        sku = skus_by_id[rid] || rid
        errors << "Can't find matching CatalogItem for sku <b>#{sku}</b><br>"
      end
    end
  end

  # Captured before the save, while the lines this request adds are still the
  # only new records — the activity note reports them apart from the lines
  # that were already on the RMA.
  added_items = items.select(&:new_record?)

  if errors.any?
    flash[:error] = errors.uniq.join
    redirect_back_or_to(root_path)
  elsif @rma.save
    @rma.rma_items.reject(&:child?).select { |ri| ri.returned_item&.is_kit? }.each(&:expand_kit_components!)
    @rma.create_documents
    @rma.publish_event(Events::RmaItemsAdded, data: { rma_id: @rma.id, added_rma_item_ids: added_items.map(&:id) })
    # Don't transition to awaiting_return yet - wait until labels are configured
    # @rma.awaiting_return if @rma.requested?

    # Redirect to edit return labels instead of return label options
    flash[:info] = 'RMA items saved successfully. Configure return labels next.'
    flash[:warning] = replacement_order_tracking_email_warning
    redirect_to edit_return_labels_rma_path(@rma)
  else
    flash.now[:error] = @rma.errors_to_s.presence || 'Could not add items to RMA.'
    set_vars_for_edit_item
    render :add_items, status: :unprocessable_content
  end
end

#create_replacement_orderObject

PUT /rmas/1/create_replacement_order
Sets the RMA replacement_order_type (if provided by the modal) and creates
the replacement order for any rma_items flagged :replacement_required.



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
# File 'app/controllers/rmas_controller.rb', line 411

def create_replacement_order
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  redirect_to(rma_path(@rma), error: "Cannot create replacement order in state #{@rma.human_state_name}") && return unless @rma.can_be_edited?

  order_type = params.dig(:rma, :replacement_order_type).to_s
  @rma.update(replacement_order_type: order_type) if REPLACEMENT_ORDER_TYPE_CHOICES.include?(order_type)

  redirect_to(rma_path(@rma), info: 'No items are pending replacement.') && return if pending_replacement_rma_items(@rma).none?

  res =
    begin
      @rma.create_replacement_order
    rescue ActiveRecord::RecordInvalid, Rma::ReplacementOrderError => e
      Rails.logger.warn("Rma#create_replacement_order failed for RMA #{@rma.id}: #{e.class}: #{e.message}")
      @rma.errors.add(:base, e.message) unless @rma.errors.any?
      nil
    end

  if @rma.errors.any?
    flash[:error] = @rma.errors_to_s
    redirect_to(rma_path(@rma)) && return
  end

  order = res.respond_to?(:order) ? res.order : nil
  flash[:info] = order ? "Replacement order #{order.reference_number} created." : 'Replacement order created.'
  warning = replacement_order_tracking_email_warning
  flash[:warning] = warning if warning.present?

  redirect_to rma_path(@rma)
end

#create_return_label_optionsvoid

This method returns an undefined value.

Saves the submitted return label options; if labels are required it also
creates the return delivery and requests shipping rates.



982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
# File 'app/controllers/rmas_controller.rb', line 982

def create_return_label_options
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  if @rma.update(return_label_params)
    if @rma.return_label_required?
      # Create return delivery and calculate shipping costs
      @rma.create_return_delivery
      @rma.return_delivery.retrieve_shipping_costs

      flash[:info] = 'Return label options saved. Shipping costs calculated.'
      redirect_to calculate_shipping_costs_rma_path(@rma)
    else
      finalize_rma_without_labels
      flash[:info] = no_label_saved_message
      redirect_to_return_path_or_default rma_path(@rma)
    end
  else
    flash.now[:error] = @rma.errors_to_s.presence || 'Could not save return label options.'
    @customer = @rma.customer
    @original_invoice = @rma.original_invoice
    @shipping_options = ShippingOption.supported_carrier_options_for_rmas(@rma&.customer&.store&.country&.iso)
    render :return_label_options, status: :unprocessable_content
  end
end

#customer_detailvoid

This method returns an undefined value.

Returns a customer's summary, contacts, and addresses as JSON, for the RMA
form's customer picker.



744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'app/controllers/rmas_controller.rb', line 744

def customer_detail
  customer_id = params[:customer_id].presence
  @customer = Customer.find_by(id: customer_id)
  if @customer
    hsh = {
      id: @customer.id,
      reference_number: @customer.reference_number,
      full_name: @customer.full_name,
      primary_sales_rep_id: @customer.primary_sales_rep_id,
      primary_sales_rep_name: @customer.primary_sales_rep&.full_name
    }
    hsh[:contacts] = @customer.contacts.active.map do |cnt|
      {
        id: cnt.id,
        full_name: cnt.full_name
      }
    end
    hsh[:addresses] = @customer.addresses.map do |addr|
      {
        id: addr.id,
        to_s: addr.to_s
      }
    end
  else
    hsh = { not_found: '1' }
  end
  respond_to do |format|
    format.json do
      render json: hsh
    end
  end
end

#discard_pending_replacementsObject

PUT /rmas/1/discard_pending_replacements
Clears the :replacement_required flag on every rma_item that was flagged
for replacement but hasn't been linked to a replacement order yet. Used
when the user backs out of the "choose replacement order type" screen
without creating a replacement order.



449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'app/controllers/rmas_controller.rb', line 449

def discard_pending_replacements
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  redirect_to(rma_path(@rma), error: "Cannot clear pending replacements in state #{@rma.human_state_name}") && return unless @rma.can_be_edited?

  cleared = pending_replacement_rma_items(@rma)
            .update_all(replacement_required: false, updated_at: Time.current)

  flash[:info] = "Cleared 'Replace' from #{helpers.pluralize(cleared, 'item')}. No replacement order was created." if cleared.positive?

  redirect_to rma_path(@rma)
end

#do_add_multiple_imagesvoid

This method returns an undefined value.

Attaches the uploads submitted on add_multiple_images to the RMA,
supporting both the uppy.js upload_ids flow and the legacy upload_ids param.



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
# File 'app/controllers/rmas_controller.rb', line 660

def do_add_multiple_images
  @rma = Rma.find(params.expect(:id))

  # Handle both old and new upload methods
  if params[:rma].present? && params[:rma][:upload_ids].present?
    # New uppy.js method - upload_ids contains Upload IDs from S3/Wasabi
    upload_ids = begin
      JSON.parse(params[:rma][:upload_ids])
    rescue StandardError
      []
    end

    if upload_ids.present?
      # Find the uploads and attach them to the RMA
      uploads = Upload.where(id: upload_ids)

      if uploads.present?
        # Update uploads to be associated with this RMA and clear expiration so they aren't auto-deleted
        uploads.update_all(resource_type: 'Rma', resource_id: @rma.id, category: 'photo', expiration_date: nil)
        redirect_to(@rma, notice: "Successfully attached #{uploads.length} image(s).")
      else
        redirect_to(@rma, alert: 'Failed to find uploaded images. Please try again.')
      end
    else
      redirect_to(@rma, alert: 'No images selected for upload.')
    end
  else
    # Fallback to old method for backward compatibility
    attachments_list = Upload.where(id: params[:upload_ids]) if params[:upload_ids].present?
    type = attachments_list&.map(&:attachment_mime_type)&.map { |i| i.split('/', 2).first } || []

    if attachments_list.present? && type.uniq.size == 1 && type.first == 'image'
      attachments_list.update_all(resource_type: 'Rma', resource_id: @rma.id, category: 'photo', expiration_date: nil)
      redirect_to(@rma, notice: 'Images have been attached successfully.')
    else
      attachments_list&.destroy_all
      redirect_to(@rma, alert: 'Unable to attach images. Only image formats are allowed.')
    end
  end
end

#do_add_rma_item_imagesvoid

This method returns an undefined value.

Attaches the submitted uploads to a single RMA item (photo or
not-returned-photo category).



705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'app/controllers/rmas_controller.rb', line 705

def do_add_rma_item_images
  @rma = Rma.find(params.expect(:id))
  rma_item = @rma.rma_items.find(params.expect(:rma_item_id))
  category = %w[photo not_returned_photo].include?(params[:category]) ? params[:category] : 'photo'

  upload_ids = begin
    JSON.parse(params.dig(:rma_item, :upload_ids).to_s)
  rescue StandardError
    []
  end

  if upload_ids.present?
    uploads = Upload.where(id: upload_ids)
    if uploads.present?
      uploads.update_all(resource_type: 'RmaItem', resource_id: rma_item.id, category: category, expiration_date: nil)
      redirect_to(receive_items_rma_path(@rma), notice: "Successfully attached #{uploads.length} photo(s) to #{rma_item.returned_item&.sku}.")
    else
      redirect_to(receive_items_rma_path(@rma), alert: 'Failed to find uploaded images. Please try again.')
    end
  else
    redirect_to(receive_items_rma_path(@rma), alert: 'No images selected for upload.')
  end
end

#editObject

GET /rmas/1/edit



129
130
131
132
133
134
135
136
137
138
139
140
# File 'app/controllers/rmas_controller.rb', line 129

def edit
  @rma = Rma.find(params.expect(:id))
  authorize!(:update, @rma)
  unless @rma.can_be_edited?
    redirect_to(@rma,
                error: "Cannot edit RMA in state #{@rma.human_state_name}") && return
  end

  @original_invoice = @rma.original_invoice
  @customer = @original_invoice&.customer || @rma.customer
  set_addresses
end

#edit_itemsObject

GET /rmas/1/edit



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

def edit_items
  @rma = Rma.includes(rma_items: [:returned_item, { returned_line_item: { item: :kit_target_item_relations } }]).find(params.expect(:id))
  authorize! :update, @rma

  return if @rma.can_be_edited?

  redirect_to(@rma, error: "Cannot edit items to RMA in state #{@rma.human_state_name}") && return
end

#edit_return_labelsvoid

This method returns an undefined value.

Renders the form for editing return labels on an editable RMA.



361
362
363
364
365
366
367
368
# File 'app/controllers/rmas_controller.rb', line 361

def edit_return_labels
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  return if @rma.can_be_edited?

  redirect_to(@rma, error: "Cannot generate return labels to RMA in state #{@rma.human_state_name}") && return
end

#finish_receive_itemsvoid

This method returns an undefined value.

Saves the item receipt submitted on receive_items, creates any resulting
credit order, and routes to label printing when labels are still needed.



847
848
849
850
851
852
853
854
855
856
857
858
859
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/rmas_controller.rb', line 847

def finish_receive_items
  @rma = Rma.where(state: %w[awaiting_return awaiting_inspection partially_returned]).find(params.expect(:id))
  authorize! :receive_items, @rma
  receive_params = finish_receive_items_params
  # Receiving items must not be blocked by legacy drift in the label setup.
  # This action does not create or regenerate labels.
  @rma.skip_shipping_option_validation = true
  @rma.skip_return_label_validation = true
  @rma.assign_attributes(receive_params)
  rma_item_ids = []
  if receive_params[:rma_items_attributes].present?
    rma_items_params = receive_params[:rma_items_attributes].to_h
    rma_items_params.each { |_, v| rma_item_ids << { rma_item_id: v['id'].to_i, qty_to_receive: v['qty_to_receive'].to_i } if v['state_event'] == 'returned' }
  end
  assigned_rma_items = @rma.rma_items.to_a
  label_rma_item_ids = assigned_rma_items.select { |ri| ri.print_label.to_b }.filter_map(&:id)
  success = false
  Rma.transaction do
    # Save the assigned item instances before the parent: legacy RMA
    # validations reload +rma_items+ and would otherwise discard their
    # in-memory nested changes. The parent save persists tracking and
    # insurance fields in the same transaction.
    success = assigned_rma_items.all?(&:save) && @rma.save
    @rma.create_credit_order(rma_item_ids) if success
    raise ActiveRecord::Rollback unless success
  end
  if success
    @rma.send_rejection_notification_to_customer if @rma.any_rejected_items?
    if label_rma_item_ids.present?
      flash[:info] = "RMA Updated, let's print some labels"
      redirect_to print_labels_rma_items_path(rma_item_ids: label_rma_item_ids)
    else
      flash[:info] = 'RMA Updated'
      redirect_to_return_path_or_default rma_path(@rma)
    end
  else
    item_errors = @rma.rma_items.flat_map { |ri| ri.errors.full_messages }.uniq
    flash.now[:error] = item_errors.presence&.join('; ') || @rma.errors_to_s.presence || 'Could not finish receive items.'
    @returnable_items = @rma.rma_items.returnable.parents_only.includes(:uploads, { children: %i[uploads returned_item] }, returned_item: [])
    render :receive_items, status: :unprocessable_content
  end
end

#generate_return_labelsObject

def generate_return_labels
@rma = Rma.find(params[:id])
if params[:rma][:number_of_return_labels_required].present?
@rma.update(number_of_return_labels_required: params[:rma][:number_of_return_labels_required], shipping_option_id: params[:rma][:shipping_option_id])
@rma.create_return_delivery
end
if @rma.return_label_required?
res = @rma.generate_return_labels # this will move rma to awaiting_return if all correctly generated
if @rma.awaiting_return?
@rma.generate_return_instructions_pdf unless @rma.service_only?
end
if res[:status] == :ok
flash[:info] = "RMA return labels were successfully created."
else
flash[:error] = "Return labels could not be generated!#{res[:errors].join('<br/>')}".html_safe
end
redirect_to(rma_path(@rma, anchor: "return_labels"))
else
flash[:error] = "Return labels not required for this RMA!"
redirect_to(rma_path(@rma))
end
end



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'app/controllers/rmas_controller.rb', line 485

def generate_return_labels
  @rma = Rma.find(params.expect(:id))
  if params[:rma].present? && params[:rma][:number_of_return_labels_required].present?
    if @rma.update(number_of_return_labels_required: params[:rma][:number_of_return_labels_required],
                   shipping_option_id: params[:rma][:shipping_option_id])
      if @rma.canada_post_return?
        finalize_rma_without_labels
        flash[:info] = no_label_saved_message
        redirect_to(rma_path(@rma))
        return
      end

      @rma.create_return_delivery
      if @rma.return_label_required?
        res = @rma.generate_return_labels
        if @rma.awaiting_return?
          @rma.generate_return_instructions_pdf unless @rma.service_only?
        end
        if res[:status] == :ok
          Shipping::ReturnShippingInsurance.new.book_internal_insurance(@rma)
          flash[:info] = 'RMA return labels were successfully created.'
        else
          flash[:error] = "Return labels could not be generated!<br/>#{res[:errors].join('<br/>')}".html_safe
        end
        redirect_to(rma_path(@rma, tab: 'return_labels'))
      else
        flash[:error] = 'Return labels not required for this RMA!'
        redirect_to(rma_path(@rma))
      end
    else
      flash[:error] = @rma.errors.full_messages.join(', ')
      redirect_to edit_return_labels_rma_path(@rma)
    end
  else
    flash[:error] = 'Number of return labels is required!'
    redirect_to edit_return_labels_rma_path(@rma)
  end
end

#indexObject

GET /rmas



53
54
55
# File 'app/controllers/rmas_controller.rb', line 53

def index
  redirect_to new_search_path(type: 'RmaSearch')
end

#newObject

GET /rmas/new



84
85
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
126
# File 'app/controllers/rmas_controller.rb', line 84

def new
  authorize!(:create, Rma)
  @rma = Rma.new(params[:rma])
  @rma.number_of_return_labels_required = nil # start off at null for validation
  # @rma.rma_items.build(:replacement_required => false)
  @original_invoice = Invoice.find(params.expect(:invoice_id)) if params[:invoice_id].present?
  @original_order = @original_invoice.order if @original_invoice.present?
  @original_order ||= Order.find(params.expect(:order_id)) if params[:order_id].present?
  @customer = Customer.find(params.expect(:customer_id)) if params[:customer_id].present?
  @customer ||= @original_order.customer if @original_order.present?
  @customer ||= @original_invoice.customer if @original_invoice.present?

  @rma.replacement_order_type ||= Rma::DEFAULT_ORDER_REPLACEMENT_TYPE
  set_addresses
  if @original_invoice.present?
    @customer = @original_invoice.customer
    @line_items = @original_invoice.line_items.non_shipping.parents_only.includes(:item, children: :item)
    @rma.company_id = @original_invoice.store.present? ? @original_invoice.store.company_id : @original_order.store.company_id
    @rma.customer_id = @original_invoice.customer_id
    @rma.original_order_id = (@original_order.presence&.id)
    @rma.original_invoice_id = @original_invoice.id
    @rma.original_po_number = @original_invoice.po_number
    @rma.return_shipping_address_id = @original_invoice.store.present? ? @original_invoice.store.warehouse_address_id : @original_order.store.warehouse_address_id
    @rma.ship_from_address_id = @original_invoice.shipping_address_id
    @rma.customer_reference = (@original_order.presence&.customer_reference)
    @rma.send_from = @original_invoice.customer.primary_sales_rep
    @rma.contact_name = if @original_order.present?
                          @original_order.contact&.full_name
                        elsif @original_invoice.shipping_address&.person_name.present?
                          @original_invoice.shipping_address.person_name
                        end
    @rma.payment_method = 'Original Payment Method'
    @rma.number_of_return_labels_required = @original_order.present? ? @original_order.shipments.completed.size : nil
  elsif @customer.present?
    @line_items = []
    @rma.company_id = @customer.store.company_id
    @rma.customer_id = @customer.id
    @rma.ship_from_address_id = @customer.shipping_address_id
    @rma.send_from = @customer.primary_sales_rep
    @rma.payment_method = 'Check'
  end
  @rma.set_default_notification_channels
end

#order_detailvoid

This method returns an undefined value.

Returns a returnable order's summary as JSON, for the RMA form's order picker.



780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'app/controllers/rmas_controller.rb', line 780

def order_detail
  @order = Order.returnable_types.find_by(id: params[:order_id])

  respond_to do |format|
    format.json do
      if @order.nil?
        render json: { status: :not_found }
      else
        @response_data = {
          status: :found,
          order_id: @order.id,
          customer_reference: @order.customer_reference,
          original_po_number: @order.po_number,
          contact_id: @order.contact_id,
          contact_full_name: @order.contact&.full_name,
          shipping_address: {
            id: @order.shipping_address_id,
            description: @order.shipping_address&.to_s
          }
        }
        render json: @response_data
      end
    end
  end
end

This method returns an undefined value.

Generates and redirects to a super-label PDF for the RMA's serial numbers.



922
923
924
925
926
# File 'app/controllers/rmas_controller.rb', line 922

def print_serial_number_labels
  @rma = Rma.find(params.expect(:id))
  pdf = SerialNumber.generate_super_label_pdf(@rma.serial_numbers)
  redirect_to upload_path(pdf)
end

#quotes_lookupvoid

This method returns an undefined value.

Returns quote autocomplete results (optionally scoped to a customer) as JSON.



809
810
811
812
813
814
815
816
817
# File 'app/controllers/rmas_controller.rb', line 809

def quotes_lookup
  q = params[:q].presence
  customer_id = params[:customer_id].presence
  quotes = Quote.joins(:opportunity).where(Opportunity[:customer_id].eq(customer_id)) if customer_id.present?
  quotes = quotes.like_lookup(q) if q.present?
  quotes = quotes.order('quotes.reference_number DESC')
  render json: TomSelect.format_json_results(self, quotes, params[:page], params[:per_page], :id,
                                           :selection_name)
end

#reason_codesvoid

This method returns an undefined value.

Returns an item's RMA reason codes as JSON, for the reason-code autocomplete.



931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
# File 'app/controllers/rmas_controller.rb', line 931

def reason_codes
  if params[:item_id].present?
    item = Item.find(params.expect(:item_id))
    results = item.rma_reason_codes.order(:code)
    if (q = params[:q].presence)
      results = results.where(
        'rma_reason_codes.code ILIKE :q OR rma_reason_codes.description ILIKE :q', q: "%#{q}%"
      )
    end
  else
    results = RmaReasonCode.none
  end

  json_data = TomSelect.format_json_results(self, results, 1, 1000) do |r|
    {
      id: r.code,
      code: r.code,
      description: r.description,
      text: r.code_and_description,
      default_location: r.default_location
    }
  end

  render json: json_data
end

#receive_itemsvoid

This method returns an undefined value.

Renders the form for receiving the RMA's returnable items, defaulting
arrival time, restocking reason, and possible serial numbers.



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

def receive_items
  @rma = Rma.where(state: %w[awaiting_return awaiting_inspection partially_returned]).find(params.expect(:id))
  authorize! :receive_items, @rma
  @returnable_items = @rma.rma_items.returnable.parents_only.includes(:uploads, { children: %i[uploads returned_item] }, returned_item: [])
  if @returnable_items.present?
    @returnable_items.each do |i|
      i.arrival_datetime ||= Time.current
      i.restocking_reason = i.returned_reason if i.restocking_reason.nil?
      i.possible_serial_numbers.each do |sn|
        i.serial_numbers << sn unless i.serial_numbers.include?(sn)
      end
      i.qty_to_receive = i.returned_item_quantity
    end
  else
    flash[:error] =
      'No returnable items present, either all items are already received/voided or were marked as will not be returned'
    redirect_to_return_path_or_default rma_path(@rma)
  end
end

#regenerate_return_instructionsObject

PUT /rmas/1/regenerate_return_instructions
Rebuilds the letter-format return labels from the already-purchased carrier
labels and re-renders the return-instructions PDF — no void, no new label
buy. For applying PDF layout fixes to existing RMAs.



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# File 'app/controllers/rmas_controller.rb', line 600

def regenerate_return_instructions
  rma = Rma.find(params.expect(:id)) # RecordNotFound follows the normal 404 path
  authorize! :update, rma

  begin
    rma.regenerate_return_documents!
  rescue StandardError => e
    return redirect_to rma_path(rma, tab: 'attachments'),
                       status: :see_other, # PUT — keep Turbo from re-PUTing the redirect
                       error: "Could not regenerate the return documents: #{e.message}"
  end

  redirect_to rma_path(rma, tab: 'attachments'),
              status: :see_other,
              notice: 'Return labels and instructions PDF regenerated from the existing carrier labels.'
end

#remove_rma_item_imagevoid

This method returns an undefined value.

Removes a photo attached to an RMA item.



732
733
734
735
736
737
738
# File 'app/controllers/rmas_controller.rb', line 732

def remove_rma_item_image
  @rma = Rma.find(params.expect(:id))
  rma_item = @rma.rma_items.find(params.expect(:rma_item_id))
  upload = rma_item.uploads.find(params.expect(:upload_id))
  upload.destroy
  redirect_to(receive_items_rma_path(@rma), notice: "Photo removed from #{rma_item.returned_item&.sku}.")
end

#reset_shipping_statevoid

This method returns an undefined value.

Clears an RMA stuck in the "requested with a return delivery but no labels
required" limbo state, dropping its return delivery and advancing it to
awaiting_return.



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/rmas_controller.rb', line 622

def reset_shipping_state
  rma = Rma.find(params.expect(:id))
  authorize! :update, rma

  # Check if RMA is in the limbo state we want to fix
  if rma.requested? && !rma.number_of_return_labels_required.zero? && rma.return_delivery.present?
    Rma.transaction do
      # Set return labels required to 0
      rma.update!(number_of_return_labels_required: 0)

      # Clear the foreign key reference first, then destroy the delivery
      delivery = rma.return_delivery
      rma.update!(return_delivery_id: nil)
      delivery&.destroy!

      # Transition to awaiting_return since items are already physically received
      rma.awaiting_return!
    end

    redirect_to(rma, notice: 'RMA shipping state has been reset. Return labels requirement removed and RMA advanced to awaiting_return state.')
  else
    redirect_to(rma, error: 'RMA is not in the correct state for shipping reset. Must be in requested state with return labels required and return delivery present.')
  end
end

#return_label_optionsvoid

This method returns an undefined value.

Renders the form for configuring return label count and shipping option,
pre-populated with existing values.



961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
# File 'app/controllers/rmas_controller.rb', line 961

def return_label_options
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma
  unless @rma.can_be_edited?
    redirect_to(@rma,
                error: "Cannot configure return labels for RMA in state #{@rma.human_state_name}") && return
  end

  @customer = @rma.customer
  @original_invoice = @rma.original_invoice
  @shipping_options = ShippingOption.supported_carrier_options_for_rmas(@rma&.customer&.store&.country&.iso)

  # Pre-populate with existing values if any
  @rma.number_of_return_labels_required ||= 0
  @rma.shipping_option_id ||= @shipping_options.first&.last
end

#save_shipping_and_generate_labelsvoid

This method returns an undefined value.

Saves the selected shipping option and generates return labels (or, for
Canada Post returns, finalizes the RMA with no physical label).



1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# File 'app/controllers/rmas_controller.rb', line 1088

def save_shipping_and_generate_labels
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  if params[:shipping_option_id].blank?
    flash[:error] = 'Please select a shipping option.'
    redirect_to calculate_shipping_costs_rma_path(@rma) and return
  end

  # Save the selected shipping option without re-rating
  @rma.update(shipping_option_id: params[:shipping_option_id])

  # Canada Post returns generate no label — the hosted Manage Returns link
  # replaces it (see Rma#canada_post_return?), so complete the no-label flow
  # instead of falling through to the "labels not required" error.
  if @rma.canada_post_return?
    finalize_rma_without_labels
    flash[:info] = no_label_saved_message
    redirect_to(rma_path(@rma))
    return
  end

  if @rma.return_delivery
    @rma.return_delivery.update(shipping_option_id: params[:shipping_option_id])
  else
    @rma.create_return_delivery
  end

  if @rma.return_label_required?
    res = @rma.generate_return_labels
    @rma.generate_return_instructions_pdf if @rma.awaiting_return? && !@rma.service_only?

    if res[:status] == :ok
      Shipping::ReturnShippingInsurance.new.book_internal_insurance(@rma)
      # Queue any draft RMA communications now that labels and instructions are ready
      @rma.communications.where(state: 'draft', email_template: EmailTemplate.find_by(system_code: 'RMA')).find_each(&:queue)
      flash[:info] = 'RMA return labels were successfully created.'
      redirect_to rma_path(@rma)
    else
      # Carrier API failure: send the user back to the shipping cost screen
      # instead of the RMA show page so they can pick another option and
      # retry without losing context.
      flash[:error] = "Return labels could not be generated!<br/>#{res[:errors].join('<br/>')}".html_safe
      redirect_to calculate_shipping_costs_rma_path(@rma)
    end
  else
    flash[:error] = 'Return labels not required for this RMA!'
    redirect_to rma_path(@rma)
  end
end

#set_addressesvoid

This method returns an undefined value.

Sets @addresses from the original invoice's customer and/or the RMA's
customer, for the address picker.



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
# File 'app/controllers/rmas_controller.rb', line 903

def set_addresses
  @addresses = if @original_invoice.present? && @customer.present?
                 @customer.all_addresses.to_a.push(@original_invoice.shipping_address).uniq
               elsif @original_invoice.present?
                 @original_invoice.customer.all_addresses.to_a.push(@original_invoice.shipping_address).uniq
               elsif @customer.present?
                 @customer.all_addresses.to_a
               else
                 []
               end

  @addresses << @rma.company.stores.first.warehouse_address if @rma.company_id.present?
  @addresses << @rma.ship_from_address if @rma.ship_from_address.present?
  @addresses.uniq!
end

#showObject

GET /rmas/1
Accepts ID or rma_number (e.g., RMA123456)



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'app/controllers/rmas_controller.rb', line 59

def show
  rma_scope = Rma.includes(
    return_delivery: [
      :origin_address,
      :destination_address,
      { rma_for_return: :customer },
      { shipments: { delivery: %i[origin_address destination_address] } }
    ]
  )
  @rma = find_by_id_or_reference(Rma, :rma_number, scope: rma_scope)
  @attachments = @rma.uploads
  @pagy_activities, @activities = pagy(@rma.activities.natural_order)
  set_context(@rma)
  respond_to do |format|
    format.html # show.html.erb
    format.pdf do
      send_data Pdf::Document::ReturnInstructions.call(@rma, output_to_file: false).pdf_data,
                filename: @rma.instructions_file_name,
                type: 'application/pdf',
                disposition: 'inline'
    end
  end
end

#tab_attachmentsvoid

This method returns an undefined value.

Renders the attachments tab fragment.



1210
1211
1212
1213
1214
1215
1216
# File 'app/controllers/rmas_controller.rb', line 1210

def tab_attachments
  load_and_authorize_rma
  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



1173
1174
1175
1176
1177
1178
1179
# File 'app/controllers/rmas_controller.rb', line 1173

def tab_main
  load_and_authorize_rma
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_return_labelsvoid

This method returns an undefined value.

Renders the return labels tab fragment.



1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
# File 'app/controllers/rmas_controller.rb', line 1196

def tab_return_labels
  @rma = Rma.includes(
    return_delivery: { shipments: %i[shipment_contents child_shipments] }
  ).find(params.expect(:id))
  authorize!(:read, @rma)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_rma_itemsvoid

This method returns an undefined value.

Renders the RMA items tab fragment.



1184
1185
1186
1187
1188
1189
1190
1191
# File 'app/controllers/rmas_controller.rb', line 1184

def tab_rma_items
  @rma = Rma.includes(rma_items: [:returned_item, :uploads, { children: %i[returned_item uploads] }]).find(params.expect(:id))
  authorize!(:read, @rma)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#transmitvoid

This method returns an undefined value.

Redirects to the new-communication form pre-filled to transmit this RMA.



893
894
895
896
897
# File 'app/controllers/rmas_controller.rb', line 893

def transmit
  @rma = Rma.find(params.expect(:id))
  com_params = CommunicationBuilder.new(resource: @rma, current_user: current_user).to_params
  redirect_to new_communication_path(com_params.merge(return_path: rma_path(@rma)))
end

#unreturn_rmavoid

This method returns an undefined value.

Unreturns every item on the RMA, reversing their ledger entries.



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# File 'app/controllers/rmas_controller.rb', line 580

def unreturn_rma
  rma = Rma.find(params.expect(:id))
  authorize! :unreturn_rma, rma
  rma.unreturn_all_items
  rma.reload
  if rma.awaiting_return?
    redirect_to(rma, notice: 'RMA has been unreturned.')
  else
    redirect_to(rma, error: 'Unable to unreturn RMA')
  end
rescue ActiveRecord::RecordInvalid => e
  # See unreturn_rma_item: the closed-period ledger guard rejects re-posting a
  # receipt into a closed period — show it, don't 500 (AppSignal #2029/#6039).
  redirect_to(rma, error: "Unable to unreturn RMA — #{e.record.errors.full_messages.to_sentence.presence || e.message}")
end

#unreturn_rma_itemvoid

This method returns an undefined value.

Unreturns a single RMA item, reversing its ledger entries.



560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'app/controllers/rmas_controller.rb', line 560

def unreturn_rma_item
  rma = Rma.find(params.expect(:id))
  authorize! :unreturn_rma_item, rma
  rma_item = rma.rma_items.find(params.expect(:rma_item_id))

  if rma_item.unreturn
    redirect_to(rma, notice: 'RMA item has been unreturned.')
  else
    redirect_to(rma, error: 'Unable to unreturn RMA item.')
  end
rescue ActiveRecord::RecordInvalid => e
  # Unreturning re-posts ledger entries; if the original RMA_RECEIPT sits in a
  # closed accounting period the append-only ledger guard correctly rejects it.
  # Surface that to the user instead of 500ing (AppSignal #2029/#6039).
  redirect_to(rma, error: "Unable to unreturn RMA item — #{e.record.errors.full_messages.to_sentence.presence || e.message}")
end

#unvoid_rmavoid

This method returns an undefined value.

Unvoids the RMA and all of its items.



547
548
549
550
551
552
553
554
555
# File 'app/controllers/rmas_controller.rb', line 547

def unvoid_rma
  rma = Rma.find(params.expect(:id))
  rma.unvoid_all_items_and_self
  if rma.awaiting_return?
    redirect_to(rma, notice: 'RMA has been unvoided.')
  else
    redirect_to(rma, error: 'Unable to unvoid RMA')
  end
end

#updateObject

PUT /rmas/1



157
158
159
160
161
162
163
164
165
166
167
# File 'app/controllers/rmas_controller.rb', line 157

def update
  @rma = Rma.find(params.expect(:id))
  if @rma.update(params[:rma])
    redirect_to_return_path_or_default rma_path(@rma)
  else
    @original_invoice = @rma.original_invoice
    @customer = @rma.customer
    set_addresses
    render :edit, status: :unprocessable_content
  end
end

#update_itemsObject

PUT /rmas/1



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'app/controllers/rmas_controller.rb', line 371

def update_items
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma
  if @rma.can_be_edited?
    (params.to_h.dig(:rma, :rma_items_attributes) || {}).values.map { |a| a.transform_values(&:presence).compact }.each do |ri|
      if ri[:id].present?
        rma_item = RmaItem.find ri[:id]
        rma_item.update(ri)
      end
    end
    @rma.has_auto_return_items? ? @rma.needs_auto_return_review : @rma.update(state: 'awaiting_return')

    redirect_to choose_replacement_order_type_rma_path(@rma) and return if pending_replacement_rma_items(@rma).any?
  else
    flash[:error] = "Cannot edit items to RMA in state #{@rma.human_state_name}"
  end

  redirect_to_return_path_or_default rma_path(@rma)
end

#update_return_labels_and_calculate_shippingvoid

This method returns an undefined value.

Applies edited return label options and re-quotes shipping (labels are
regenerated after the save, so validations are skipped for this step).



1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
# File 'app/controllers/rmas_controller.rb', line 1143

def update_return_labels_and_calculate_shipping
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  # Skip shipping option and return label validations during this step — labels
  # are regenerated *after* the save, so they can't be correct yet.
  @rma.skip_shipping_option_validation = true
  @rma.skip_return_label_validation = true

  if @rma.update(return_label_params)
    if @rma.return_label_required?
      # Create return delivery and calculate shipping costs
      @rma.create_return_delivery
      @rma.return_delivery.retrieve_shipping_costs

      flash[:info] = 'Return label options saved. Shipping costs calculated.'
      redirect_to calculate_shipping_costs_rma_path(@rma)
    else
      finalize_rma_without_labels
      flash[:info] = no_label_saved_message
      redirect_to_return_path_or_default rma_path(@rma)
    end
  else
    @customer = @rma.customer
    @original_invoice = @rma.original_invoice
    render :edit_return_labels, status: :unprocessable_content
  end
end

#update_shipping_optionvoid

This method returns an undefined value.

Updates the return delivery's shipping option and re-quotes shipping costs.



1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
# File 'app/controllers/rmas_controller.rb', line 1063

def update_shipping_option
  @rma = Rma.find(params.expect(:id))
  authorize! :update, @rma

  if params[:shipping_option_id].present?
    @rma.update(shipping_option_id: params[:shipping_option_id])

    if @rma.return_delivery
      @rma.return_delivery.update(shipping_option_id: params[:shipping_option_id])
      @rma.return_delivery.shipping_costs.destroy_all
      @rma.return_delivery.retrieve_shipping_costs
    end

    flash[:info] = 'Shipping option updated successfully.'
  else
    flash[:error] = 'No shipping option selected.'
  end

  redirect_to calculate_shipping_costs_rma_path(@rma)
end

#void_rmavoid

This method returns an undefined value.

Voids the RMA and all of its items.



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'app/controllers/rmas_controller.rb', line 527

def void_rma
  rma = Rma.find(params.expect(:id))
  rma.void_all_items_and_self
  if rma.voided?
    msg = ''
    if rma.orders.present?
      replacement_orders_msg = rma.orders.map do |o|
        "<a href='#{order_path(o)}'>order #{o.reference_number}</a>"
      end.join(', ')
      msg = "You should cancel any replacement orders (#{replacement_orders_msg}) if they are no longer required."
    end
    redirect_to(rma, notice: "RMA has been voided. #{msg}")
  else
    redirect_to(rma, error: 'Unable to void RMA')
  end
end