|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +class Feedback < ApplicationRecord |
| 4 | + belongs_to :school_project |
| 5 | + validates :content, presence: true |
| 6 | + validates :user_id, presence: true |
| 7 | + validate :user_has_the_school_owner_or_school_teacher_role_for_the_school |
| 8 | + validate :parent_project_belongs_to_lesson |
| 9 | + validate :parent_project_belongs_to_school_class |
| 10 | + validate :user_is_the_class_teacher_for_the_school_project |
| 11 | + |
| 12 | + has_paper_trail( |
| 13 | + meta: { |
| 14 | + meta_school_project_id: ->(f) { f.school_project&.id }, |
| 15 | + meta_school_id: ->(f) { f.school_project&.school_id } |
| 16 | + } |
| 17 | + ) |
| 18 | + |
| 19 | + private |
| 20 | + |
| 21 | + def user_has_the_school_owner_or_school_teacher_role_for_the_school |
| 22 | + school = school_project&.school |
| 23 | + return unless user_id_changed? && errors.blank? && school |
| 24 | + |
| 25 | + user = User.new(id: user_id) |
| 26 | + return if user.school_owner?(school) |
| 27 | + return if user.school_teacher?(school) |
| 28 | + |
| 29 | + msg = "'#{user_id}' does not have the 'school-owner' or 'school-teacher' role for organisation '#{school.id}'" |
| 30 | + errors.add(:user, msg) |
| 31 | + end |
| 32 | + |
| 33 | + def parent_project_belongs_to_lesson |
| 34 | + parent_project = school_project&.project&.parent |
| 35 | + return if parent_project&.lesson_id.present? |
| 36 | + |
| 37 | + msg = "Parent project '#{parent_project&.id}' does not belong to a 'lesson'" |
| 38 | + errors.add(:user, msg) |
| 39 | + end |
| 40 | + |
| 41 | + def parent_project_belongs_to_school_class |
| 42 | + parent_project = school_project&.project&.parent |
| 43 | + return if parent_project&.lesson&.school_class_id.present? |
| 44 | + |
| 45 | + msg = "Parent project '#{parent_project&.id}' does not belong to a 'school-class'" |
| 46 | + errors.add(:user, msg) |
| 47 | + end |
| 48 | + |
| 49 | + def user_is_the_class_teacher_for_the_school_project |
| 50 | + return if !school_project || school_class&.teacher_ids&.include?(user_id) |
| 51 | + |
| 52 | + errors.add(:user, "'#{user_id}' is not the 'school-teacher' for school_project '#{school_project.id}'") |
| 53 | + end |
| 54 | + |
| 55 | + def school_class |
| 56 | + school_project&.project&.parent&.lesson&.school_class |
| 57 | + end |
| 58 | +end |
0 commit comments