def betsOfTheDayInCommunity(com_id): u""" :return les matchs du jour dans la communauté :param com_id: id of community (uuid) """ betsMgr = BetsManager() d = dict() rankings = betsMgr.getBetsOfTheDay(com_id) d["rankings"]=rankings return jsonify({'data': d})
def betsOfTheDayInCommunity(com_id): u""" :return les matchs du jour dans la communauté :param com_id: id of community (uuid) """ betsMgr = BetsManager() d = dict() rankings = betsMgr.getBetsOfTheDay(com_id) d["rankings"] = rankings return jsonify({'data': d})
def listOfPlayers(com_id): u""" :return la représentation json de { "data": { "playerCount": x}} :param com_id: id of community (uuid) :param user_id: id of user (uuid) """ betsMgr = BetsManager() d = dict() players = betsMgr.players(com_id) d["players"] = players return jsonify({'data': d})
def send_email_to_all(self, com_id, blog): u"""" send email to all user of community :param com_id the com_id :param blog the blog send """ bet_mgr = BetsManager() recipients = list() for user in bet_mgr.players(blog.com_id): recipients.append(user["email"]) return self.send_email(com_id, blog, recipients)
def listOfPlayers(com_id): u""" :return la représentation json de { "data": { "playerCount": x}} :param com_id: id of community (uuid) :param user_id: id of user (uuid) """ betsMgr = BetsManager() d= dict() players= betsMgr.players(com_id) d["players"]=players return jsonify({'data': d})
def ranking(): u""" :return la représentation json du classement général :param filter: the phasis we want the ranking for (ALL, GROUPE or FINAL) :param requester: COMMUNITIES_RANKING when the requester is the ranking of the communities """ filter=request.args.get('filter') requester=request.args.get('requester') betsMgr = BetsManager() d = dict() rankings = betsMgr.getRanking(None,filter,requester) d["rankings"]=rankings return jsonify({'data': d})
def getBets(com_id, user_id): u""" return the list of all bets of a user in a community. If user has never bet, we return the list of Matchs. :param com_id: id of community (uuid) :param user_id: id of user (uuid) :return: a json form for the list of bet """ betsMgr = BetsManager() bets = betsMgr.getBetsOfUserAndCom(user_id, com_id) logger.debug(u" ------------ ") logger.debug(u"bets={}".format(bets)) return jsonify({'bets': bets})
def createHistoryRankings(self): u""" Create the history rankings (all communities, and for the general ranking) """ localdb = self.getDb() betsManager = BetsManager() comManager = CommunityManager() comList = comManager.getAllCommunities() nbHits = 0 currDate = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") # Communities ranking for com in comList: rankings = betsManager.getRanking(com["com_id"],"ALL","HISTORY_RANKING") for ranking in rankings: bsonHR =dict() bsonHR["com_id"]=com["com_id"] bsonHR["date_ranking"]=currDate bsonHR["nb_points"]=ranking["nbPoints"] bsonHR["user_id"]=ranking["user"]["user_id"] bsonHR["user_nickname"]=ranking["user"]["nickName"] logger.info(u'\tHistory ranking - to create : {}'.format(bsonHR)) id = localdb.historyrankings.insert_one(bsonHR).inserted_id logger.info(u'\tid : {}'.format(id)) nbHits = nbHits + 1 # General ranking rankings = betsManager.getRanking(None,"ALL","HISTORY_RANKING") for ranking in rankings: bsonHR =dict() bsonHR["com_id"]="all" bsonHR["date_ranking"]=currDate bsonHR["nb_points"]=ranking["nbPoints"] bsonHR["user_id"]=ranking["user"]["user_id"] bsonHR["user_nickname"]=ranking["user"]["nickName"] logger.info(u'\tHistory ranking - to create : {}'.format(bsonHR)) id = localdb.historyrankings.insert_one(bsonHR).inserted_id logger.info(u'\tid : {}'.format(id)) nbHits = nbHits + 1 return nbHits
def listOfCommunitiesByUserId(user_id): u""" :return la représentation json de la liste des communautés dans lesquelles a parié le user user_id :param user_id: id of user (uuid) """ betsMgr = BetsManager() d = dict() comIdList = betsMgr.getCommunitiesIdByUser(user_id) mgr = CommunityManager() result = list() for uuid in comIdList: com = mgr.getCommunityByCommunityId(uuid) if com is not None: result.append(com.__dict__) logger.info(u'\t\tcommunities : {}'.format(result)) result.sort(key=lambda community: community["title"]) d["communities"] = result return jsonify({'communities': d})
def listOfCommunitiesByUserId(user_id): u""" :return la représentation json de la liste des communautés dans lesquelles a parié le user user_id :param user_id: id of user (uuid) """ betsMgr = BetsManager() d= dict() comIdList= betsMgr.getCommunitiesIdByUser(user_id) mgr = CommunityManager() result=list() for uuid in comIdList: com = mgr.getCommunityByCommunityId(uuid) if com is not None: result.append(com.__dict__) logger.info(u'\t\tcommunities : {}'.format(result)) result.sort(key=lambda community: community["title"]) d["communities"]=result return jsonify({'communities': d})
def test_createOrUpdate(self): os.environ['OPENSHIFT_MONGODB_DB_URL']=u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = BetsManager() self.assertIsNotNone(mgr.getDb()) bet = Bet() bet.resultA=1 bet.resultB=10 bet.user_id="moi_en_uuid" bet.com_id="ma_com_id_en_uuid" bet.category="categcode" bet.categoryName="categname" bet.key="keymatch" bet.libteamA="theliba" bet.libteamB="thelibb" bet.teamA="theteamA" bet.teamB="theteamb" bet.dateDeadLineBet=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) bet.dateMatch=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) mgr.createOrUpdate(bet) bets = mgr.getBetsOfUserAndCom(user_id="moi_en_uuid", com_id="ma_com_id_en_uuid") self.assertGreater(len(bets), 0) for u in bets: print(u) self.assertIsNotNone(bets) nb = mgr.delete(bet) self.assertEqual(1, nb)
def test_createOrUpdateBets(self): os.environ[ 'OPENSHIFT_MONGODB_DB_URL'] = u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = BetsManager() self.assertIsNotNone(mgr.getDb()) d = dict() d["resultA"] = 1 d["resultB"] = 10 d["user_id"] = "moi_en_uuid" d["com_id"] = "ma_com_id_en_uuid" d["category"] = "categcode" d["categoryName"] = "categname" d["key"] = "keymatch" d["libteamA"] = "theliba" d["libteamB"] = "thelibb" d["teamA"] = "theteamA" d["teamB"] = "theteamb" d["dateDeadLineBet"] = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) d["dateMatch"] = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) blist = list() blist.append(d) res = mgr.createOrUpdateBets("baduserid", "badcomid", blist) self.assertEqual(0, res)
def createOrUpdateBets(com_id, user_id): u""" save the list of bets of a user in a community. the list of bets is defined inrequest.json. :param com_id: id of community (uuid) :param user_id: id of user (uuid) :return the numbers of bets created or updated """ betsMgr = BetsManager() logger.info(u"createOrUpdateBets::json param:{} ".format(request.json)) betsJSON = request.json["bets"] checkRight=False if "cookieUserKey" in session: cookieUserKey = session['cookieUserKey'] logger.info(u"createOrUpdateBets::cookieUserKey={}".format(cookieUserKey)) if (user_id==cookieUserKey): checkRight=True if (checkRight): nbHit = betsMgr.createOrUpdateBets(user_id, com_id, betsJSON) return jsonify({'nbHit': nbHit}) else: return "Ha ha ha ! Mais t'es pas la bonne personne pour faire ça, mon loulou", 403
def createOrUpdateBets(com_id, user_id): u""" save the list of bets of a user in a community. the list of bets is defined inrequest.json. :param com_id: id of community (uuid) :param user_id: id of user (uuid) :return the numbers of bets created or updated """ betsMgr = BetsManager() logger.info(u"createOrUpdateBets::json param:{} ".format(request.json)) betsJSON = request.json["bets"] checkRight = False if "cookieUserKey" in session: cookieUserKey = session['cookieUserKey'] logger.info( u"createOrUpdateBets::cookieUserKey={}".format(cookieUserKey)) if (user_id == cookieUserKey): checkRight = True if (checkRight): nbHit = betsMgr.createOrUpdateBets(user_id, com_id, betsJSON) return jsonify({'nbHit': nbHit}) else: return "Ha ha ha ! Mais t'es pas la bonne personne pour faire ça, mon loulou", 403
def test_createOrUpdateBets(self): os.environ['OPENSHIFT_MONGODB_DB_URL']=u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = BetsManager() self.assertIsNotNone(mgr.getDb()) d = dict() d["resultA"]=1 d["resultB"]=10 d["user_id"]="moi_en_uuid" d["com_id"]="ma_com_id_en_uuid" d["category"]="categcode" d["categoryName"]="categname" d["key"]="keymatch" d["libteamA"]="theliba" d["libteamB"]="thelibb" d["teamA"]="theteamA" d["teamB"]="theteamb" d["dateDeadLineBet"]=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) d["dateMatch"]=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) blist = list() blist.append(d) res = mgr.createOrUpdateBets("baduserid", "badcomid", blist) self.assertEqual(0, res)
def test_createOrUpdate(self): os.environ[ 'OPENSHIFT_MONGODB_DB_URL'] = u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = BetsManager() self.assertIsNotNone(mgr.getDb()) bet = Bet() bet.resultA = 1 bet.resultB = 10 bet.user_id = "moi_en_uuid" bet.com_id = "ma_com_id_en_uuid" bet.category = "categcode" bet.categoryName = "categname" bet.key = "keymatch" bet.libteamA = "theliba" bet.libteamB = "thelibb" bet.teamA = "theteamA" bet.teamB = "theteamb" bet.dateDeadLineBet = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) bet.dateMatch = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) mgr.createOrUpdate(bet) bets = mgr.getBetsOfUserAndCom(user_id="moi_en_uuid", com_id="ma_com_id_en_uuid") self.assertGreater(len(bets), 0) for u in bets: print(u) self.assertIsNotNone(bets) nb = mgr.delete(bet) self.assertEqual(1, nb)
def test_countPlayer(self): os.environ['OPENSHIFT_MONGODB_DB_URL']=u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = BetsManager() self.assertIsNotNone(mgr.getDb()) bet = Bet() bet.resultA=1 bet.resultB=10 bet.user_id="moi_en_uuid" bet.com_id="ma_com_id_en_uuid" bet.category="categcode" bet.categoryName="categname" bet.key="keymatch" bet.libteamA="theliba" bet.libteamB="thelibb" bet.teamA="theteamA" bet.teamB="theteamb" bet.dateDeadLineBet=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) bet.dateMatch=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) mgr.createOrUpdate(bet) result = mgr.countPlayers("ma_com_id_en_uuid") self.assertEqual(1, result) players = mgr.players("ma_com_id_en_uuid") self.assertEqual(1, len(players)) bet2 = Bet() bet2.resultA=1 bet2.resultB=10 bet2.user_id="moi_en_uuid" bet2.com_id="ma_com_id_en_uuid" bet2.category="categcode" bet2.categoryName="categname" bet2.key="keymatch" bet2.libteamA="theliba" bet2.libteamB="thelibb" bet2.teamA="theteamA" bet2.teamB="theteamb" bet2.dateDeadLineBet=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) bet2.dateMatch=datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) mgr.createOrUpdate(bet) mgr.delete(bet) mgr.delete(bet2)
def update_all_matchs(self, matchs_to_update, no_save): #load all match from db (because we just want to update result logger.info(u"update_all_matchs::start-before getAllMatchs") matchs = self.getAllMatchs() logger.info(u"update_all_matchs::end getAllMatchs") nb_hits=0 bets_for_mail = list() bet_mgr = BetsManager() betList = bet_mgr.get_all_bets() logger.info(u"update_all_matchs::end get_all_bets") for m in matchs: match = Match() match.convertFromBson(m) match_key=match.key #quick filter !! i love python unique_match_list = [x for x in matchs_to_update if x["key"] == match_key] match_dict=unique_match_list[0] if match_dict is not None: match.resultA = match_dict["resultA"] match.resultB = match_dict["resultB"] if not no_save: # mettre à jour juste les resultats logger.info(u'\tupdate_all_matchs::try update match["key" : {}] with match={}'.format(match_key, match_dict)) result = self.getDb().matchs.update_one({"key": match_key}, {"$set": {"resultA": match_dict["resultA"], "resultB": match_dict["resultB"]}}, upsert=True) nb_hits = nb_hits + result.matched_count else: logger.info("no match updated") else: logger.warn(u'\tmatch notfound in matchs_to_update["key" : {}]'.format(match_key)) # pour chaque match demander à betmanager de calculer le nb de points de chq bet # le principe sera de calculer le nbde pts d'un user = somme de ses paris shortList = [b for b in betList if b.key == m["key"]] for bet in shortList: match.computeResult(bet) logger.info( u'\t\tupdate_all_matchs::bet={}/{} - nbpts={}'.format(bet.key, bet.user_id, bet.nbpoints)) bets_for_mail.append(self.format_bet(bet, match)) if not no_save: for bet in betList: logger.info("bet update") bet_mgr.saveScore(bet) message = sendgrid.Mail() message.add_to("*****@*****.**") message.set_from("*****@*****.**") message.set_subject("euroxxxvi - bets") head = u"<html><head></head><body><table border='1'><tr><td>m.key</td><td>teamA</td><td>teamB</td><td>resultA</td>" head=head+u"<td>resultB</td><td> </td><td>bet.key</td><td>com_id</td><td>user_id</td>" head=head+u"<td>bet.resultA</td><td>bet.resultB</td><td>bet.nbpoints</td></tr>" content = head+"\n".join(bets_for_mail)+"</table></body></html>" logger.info(content) message.set_html(content) tool = ToolManager() sg = tool.get_sendgrid() sg.send(message) return None
def test_countPlayer(self): os.environ[ 'OPENSHIFT_MONGODB_DB_URL'] = u"mongodb://*****:*****@127.0.0.1:27017/euroxxxvi" mgr = BetsManager() self.assertIsNotNone(mgr.getDb()) bet = Bet() bet.resultA = 1 bet.resultB = 10 bet.user_id = "moi_en_uuid" bet.com_id = "ma_com_id_en_uuid" bet.category = "categcode" bet.categoryName = "categname" bet.key = "keymatch" bet.libteamA = "theliba" bet.libteamB = "thelibb" bet.teamA = "theteamA" bet.teamB = "theteamb" bet.dateDeadLineBet = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) bet.dateMatch = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) mgr.createOrUpdate(bet) result = mgr.countPlayers("ma_com_id_en_uuid") self.assertEqual(1, result) players = mgr.players("ma_com_id_en_uuid") self.assertEqual(1, len(players)) bet2 = Bet() bet2.resultA = 1 bet2.resultB = 10 bet2.user_id = "moi_en_uuid" bet2.com_id = "ma_com_id_en_uuid" bet2.category = "categcode" bet2.categoryName = "categname" bet2.key = "keymatch" bet2.libteamA = "theliba" bet2.libteamB = "thelibb" bet2.teamA = "theteamA" bet2.teamB = "theteamb" bet2.dateDeadLineBet = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) bet2.dateMatch = datetime(2016, 6, 2, 18, 15, 0, 0, tzinfo=timezone.utc) mgr.createOrUpdate(bet) mgr.delete(bet) mgr.delete(bet2)
def update_all_matchs(self, matchs_to_update, no_save): #load all match from db (because we just want to update result logger.info(u"update_all_matchs::start-before getAllMatchs") matchs = self.getAllMatchs() logger.info(u"update_all_matchs::end getAllMatchs") nb_hits = 0 bets_for_mail = list() bet_mgr = BetsManager() betList = bet_mgr.get_all_bets() logger.info(u"update_all_matchs::end get_all_bets") for m in matchs: match = Match() match.convertFromBson(m) match_key = match.key #quick filter !! i love python unique_match_list = [ x for x in matchs_to_update if x["key"] == match_key ] match_dict = unique_match_list[0] if match_dict is not None: match.resultA = match_dict["resultA"] match.resultB = match_dict["resultB"] if not no_save: # mettre à jour juste les resultats logger.info( u'\tupdate_all_matchs::try update match["key" : {}] with match={}' .format(match_key, match_dict)) result = self.getDb().matchs.update_one( {"key": match_key}, { "$set": { "resultA": match_dict["resultA"], "resultB": match_dict["resultB"] } }, upsert=True) nb_hits = nb_hits + result.matched_count else: logger.info("no match updated") else: logger.warn( u'\tmatch notfound in matchs_to_update["key" : {}]'.format( match_key)) # pour chaque match demander à betmanager de calculer le nb de points de chq bet # le principe sera de calculer le nbde pts d'un user = somme de ses paris shortList = [b for b in betList if b.key == m["key"]] for bet in shortList: match.computeResult(bet) logger.info( u'\t\tupdate_all_matchs::bet={}/{} - nbpts={}'.format( bet.key, bet.user_id, bet.nbpoints)) bets_for_mail.append(self.format_bet(bet, match)) if not no_save: for bet in betList: logger.info("bet update") bet_mgr.saveScore(bet) from_email = Email("*****@*****.**") to_email = Email("*****@*****.**") subject = "phipha2018 - bets saved" head = u"<html><head></head><body><table border='1'><tr><td>m.key</td><td>teamA</td><td>teamB</td><td>resultA</td>" head = head + u"<td>resultB</td><td> </td><td>bet.key</td><td>com_id</td><td>user_id</td>" head = head + u"<td>bet.resultA</td><td>bet.resultB</td><td>bet.nbpoints</td></tr>" content = Content( "text/html", head + "\n".join(bets_for_mail) + "</table></body></html>") mail = Mail(from_email, subject, to_email, content) tool = ToolManager() sg = tool.get_sendgrid() response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) return None