Class: Invoicing::PatchDiscount

Inherits:
BaseService
  • Object
show all
Defined in:
app/services/invoicing/patch_discount.rb

Instance Method Summary collapse

Instance Method Details

#process(invoices = nil) ⇒ Object



3
4
5
6
7
8
9
10
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
44
45
46
47
48
49
50
# File 'app/services/invoicing/patch_discount.rb', line 3

def process(invoices=nil)
  invoices ||= Invoice.
                where("exists(select 1 from line_discounts ldi inner join line_items lii on lii.resource_id = invoices.id and lii.resource_type = 'Invoice' and lii.id = ldi.line_item_id inner join discounts di on di.id = ldi.discount_id and di.itemizable_type <> 'Invoice')").
                where("not exists(select 1 from discounts di where di.itemizable_type = 'Invoice' and di.itemizable_id = invoices.id)")
  invoices = [invoices].flatten
  total_size  = invoices.size
  unprocessables = {}

  invoices.flatten.each_with_index do |invoice,index|
    puts "[#{index+1}/#{total_size}] Invoice id #{invoice.id}"
    if invoice.discounts.present? #Already has its own discount
      puts "! Invoice #{invoice.id} already has discounts"
      next
    end

    begin
      Invoice.transaction do
        discounts = invoice.line_discounts.map(&:discount).uniq
        puts " - Found #{discounts.size} discounts"
        discount_map = {}
        if discounts.present?
          discounts.each do |discount|
            discount_copy = discount.dup
            discount_copy.itemizable_id = invoice.id
            discount_copy.itemizable_type = 'Invoice'
            discount_copy.save!
            puts " - Discount #{discount.id} duplicated and assigned to invoice as discount id #{discount_copy.id}"
            discount_map[discount.id] = discount_copy.id
          end
          # Remapping line discounts
          invoice.line_discounts.each do |line_discount|
            line_discount.discount_id = discount_map[line_discount.discount_id]
            puts " - Line Discount #{line_discount.id} has been remapped to discount id #{line_discount.discount_id}"
            line_discount.save!
          end # End line discount processing
        end # End discount processing
      end # End Invoice Transaction
    rescue StandardError => exc
      unprocessables[invoice.id] = exc.to_s
    end
    puts "Unprocessables: #{unprocessables.keys.size}"
    unprocessables.each do |invoice_id, reason|
      puts " ! #{invoice_id} : #{reason}"
    end
    puts "#{unprocessables.keys.join(',')}"
  end
  "Processed #{total_size}, converted #{total_size - unprocessables.keys.size}, failed #{unprocessables.keys.size}.  Reason #{unprocessables.values.join(',')}"
end