1
2
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
51
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class Invoice < ActiveRecord::Base
  belongs_to :created_operator, :class_name=>"Person"
  belongs_to :person
  belongs_to :saved_operator, :class_name=>"Person"
  belongs_to :created_operator, :class_name=>"Person"
  has_many :invoice_item_groups
  has_many :invoice_items, :through=>:invoice_item_groups
  has_many :activities, :through=>:invoice_item_groups, :source=>:activities
  has_many :payments
  has_many :comments
  before_save :calc_or_not
  
  attr_accessor :speed_save #When true, skip calc on save

  # Invoice Statuses
  # 0 = Normal
  # 1 = Refunded
  # 2 = Cancelled
  
  def activity_summary
    activity_titles = self.invoice_items.collect {|ii|
      "[#{ii.activity.invoiceprefix}]" if ii.activity
    }
    activity_titles.delete(nil)
    if activity_titles.length > 0
      return "#{activity_titles.join(",")}"
    else
      return ""
    end
  end

  def to_s
    "Items: #{self.itemcount} Discount total:#{self.discount_total} Total: #{self.total} Paid: #{self.paid} Credited: #{self.credited} Balance: #{self.balance}"
  end

  def calc_or_not
    unless self.speed_save
      self._calc
    end
  end

  def calc()
      self._calc
      self.save
  end

  def _calc()
    self.itemcount = 0
    self.discount_total = 0
    self.total = 0
    self.paid = 0
    self.credited = 0
    self.balance = 0

    self.invoice_item_groups.each do |g|
      if g.invoice_items.length == 0
        g.destroy
      else
        g.calc()
        self.itemcount += g.itemcount
        self.total += g.total
        self.discount_total += g.discount_total
        self.credited += g.credited
      end
    end

    if self.fixedtotal and self.fixedtotal > 0
      self.total = self.fixedtotal
      self.discount_total = 0
      self.credited = 0
    end

    self.payments.each do |p|
      self.paid += p.amount if p.apply
    end

    self.balance = self.total - self.discount_total - self.paid
  end
  
  def applyPayment(operator, amount, source, info, cardTransaction=nil)
    p = Payment.create(:operator => operator,
      :date=>Time.now(),
      :person=>self.person,
      :amount=>amount,
      :source=>source,
      :invoice=>self,
      :info => info,
      :care_transaction =>cardTransaction)
    self.paid += amount
    self.calc()
    return p
  end
  
end