chexton
1/4/2013 - 10:29 PM

jobs.rb

jobs.rb

  def schedule_evaluation_with_communications(communications)
    return if person.nil? || person.unsubscribed?

    communications = Array(communications)
    
    update_trigger_log!(communications.map(&:id))

    c_req_opt_in, c_wo_opt_in = communications.partition(&:requires_opt_in?)
    send_opt_in_email = !!extras.with_indifferent_access[:opt_in] || !c_req_opt_in.empty?
    
    communications_to_queue = if !person.opted_in? && send_opt_in_email
      CommunicationEvaluationJob.new(company.opt_in_communication.id, id).perform 
      c_wo_opt_in
    else
      communications
    end

    communications_to_queue.each do |c|
      # Here it saves a job for e.g. 2 days time and includes the communication ID and the event occurrence ID
      Delayed::Job.enqueue CommunicationEvaluationJob.new(c.id, id), run_at: c.delivery_time_for_event_occurrence(self), queue: 'email', priority: 1
    end

    BoocxQueueEvaluationWorker.perform_async(event.company_id, id, communications_to_queue.map(&:id)) unless Rails.env.test?
  end
  
  class CommunicationEvaluationJob < Struct.new(:communication_id, :event_occurrence_id)
  def perform
    communication = Communication.find(communication_id)
    event_occurrence = EventOccurrence.find(event_occurrence_id)

    event_occurrence.update_trigger_log!
    # IT runs this method below
    schedule_evaluation(communication, event_occurrence)
  end

  def error(job, exception)
    Airbrake.notify(exception)
  end

  private
  def schedule_evaluation(communication, event_occurrence)
    person    = event_occurrence && event_occurrence.person
    variation = communication.selected_variation
    
    # Here it evaluates conditions and sends an email (cominbing the variables of the event occurrence)
    communication.evaluate_and_send_communication(variation, event_occurrence)
  end
end