class TimesheetForceCommitsController

File

timesheet_force_commits_controller.rb

(C)

Hipposoft 2013

Purpose

Allow administrators to bulk-commit timesheets forcibly, to help deal with users who never manually commit them.


31-Jul-2013 (ADH): Created.

Public Instance Methods

create() click to toggle source
# File app/controllers/timesheet_force_commits_controller.rb, line 27
def create

  # Unless we get here by someone hacking around with a web page,
  # the only explanation for a submitted form but a re-counted
  # timesheet count of zero would be that users submitted things
  # in other browser sessions while the admin was thinking about
  # filling in the submitted form.

  if ( @timesheets.count.zero? )
    flash[ :error ] = "No action taken - while you were using the form, all timesheets were committed by their users anyway."
    redirect_to( home_path() ) and return
  end

  # Get a valid, parsed set of Dates into @earliest/@latest
  # - or nil.

  form_data = params[ :timesheet_force_commit ]

  # The "to_date" call may cause date parsing exceptions.

  begin
    @object.earliest = @object.to_date( form_data[ :earliest ] )
    @object.latest   = @object.to_date( form_data[ :latest   ] )

  rescue => error
    complain( error ) and return

  end

  # Pick earliest/latest instead of 'nil' and bounds check dates.

  @object.earliest = @object.earliest_limit if ( @object.earliest.nil? || @object.earliest < @object.earliest_limit )
  @object.latest   = @object.latest_limit   if ( @object.latest.nil?   || @object.latest   > @object.latest_limit   )

  # Update timesheets.

  begin

    Timesheet.transaction do

      # Construct an ActiveRecord::Relation instance with the
      # appropriate constraints, then iterate over it in batches
      # using "find_each".
      #
      # Remember that "@object.latest" is an inclusive timesheet
      # end date and everything runs in UTC.
      #
      # We can't use "update_all", even though it'd be fast, as
      # it doesn't trigger callbacks or validations and both are
      # important (particularly callbacks).

      timesheets = Timesheet.where( :committed => false )
      timesheets = timesheets.where( 'start_day_cache >= ?', @object.earliest )
      timesheets = timesheets.where( 'start_day_cache <= ?', @object.latest - 6.days )

      timesheets.find_each do | timesheet |
        timesheet.committed = true
        timesheet.save!
      end
    end

  rescue => error
    complain( error ) and return

  end

  flash[ :notice ] = "Timesheets committed successfully."
  redirect_to( home_path() )
end
new() click to toggle source
# File app/controllers/timesheet_force_commits_controller.rb, line 20
def new
  unless ( @timesheets.count.zero? )
    @object.earliest = @object.earliest_limit
    @object.latest   = @object.latest_limit
  end
end