2021-09-07 10:36:09 +02:00
|
|
|
class DossierTransfer < ApplicationRecord
|
2023-01-31 14:36:51 +01:00
|
|
|
include EmailSanitizableConcern
|
2021-09-07 10:36:09 +02:00
|
|
|
has_many :dossiers, dependent: :nullify
|
|
|
|
|
|
|
|
EXPIRATION_LIMIT = 2.weeks
|
|
|
|
|
2022-08-02 12:37:29 +02:00
|
|
|
validates :email, format: { with: Devise.email_regexp }
|
2023-01-31 14:36:51 +01:00
|
|
|
before_validation -> { sanitize_email(:email) }
|
2022-08-02 12:37:29 +02:00
|
|
|
|
2021-09-07 10:36:09 +02:00
|
|
|
scope :pending, -> { where('created_at > ?', (Time.zone.now - EXPIRATION_LIMIT)) }
|
|
|
|
scope :stale, -> { where('created_at < ?', (Time.zone.now - EXPIRATION_LIMIT)) }
|
2022-03-09 10:27:43 +01:00
|
|
|
scope :with_dossiers, -> { joins(:dossiers).merge(Dossier.visible_by_user) }
|
2023-01-31 14:36:51 +01:00
|
|
|
scope :for_email, -> (email) { includes(dossiers: :user).with_dossiers.where(email: email) }
|
2021-09-07 10:36:09 +02:00
|
|
|
|
|
|
|
after_create_commit :send_notification
|
|
|
|
|
|
|
|
def self.initiate(email, dossiers)
|
|
|
|
create(email: email, dossiers: dossiers)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.accept(id, current_user)
|
|
|
|
transfer = pending.find_by(id: id, email: current_user.email)
|
|
|
|
|
|
|
|
if transfer && transfer.dossiers.present?
|
|
|
|
Invite
|
|
|
|
.where(dossier: transfer.dossiers, email: transfer.email)
|
|
|
|
.destroy_all
|
|
|
|
DossierTransferLog.create(transfer.dossiers.map do |dossier|
|
|
|
|
{
|
|
|
|
dossier: dossier,
|
|
|
|
from: dossier.user.email,
|
|
|
|
to: transfer.email
|
|
|
|
}
|
|
|
|
end)
|
|
|
|
transfer.dossiers.update_all(user_id: current_user.id)
|
2021-10-22 10:55:10 +02:00
|
|
|
transfer.destroy_and_nullify
|
2021-09-07 10:36:09 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def user_locale
|
|
|
|
User.find_by(email: email)&.locale || I18n.default_locale
|
|
|
|
end
|
|
|
|
|
2021-10-21 12:19:40 +02:00
|
|
|
def destroy_and_nullify
|
|
|
|
transaction do
|
|
|
|
# Rails cascading is not working with default scopes. Doing nullify cascade manually.
|
2022-03-09 10:27:43 +01:00
|
|
|
dossiers.update_all(dossier_transfer_id: nil)
|
2021-10-21 12:19:40 +02:00
|
|
|
destroy
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.destroy_stale
|
|
|
|
transaction do
|
|
|
|
# Rails cascading is not working with default scopes. Doing nullify cascade manually.
|
2022-03-09 10:27:43 +01:00
|
|
|
Dossier.where(transfer: stale).update_all(dossier_transfer_id: nil)
|
2021-10-21 12:19:40 +02:00
|
|
|
stale.destroy_all
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-09-07 10:36:09 +02:00
|
|
|
private
|
|
|
|
|
|
|
|
def send_notification
|
|
|
|
DossierMailer.notify_transfer(self).deliver_later
|
|
|
|
end
|
|
|
|
end
|