Class: MassSearch::VoucherCreatePaymentWorker

Inherits:
Object
  • Object
show all
Includes:
Sidekiq::Status::Worker, Sidekiq::Worker
Defined in:
app/workers/mass_search/voucher_create_payment_worker.rb

Overview

Creates OutgoingPayment records from selected Vouchers in the background.
action_params: { payments: { "1" => { bank_account_id:, voucher_ids:, ... } } }

Instance Method Summary collapse

Instance Method Details

#perform(args = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/workers/mass_search/voucher_create_payment_worker.rb', line 11

def perform(args = {})
  args   = args.with_indifferent_access
  search = Search.find(args[:search_id])
  CurrentScope.locale = args[:locale]&.to_sym || :en

  params       = (args[:action_params] || {}).with_indifferent_access
  dash_path    = UrlHelper.instance.accounts_payable_dashboard_path
  new_payments = []

  OutgoingPayment.transaction do
    (params[:payments] || {}).each do |_num, attrs|
      attrs        = attrs.with_indifferent_access
      voucher_ids  = attrs.delete(:voucher_ids).to_s
      pt           = OutgoingPayment.new(attrs)
      voucher_ids.gsub(' ', '').split(',').each do |vid|
        v = Voucher.find(vid)
        v.voucher_items.where(state: %w[approved partially_paid]).each do |vi|
          pt.outgoing_payment_items.build(voucher_item: vi, amount: vi.balance)
        end
      end
      pt.save!
      pt.payments_applied!
      new_payments << pt
    end
  end

  refs = new_payments.map { |pt| "#{pt.reference_number} (##{pt.id})" }.join(', ')
  store info_message: "New payments created: #{refs}.",
        redirect_to:  dash_path
rescue ActiveRecord::RecordInvalid, StandardError => e
  store error_message: e.message,
        redirect_to:   dash_path
end