demarches-normaliennes/app/models/commentaire.rb

84 lines
2.1 KiB
Ruby
Raw Normal View History

2018-03-06 13:44:29 +01:00
class Commentaire < ApplicationRecord
2019-09-17 10:16:52 +02:00
self.ignored_columns = ['file', 'piece_justificative_id']
2019-08-28 16:14:20 +02:00
belongs_to :dossier, inverse_of: :commentaires, touch: true
belongs_to :user
belongs_to :instructeur
validate :messagerie_available?, on: :create
has_one_attached :piece_jointe
2018-03-06 13:44:29 +01:00
validates :body, presence: { message: "Votre message ne peut être vide" }
2017-10-30 16:07:02 +01:00
default_scope { order(created_at: :asc) }
scope :updated_since?, -> (date) { where('commentaires.updated_at > ?', date) }
after_create :notify
2016-12-26 11:08:53 +01:00
def email
if user
user.email
elsif instructeur
instructeur.email
else
read_attribute(:email)
end
end
def header
"#{redacted_email}, #{I18n.l(created_at, format: '%d %b %Y %H:%M')}"
end
def redacted_email
if instructeur.present?
instructeur.email.split('@').first
else
email
end
end
2016-12-26 11:08:53 +01:00
def sent_by_system?
[CONTACT_EMAIL, OLD_CONTACT_EMAIL].include?(email) &&
user.nil? && instructeur.nil?
end
def sent_by?(someone)
email == someone.email
end
def file_url
2019-08-14 14:00:52 +02:00
if piece_jointe.attached? && piece_jointe.virus_scanner.safe?
Rails.application.routes.url_helpers.url_for(piece_jointe)
end
end
2016-12-26 11:08:53 +01:00
private
def notify
dossier_user_email = dossier.user.email
2018-10-10 09:23:08 +02:00
invited_users_emails = dossier.invites.pluck(:email).to_a
2018-03-06 12:03:32 +01:00
# - If the email is the contact email, the commentaire is a copy
# of an automated notification email we sent to a user, so do nothing.
# - If a user or an invited user posted a commentaire, do nothing,
# the notification system will properly
# - Otherwise, a instructeur posted a commentaire, we need to notify the user
2018-05-31 15:45:25 +02:00
if !email.in?([CONTACT_EMAIL, dossier_user_email, *invited_users_emails])
notify_user
end
2016-12-26 11:08:53 +01:00
end
def notify_user
DossierMailer.notify_new_answer(dossier).deliver_later
end
2017-11-08 16:37:04 +01:00
def messagerie_available?
return if sent_by_system?
if dossier.present? && !dossier.messagerie_available?
errors.add(:dossier, "Il nest pas possible denvoyer un message sur un dossier archivé ou en brouillon")
end
end
2015-08-10 11:05:06 +02:00
end