jeudi 28 avril 2016

Summing an array of numbers in ruby and extracting time over 40 hours

I wrote a payroll type app which takes a clock_event and has a punch_in and punch_out field. In a the clock_event class I have a method that takes the employee, sums their total hours and exports to CSV. This gives total hours for the employee, and then a total sum of their total_hours which is a method in the class calculated on the fly.

Here is my code:

clock_event.rb

 def total_hours
    self.clock_out.to_i - self.clock_in.to_i
  end

  def self.to_csv(records = [], options = {})
          CSV.generate(options) do |csv|
            csv << ["Employee", "Clock-In", "Clock-Out", "Station", "Comment", "Total Shift Hours"]
              records.each do |ce|
              csv << [ce.user.try(:full_name), ce.formatted_clock_in, ce.formatted_clock_out, ce.station.try(:station_name), ce.comment, TimeFormatter.format_time(ce.total_hours)]
            end
           records.map(&:user).uniq.each do |user|
             csv << ["Total Hours for: #{user.full_name}"]
             csv << [TimeFormatter.format_time(records.select{ |r| r.user == user}.sum(&:total_hours))]
           end

            csv << ["Total Payroll Hours"]
            csv << [TimeFormatter.format_time(records.sum(&:total_hours))]
          end
        end
    end

This method works and exports a CSV with all total time entries for each day then a sum of the hours at the bottom of the CSV file.

Here's my problem...

I can sum no problem, but I need to show the following:

1.) Total Sum of hours (done) 2.) Any hours over 40 hours I need to pull that amount into another field in the CSV file. So if an employee hits 40 hours it will show the 40 hours in one field then show the remaining ours as overtime right next to it.

I know how to sum the hours but am unsure as to how to extra the hours over 40 into another field into the CSV.

I'm sure there's a Ruby way to do it but I'm not certain on how this would work.

Any help would be greatly appreciated. If you need more code or context, please let me know.

Aucun commentaire:

Enregistrer un commentaire