Class: InvoicesController

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

Overview

== Schema Information

Table name: invoices

id :integer not null, primary key
order_id :integer
jde_number :integer
total :decimal(8, 2)
created_at :datetime
updated_at :datetime
due_date :date
currency :string(255)
invoice_type :string(255)
discount :decimal(8, 2) default(0.0)
discount_code :string(255)
line_total :decimal(8, 2)
completion_date :date
state :string(255)
billing_address_id :integer
shipping_address_id :integer
tax_total :decimal(8, 2)
shipping_cost :decimal(8, 2)
reference_number :string(255)
terms :string(255)
shipped_date :date
uploads_count :integer
transmission_state :string(255)
customer_id :integer
company_id :integer
early_payment_discount :integer
early_payment_timescale :integer
local_sales_rep_id :integer
primary_sales_rep_id :integer
secondary_sales_rep_id :integer
buying_group_id :integer
shipping_coupon :decimal(8, 2)
creator_id :integer
updater_id :integer
document_date :date
gl_date :date
tax_date :date
po_number :string(255)
store_id :integer
gl_offset_account_id :integer
business_unit_id :integer
taxable_total :decimal(12, 2)
legacy_taxes :boolean
line_total_discounted :decimal(8, 2)
delivery_id :integer
old_total :decimal(8, 2)
old_tax_total :decimal(8, 2)
old_shipping_cost :decimal(8, 2)
revenue_consolidated :decimal(8, 2)
consolidated_exchange_rate :float
profile_id :integer
report_grouping :string(255)
billing_customer_id :integer
account_specialist_id :integer
profit :decimal(8, 2) default(0.0)
profit_consolidated :decimal(8, 2) default(0.0)
source_id :integer
technical_support_rep_id :integer

Constant Summary collapse

TAB_ACTIONS =

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

%i[tab_edi_documents tab_line_items tab_attachments tab_receipts tab_payments tab_rmas tab_credit_memos tab_item_ledger tab_account_ledger tab_outlet_purchases].freeze

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

require_in_pane_tab_frames, require_turbo_frame

Methods included from Controllers::Workflowable

#render_workflow_error_stream, #render_workflow_success_stream, #workflow_action, #workflow_action_complete

Methods inherited from CrmController

#access_denied, #context_id, #context_object, #crm_home_path, #current_ability, #default_url_options, #download_temp, #get_tempfile_path_for_download, #init_status_job_collector, #initialize_crm_lazy_chunks, #persist_enqueued_status_jobs, #record_not_found, #redirect_to_job_or_fallback, #render_edit_action, #set_context, #set_download_path, #stash_file_for_temp_download, #sync_admin_presence_cookie, #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

#approveObject

POST /invoices/:id/approve — fire the state-machine approve!
transition. Catches StandardError so an approval blocked by a
validation surfaces as a user-facing flash rather than a 500.



350
351
352
353
354
355
356
357
358
359
360
361
# File 'app/controllers/invoices_controller.rb', line 350

def approve
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  begin
    @invoice.approve!
    flash[:info] = 'Invoice approved successfully'
  rescue StandardError => e
    flash[:error] = "Invoice could not be approved, message: #{e}"
  end
  redirect_to @invoice
end

#capture_paymentObject

POST /invoices/:id/capture_payment — enqueue
InvoiceCaptureFundsWorker to run gateway captures asynchronously
(we don't want the CRM thread to block on Stripe / PayPal). The
flash tells the user to refresh.



450
451
452
453
454
455
456
457
# File 'app/controllers/invoices_controller.rb', line 450

def capture_payment
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  InvoiceCaptureFundsWorker.perform_async(@invoice.id)
  flash[:info] = 'Payment process started. Please reload this page in a few seconds to verify the payment was captured successfuly.'
  redirect_to @invoice
end

#createObject

POST /invoices
POST /invoices.xml



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

def create
  authorize! :create, Invoice

  @invoice = Invoice.new(params[:invoice])
  @new_address = Address.new(params[:address])
  @addresses = @invoice.customer.nil? ? [] : @invoice.customer.all_addresses.to_a
  order = @invoice.order
  if order
    @addresses << order.shipping_address unless @addresses.include?(order.shipping_address)
    @addresses << order.billing_address unless @addresses.include?(order.billing_address)
  end
  if @invoice.enter_new_address.to_b
    @invoice.shipping_address_id = nil
    @invoice.shipping_address_attributes = params[:address]
  end
  if @invoice.save
    redirect_to(@invoice, info: 'Invoice was successfully created.')
  else
    render action: 'new', status: :unprocessable_content
  end
end

#destroyObject

DELETE /invoices/1
DELETE /invoices/1.xml



251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'app/controllers/invoices_controller.rb', line 251

def destroy
  authorize! :delete, Invoice

  @invoice = Invoice.find(params[:id])

  if @invoice.editing_locked?
    flash[:error] = 'Invoice cannot be deleted'
    redirect_to(@invoice) and return
  end

  flash[:info] = 'Invoice successfully deleted'
  @invoice.destroy
  redirect_to_return_path_or_default(invoices_url)
end

#editObject

GET /invoices/1/edit



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'app/controllers/invoices_controller.rb', line 177

def edit
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  if @invoice.editing_locked?
    flash[:error] = 'Invoice cannot be edited'
    redirect_to(@invoice) and return
  end
  @addresses = @invoice.customer.all_addresses.to_a.push(@invoice.shipping_address).compact.uniq
  @new_address = Address.new
  order = @invoice.order
  if order
    @addresses << order.shipping_address unless @addresses.include?(order.shipping_address)
    @addresses << order.billing_address unless @addresses.include?(order.billing_address)
  end
  @invoice.line_items.build if @invoice.line_items.empty?
end

#exclude_notificationObject

POST /invoices/:id/exclude_notification — flip the invoice's
exclude_fund_capture_notification flag on so accounting doesn't
email the customer when funds are captured (used for offline-paid
invoices). See #include_notification for the inverse action.



426
427
428
429
430
431
432
# File 'app/controllers/invoices_controller.rb', line 426

def exclude_notification
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  @invoice.update(exclude_fund_capture_notification: true)
  redirect_to @invoice
end

#fba_pullObject

GET /customers/:customer_id/invoices/fba_pull — form for pulling
Amazon FBA-fulfilled-orders into Heatwave as consignment invoices.
Bounces non-Amazon-seller customers back to the customer accounting tab.



396
397
398
399
400
# File 'app/controllers/invoices_controller.rb', line 396

def fba_pull
  authorize! :create, Invoice
  @customer = Customer.find(params[:customer_id])
  redirect_to_return_path_or_default(customer_path(@customer, tab: 'accounting'), error: 'Customer is not an Amazon seller') unless @customer.is_amazon_seller_central?
end

#include_notificationObject

POST /invoices/:id/include_notification — clears
exclude_fund_capture_notification so the customer once again
receives capture-notification emails. Inverse of
#exclude_notification.



438
439
440
441
442
443
444
# File 'app/controllers/invoices_controller.rb', line 438

def include_notification
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  @invoice.update(exclude_fund_capture_notification: false)
  redirect_to @invoice
end

#indexObject

GET /invoices
GET /invoices.xml



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'app/controllers/invoices_controller.rb', line 74

def index
  authorize! :read, Invoice
  qt = InvoiceSearch.instantiate_query_template(:default)
  search = qt.search
  search.employee = current_user
  authorize! :create, search
  if search.save
    redirect_to search_path(search)
  else
    flash[:error] = 'Unable to create default invoice search'
    redirect_to root_path
  end
end

#lookupObject

GET /invoices/lookup — JSON typeahead endpoint for the invoice
picker (used on RMA forms, payment forms, etc.). Accepts a free-text
q, an optional customer_id to scope the search, and an optional
state_in to filter by invoice state. With allow_open_invoice_link
the search broadens to any invoice in the customer's company.



556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'app/controllers/invoices_controller.rb', line 556

def lookup
  authorize! :read, Invoice

  q = params[:q].try(:upcase)&.split&.first
  invoice_id = params[:invoice_id].presence
  customer_id = params[:customer_id].presence
  state_in = params[:state_in].presence
  if invoice_id
    invoice = Invoice.find(invoice_id)
    render json: { results: [{ id: invoice.id, text: invoice.selection_name_for_rmas }] }
  else
    @results = Invoice.all
    @results = @results.where(state: state_in) if state_in
    if customer_id
      # You can search outside the customer's order scope if this flag is specified
      if params[:allow_open_invoice_link].to_b && q.present?
        # if a customer id was specified, we will still limit to orders in the same company id as the original customer
        company_id = Customer.joins(:catalog).where(id: customer_id).pick('catalogs.company_id')
        @results = @results.joins(customer: :catalog).where(Catalog[:company_id].eq(company_id))
      else
        @results = @results.where(customer_id: customer_id)
      end
    end
    if q.present?
      @results = if params[:with_wildcard].to_b
                   @results.like_lookup(q)
                 else
                   @results.lookup(q)
                 end
    end

    json_result = TomSelect.format_json_results(self, @results, params[:page].presence, params[:per_page].presence) do |e|
      {
        id: e.id,
        text: e.selection_name_for_rmas,
        label: e.selection_name,
        reference: e.reference_number,
        order_link: invoice_path(e),
        state: e.state,
        shipped: e.shipped_date.present? ? e.shipped_date.to_fs(:crm_default) : 'not shipped',
        customer: e.customer.full_name,
        customer_link: customer_path(e.customer)
      }
    end
    render json: json_result
  end
end

#newObject

GET /invoices/new



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'app/controllers/invoices_controller.rb', line 115

def new
  authorize! :create, Invoice

  customer = Customer.where(id: params[:customer_id]).first
  order = Order.where(id: params[:order_id]).first
  @new_address = Address.new
  if order.present?
    company_id = order.store.company_id
    currency = order.currency
    shipping_address_id = order.shipping_address_id
    store_id = order.store.id
    primary_sales_rep_id = order.primary_sales_rep.try(:id)
    secondary_sales_rep_id = order.secondary_sales_rep.try(:id)
    local_sales_rep_id = order.local_sales_rep.try(:id)
    shipped_date = order.shipped_date
    order_id = order.id
    po_number = order.po_number
  elsif customer.present?
    company_id = customer.catalog.store.company_id
    currency = customer.catalog.store.company.currency
    shipping_address_id = nil
    primary_sales_rep_id = customer.store.id
    secondary_sales_rep_id = customer.secondary_sales_rep_id
    local_sales_rep_id = customer.local_sales_rep_id
    shipped_date = nil
    order_id = nil
    po_number = nil
  else
    company_id = nil
    currency = nil
    shipping_address_id = nil
    store_id = nil
    primary_sales_rep_id = nil
    secondary_sales_rep_id = nil
    local_sales_rep_id = nil
    shipped_date = nil
    order_id = nil
    po_number = nil
  end

  @addresses = customer.nil? ? [] : customer.all_addresses
  @invoice = Invoice.new(customer_id: params[:customer_id],
                         company_id: company_id,
                         shipping_address_id: shipping_address_id,
                         billing_address_id: customer&.billing_address_id,
                         terms: customer&.terms,
                         currency: currency,
                         gl_date: Date.current,
                         document_date: Date.current,
                         tax_date: Date.current,
                         store_id: store_id,
                         primary_sales_rep_id: primary_sales_rep_id,
                         secondary_sales_rep_id: secondary_sales_rep_id,
                         local_sales_rep_id: local_sales_rep_id,
                         order_id: order_id,
                         shipped_date: shipped_date,
                         po_number: po_number,
                         report_grouping: customer&.report_grouping)
  @invoice.line_items.build
end

GET /invoices/:id/payment_link — render the form for emailing a
public, tokenised pay-by-link to the customer. Submission posts to
#send_payment_link.



366
367
368
369
370
# File 'app/controllers/invoices_controller.rb', line 366

def payment_link
  authorize! :read, Invoice

  @invoice = Invoice.find(params[:id])
end

#pdfObject

GET /invoices/:id/pdf — return the cached invoice PDF, regenerating
only if the stored copy is missing or stale (see
Invoice#get_or_regen_pdf). Redirects to the Upload record.



328
329
330
331
332
333
334
# File 'app/controllers/invoices_controller.rb', line 328

def pdf
  authorize! :read, Invoice

  @invoice = Invoice.find(params[:id])
  @pdf = @invoice.get_or_regen_pdf
  redirect_to upload_path(@pdf)
end

#process_fba_pullObject

POST /customers/:customer_id/invoices/process_fba_pull — submit the
FBA pull form: fetch the listed PO numbers from the Amazon
Seller-Central orchestrator and turn each into a consignment invoice.
Reports the number created in the flash.



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'app/controllers/invoices_controller.rb', line 406

def process_fba_pull
  authorize! :create, Invoice
  @customer = Customer.find(params[:customer_id])
  redirect_to_return_path_or_default(customer_path(@customer, tab: 'accounting'), error: 'Customer is not an Amazon seller') unless @customer.is_amazon_seller_central?
  po_numbers = params[:po_numbers].split(',').map { |po| po.strip.delete(' ') }
  if po_numbers.any?
    orchestrator = @customer.edi_orchestrator
    orchestrator.fba_pull_orders_by_po_numbers(po_numbers)
    res = orchestrator.fba_order_message_processor.process
    invoices_created = res.batch_process_results.sum { |bpr| bpr.invoices_created.size }
    redirect_to_return_path_or_default(customer_path(@customer, tab: 'accounting'), notice: "PO number(s) processed and #{invoices_created} consignment invoice(s) created")
  else
    redirect_to_return_path_or_default(customer_path(@customer, tab: 'accounting'), error: 'No PO number(s) provided, skipping')
  end
end

#regenerate_edi_documentsObject

POST /invoices/:id/regenerate_edi_documents — re-fire the EDI 810
(invoice) creation pipeline through Edi::InvoiceEventProcessor, the
CRM lever for "the partner says they didn't get our invoice".



292
293
294
295
296
297
298
299
# File 'app/controllers/invoices_controller.rb', line 292

def regenerate_edi_documents
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  Edi::InvoiceEventProcessor.new.process_creation(@invoice)
  flash[:info] = "EDI documents queued for regeneration for #{@invoice.reference_number}."
  redirect_to url_from(params[:return_to]) || @invoice
end

#regenerate_pdfObject

POST /invoices/:id/regenerate_pdf — force a new Invoice#generate_pdf
run (e.g. after fixing a billing-address typo) and redirect to the
newly-stored Upload.



269
270
271
272
273
274
275
# File 'app/controllers/invoices_controller.rb', line 269

def regenerate_pdf
  authorize! :read, Invoice

  @invoice = Invoice.find(params[:id])
  @pdf = @invoice.generate_pdf
  redirect_to upload_path(@pdf)
end

#regenerate_receiptsObject

POST /invoices/:id/regenerate_receipts — re-create Receipt rows for
every captured Payment on the invoice. Used to recover from
missing-receipt bugs without re-running the capture itself.



280
281
282
283
284
285
286
287
# File 'app/controllers/invoices_controller.rb', line 280

def regenerate_receipts
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  @invoice.create_receipts_for_captured_payments
  flash[:info] = 'Regeneration process finished. If no receipts were created there are probably no payments attached to this invoice.'
  redirect_to @invoice
end

POST /invoices/:id/send_payment_link — build a draft INVOICE_PAYMENT
communication carrying a https://.../pay-invoice/<token> URL. The
token is an Encryption-encrypted invoice id so the URL doesn't leak
sequential ids. Lands the user on the editable communication page.



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'app/controllers/invoices_controller.rb', line 376

def send_payment_link
  authorize! :read, Invoice

  @invoice = Invoice.find(params[:id])
  @customer = @invoice.customer
  token = Encryption.encrypt_string(params[:id])
  url = "https://#{WEB_HOSTNAME}/pay-invoice/#{token}"
  comm = CommunicationBuilder.new(sender_party: @customer.primary_sales_rep || current_user,
                                  recipient_party: @customer,
                                  emails: params[:payment_link][:email],
                                  merge_options: { receipt_link: url },
                                  save_merge_options: true,
                                  use_best_email: true,
                                  template_system_code: 'INVOICE_PAYMENT').create(keep_as_draft: true)
  redirect_to communication_path(comm)
end

#showObject

GET /invoices/1
GET /invoices/1.xml
Accepts ID or reference_number (e.g., IN123456)



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'app/controllers/invoices_controller.rb', line 91

def show
  authorize! :read, Invoice

  invoice_scope = Invoice.includes(line_items: [:reserved_serial_numbers], item_ledger_entries: %i[store_item_audit ledger_transaction serial_numbers])
  @invoice = find_by_id_or_reference(Invoice, :reference_number, scope: invoice_scope)
  @customer = @invoice.customer
  @show_kits_and_sn = params[:show_kits_and_sn].to_b
  @attachments = @invoice.uploads
  @pagy_activities, @activities = pagy(@invoice.activities.natural_order)
  set_context(@invoice)
  @old_style = params[:old_style]
  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render xml: @invoice }
    format.pdf do
      send_data Invoicing::CombinedPdfGenerator.new.process(@invoice, { output_to_file: false }).pdf_data,
                filename: @invoice.file_name,
                type: 'application/pdf',
                disposition: 'inline'
    end
  end
end

#tab_account_ledgerObject

GET /invoices/:id/tab_account_ledger — turbo-frame content for the
GL-side (LedgerEntry) view of this invoice.



543
544
545
546
547
548
549
# File 'app/controllers/invoices_controller.rb', line 543

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

#tab_attachmentsObject

GET /invoices/:id/tab_attachments — turbo-frame content for the
attachments tab.



479
480
481
482
483
484
485
# File 'app/controllers/invoices_controller.rb', line 479

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

#tab_credit_memosObject

GET /invoices/:id/tab_credit_memos — turbo-frame content listing
CreditMemo records issued against this invoice.



522
523
524
525
526
527
528
529
# File 'app/controllers/invoices_controller.rb', line 522

def tab_credit_memos
  load_invoice
  @customer = @invoice.customer
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_edi_documentsObject

GET /invoices/:id/tab_edi_documents — turbo-tab content for the EDI
communication log on the invoice show page (most-recent first).



303
304
305
306
307
308
309
310
# File 'app/controllers/invoices_controller.rb', line 303

def tab_edi_documents
  load_invoice
  @edi_communication_logs = @invoice.edi_communication_logs.order(created_at: :desc)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_item_ledgerObject

GET /invoices/:id/tab_item_ledger — turbo-frame content for the
inventory-side (ItemLedgerEntry) view of this invoice.



533
534
535
536
537
538
539
# File 'app/controllers/invoices_controller.rb', line 533

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

#tab_line_itemsObject

GET /invoices/:id/tab_line_items — turbo-frame content for the
line-items tab of the invoice show page.



466
467
468
469
470
471
472
473
474
475
# File 'app/controllers/invoices_controller.rb', line 466

def tab_line_items
  load_invoice
  # The "Show/Hide Kit Contents/SN" toggle navigates this frame with
  # ?show_kits_and_sn=1; without reading it here the tab re-renders collapsed.
  @show_kits_and_sn = params[:show_kits_and_sn].to_b
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_outlet_purchasesObject

Opportunities a rep worked that this outlet invoice satisfied. Only ever
populated for retailer invoices — see
doc/tasks/202608081330_OUTLET_PURCHASE_ATTRIBUTION.md.



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

def tab_outlet_purchases
  load_invoice
  @outlet_purchases = @invoice.outlet_purchases.includes(:verified_by, opportunity: :customer)
                              .order(created_at: :desc)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_paymentsObject

GET /invoices/:id/tab_payments — turbo-frame content for the
payments tab. Loads the invoice's payment scope through
#payments_for_invoice_tab so authorisations from the source order
show up alongside this invoice's own captures.



501
502
503
504
505
506
507
508
# File 'app/controllers/invoices_controller.rb', line 501

def tab_payments
  load_invoice
  @payments = payments_for_invoice_tab(@invoice)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_receiptsObject

GET /invoices/:id/tab_receipts — turbo-frame content for the
receipts tab (paid amounts against this invoice).



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

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

#tab_rmasObject

GET /invoices/:id/tab_rmas — turbo-frame content for the linked-RMAs
tab.



512
513
514
515
516
517
518
# File 'app/controllers/invoices_controller.rb', line 512

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

#transmitObject

GET /invoices/:id/transmit — kick off a Send Invoice communication
by routing to new_communication_path with the invoice pre-bound as
the resource (the user picks recipients/template on the next page).



339
340
341
342
343
344
345
# File 'app/controllers/invoices_controller.rb', line 339

def transmit
  authorize! :read, Invoice

  @invoice = Invoice.find(params[:id])
  redir_params = CommunicationBuilder.new(resource: @invoice, current_user: current_user).to_params
  redirect_to new_communication_path(redir_params)
end

#updateObject

PUT /invoices/1
PUT /invoices/1.xml



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

def update
  authorize! :update, Invoice

  @invoice = Invoice.find(params[:id])
  if @invoice.editing_locked?
    flash[:error] = 'Invoice cannot be edited'
    redirect_to(@invoice) and return
  end
  @invoice.assign_attributes(params[:invoice])
  @new_address = Address.new(params[:address])
  if @invoice.enter_new_address == '1'
    @invoice.shipping_address_id = nil
    @invoice.shipping_address_attributes = params[:address]
  end
  if @invoice.save
    redirect_to_return_path_or_default(invoice_path(@invoice))
  else
    @addresses = @invoice.customer.nil? ? [] : @invoice.customer.all_addresses
    @addresses = @addresses.to_a.push(@invoice.shipping_address).compact.uniq
    order = @invoice.order
    if order
      @addresses << order.shipping_address unless @addresses.include?(order.shipping_address)
      @addresses << order.billing_address unless @addresses.include?(order.billing_address)
    end
    render action: 'edit', status: :unprocessable_content
  end
end