1 class PartItemRga < ActiveRecord::Base
 2   has_one :part_order_line_item
 3   delegate :dealer, :to => :part_order_line_item
 4   delegate :boat_serial_number, :to => :part_order_line_item
 5 
 6   is_an_rga_state_machine
 7 
 8   # END STATES PORTION
 9 
10   validates_presence_of :return_due_date
11   validates_inclusion_of :return_due_date,
12                          :if => Proc.new{ |s| !s.unchanged_due_date},
13                          :allow_nil => true,
14                          :in => Range.new(Time.now,Time.now + 10.years), 
15                          :message => "must not be in the past"
16 
17   validates_numericality_of :return_quantity, 
18                               :allow_nil => true
19   attr_accessor :unchanged_due_date  # This is an internal flag that is only set to true for existing records
20                                      #  that are saved with an unchanged return due date. It's used so past-due items can be modified
21 
22  
23   def wait_days
24     ((return_due_date - Time.now) / 1.day).round
25   end
26 
27   def for_transaction_id
28     part_order_line_item.transaction_id rescue ''
29   end
30   #
31   #the reason for this overloading is so that one may set a due date with an integer
32   # Also, to allow past-due items to be modified, this field is not saved if the
33   # the current value is the same as the new value
34   def return_due_date=(due_date)
35     if due_date
36       begin
37         due_date = DateTime.parse("#{due_date}").to_time
38       rescue
39         wait_days = due_date.to_i.days
40         wait_until_date = Time.now + wait_days
41         due_date = Time.parse(wait_until_date.beginning_of_day.to_s)
42       end
43     end
44 
45     if due_date == return_due_date
46       self.unchanged_due_date = true
47     end
48     super due_date.to_s(:db)
49   end
50 
51 end