2012-10-26 10:33:39 +00:00
module JamRuby
class Invitation < ActiveRecord :: Base
2016-04-06 02:23:15 +00:00
INVITATION_NOT_TEACHER_VALIDATION_ERROR = " Lessons can only sent invitations to teachers "
2012-10-26 10:33:39 +00:00
FRIENDSHIP_REQUIRED_VALIDATION_ERROR = " You can only invite friends "
2012-10-27 19:22:05 +00:00
MEMBERSHIP_REQUIRED_OF_MUSIC_SESSION = " You must be a member of the music session to send invitations on behalf of it "
2012-11-30 15:23:43 +00:00
JOIN_REQUEST_IS_NOT_FOR_RECEIVER_AND_MUSIC_SESSION = " You can only associate a join request with an invitation if that join request comes from the invited user and if it's for the same music session "
2012-10-26 10:33:39 +00:00
self . primary_key = 'id'
belongs_to :sender , :inverse_of = > :sent_invitations , :class_name = > " JamRuby::User " , :foreign_key = > " sender_id "
belongs_to :receiver , :inverse_of = > :received_invitations , :class_name = > " JamRuby::User " , :foreign_key = > " receiver_id "
2014-05-06 13:34:38 +00:00
belongs_to :music_session , :inverse_of = > :invitations , :class_name = > " JamRuby::MusicSession " , :foreign_key = > " music_session_id "
2012-11-30 15:23:43 +00:00
belongs_to :join_request , :inverse_of = > :invitations , :class_name = > " JamRuby::JoinRequest "
2012-10-26 10:33:39 +00:00
validates :sender , :presence = > true
validates :receiver , :presence = > true
validates :music_session , :presence = > true
2016-08-03 01:46:15 +00:00
2016-04-06 02:23:15 +00:00
validate :require_sender_in_music_session , :require_are_friends_or_requested_to_join_or_teacher
2012-10-26 10:33:39 +00:00
private
2012-10-27 19:22:05 +00:00
def require_sender_in_music_session
2014-06-17 19:10:24 +00:00
if music_session && ! music_session . part_of_session? ( sender )
2016-08-03 01:46:15 +00:00
errors . add ( :music_session , MEMBERSHIP_REQUIRED_OF_MUSIC_SESSION )
2012-10-27 19:22:05 +00:00
end
end
2016-04-06 02:23:15 +00:00
def require_are_friends_or_requested_to_join_or_teacher
2012-11-30 15:23:43 +00:00
if ! join_request . nil? && ( join_request . user != receiver || join_request . music_session != music_session )
2016-08-03 01:46:15 +00:00
errors . add ( :join_request , JOIN_REQUEST_IS_NOT_FOR_RECEIVER_AND_MUSIC_SESSION )
elsif music_session . is_lesson?
if ( receiver != music_session . lesson_session . teacher )
errors . add ( :receiver , INVITATION_NOT_TEACHER_VALIDATION_ERROR )
end
2012-11-30 15:23:43 +00:00
elsif join_request . nil?
2016-08-03 01:46:15 +00:00
# we only check for friendship requirement if this was not in response to a join_request and not a lesson
if ! receiver . friends . exists? ( sender . id )
errors . add ( :receiver , FRIENDSHIP_REQUIRED_VALIDATION_ERROR )
2012-11-30 15:23:43 +00:00
end
2012-10-26 10:33:39 +00:00
end
end
end
end