2012-11-24 18:22:44 +00:00
|
|
|
module JamRuby
|
|
|
|
|
class BandInvitation < ActiveRecord::Base
|
|
|
|
|
|
|
|
|
|
self.table_name = "band_invitations"
|
|
|
|
|
|
|
|
|
|
self.primary_key = 'id'
|
|
|
|
|
|
2012-12-02 07:06:51 +00:00
|
|
|
BAND_INVITATION_FAN_RECIPIENT_ERROR = "A Band invitation can only be sent to a Musician."
|
|
|
|
|
|
2012-11-25 19:37:54 +00:00
|
|
|
belongs_to :receiver, :inverse_of => :received_band_invitations, :foreign_key => "user_id", :class_name => "JamRuby::User"
|
|
|
|
|
belongs_to :sender, :inverse_of => :sent_band_invitations, :foreign_key => "creator_id", :class_name => "JamRuby::User"
|
|
|
|
|
belongs_to :band, :inverse_of => :invitations, :foreign_key => "band_id", :class_name => "JamRuby::Band"
|
2012-11-24 18:22:44 +00:00
|
|
|
|
|
|
|
|
def self.save(id, band_id, user_id, creator_id, accepted)
|
2012-11-25 19:37:54 +00:00
|
|
|
|
2012-12-30 14:39:41 +00:00
|
|
|
band_invitation = BandInvitation.new()
|
|
|
|
|
|
|
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
|
# ensure certain fields are only updated on creation
|
|
|
|
|
if id.nil?
|
|
|
|
|
# ensure recipient is a Musician
|
|
|
|
|
user = User.find(user_id)
|
|
|
|
|
unless user.musician?
|
|
|
|
|
raise JamRuby::JamArgumentError, BAND_INVITATION_FAN_RECIPIENT_ERROR
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
band_invitation.band_id = band_id
|
|
|
|
|
band_invitation.user_id = user_id
|
|
|
|
|
band_invitation.creator_id = creator_id
|
|
|
|
|
|
|
|
|
|
# only the accepted flag can be updated after initial creation
|
|
|
|
|
else
|
|
|
|
|
band_invitation = BandInvitation.find(id)
|
|
|
|
|
band_invitation.accepted = accepted
|
2012-11-26 03:35:48 +00:00
|
|
|
end
|
2012-11-24 18:22:44 +00:00
|
|
|
|
2012-12-30 14:39:41 +00:00
|
|
|
band_invitation.updated_at = Time.now.getutc
|
|
|
|
|
band_invitation.save
|
2012-11-24 18:22:44 +00:00
|
|
|
|
2012-12-30 14:39:41 +00:00
|
|
|
# accept logic => (1) auto-friend each band member and (2) add the musician to the band
|
|
|
|
|
if accepted
|
|
|
|
|
band_musicians = BandMusician.where(:band_id => band_invitation.band.id)
|
|
|
|
|
unless band_musicians.nil?
|
|
|
|
|
band_musicians.each do |bm|
|
|
|
|
|
Friendship.save(band_invitation.receiver.id, bm.user_id)
|
|
|
|
|
end
|
|
|
|
|
end
|
2012-11-25 19:37:54 +00:00
|
|
|
|
2012-12-30 14:39:41 +00:00
|
|
|
# accepting an invitation adds the musician to the band
|
|
|
|
|
BandMusician.create(:band_id => band_invitation.band.id, :user_id => band_invitation.receiver.id, :admin => false)
|
|
|
|
|
end
|
2012-11-25 19:37:54 +00:00
|
|
|
end
|
2012-11-24 18:22:44 +00:00
|
|
|
return band_invitation
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
end
|