I'm trying to design a reporting system that notifies administrators about user's messaging rate and response time for a customer service app.
I have a tenant class that looks like this:
class Tenant < ApplicationRecord
has_many :users
has_many :chat_messages
end
And a user class that looks like this:
class User < ApplicationRecord
belongs_to :organization
has_many :authored_conversations, class_name: 'Conversation', :as => :author
has_many :chat_messages, as: :user, dependent: :nullify
has_many :received_conversations, :as => :receiver, class_name: 'Conversation'
def conversations
authored_conversations + received_conversations
end
def response_time
# calculate the user's average response time
end
end
Right now we have to manually run a rake task to take care of business. But automating the process would be so much better.
So designed a ReportGenerator class like this:
class ReportGenerator
def initialize(org_id)
@organization = Organization.find org_id
end
def generate_report
report = Report.generate(@organization)
ReportMailer.new_report(report).deliver_later
end
end
I also set my mailer like so:
class ReportMailer < ApplicationMailer
default from: ENV["DEFAULT_MAILER_FROM"],
template_path: 'mailers/chat_message_mailer'
def new_message(report, recipient)
@report = report
@recipient = recipient
@subject = "Monthly report for #{report.created_at}"
@greeting = "Hi, #{recipient.name}"
@body = @report.body
mail(to: @recipient.email, subject: @subject)
end
end
However, I'm struggling to set up the schedule I found this example But I believe doing it that way can get out of hand very quickly. I also want to know, What is the best approach? Executing a background job or a rake task?