|
| 1 | +class DeletionRequest < ApplicationRecord |
| 2 | + belongs_to :user |
| 3 | + belongs_to :admin_approved_by, class_name: "User", optional: true |
| 4 | + |
| 5 | + enum :status, { |
| 6 | + pending: 0, |
| 7 | + approved: 1, |
| 8 | + cancelled: 2, |
| 9 | + completed: 3 |
| 10 | + } |
| 11 | + |
| 12 | + validates :requested_at, presence: true |
| 13 | + validate :user_not_banned_from_deletion, on: :create |
| 14 | + |
| 15 | + scope :active, -> { where(status: [ :pending, :approved ]) } |
| 16 | + scope :ready_for_deletion, -> { approved.where("scheduled_deletion_at <= ?", Time.current) } |
| 17 | + |
| 18 | + def self.create_for_user!(user) |
| 19 | + create!( |
| 20 | + user: user, |
| 21 | + requested_at: Time.current, |
| 22 | + status: :pending |
| 23 | + ) |
| 24 | + end |
| 25 | + |
| 26 | + def approve!(admin) |
| 27 | + update!( |
| 28 | + status: :approved, |
| 29 | + admin_approved_by: admin, |
| 30 | + admin_approved_at: Time.current, |
| 31 | + scheduled_deletion_at: Time.current + 30.days # grace period, if shit changes, change this |
| 32 | + ) |
| 33 | + end |
| 34 | + |
| 35 | + def cancel! |
| 36 | + update!( |
| 37 | + status: :cancelled, |
| 38 | + cancelled_at: Time.current |
| 39 | + ) |
| 40 | + end |
| 41 | + |
| 42 | + def complete! |
| 43 | + update!( |
| 44 | + status: :completed, |
| 45 | + completed_at: Time.current |
| 46 | + ) |
| 47 | + end |
| 48 | + |
| 49 | + def days_until_deletion |
| 50 | + return nil unless scheduled_deletion_at.present? |
| 51 | + [ (scheduled_deletion_at.to_date - Date.current).to_i, 0 ].max |
| 52 | + end |
| 53 | + |
| 54 | + def can_be_cancelled? |
| 55 | + pending? || approved? |
| 56 | + end |
| 57 | + |
| 58 | + private |
| 59 | + |
| 60 | + def user_not_banned_from_deletion |
| 61 | + return unless user.present? |
| 62 | + |
| 63 | + if user.red? |
| 64 | + last_audit = user.trust_level_audit_logs.order(created_at: :desc).first |
| 65 | + if last_audit && last_audit.created_at > 365.days.ago |
| 66 | + errors.add(:base, "You can not request data deletion due to a recent ban") |
| 67 | + end |
| 68 | + end |
| 69 | + end |
| 70 | +end |
0 commit comments