Class: VouchersController

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

Overview

== Schema Information

Table name: vouchers

id :integer not null, primary key
reference_number :string(255)
category :string(255)
company_id :integer
supplier_id :integer
invoice_number :string(255)
invoice_date :date
gl_date :date
currency :string(255)
exchange_rate :float
business_unit_id :integer
payment_terms :string(255)
state :string(255)
creator_id :integer
updater_id :integer
created_at :datetime
updated_at :datetime
order_id :integer
reversal_date :date

Constant Summary

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

#createObject

POST /vouchers — persist a new voucher and route the user to
#gl_distribution so they can split the voucher amount across
the GL accounts that make up the expense.



86
87
88
89
90
91
92
93
94
95
# File 'app/controllers/vouchers_controller.rb', line 86

def create
  @voucher = Voucher.new(params[:voucher])

  if @voucher.save
    redirect_to(gl_distribution_voucher_path(@voucher))
  else
    @voucher.voucher_items.build if @voucher.voucher_items.empty?
    render action: 'new', status: :unprocessable_content
  end
end

#do_import_from_excelObject

POST /vouchers/do_import_from_excel — bulk-create vouchers and
their GL distribution from the canonical Excel template (see
#download_sample_excel). Validates per-row, accumulates the
error list across all rows so users see every problem at once,
and rolls the whole batch back if any row fails.



113
114
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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
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
324
325
326
327
328
329
330
331
332
333
# File 'app/controllers/vouchers_controller.rb', line 113

def do_import_from_excel
  vouchers = []
  initial_ledger_entries = []
  errors = []

  attachments_list = Upload.where(id: params[:voucher][:upload_ids]) if params[:voucher].present?

  imported_vouchers_excel = params.dig(:upload, :imported_vouchers_excel)
  if imported_vouchers_excel
    unless imported_vouchers_excel.original_filename.to_s.match?(/\.(xlsx|xls|csv|ods)\z/i)
      flash.now[:error] = 'Please upload a spreadsheet file (.xlsx, .xls, .csv, or .ods). PDF and other formats are not supported.'
      render :import_from_excel, status: :unprocessable_content
      return
    end

    file_path = imported_vouchers_excel.tempfile.path.to_s
    require 'roo'
    vouchers_xlsx = Roo::Spreadsheet.open(file_path)
    voucher_ref = 0
    vouchers_xlsx.parse(headers: true, clean: true).each_with_index do |row, index|
      next unless index >= 1

      if row.map { |_k, v| v }.uniq.compact.present?
        if row['v_company_id'].present?
          voucher_ref = (index + 1).to_s
          @supplier = Party.find_by(id: row['v_supplier_id'])
          errors << "-<b> Voucher located on row #{voucher_ref}:</b> Column v_supplier_id can't be blank. <br>" if row['v_supplier_id'].nil?
          @business_unit = BusinessUnit.where(number: row['gld_business_unit']).first
          errors << "-<b> Voucher located on row #{voucher_ref}:</b> Column gld_business_unit can't be blank. <br>" if row['gld_business_unit'].nil?

          if row['v_currency'].nil?
            currency = Company.find_by(id: row['v_company_id'].to_i)&.currency
          else
            currency_row = row['v_currency']
            if Money::Currency.table[currency_row.to_s.downcase.to_sym].nil?
              errors << "-<b> Voucher located on row #{voucher_ref}:</b> Column v_currency isn't formatted correctly. <br>"
            else
              currency = currency_row.to_s.upcase
            end
          end
          # we get the info needed to crete voucher
          gl_date = parse_excel_date(row['v_gl_date']) { errors << "-<b> Voucher located on row #{voucher_ref}:</b> Column v_gl_date has an invalid date format (#{row['v_gl_date'].inspect}). <br>" }
          invoice_date = parse_excel_date(row['v_invoice_date']) { errors << "-<b> Voucher located on row #{voucher_ref}:</b> Column v_invoice_date has an invalid date format (#{row['v_invoice_date'].inspect}). <br>" }
          @voucher = Voucher.new(
            company_id: row['v_company_id'], supplier: @supplier, category: row['v_category'], business_unit: @business_unit, gl_date: gl_date, invoice_number: row['v_invoice_number'],
            invoice_date: invoice_date, payment_terms: @supplier&.terms.nil? ? 'Due' : @supplier.terms, currency: currency, exchange_rate: row['v_exchange_rate'], state: 'unpaid'
          )
          # as we have our voucher, we need to have ready the info to create its transaction
          @ledger_transaction = LedgerTransaction.new(company_id: @voucher.company_id, transaction_type: 'VOUCHER', transaction_date: @voucher.gl_date, currency: @voucher.currency, exchange_rate: @voucher.exchange_rate)
          # clean initial_ledger_entries for new transaction
          initial_ledger_entries = []
        end

        # collect all the necesary voucher items to link to its voucher
        if @voucher.present? && row['vi_gross_amount'].present?
          @gl_offset_account = if row['vi_gl_offset_company_override'].present? && row['vi_gl_offset_account_override'].present?
                                 LedgerCompanyAccount.get_by_identifier("#{row['vi_gl_offset_company_override']}.#{row['vi_gl_offset_account_override']}")
                               elsif @supplier&..present?
                                 LedgerCompanyAccount.where(company_id: @voucher.company_id, ledger_detail_account_id: @supplier.).first
                               end
          @voucher.voucher_items << VoucherItem.new(
            gross_amount: row['vi_gross_amount'], taxable_amount: row['vi_tax_type'].nil? || row['vi_tax_type'] == 'N/A' ? nil : row['vi_taxable_amount'],
            tax_amount: row['vi_tax_type'].nil? || row['vi_tax_type'] == 'N/A' ? nil : row['vi_tax_amount'], tax_type: row['vi_tax_type'].nil? ? 'N/A' : row['vi_tax_type'],
            tax_rate_id: if row['vi_tax_type'].nil? || row['vi_tax_type'] == 'N/A'
                           nil
                         else
                           (row['vi_tax_rate'].nil? ? nil : TaxRate.rates_for_voucher_entry.select { |r| r if r['label'] == row['vi_tax_rate'] }.reduce({}) { |k, v| k.merge(v) }['id'])
                         end,
            tax_rate_percentage: if row['vi_tax_type'].nil? || row['vi_tax_type'] == 'N/A'
                                   nil
                                 else
                                   (if row['vi_tax_rate'].present?
                                      TaxRate.rates_for_voucher_entry.select do |r|
                                        r if r['label'] == row['vi_tax_rate']
                                      end.reduce({}) { |k, v| k.merge(v) }['rate']
                                    else
                                      row['vi_tax_rate_%']
                                    end)
                                 end,
            tax_only: row['vi_tax_only'].nil? || row['vi_tax_only'] == 'N' ? false : true, due_date: row['vi_due_date']&.to_date, remark: row['vi_remark'], gl_offset_account: @gl_offset_account,
            business_unit: @business_unit, payee_id: row['vi_payee_override_id']
          )
        end

        if @voucher.present? && row['gld_company'].present?
          if row['gld_project_id'].present?
            ledger_detail_project = LedgerDetailProject.where(project_number: row['gld_project_id']).first
            errors << "-<b> Voucher located on row #{voucher_ref}:</b> Cannot find project for project id #{row['gld_project_id']}. You must create a project with this id before you use it for ledger entries <br>" if ledger_detail_project.nil?
          else
            ledger_detail_project = nil
          end
          business_unit_by_ledger_entry = BusinessUnit.where(number: row['gld_business_unit']).first
          errors << "-<b> Voucher located on row #{voucher_ref}:</b> GL Distribution business unit can't be blank. <br>" if business_unit_by_ledger_entry.nil?
          initial_ledger_entries << LedgerEntry.new(
            ledger_company_account: LedgerCompanyAccount.joins(:company, :ledger_detail_account).where(companies: { number: row['gld_company'] }, ledger_accounts: { number: row['gld_account'] }).first,
            ledger_detail_project: ledger_detail_project, amount: row['gld_amount'], business_unit: business_unit_by_ledger_entry, description: row['gld_remark']
          )
        end

        if @voucher.present? && row['atch_name'].present? && attachments_list.present?
          attachments_list.each do |atch|
            @voucher.uploads << atch if atch.attachment_name.to_s.downcase == row['atch_name'].to_s.downcase
          end
        end
      end

      next unless errors.empty? && @voucher.present?

      next unless row.map { |_k, v| v }.uniq.compact.empty? || vouchers_xlsx.last_row == (index + 1)

      @voucher.errors.full_messages.map { |e| errors << "-<b> Voucher located on row #{voucher_ref}:</b> #{e}. <br>" } unless @voucher.valid?
      v_total = @voucher.voucher_items.sum(&:gross_amount)
      amount_to_distribute = BigDecimal(0)
      @voucher.voucher_items.each do |vi|
        amount_to_distribute += case vi.tax_type
                                when 'V'
                                  (vi.gross_amount - vi.tax_amount)
                                when 'U'
                                  (vi.gross_amount + vi.tax_amount)
                                else
                                  vi.gross_amount
                                end
      end
      amount_to_distribute = amount_to_distribute.round(2)
      total_amount = initial_ledger_entries.sum(&:amount).round(2)

      if v_total.zero? && (initial_ledger_entries.length < 2)
        errors << "-<b> Voucher located on row #{voucher_ref}:</b> Voucher must have at least 2 ledger entries for a $0 voucher <br>"
      elsif initial_ledger_entries.empty?
        errors << "-<b> Voucher located on row #{voucher_ref}:</b> Voucher must have at least 1 ledger entries <br>"
      elsif initial_ledger_entries.any? { |e| e.amount.blank? || e..blank? }
        errors << "-<b> Voucher located on row #{voucher_ref}:</b> Voucher must specify an account and amount for each entry <br>"
      elsif total_amount != amount_to_distribute
        errors << "-<b> Voucher located on row #{voucher_ref}:</b> Total of entries must match amount to distribute <br>"
      else
        count_errors = 0
        initial_ledger_entries.each do |attrs|
           = attrs.
          business_unit = attrs.business_unit
          count_errors += 1 if .requires_business_unit? && (business_unit.nil? || (business_unit.company_id != .company_id))
        end
        errors << "-<b> Voucher located on row #{voucher_ref}:</b> Business unit must be present and it must belong to the same company as the selected GL account if using a profit and loss GL account <br>" if count_errors > 0
      end

      # add account entries and taxes entries to ledger entries by transaction
      if errors.empty?
         = if @supplier..present?
                                   LedgerCompanyAccount.(@voucher.company_id, @supplier..number)
                                 else
                                   LedgerCompanyAccount.(@voucher.company_id, TRADE_ACCOUNTS_PAYABLE_ACCOUNT)
                                 end

        accounts = {  => { amount: 0, business_unit: nil } }
        tax_accounts = {}

        @voucher.voucher_items.each do |vi|
          case vi[:tax_type]
          when 'U'
             = LedgerCompanyAccount.where(company_id: @voucher.company_id, ledger_detail_account_id: TaxRate.find_by(id: vi.tax_rate_id)&.).first
            if .nil?
              errors << "-<b> Voucher located on row #{voucher_ref}:</b> Cannot find use tax account for tax rate id #{vi.tax_rate_id} <br>"
            else
              tax_accounts[.id] = tax_accounts[.id].nil? ? -vi.tax_amount : (tax_accounts[.id] += -vi.tax_amount)
            end
          when 'V'
             = LedgerCompanyAccount.where(company_id: @voucher.company_id, ledger_detail_account_id: TaxRate.find_by(id: vi.tax_rate_id)&.).first
            if .nil?
              errors << "-<b> Voucher located on row #{voucher_ref}:</b> Cannot find output tax account for tax rate id #{vi.tax_rate_id} <br>"
            else
              tax_accounts[.id] = tax_accounts[.id].nil? ? vi.tax_amount : (tax_accounts[.id] += vi.tax_amount)
            end
          end
          if vi..present?
            accounts[vi.] ||= { amount: 0, business_unit: vi.business_unit }
            accounts[vi.][:amount] += -vi.gross_amount
          else
            accounts[][:amount] += -vi.gross_amount
          end
        end

        accounts.each do |, details|
          @ledger_transaction.ledger_entries << LedgerEntry.new(ledger_company_account: , currency: @voucher.currency, amount: details[:amount], business_unit: details[:business_unit]) unless details[:amount] == 0
        end
        tax_accounts.each do |, amount|
          @ledger_transaction.ledger_entries << LedgerEntry.new(ledger_company_account_id: , currency: @voucher.currency, amount: amount)
        end
        initial_ledger_entries.each do |ile|
          @ledger_transaction.ledger_entries << ile
        end
      end

      @voucher.ledger_transactions << @ledger_transaction
      vouchers << @voucher
    end

    if errors.any?
      flash.now[:error] = errors.uniq.join
      render :import_from_excel, status: :unprocessable_content
    else
      begin
        Voucher.transaction do
          voucher_ids = []
          vouchers.each do |v|
            v.ledger_transactions.each { |t| t.transaction_number = nil, t.exchange_rate = v.exchange_rate }
            v.save!
            v.intercompany_posting_assign_ledger_project
            voucher_ids << v.id
          end
          flash[:info] = 'Vouchers have been imported'
          redirect_to imported_vouchers_path(voucher_ids: voucher_ids)
        end
      rescue StandardError => e
        flash.now[:error] = "Unable to create ledger transaction, message : #{e}."
        render :import_from_excel, status: :unprocessable_content
      end
    end
  else
    flash.now[:error] = 'No file was uploaded'
    render :import_from_excel, status: :unprocessable_content
  end
end

#do_reversalObject

POST /vouchers/:id/do_reversal — execute the reversal entry on
params[:reversal_date]. Refuses double-reversals and re-renders
on missing/invalid dates.



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'app/controllers/vouchers_controller.rb', line 478

def do_reversal
  @voucher = Voucher.find(params[:id])

  if @voucher.reversal_date.present? && @voucher.voided?
    redirect_to @voucher, error: 'Voucher has already been reversed.'
  elsif params[:reversal_date].blank?
    flash.now[:error] = 'You must specify a reversal date.'
    render :reverse, status: :unprocessable_content
  else
    begin
      @voucher.reverse(params[:reversal_date])
      redirect_to @voucher, info: 'Voucher successfully reversed.'
    rescue StandardError => e
      flash.now[:error] = "Unable to reverse voucher, message : #{e}."
      render :reverse, status: :unprocessable_content
    end
  end
end

#download_sample_excelObject

GET /vouchers/download_sample_excel — serve the canonical bulk-
import template so users start from the right column layout.



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

def download_sample_excel
  file_path = Rails.root.join('data/import_templates/vouchers/voucher_creation_template.xlsx')
  send_file_accelerated(file_path, download: true, preserve_source: true)
end

#editObject

GET /vouchers/:id/edit — render the edit form.



79
80
81
# File 'app/controllers/vouchers_controller.rb', line 79

def edit
  @voucher = Voucher.find(params[:id])
end

#gl_distributionObject

GET /vouchers/:id/gl_distribution — render the form for splitting
the voucher's amount across GL accounts. Pre-seeds with one
blank entry; the form lets the user add rows up to the voucher's
total.



346
347
348
349
350
# File 'app/controllers/vouchers_controller.rb', line 346

def gl_distribution
  @voucher = Voucher.find(params[:id])
  @ledger_entries = [{ account_id: nil, account_ref: nil, remark: nil, project_id: nil, amount: nil, project_ref: nil, business_unit_id: nil }]
  set_gon_accounts_and_projects
end

#import_gl_from_csvObject

GET /vouchers/:id/import_gl_from_csv — render the per-voucher
GL-distribution upload form (alternative to typing the rows
directly into #gl_distribution).



427
428
429
# File 'app/controllers/vouchers_controller.rb', line 427

def import_gl_from_csv
  @voucher = Voucher.find(params[:id])
end

#importedObject

GET /vouchers/imported — landing page after Excel import,
showing the just-created vouchers.



337
338
339
340
# File 'app/controllers/vouchers_controller.rb', line 337

def imported
  vouchers_ids = params[:voucher_ids].presence || []
  @vouchers_just_imported = Voucher.where(id: vouchers_ids)
end

#indexObject

GET /vouchers — paginated, ransack-filtered list of supplier
vouchers. Sorts by integer-cast reference_number (desc) so a
voucher 100 sorts after voucher 99 rather than before.



37
38
39
40
# File 'app/controllers/vouchers_controller.rb', line 37

def index
  @q = Voucher.includes(:company, :supplier, :business_unit).ransack(params[:q])
  @pagy, @vouchers = pagy(@q.result.order(Arel.sql('reference_number::integer DESC')))
end

#newObject

GET /vouchers/new — render a new voucher form. Two flows:
spiff_order_id builds a commission-category voucher pre-filled
from a SPIFF-eligible order's enrolment; everything else builds
a blank voucher with one empty VoucherItem.



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

def new
  if params[:spiff_order_id]
    order = Order.find(params[:spiff_order_id])
    @voucher = Voucher.new(company: order.catalog.company,
                           supplier: order.spiff_rep,
                           category: 'commission',
                           gl_date: order.shipped_date.end_of_month,
                           invoice_date: order.shipped_date.end_of_month,
                           invoice_number: order.spiff_enrollment.spiff.invoice_number(order),
                           currency: order.currency,
                           order: order,
                           payment_terms: Customer::TERM_DUE)
    order.spiff_enrollment.spiff.eligible_rewards(order).each do |name, amount|
      @voucher.voucher_items.build(gross_amount: amount,
                                   tax_type: 'N/A',
                                   remark: "SO#{order.reference_number}-#{name}",
                                   due_date: order.shipped_date.end_of_month,
                                   payee: order.spiff_enrollment.payable_to == order.spiff_rep ? nil : order.spiff_enrollment.payable_to)
    end
  else
    @voucher = Voucher.new
    @voucher.supplier_id = params[:supplier_id] if params[:supplier_id].present?
    @voucher.voucher_items.build
  end
end

#post_gl_distributionObject

POST /vouchers/:id/post_gl_distribution — persist the GL
distribution. Validates the totals balance and that any
P&L-account entry has a matching same-company business unit
before delegating to Voucher#distribute_to_gl. The
voucher_logging category gets a single-account shortcut
(everything goes to a temporary holding account, distributed
later).



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'app/controllers/vouchers_controller.rb', line 359

def post_gl_distribution
  @voucher = Voucher.find(params[:id])
  @gl_account_id = params['gl_account_id']
  @gl_account_ref = params['gl_account_ref']
  @ledger_entries = []
  params['entries']&.each { |_k, v| @ledger_entries << v }
  total_amount = @ledger_entries.sum do |e|
    BigDecimal(e['amount'])
  rescue StandardError
    0
  end
  set_gon_accounts_and_projects

  if @voucher.category == 'voucher_logging'
    if @gl_account_id.blank?
      flash.now[:error] = 'You must specify the temporary G/L account'
      render :gl_distribution, status: :unprocessable_content
    else
      begin
        @voucher.distribute_to_gl(@gl_account_id)
        redirect_to @voucher
      rescue StandardError => e
        flash.now[:error] = "Unable to distrute to G/L, message: #{e}"
        render :gl_distribution, status: :unprocessable_content
      end
    end
  elsif @voucher.total.zero? && (@ledger_entries.length < 2)
    flash.now[:error] = 'You must have at least 2 ledger entries for a $0 voucher'
    render :gl_distribution, status: :unprocessable_content
  elsif @ledger_entries.empty?
    flash.now[:error] = 'You must have at least 1 ledger entries'
    render :gl_distribution, status: :unprocessable_content
  elsif @ledger_entries.any? { |e| e['amount'].blank? || e['account_id'].blank? }
    flash.now[:error] = 'You must specify an account and amount for each entry'
    render :gl_distribution, status: :unprocessable_content
  elsif total_amount != @voucher.amount_to_distribute
    flash.now[:error] = 'Total of entries must match amount to distribute'
    render :gl_distribution, status: :unprocessable_content
  else
    errors = 0
    @ledger_entries.each do |attrs|
       = LedgerCompanyAccount.find(attrs['account_id'])
      business_unit = begin
        BusinessUnit.find(attrs['business_unit_id'])
      rescue StandardError
        nil
      end
      errors += 1 if .requires_business_unit? && (business_unit.nil? || (business_unit.company_id != .company_id))
    end

    if errors > 0
      flash.now[:error] = 'Business unit must be present and it must belong to the same company as the selected GL account if using a profit and loss GL account'
      render :gl_distribution, status: :unprocessable_content
    else
      begin
        @voucher.distribute_to_gl(nil, @ledger_entries)
        redirect_to @voucher
      rescue StandardError => e
        flash.now[:error] = "Unable to distrute to G/L, message: #{e}"
        render :gl_distribution, status: :unprocessable_content
      end
    end
  end
end

#reverseObject

GET /vouchers/:id/reverse — render the reversal form (the user
picks the GL date for the reversing entry). Submission posts to
#do_reversal.



471
472
473
# File 'app/controllers/vouchers_controller.rb', line 471

def reverse
  @voucher = Voucher.find(params[:id])
end

#showObject

GET /vouchers/:id — render the voucher show page with all
related associations preloaded (Voucher.with_lazy_loads).



44
45
46
# File 'app/controllers/vouchers_controller.rb', line 44

def show
  @voucher = Voucher.with_lazy_loads.find(params[:id])
end

#tab_account_ledgerObject

GET /vouchers/:id/tab_account_ledger — turbo-frame body for the
GL view of this voucher's LedgerEntry postings.



541
542
543
544
545
546
547
548
# File 'app/controllers/vouchers_controller.rb', line 541

def 
  @voucher = Voucher.with_lazy_loads.find(params[:id])
  authorize!(:read, @voucher)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_attachmentsObject

GET /vouchers/:id/tab_attachments — turbo-frame body for the
attachments tab.



519
520
521
522
523
524
525
526
# File 'app/controllers/vouchers_controller.rb', line 519

def tab_attachments
  @voucher = Voucher.with_lazy_loads.find(params[:id])
  authorize!(:read, @voucher)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_paymentsObject

GET /vouchers/:id/tab_payments — turbo-frame body for the
outgoing-payments tab.



530
531
532
533
534
535
536
537
# File 'app/controllers/vouchers_controller.rb', line 530

def tab_payments
  @voucher = Voucher.with_lazy_loads.find(params[:id])
  authorize!(:read, @voucher)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#tab_voucher_detailsObject

GET /vouchers/:id/tab_voucher_details — turbo-frame body for the
voucher-details tab.



508
509
510
511
512
513
514
515
# File 'app/controllers/vouchers_controller.rb', line 508

def tab_voucher_details
  @voucher = Voucher.with_lazy_loads.find(params[:id])
  authorize!(:read, @voucher)
  respond_to do |format|
    format.html { render layout: should_render_layout? }
    format.turbo_stream
  end
end

#updateObject

PATCH/PUT /vouchers/:id — update voucher attributes (the GL
distribution is edited separately via #gl_distribution).



99
100
101
102
103
104
105
106
# File 'app/controllers/vouchers_controller.rb', line 99

def update
  @voucher = Voucher.find(params[:id])
  if @voucher.update(params[:voucher])
    redirect_to(@voucher, notice: 'Voucher was successfully updated.')
  else
    render action: 'edit', status: :unprocessable_content
  end
end

#upload_gl_from_csvObject

POST /vouchers/:id/upload_gl_from_csv — parse the uploaded CSV
via Voucher.build_gl_entries_from_csv and re-render the
gl-distribution form pre-populated with those entries so the
user can review before posting.



435
436
437
438
439
440
441
442
443
444
445
446
# File 'app/controllers/vouchers_controller.rb', line 435

def upload_gl_from_csv
  @voucher = Voucher.find(params[:id])
  ledger_csv = params.dig(:upload, :ledger_csv)
  if ledger_csv
    @ledger_entries = Voucher.build_gl_entries_from_csv(ledger_csv.tempfile.path.to_s)
    set_gon_accounts_and_projects
    render :gl_distribution
  else
    flash.now[:error] = 'No file was uploaded'
    render :import_gl_from_csv, status: :unprocessable_content
  end
end

#voidObject

POST /vouchers/:id/void — soft-void the voucher. Refused if any
linked outgoing payments are still active — those have to be
voided first to keep the AP balance consistent.



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'app/controllers/vouchers_controller.rb', line 451

def void
  @voucher = Voucher.find(params[:id])
  if @voucher.void
    redirect_to @voucher, info: 'Voucher was successfully voided.'
  else
    redirect_to @voucher, error: 'Unable to void voucher, ensure all linked payments have been voided first.'
  end
rescue ActiveRecord::RecordInvalid => e
  # Voiding reverses the voucher's ledger transactions on their original
  # GL dates. When that date sits in a closed accounting period the
  # reversing entry fails the period_not_closed validation and the whole
  # transition rolls back — but the raised RecordInvalid previously 500'd
  # (AppSignal #5586). Surface the accounting message so the user can
  # reopen the period or use the explicit Reverse flow with an open date.
  redirect_to @voucher, error: "Unable to void voucher: #{e.record.errors.full_messages.to_sentence}"
end