def save_comments(self, clubid, roleid, request, *args, **kwargs):
     evaluateeRole = RoleTaken.objects.get(id__exact = roleid)
     owner = Person.objects.get(id__exact = evaluateeRole.ownerid)
     
     club = None
     if clubid != 0:
         try:
             club = Club.objects.get(id__exact=clubid)
         except:
             pass
     else:
         try:
             club = Meeting.objects.get(id__exact=evaluateeRole.meeting.id).club
         except:
             pass
     if club is None:
         return
     
     try:
         msgfname = club.fullname
     except:
         msgfname = club.briefname
         
     if request.DATA["passed"] is True or request.DATA["passed"] == 1 :
         msgcontent = "Congratulation!\n" + owner.displayname + " has passed the project:" \
             + evaluateeRole.title + "(" + evaluateeRole.ctask + " " + evaluateeRole.ltask +")" \
             + "\nComments from the evaluator:" + request.DATA["msg"]
     else:
         msgcontent =  owner.displayname + " didn't pass the project:" \
             + evaluateeRole.title + "(" + evaluateeRole.ctask + " " + evaluateeRole.ltask +")" \
             + "\nComments from the evaluator:" + request.DATA["msg"]
             
     MessageUtil.sendClubNty(club.id, msgfname, club.id, msgcontent)
 def post_process(self,userid,displayname,serializer):
     try:
         club = serializer.object.club
         
         #curTimeticks = int(time.mktime(datetime.now().timetuple())*1000)
         #term = Term.objects.filter(club_id__exact=club.id,finished__exact=False,\
         #            startdate__lt=curTimeticks, enddate__gt=curTimeticks).order_by("startdate")[0]
         term = Term.objects.get(id=club.curterm)
         
         person = Person.objects.get(id__exact=userid)
         
         #P1 update person profile if required
         if len(displayname) > 2:
             person.displayname = displayname
             person.save()
             
         #P2 get_or_create Membership
         ms, created = Membership.objects.get_or_create(club=club, term=term, person=person)
         ms.type = MemberType.Applicant
         ms.access=UserUtil.getExpectedAccess(MemberType.Applicant)
         ms.status = True
         ms.save()
         
         #P3 send club to person notification
         try:
             msgfname = club.fullname
         except:
             msgfname = club.briefname
         msgcontent = "Your request to join club {} is being handled.".format(msgfname)
         MessageUtil.sendClubToPersonNty(club.id,msgfname,userid, msgcontent)
     except:
         pass
 def reject_ccr(ccrid,reason):
     ccr = None        
     try:
         ccr = CreateClubRequest.objects.get(id__exact=ccrid)
     except:
         pass
     
     if ccr:
         try:
             msgcontent = "Sorry, the request to create the Club {} has been rejected as '{}'.".format(ccr.fullname,reason)
             MessageUtil.sendClubToPersonNty(0, "System", ccr.user.id, msgcontent)                
             CreateClubRequest.objects.filter(id__exact=ccrid).delete()                
             print("The create request is deleted!")
         except:
             pass
     else:
         print("The create request is not existed!")
         return False
    def post(self, request, *args, **kwargs):
        roleid = 0
        respData = {"code":"comment error!"}        
        
        try:
            meetingid = int(kwargs['m_pk'])
            roleid = int(kwargs['pk'])
            clubid = 0
            if 'c_pk' in  kwargs:
                clubid = int(kwargs['c_pk'])
            if not MeetingUtil.validateClubMeetingPermission(request, clubid, meetingid):
                return Response({"msg":"club-meeting no matching"}, status=status.HTTP_400_BAD_REQUEST)
        except:
            pass
        
        evaluateeRole = RoleTaken.objects.get(id__exact = roleid)
        receiver = Person.objects.get(id__exact = evaluateeRole.ownerid)
        sender = Person.objects.get(id__exact = request.user.id)        
        try:
            msgfname = sender.displayname
        except:
            msgfname = sender.username        
        messageid = MessageUtil.sendFriendConversation(sender.id, msgfname, receiver.id, request.DATA["msg"])
                    
        request.DATA["meeting"] = meetingid
        request.DATA["roleTaken"] = roleid
        request.DATA["evaluator"] = request.user.id
        request.DATA["message"] = messageid
        
        serializer = RoleCommentSerializer(data=request.DATA)

        if serializer.is_valid():
            serializer.save()
            respData["code"] = "ok"
            return Response(respData)
        return Response(respData,status=status.HTTP_400_BAD_REQUEST)
    def post(self, request, *args, **kwargs):
        respData = {"errorcode":""}
        
        try:
            clubid = int(kwargs['clubid'])
            pk = int(kwargs['pk'])
        except:
            respData["errorcode"] = "Invalid club or request!"
            return Response(respData, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            action = int(request.GET.get("action"))
        except:
            pass

        joinreq = self.get_object(pk)            
        requestDATA = {}
        requestDATA["id"] = pk
        
        if action == 1:
            requestDATA["status"] = JoinClubReqStatus.APPROVED
        elif action == 2:
            requestDATA["status"] = JoinClubReqStatus.REJECTED
            requestDATA["comment"] = request.DATA["comment"]
        else:
            requestDATA["status"] = JoinClubReqStatus.DETAILED        

        serializer = JoinClubUpdateSerializer(joinreq, data=requestDATA)
        if serializer.is_valid():
            serializer.save()
            club = serializer.object.club
            person = Person.objects.get(id__exact=serializer.object.user.id)
            #curTimeticks = int(time.mktime(datetime.now().timetuple())*1000)
            #term = Term.objects.filter(club_id__exact=club.id,finished__exact=False,\
            #            startdate__lt=curTimeticks, enddate__gt=curTimeticks).order_by("startdate")[0]
            term = Term.objects.get(id=club.curterm)
            if action == 1:
                access = UserUtil.getExpectedAccess(joinreq.type)
                Membership.objects.filter(club_id__exact=club.id, term_id__exact=term.id,\
                                 person_id__exact=person.id).update(access=access,type=joinreq.type)
                                 
                #the first club
                if Membership.objects.filter(person=person).count()==1:                
                    person.defclub = club.id
                    person.save()
                
                #send club notification to all club member
                try:
                    msgfname = club.fullname
                except:
                    msgfname = club.briefname
                msgcontent = "Welcome! {} has joined {}.".format(person.get_identification(),msgfname)
                MessageUtil.sendClubNty(club.id,msgfname,club.id, msgcontent)
            elif action == 2:
                Membership.objects.filter(club_id__exact=club.id, term_id__exact=term.id,person_id__exact=person.id).delete()
                                
                #send club notification to person
                try:
                    msgfname = club.fullname
                except:
                    msgfname = club.briefname
                msgcontent = "Your request to join {} has been rejected.".format(msgfname)
                if "comment" in request.DATA and len(request.DATA["comment"])>0:
                    msgcontent += "The reason is '{}'.".format(request.DATA["comment"])
                MessageUtil.sendClubToPersonNty(club.id, msgfname,person.id, msgcontent)

            return Response(serializer.data)
        else:
            respData["errorcode"] = "Invalid club or request!"
            return Response(respData, status=status.HTTP_400_BAD_REQUEST)
 def approve_ccr(ccrid):
     ccr = None
     exclub = None
     
     try:
         ccr = CreateClubRequest.objects.get(id__exact=ccrid)
     except:
         pass
     
     try:
         exclub = Club.objects.get(tmid__exact=ccr.tmid)
     except:
         pass
     
     if exclub is None and ccr:
         club = Club()
         club.tmid = ccr.tmid
         club.fullname = ccr.fullname
         club.briefname = ccr.briefname
         club.address = ccr.address
         club.addressd = ccr.addressd
         
         club.mday = ccr.mday
         club.mtime = ccr.mtime
         
         club.conperson = ccr.conperson
         club.conphone = ccr.conphone
         
         club.email = ccr.email
         club.website = ccr.website
         club.qq = ccr.qq
         club.weibo = ccr.weibo
         club.facebook = ccr.facebook
         
         club.cdate = ccr.cdate            
         club.advanced = ccr.advanced            
         club.cstatus = 0 # set as created
         
         club.desc = ccr.desc            
         #process the location/section: district/area/division  country/province              
         club.location = ccr.location
         club.section = ccr.section
         
         club.active = True
         
         club.save()
         print("club: {} {}".format(club.id, club.fullname))            
         
         term = Term()
         term.startdate = int(time.mktime(datetime.now().timetuple())*1000)
         term.enddate = term.startdate + 16416000000 # half a year: 190*24*3600000
         term.club = club
         term.save()
         club.curterm = term.id
         club.save()
         print("term: {} {}".format(term.id, term.startdate))
         
         membership = Membership(club=club,term=term, person=ccr.user,type=MemberType.President,access=UserUtil.getExpectedAccess(MemberType.President))
         membership.save()
         print("membership(Set requester as President)# club:{} term:{} person: {}".format(membership.club.id, membership.club.id,membership.person.username))
         
         #the first club
         if Membership.objects.filter(person=ccr.user).count()==1:
             ccr.user.defclub = club.id
             ccr.user.save()
         
         msgcontent = "Congratulation! Club {} has bee setup with {} as president.".format(club.fullname,membership.person.username)
         MessageUtil.sendClubNty(club.id,club.fullname, club.id, msgcontent)
         
         print(msgcontent)
         CreateClubRequest.objects.filter(id__exact=ccrid).delete()
     else:
         print("This club has been created or the create request is not existed!")
         return False
    def post(self, request, *args, **kwargs):
        roleid = 0
        action = 99999
        aid = 0
        respData = {"code":"like error!"}        
        
        try:
            meetingid = int(kwargs['m_pk'])
            roleid = int(kwargs['pk'])
            clubid = 0
            if 'c_pk' in  kwargs:
                clubid = int(kwargs['c_pk'])
            if not MeetingUtil.validateClubMeetingPermission(request, clubid, meetingid):
                return Response({"msg":"club-meeting no matching"}, status=status.HTTP_400_BAD_REQUEST)
            action = int(request.GET.get("action"))
            aid = int(request.GET.get("aid"))            
        except:
            pass


        if action == 1:
            if self.get_like_existing(request, meetingid, aid, roleid)==False:
                requestDATA = {}
                arrelation = ARRelation.objects.get(roletaken_id__exact=roleid, activity_id__exact=aid)
                requestDATA["meeting"] = meetingid
                requestDATA["arrelation"] = arrelation.id
                requestDATA["evaluator"] = request.user.id
                requestDATA["like"] = 1
                                
                serializer = RoleLikerSerializer(data=requestDATA)
                if serializer.is_valid():
                    serializer.save()
                    respData["code"] = "ok"
                    
                    #send Club Conversation
                    role = RoleTaken.objects.get(id__exact = roleid)
                    owner = Person.objects.get(id__exact = role.ownerid)
                    sender = Person.objects.get(id__exact = request.user.id)
                    try:
                        msgfname = sender.displayname
                    except:
                        msgfname = sender.username
                    if(clubid != 0):
                        msgtouser = clubid
                    else:
                        msgtouser = role.meeting.term.club.id
                    msgcontent = owner.displayname + "'s " + role.title + " got ♥ from " + sender.displayname                    
                    MessageUtil.sendClubConversation(sender.id,msgfname, msgtouser, msgcontent)
                    
                    return Response(respData)
                
                return Response(respData,status=status.HTTP_400_BAD_REQUEST)
            else:
                self.update_like(request,meetingid,aid,roleid,1)
                respData["code"] = "ok"
                return Response(respData)
        
        elif action == 0:
            self.update_like(request,meetingid,aid,roleid,0)
            respData["code"] = "ok"
            return Response(respData)
        
        else:
            return Response(respData,status=status.HTTP_400_BAD_REQUEST)