Class: RmasController

Inherits:
CrmController show all
Includes:
Controllers::Attachable, Controllers::Destroyable, 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

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

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

Methods inherited from ApplicationController

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

Methods included from Controllers::ReturnPathHandling

#check_for_return_path, #redirect_to_return_path_or_default

Methods included from Controllers::AnalyticsEvents

#consume_queued_analytics_events, #track_event

Methods included from Controllers::DeviceDetection

#device_detector, #is_ie?

Methods included from Controllers::SubdomainDetection

#is_crm_request?, #is_www_request?, #json_request?

Methods included from Controllers::TurboSafeRedirect

#redirect_to

Methods included from Controllers::TrackingDetection

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

Methods included from Controllers::AcceleratedFileSending

#send_file_accelerated, #send_upload_accelerated

Methods included from Controllers::ErrorRendering

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

Methods included from Controllers::TurnstileVerification

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

Methods included from Controllers::CloudflareCaching

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

Methods included from Controllers::Webpackable

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

Methods included from Controllers::Localizable

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

Methods included from Controllers::Authenticable

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

Methods included from ApplicationHelper

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

Methods included from UppyUploaderHelper

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

Methods included from Www::ImagesHelper

#image_asset_tag, #image_asset_url

Methods included from Www::SeoHelper

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

Methods included from UrlsHelper

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

Methods included from IconHelper

#account_nav_icon, #fa_icon, #star_rating_html

Instance Method Details

#add_itemsObject



166
167
168
169
170
171
172
173
174
175
# File 'app/controllers/rmas_controller.rb', line 166

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_imagesObject



577
578
579
580
581
# File 'app/controllers/rmas_controller.rb', line 577

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

#bulk_add_itemsObject



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
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
# File 'app/controllers/rmas_controller.rb', line 242

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

    if @rma.save
      @rma.rma_items.reject(&:child?).select { |ri| ri.returned_item&.is_kit? }.each(&:expand_kit_components!)
      @rma.create_documents
      @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_costsObject



893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
# File 'app/controllers/rmas_controller.rb', line 893

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.



369
370
371
372
373
374
375
376
377
378
379
380
# File 'app/controllers/rmas_controller.rb', line 369

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



139
140
141
142
143
144
145
146
147
148
149
150
# File 'app/controllers/rmas_controller.rb', line 139

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_itemsObject



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

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

  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
    # 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.



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'app/controllers/rmas_controller.rb', line 385

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_optionsObject



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
889
890
891
# File 'app/controllers/rmas_controller.rb', line 849

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
      # If no labels are needed and a return delivery exists, remove it (and its labels)
      if @rma.return_delivery
        delivery = @rma.return_delivery
        @rma.update(return_delivery_id: nil)
        delivery.destroy
      end

      # Transition to awaiting_return now that we know no labels are needed
      # This will trigger the email callback (only if transitioning from requested)
      if @rma.requested?
        @rma.awaiting_return
        @rma.generate_return_instructions_pdf unless @rma.service_only?
        # Queue any draft RMA communications now that instructions are ready
        @rma.communications.where(state: 'draft', email_template: EmailTemplate.find_by(system_code: 'RMA')).find_each(&:queue)
      elsif Communication.where(resource: @rma, state: 'draft').exists?
        # Regenerate instructions and update attachments on draft communications
        @rma.generate_return_instructions_pdf unless @rma.service_only?
      end

      flash[:info] = 'Return label options saved. No return labels required.'
      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_detailObject



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# File 'app/controllers/rmas_controller.rb', line 656

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.



423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'app/controllers/rmas_controller.rb', line 423

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_imagesObject



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

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_imagesObject



624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'app/controllers/rmas_controller.rb', line 624

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



125
126
127
128
129
130
131
132
133
134
135
136
# File 'app/controllers/rmas_controller.rb', line 125

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



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

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_labelsObject



335
336
337
338
339
340
341
342
# File 'app/controllers/rmas_controller.rb', line 335

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_itemsObject



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

def finish_receive_items
  @rma = Rma.where(state: %w[awaiting_return awaiting_inspection partially_returned]).find(params.expect(:id))
  authorize! :receive_items, @rma
  @rma.assign_attributes(params[:rma]) if params[:rma].present?
  rma_item_ids = []
  if params[:rma][:rma_items_attributes].present?
    rma_items_params = params[:rma][: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
  label_rma_item_ids = @rma.rma_items.select { |ri| ri.print_label.to_b }.filter_map(&:id)
  success = false
  Rma.transaction do
    success = @rma.rma_items.all?(&:save)
    @rma.create_credit_order(rma_item_ids) if success
  end
  if success
    Shipping::ReturnShippingInsurance.new.start_external_tracking(@rma)
    @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!#raw HTML omitted -->')".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



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'app/controllers/rmas_controller.rb', line 460

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])
      @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



49
50
51
# File 'app/controllers/rmas_controller.rb', line 49

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

#newObject

GET /rmas/new



80
81
82
83
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
# File 'app/controllers/rmas_controller.rb', line 80

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_detailObject



689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
# File 'app/controllers/rmas_controller.rb', line 689

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


800
801
802
803
804
# File 'app/controllers/rmas_controller.rb', line 800

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_lookupObject



715
716
717
718
719
720
721
722
723
# File 'app/controllers/rmas_controller.rb', line 715

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_codesObject



806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# File 'app/controllers/rmas_controller.rb', line 806

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_itemsObject



725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'app/controllers/rmas_controller.rb', line 725

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

#remove_rma_item_imageObject



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

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_stateObject



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

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_optionsObject



832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# File 'app/controllers/rmas_controller.rb', line 832

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_labelsObject



961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File 'app/controllers/rmas_controller.rb', line 961

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])

  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_addressesObject



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
# File 'app/controllers/rmas_controller.rb', line 784

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)



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'app/controllers/rmas_controller.rb', line 55

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_attachmentsObject



1078
1079
1080
1081
1082
1083
1084
# File 'app/controllers/rmas_controller.rb', line 1078

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



1050
1051
1052
1053
1054
1055
1056
# File 'app/controllers/rmas_controller.rb', line 1050

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_labelsObject



1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
# File 'app/controllers/rmas_controller.rb', line 1067

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_itemsObject



1058
1059
1060
1061
1062
1063
1064
1065
# File 'app/controllers/rmas_controller.rb', line 1058

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

#transmitObject



778
779
780
781
782
# File 'app/controllers/rmas_controller.rb', line 778

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_rmaObject



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

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_itemObject



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

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_rmaObject



509
510
511
512
513
514
515
516
517
# File 'app/controllers/rmas_controller.rb', line 509

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



153
154
155
156
157
158
159
160
161
162
163
164
# File 'app/controllers/rmas_controller.rb', line 153

def update
  @rma = Rma.find(params.expect(:id))
  if @rma.update(params[:rma])
    Shipping::ReturnShippingInsurance.new.start_external_tracking(@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



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'app/controllers/rmas_controller.rb', line 345

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_shippingObject



1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
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
# File 'app/controllers/rmas_controller.rb', line 1002

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
      # If no labels are needed and a return delivery exists, remove it (and its labels)
      if @rma.return_delivery
        delivery = @rma.return_delivery
        @rma.update(return_delivery_id: nil)
        delivery.destroy
      end

      # Transition to awaiting_return now that we know no labels are needed
      # This will trigger the email callback (only if transitioning from requested)
      if @rma.requested?
        @rma.awaiting_return
        @rma.generate_return_instructions_pdf unless @rma.service_only?
        # Queue any draft RMA communications now that instructions are ready
        @rma.communications.where(state: 'draft', email_template: EmailTemplate.find_by(system_code: 'RMA')).find_each(&:queue)
      elsif Communication.where(resource: @rma, state: 'draft').exists?
        # Regenerate instructions and update attachments on draft communications
        @rma.generate_return_instructions_pdf unless @rma.service_only?
      end

      flash[:info] = 'Return label options saved. No return labels required.'
      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_optionObject



940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'app/controllers/rmas_controller.rb', line 940

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_rmaObject



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'app/controllers/rmas_controller.rb', line 492

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