From f8e60897ba699e13b43cc83994f511f6026129a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ch=C3=A9rifBALDE?= Date: Thu, 15 Sep 2022 15:10:27 +0200 Subject: [PATCH] 15/09/22 - 15h00 --- class_mgt.py | 162 +++++++++++++++++++++++++++++++++++++++++ main.py | 29 +++++++- statistics.py | 197 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 387 insertions(+), 1 deletion(-) diff --git a/class_mgt.py b/class_mgt.py index e180d46..b4d0945 100644 --- a/class_mgt.py +++ b/class_mgt.py @@ -1705,6 +1705,168 @@ def get_partner_class(diction): mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e)+" - Line : "+ str(exc_tb.tb_lineno) ) return False, " Impossible de recuperer la formation" +""" +Cette fonction retrourne +- le code externe, +- internal_url +des formations d'un partner +""" + +def get_partner_class_external_code(diction): + try: + ''' + # Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés + # Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API + # Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste + # field_list. + ''' + field_list = ['internal_url', 'token', 'title', 'valide', 'locked', 'external_code'] + incom_keys = diction.keys() + for val in incom_keys: + if val not in field_list: + mycommon.myprint(str(inspect.stack()[0][ + 3]) + " - get_partner_class : Le champ '" + val + "' n'existe pas, Creation formation annulée") + return False, " Impossible de recuperer la formation" + + ''' + Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, + On controle que les champs obligatoires sont presents dans la liste + ''' + field_list_obligatoire = ['token'] + + for val in field_list_obligatoire: + if val not in diction: + mycommon.myprint( + str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans liste ") + return False, " Impossible de recuperer la formation" + + # recuperation des paramettre + mydata = {} + my_external_code = "" + my_token = "" + my_internal_url = "" + + if ("internal_url" in diction.keys()): + if diction['internal_url']: + my_internal_url = diction['internal_url'] + + if ("external_code" in diction.keys()): + if diction['external_code']: + my_external_code = diction['external_code'] + + if ("token" in diction.keys()): + if diction['token']: + my_token = diction['token'] + + ''' + Gestion des filters. + ''' + + internal_url_crit = {} + if ("internal_url" in diction.keys()): + if diction['internal_url']: + internal_url_crit['internal_url'] = diction['internal_url'] + + external_code_crit = {} + if ("external_code" in diction.keys()): + if diction['external_code']: + external_code_crit['external_code'] = diction['external_code'] + + title_crit = {} + if ("title" in diction.keys()): + if diction['title']: + title_crit['title'] = diction['title'] + + coll_name = MYSY_GV.dbname['myclass'] + + # verifier que le token et l'email sont ok + coll_token = MYSY_GV.dbname['user_token'] + + # Verification de la validité du token dans le cas des user en mode connecté + ''' + /!\ Important : le token ne doit jamais etre vide car cette fonction a pour objectif + de retourner les formation edité par un partenaire. + + Il dont obligatoirement est en mode connecté + ''' + + user_recid = "None" + # Verification de la validité du token/mail dans le cas des user en mode connecté + if (len(str(my_token)) > 0): + retval = mycommon.check_partner_token_validity("", my_token) + + if retval is False: + mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token n'est pas valide") + return False, " Impossible de recuperer la formation" + + # Recuperation du recid de l'utilisateur + user_recid = mycommon.get_parnter_recid_from_token(my_token) + if user_recid is False: + mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de recuperer le token de l'utilisateur") + return False, " Impossible de recuperer la formation" + + if (len(str(my_token)) <= 0): + mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token est vide") + return False, " Impossible de recuperer la formation" + + RetObject = [] + filt_external_code = {} + if ("external_code" in diction.keys()): + filt_external_code = {'external_code': str(diction['external_code'])} + # print(" GRRRRRRRRRRRRR "+str(filt_external_code)) + + filt_title = {} + if ("title" in diction.keys()): + filt_title = {'title': {'$regex': str(diction['title'])}} + + filt_internal_url = {} + if ("internal_url" in diction.keys()): + filt_internal_url = {'internal_url': {'$regex': str(diction['internal_url'])}} + # print(" filt_internal_url GRRRRRRRRRRRRRRRRRRRRrr "+str(filt_internal_url)) + + print( + " ATTTTENNTION : GESTION DU CAS OU LA PERSONNE QUI CHERCHE LE COURS EST UN UTILISATEUR : PB avec : partner_owner_recid ") + print(" #### avant requete get partner_owner_recid =" + str(user_recid) + + " filt_external_code = " + str(filt_external_code) + + " filt_internal_url = " + str(filt_internal_url) + + " filt_title = " + str(filt_title)) + + val_tmp = 1 + for retVal in coll_name.find({"$and": [{'valide': '1'}, {'locked': '0'}, + {'partner_owner_recid': user_recid}, + filt_external_code, filt_title, filt_internal_url]}, + {'external_code':1, 'internal_url':1}, + ).sort([("external_code",pymongo.ASCENDING),]): + # mycommon.myprint(str(retVal)) + user = retVal + user['id'] = str(val_tmp) + + ''' + Pour des facilité d'affichage coté front + on va reformater le champ "zone_diffusion" de sorte à le renvoyer + sous la forme "code_pays-ville" + ''' + i = 0 + tmp_zone_diffusion = "" + if ("zone_diffusion" in user.keys()): + if (user['zone_diffusion'] and user['zone_diffusion']["city"]): + for tmp_val in user['zone_diffusion']["city"]: + tmp_zone_diffusion = tmp_zone_diffusion + str(user['zone_diffusion']["country"][i]) + "-" + str( + user['zone_diffusion']["city"][i]) + ";" + i = i + 1 + + user['zone_diffusion_str'] = str(tmp_zone_diffusion[:-1]) + RetObject.append(JSONEncoder().encode(user)) + val_tmp = val_tmp + 1 + + # print(str(RetObject)) + return True, RetObject + + + except Exception as e: + exc_type, exc_obj, exc_tb = sys.exc_info() + mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)) + return False, " Impossible de recuperer la formation" def get_class_global_search(search_string): diff --git a/main.py b/main.py index e2b5317..c6a1cb8 100644 --- a/main.py +++ b/main.py @@ -287,11 +287,25 @@ def get_partner_class(): # On recupere le corps (payload) de la requete payload = request.form.to_dict() print(" ### payload = ",str(payload)+" IP requester = "+str(request.remote_addr)) - status, retval = cm.get_partner_class(payload) return jsonify(status=status, message=retval) +""" +Cette API retourne le code externe de toutes les formations +d'un partenaire +""" +@app.route('/myclass/api/get_partner_class_external_code/', methods=['POST','GET']) +@crossdomain(origin='*') +def get_partner_class_external_code(): + # On recupere le corps (payload) de la requete + payload = request.form.to_dict() + print(" ### payload = ",str(payload)+" IP requester = "+str(request.remote_addr)) + status, retval = cm.get_partner_class_external_code(payload) + return jsonify(status=status, message=retval) + + + @app.route('/myclass/api/update_class/', methods=['POST']) @crossdomain(origin='*') @@ -1426,6 +1440,19 @@ def Get_X_Best_Class_On_Given_period(): return jsonify(status=status, message=message) +""" +Cette API retour les statistiques d'une formation données +""" +@app.route('/myclass/api/GetStat_class_by_internal_url/', methods=['GET','POST']) +@crossdomain(origin='*') +def GetStat_class_by_internal_url(): + # On recupere le corps (payload) de la requete + payload = request.form.to_dict() + print(" ### payload = ", str(payload)) + status, message = Stat.GetStat_class_by_internal_url(payload) + return jsonify(status=status, message=message) + + @app.route('/myclass/api/test_return/', methods=['GET','POST']) @crossdomain(origin='*') def test_return(): diff --git a/statistics.py b/statistics.py index 5fa4eb3..dba899a 100644 --- a/statistics.py +++ b/statistics.py @@ -339,6 +339,11 @@ def GetStat_class_view_topX(diction): categories_val = categories_val+str(day_before)+"," print(" day_before DATE = " + str(day_before)+ " VS "+str(new_from_date)) + if(categories_val.endswith(',') ): + categories_val = categories_val[:-1] + + print(" categories_val = "+categories_val) + categories['categories'] = str(categories_val) # Verification de la validité du token ''' @@ -594,3 +599,195 @@ def test_return(): mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, "Impossible de test_return" + +""" +Cette fonction retourne les statistiques d'une formation données +""" + +def GetStat_class_by_internal_url(diction): + try: + ''' + # Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés + # Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API + # Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste + # field_list. + ''' + field_list = ['external_code', 'internal_url', 'zone_diffusion', 'metier', 'date_lieu', + 'published', 'token', 'date_start', 'date_end'] + incom_keys = diction.keys() + for val in incom_keys: + if val not in field_list: + mycommon.myprint(str(inspect.stack()[0][ + 3]) + " - Le champ '" + val + "' n'est pas autorisé, Creation formation annulée") + return False, " Verifier votre API" + + ''' + Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, + On controle que les champs obligatoires sont presents dans la liste + ''' + field_list_obligatoire = [ 'token', 'internal_url'] + + for val in field_list_obligatoire: + if val not in diction: + mycommon.myprint(str(inspect.stack()[0][3])+" - La valeur '" + val + "' n'est pas presente dans liste ") + return False, " Verifier votre API" + + ''' + Verification si le token et l'email sont valident + ''' + + # recuperation des paramettre + mydata = {} + + + if ("token" in diction.keys()): + if diction['token']: + mydata['token'] = diction['token'] + + date_start = "" + if ("date_start" in diction.keys()): + if diction['date_start']: + date_start = diction['date_start'] + + date_end = "" + if ("date_end" in diction.keys()): + if diction['date_end']: + date_end = diction['date_end'] + + + + local_status, try_end_date = mycommon.TryToDateYYYMMDD(str(diction['date_end'])) + new_end_date = try_end_date.date() + + + local_status, try_from_date = mycommon.TryToDateYYYMMDD(str(diction['date_start'])) + new_from_date = try_from_date.date() + + day_before = new_end_date - timedelta(days=0) + tmp = 0 + + categories = {} + categories_val = "" + while ( tmp > -10 and str(day_before) != str(new_from_date) ) : + tmp = tmp - 1 + day_before = new_end_date + timedelta(days=tmp) + categories_val = categories_val+str(day_before)+"," + print(" day_before DATE = " + str(day_before)+ " VS "+str(new_from_date)) + + if(categories_val.endswith(',') ): + categories_val = categories_val[:-1] + + print(" categories_val = "+categories_val) + + categories['categories'] = str(categories_val) + # Verification de la validité du token + ''' + Important : pour créer une formation, il faut obligatoirement avoir un token. + PAS DE CREATION DE FORMATION EN MODE NON CONNECTE. + + CONCERNANT LES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT + + ''' + retval = mycommon.check_partner_token_validity("", str(mydata['token'])) + + if retval is False: + mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token n'est pas valide") + return False, "L'email ou le token ne sont pas valident" + + # Recuperation du recid du partenaire + user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token'])) + if user_recid is False: + mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de recuperer le recid du partenaire") + return False, " Les informations d'identification sont incorrectes" + + + """ + Recuperation des id (internal_url) des formations + """ + liste_formation = [] + myinternal_url = "" + if ("internal_url" in diction.keys()): + if diction['internal_url']: + myinternal_url = diction['internal_url'] + liste_formation.append(str(myinternal_url)) + + # collection + collection = MYSY_GV.dbname["user_recherche_result"] + + """ + Pour avoir une requete qui groupe par jour, ou jour-heure + on doit jouer avec le + "date" : { $substr: [ "$date_update", 0, 25 ] } ==> ou 25 et la largeur de la coupure, + """ + + thisweek = datetime.today() - timedelta(days=0) + thisweek_format = thisweek.strftime('%Y-%m-%d') + + QUERY_BY = "jour" + SUBSTR = 0 + + if (QUERY_BY == 'heure'): + SUBSTR = 13 + elif (QUERY_BY == 'jour'): + SUBSTR = 10 + elif (QUERY_BY == 'mois'): + SUBSTR = 7 + + pipe2 = [ + {'$match': {'date_update' : { '$gte' : str(date_start), '$lte' : str(date_end)}, + 'token':str(mydata['token']), + 'internal_url': {'$in': liste_formation}, + }}, + { + '$group': { + '_id': { + "Date_view": {"$substr": ["$date_update", 0, SUBSTR]}, + "INTERNAL URL": "$internal_url", + "OWNER": "$owner", + + }, + 'count': {'$count': {} + } + } + }, + { + "$sort": {"_id": 1} + }, + + ] + + print(" PIP 2 ="+str(pipe2)) + for result in collection.aggregate(pipe2): + print(str(result['_id']) + " ===> " + str(result['count'])) + + + insertObject = [] + i = 0 + for tmp in liste_formation : + i = i +1 + print(" Traitement de "+str(tmp)) + ret_val = {} + ret_val['name'+str(i)] = tmp + name = tmp + tab_valeur = [] + for result in collection.aggregate(pipe2): + print(str(result['_id'])+" ===> "+str(result['count'])) + if( name in result['_id']['INTERNAL URL']): + print(" OKKKKKKKKKKKKKKKKKKKK ") + tab_valeur.append(str(result['count'])) + + ret_val['data'+str(i)] = tab_valeur + print(" valll = "+str(ret_val)) + insertObject.append(JSONEncoder().encode(ret_val)) + + insertObject.append(JSONEncoder().encode(categories)) + + # print(result) + + return True, insertObject + + except Exception as e: + exc_type, exc_obj, exc_tb = sys.exc_info() + mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) + return False, "Impossible de recuperer les stat" +