demarches-normaliennes/app/models/commentaire.rb

54 lines
1.6 KiB
Ruby
Raw Normal View History

2018-03-06 13:44:29 +01:00
class Commentaire < ApplicationRecord
belongs_to :dossier, touch: true
2016-11-14 18:00:26 +01:00
belongs_to :champ
belongs_to :piece_justificative
2017-10-30 16:07:02 +01:00
mount_uploader :file, CommentaireFileUploader
2017-11-08 16:38:07 +01:00
validates :file, file_size: { maximum: 20.megabytes, message: "La taille du fichier doit être inférieure à 20 Mo" }
2017-11-08 16:37:04 +01:00
validate :is_virus_free?
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 header
2018-01-30 15:16:05 +01:00
"#{email}, #{I18n.l(created_at.localtime, format: '%d %b %Y %H:%M')}"
end
2016-12-26 11:08:53 +01:00
def file_url
if Features.remote_storage
RemoteDownloader.new(file.path).url
else
file.url
end
end
2016-12-26 11:08:53 +01:00
private
def notify
dossier_user_email = dossier.user.email
invited_users_emails = dossier.invites_user.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 gestionnaire posted a commentaire, we need to notify the user
if !email.in?([I18n.t("dynamics.contact_email"), dossier_user_email, *invited_users_emails])
notify_user
end
2016-12-26 11:08:53 +01:00
end
def notify_user
NotificationMailer.new_answer(dossier).deliver_now!
end
2017-11-08 16:37:04 +01:00
def is_virus_free?
if file.present? && file_changed? && !ClamavService.safe_file?(file.path)
errors.add(:file, "Virus détecté dans le fichier joint, merci de changer de fichier")
end
end
2015-08-10 11:05:06 +02:00
end