1namespace :epets do
 
2  namespace :petitions do
 
3    desc "Add a task to the queue to close petitions at midnight"
 
4    task :close => :environment do
 
5      Task.run("epets:petitions:close") do
 
6        time = Date.tomorrow.beginning_of_day
 
7        ClosePetitionsJob.set(wait_until: time).perform_later(time.iso8601)
 
8      end
 
 9    end
 
 
11    desc "Add a task to the queue to validate petition counts"
 
12    task :count => :environment do
 
13      Task.run("epets:petitions:count") do
 
14        PetitionCountJob.perform_later
 
15      end
 
16    end
 
 
18    desc "Add a task to the queue to mark petitions as debated at midnight"
 
19    task :debated => :environment do
 
20      Task.run("epets:petitions:debated") do
 
21        date = Date.tomorrow
 
22        DebatedPetitionsJob.set(wait_until: date.beginning_of_day).perform_later(date.iso8601)
 
23      end
 
24    end
 
 
26    desc "Add a task to the queue to update petition statistics"
 
27    task :update_statistics => :environment do
 
28      Task.run("epets:petitions:update_statistics", 12.hours) do
 
29        EnqueuePetitionStatisticsUpdatesJob.perform_later(24.hours.ago.iso8601)
 
30      end
 
31    end
 
 
33    desc "Backfill moderation lag"
 
34    task :backfill_moderation_lag => :environment do
 
35      %w[petitions archived_petitions].each do |table_name|
 
36        klass = Class.new(ActiveRecord::Base) do
 
37          self.table_name = table_name
 
 
39          def self.default_scope
 
40            where(moderation_lag: nil).where.not(moderation_threshold_reached_at: nil)
 
41          end
 
 
43          def moderated?
 
44            if respond_to?(:open_at)
 
45              open_at? || rejected_at?
 
46            else
 
47              opened_at? || rejected_at?
 
48            end
 
49          end
 
 
51          def moderated_at
 
52            if respond_to?(:open_at)
 
53              [open_at, rejected_at].compact.min
 
54            else
 
55              [opened_at, rejected_at].compact.min
 
56            end
 
57          end
 
 
59          def moderation_lag
 
60            moderated_at.to_date - moderation_threshold_reached_at.to_date
 
61          end
 
 
63          def update_moderation_lag
 
64            update_column(:moderation_lag, moderation_lag)
 
65          end
 
66        end
 
 
68        klass.find_each do |petition|
 
69          next unless petition.moderated?
 
 
71          petition.update_column(:moderation_lag, petition.moderation_lag)
 
72        end
 
73      end
 
74    end
 
75  end
 
76end