master
cherif 2024-08-23 16:53:03 +02:00
parent 272665efde
commit 74bc2fe20b
8 changed files with 26218 additions and 18 deletions

View File

@ -1,13 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="c6d0259a-16e1-410d-91a1-830590ee2a08" name="Changes" comment="20/08/2024 - 21h55">
<list default="true" id="c6d0259a-16e1-410d-91a1-830590ee2a08" name="Changes" comment="21/08/2024 - 13h55">
<change afterPath="$PROJECT_DIR$/base_partner_catalog_config.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Log/log_file.log" beforeDir="false" afterPath="$PROJECT_DIR$/Log/log_file.log" afterDir="false" />
<change beforePath="$PROJECT_DIR$/lms_chamilo/mysy_lms.py" beforeDir="false" afterPath="$PROJECT_DIR$/lms_chamilo/mysy_lms.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ressources_humaines.py" beforeDir="false" afterPath="$PROJECT_DIR$/ressources_humaines.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/suivi_pedagogique_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/suivi_pedagogique_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/survey_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/survey_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/partner_document_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/partner_document_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/prj_common.py" beforeDir="false" afterPath="$PROJECT_DIR$/prj_common.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/wrapper.py" beforeDir="false" afterPath="$PROJECT_DIR$/wrapper.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -77,13 +79,6 @@
<option name="presentableId" value="Default" />
<updated>1680804787304</updated>
</task>
<task id="LOCAL-00329" summary="qqsd">
<created>1718034595563</created>
<option name="number" value="00329" />
<option name="presentableId" value="LOCAL-00329" />
<option name="project" value="LOCAL" />
<updated>1718034595564</updated>
</task>
<task id="LOCAL-00330" summary="11/06/2024 - 23h30">
<created>1718141094205</created>
<option name="number" value="00330" />
@ -420,7 +415,14 @@
<option name="project" value="LOCAL" />
<updated>1724183059276</updated>
</task>
<option name="localTasksCounter" value="378" />
<task id="LOCAL-00378" summary="21/08/2024 - 13h55">
<created>1724240924909</created>
<option name="number" value="00378" />
<option name="presentableId" value="LOCAL-00378" />
<option name="project" value="LOCAL" />
<updated>1724240924910</updated>
</task>
<option name="localTasksCounter" value="379" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
@ -462,7 +464,6 @@
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="21/07/2024 - 12h" />
<MESSAGE value="23/07/2024 - 12h" />
<MESSAGE value="26/07/2024 - 12h" />
<MESSAGE value="29/07/2024 - 12h" />
@ -487,6 +488,7 @@
<MESSAGE value="18/08/2024 - 21h55" />
<MESSAGE value="20/08/2024 - 13h55" />
<MESSAGE value="20/08/2024 - 21h55" />
<option name="LAST_COMMIT_MESSAGE" value="20/08/2024 - 21h55" />
<MESSAGE value="21/08/2024 - 13h55" />
<option name="LAST_COMMIT_MESSAGE" value="21/08/2024 - 13h55" />
</component>
</project>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,222 @@
""""
Ce fichier permet de configurer le catalogue public d'un partenaire
"""
from base64 import b64encode
import bson
import pymongo
from pymongo import MongoClient
import json
from bson import ObjectId
import re
from datetime import datetime
import prj_common as mycommon
import secrets
import inspect
import sys, os
import csv
import pandas as pd
from pymongo import ReturnDocument
import GlobalVariable as MYSY_GV
from math import isnan
import GlobalVariable as MYSY_GV
"""
Fonction permet de récuperer la liste des
thèmes de catalogue public
"""
def Get_List_Theme_Catalog_Pub(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', ]
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list and val.startswith('my_') is False:
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'existe pas")
return False, " Les informations fournies sont incorrectes",
"""
Verification des champs obligatoires
"""
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, " Les informations fournies sont incorrectes",
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
"""
Clés de mise à jour
"""
data_cle = {}
data_cle['partner_owner_recid'] = "default"
data_cle['valide'] = "1"
data_cle['locked'] = "0"
RetObject = []
val_tmp = 0
for retval in MYSY_GV.dbname['config_partner_catalog_theme'].find(data_cle).sort([("_id", pymongo.DESCENDING), ]):
user = retval
user['id'] = str(val_tmp)
val_tmp = val_tmp + 1
RetObject.append(mycommon.JSONEncoder().encode(user))
#print(" ### RetObject = ", 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 récupérer la liste des thèmes "
"""
Cette fonction enregistrer les données de configuration
du catalog public d'un partenaire
"""
def Add_Update_Partner_Catalog_Pub_Config(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', '_id',]
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list and val.startswith('my_') is False:
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas autorisé")
return False, " Les informations fournies sont incorrectes"
"""
Verification des champs obligatoires
"""
field_list_obligatoire = ['token', '_id', ]
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, " Les informations fournies sont incorrectes"
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
return True, " La configuration du catalogue a été correctement mis à jour"
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 d'ajouter ou mettre à jour la configuration du catalogue public "
"""
Recuperation des la configuration du catalogue public
d'un partenaire
"""
def Get_Partner_Catalog_Pub_Config(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', ]
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list and val.startswith('my_') is False:
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'existe pas")
return False, " Les informations fournies sont incorrectes",
"""
Verification des champs obligatoires
"""
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, " Les informations fournies sont incorrectes",
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
"""
Clés de mise à jour
"""
data_cle = {}
data_cle['partner_owner_recid'] = my_partner['recid']
data_cle['valide'] = "1"
data_cle['locked'] = "0"
RetObject = []
val_tmp = 0
for retval in MYSY_GV.dbname['config_partner_catalog'].find(data_cle).sort([("_id", pymongo.DESCENDING), ]):
user = retval
user['id'] = str(val_tmp)
val_tmp = val_tmp + 1
RetObject.append(mycommon.JSONEncoder().encode(user))
#print(" ### RetObject = ", 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 récupérer la configuration du catalogue public "

View File

@ -2065,7 +2065,7 @@ def LMS_Get_Partner_Data(diction):
return local_status, connected_user_data
print(" #### connected_user_data = ", connected_user_data)
#print(" #### connected_user_data = ", connected_user_data)
partner_recid = mycommon.get_parnter_recid_from_token(my_token)
if (partner_recid is False):

81
main.py
View File

@ -93,7 +93,7 @@ import groupe_inscrit_mgt as groupe_inscrit_mgt
import suivi_pedagogique_mgt as suivi_pedagogique_mgt
import partner_produit_service_mgt as partner_produit_service_mgt
import model_planning_sequence_mgt as model_planning_sequence_mgt
import base_partner_catalog_config as base_partner_catalog_config
app = Flask(__name__)
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
@ -647,6 +647,28 @@ def get_all_class():
"""
Cette API retoune les formation d'un partenaore pour permettre
d'afficher son catalogue PUBLIC
"""
@app.route('/myclass/api/get_all_class_Given_partner_owner_recid_No_Login/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_all_class_Given_partner_owner_recid_No_Login():
payload = mycommon.strip_dictionary (request.form.to_dict())
print(" ### get_all_class_Given_partner_owner_recid_No_Login : payload = ", payload)
if mycommon.check_source_ipv4(str(request.remote_addr)) is False :
return jsonify(status="False", message="Security check : "+request.remote_addr+"' is not autorized")
status, result = wp.get_all_class_Given_partner_owner_recid_No_Login(payload)
response = jsonify(status=status, message=result)
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "*")
response.headers.add("Access-Control-Allow-Methods", "*")
return response
@app.route('/myclass/api/update_class_by_attribut/<objId>,<attribut>,<value>', methods=['GET','POST'])
def update_class_by_attribut(objId, attribut, value):
print(" update_class_by_attribut ")
@ -10883,6 +10905,63 @@ def Print_Employee_Given_Contrat(token, rh_id, contract_id):
return False
"""
API permet de recuperer les data du partenaire proprietaire d'un sous domaine
"""
@app.route('/myclass/api/Get_Partner_Data_From_Subdomain/', methods=['POST','GET'])
@crossdomain(origin='*')
def Get_Partner_Data_From_Subdomain():
# On recupere le corps (payload) de la requete
payload = mycommon.strip_dictionary (request.form.to_dict())
print(" ### Get_Partner_Data_From_Subdomain payload = ",payload)
status, retval = mycommon.Get_Partner_Data_From_Subdomain(payload)
return jsonify(status=status, message=retval)
"""
API de Recuperation des thème des catalog publics
"""
@app.route('/myclass/api/Get_List_Theme_Catalog_Pub/', methods=['POST','GET'])
@crossdomain(origin='*')
def Get_List_Theme_Catalog_Pub():
# On recupere le corps (payload) de la requete
payload = mycommon.strip_dictionary (request.form.to_dict())
print(" ### Get_List_Theme_Catalog_Pub payload = ",payload)
status, retval = base_partner_catalog_config.Get_List_Theme_Catalog_Pub(payload)
return jsonify(status=status, message=retval)
"""
API pour mettre à jour la configuration du catalogue public du
partenaire
"""
@app.route('/myclass/api/Add_Update_Partner_Catalog_Pub_Config/', methods=['POST','GET'])
@crossdomain(origin='*')
def Add_Update_Partner_Catalog_Pub_Config():
# On recupere le corps (payload) de la requete
payload = mycommon.strip_dictionary (request.form.to_dict())
print(" ### Add_Update_Partner_Catalog_Pub_Config payload = ",payload)
status, retval = base_partner_catalog_config.Add_Update_Partner_Catalog_Pub_Config(payload)
return jsonify(status=status, message=retval)
"""
API de Recuperation des la configuration du catalogue public
d'un partenaire
"""
@app.route('/myclass/api/Get_Partner_Catalog_Pub_Config/', methods=['POST','GET'])
@crossdomain(origin='*')
def Get_Partner_Catalog_Pub_Config():
# On recupere le corps (payload) de la requete
payload = mycommon.strip_dictionary (request.form.to_dict())
print(" ### Get_Partner_Catalog_Pub_Config payload = ",payload)
status, retval = base_partner_catalog_config.Get_Partner_Catalog_Pub_Config(payload)
return jsonify(status=status, message=retval)
if __name__ == '__main__':

View File

@ -1579,7 +1579,7 @@ def Get_Default_Partner_Document_By_Internal_Ref(diction):
RetObject = []
val_tmp = 1
val_tmp = 0
#print(" ### data_cle = ", data_cle)
for retval in MYSY_GV.dbname['courrier_template'].find({'_id':ObjectId(str(diction['original_courrier_template_id'])),

View File

@ -56,6 +56,9 @@ class JSONEncoder(json.JSONEncoder):
if ( isinstance(o, (datetime, date)) ):
return o.isoformat()
if isinstance(o, bytes):
return base64.b64encode(o).decode()
return json.JSONEncoder.default(self, o)
def myprint(message = ""):
@ -6319,3 +6322,97 @@ def Get_Courrier_Template_Exclude_Default_Data(diction):
exc_type, exc_obj, exc_tb = sys.exc_info()
myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récuperer les données du modèle de courrier "
"""
Cette fonction prend en subdomain et retourne les
données du partenaire concernée.
pour info, le subdomain = partnair_account.nom
"""
def Get_Partner_Data_From_Subdomain(diction):
try:
diction = strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['subdomain',]
"""
Verification des champs obligatoires
"""
field_list_obligatoire = ['subdomain', ]
for val in field_list_obligatoire:
if val not in diction:
myprint(
str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans liste ")
return False, " Les informations fournies sont incorrectes"
partnair_data_count = MYSY_GV.dbname['partnair_account'].count_documents({'nom':diction['subdomain'],
'active':'1',
'locked':'0',
'firstconnexion':'0'
})
if( partnair_data_count != 1 ):
myprint(
str(inspect.stack()[0][3]) + " Sous Domaine invalide ")
return False, " Sous Domaine invalide"
RetObject = []
val_tmp = 0
# print(" ### data_cle = ", data_cle)
for retval in MYSY_GV.dbname['partnair_account'].find({'nom': diction['subdomain'],
'active': '1',
'locked': '0',
'firstconnexion': '0'
}, {'_id':1, 'recid':1, 'nom':1}):
user = retval
user['id'] = str(val_tmp)
val_tmp = val_tmp + 1
"""
Recuperer les elements graphique : logo, bannière, etc
"""
config_partner_catalog_data = MYSY_GV.dbname['config_partner_catalog'].find_one({'valide':'1', 'locked':'0',
'partner_owner_recid':str(retval['recid'])})
user['catalog_pub_logo'] = ""
if( config_partner_catalog_data and "logo" in config_partner_catalog_data.keys() ):
user['catalog_pub_logo'] = config_partner_catalog_data['logo']
user['catalog_pub_message_1_txt'] = ""
if (config_partner_catalog_data and "message_1_txt" in config_partner_catalog_data.keys()):
user['catalog_pub_message_1_txt'] = config_partner_catalog_data['message_1_txt']
user['catalog_pub_message_2_txt'] = ""
if (config_partner_catalog_data and "message_2_txt" in config_partner_catalog_data.keys()):
user['catalog_pub_message_2_txt'] = config_partner_catalog_data['message_2_txt']
user['catalog_pub_banniere_img'] = ""
if (config_partner_catalog_data and "banniere_img" in config_partner_catalog_data.keys()):
user['catalog_pub_banniere_img'] = config_partner_catalog_data['banniere_img']
user['catalog_pub_theme_id'] = ""
if (config_partner_catalog_data and "theme_id" in config_partner_catalog_data.keys()):
user['catalog_pub_banniere_theme_id'] = config_partner_catalog_data['theme_id']
RetObject.append(JSONEncoder().encode(user))
# print(" ### RetObject = ", RetObject)
return True, RetObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récuperer les données liées au sous domaine "

View File

@ -341,6 +341,256 @@ def get_all_class(diction):
return False, " Impossible de récupérer les formations"
"""
A l'image de la fonction get_all_class, cette fonction
retourne les formation avec un recid donnée
"""
def get_all_class_Given_partner_owner_recid_No_Login(diction):
try:
# Dictionnaire des champs utilisables
field_list = ['token', 'user_ip', 'user_country_code', 'user_country_name', 'user_city',
'user_postal', 'user_latitude', 'user_longitude', 'user_state', 'search_text', 'certif',
'support', 'type', 'lang', 'price', 'distance', 'duration', 'cpf', 'connection_type',
'partner_owner_recid', 'subdomain']
incom_keys = diction.keys()
'''
# 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.
'''
for val in incom_keys:
if str(val).lower() not in str(field_list).lower():
mycommon.myprint(str(inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas autorisé")
return False, " Recherche impossible"
# Recuperation des parametres
mydata = {}
if ("user_ip" in diction.keys()):
if diction['user_ip']:
mydata['user_ip'] = diction['user_ip']
if ("user_country_code" in diction.keys()):
if diction['user_country_code']:
mydata['user_country_code'] = diction['user_country_code']
if ("user_country_name" in diction.keys()):
if diction['user_country_name']:
mydata['user_country_name'] = diction['user_country_name']
if ("user_city" in diction.keys()):
if diction['user_city']:
mydata['user_city'] = diction['user_city']
if ("user_postal" in diction.keys()):
if diction['user_postal']:
mydata['user_postal'] = diction['user_postal']
if ("user_latitude" in diction.keys()):
if diction['user_latitude']:
mydata['user_latitude'] = diction['user_latitude']
if ("user_longitude" in diction.keys()):
if diction['user_longitude']:
mydata['user_longitude'] = diction['user_longitude']
if ("user_state" in diction.keys()):
if diction['user_state']:
mydata['user_state'] = diction['user_state']
connection_type = ""
if ("connection_type" in diction.keys()):
if diction['connection_type']:
connection_type = diction['connection_type']
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
# print(" My Data ="+str(mydata))
partner_owner_recid = ""
if( "subdomain" in diction.keys() and diction['subdomain']):
partnair_data_count = MYSY_GV.dbname['partnair_account'].count_documents({'nom': diction['subdomain'],
'active': '1',
'locked': '0',
'firstconnexion': '0'
})
if (partnair_data_count == 1):
partnair_data = MYSY_GV.dbname['partnair_account'].find_one({'nom': diction['subdomain'],
'active': '1',
'locked': '0',
'firstconnexion': '0'
}, {'_id': 1, 'recid': 1, 'nom': 1})
if( partnair_data and 'recid' in partnair_data.keys() ):
partner_owner_recid = partnair_data['recid']
status, tab_training_inzone = get_training_in_user_zone(diction)
nb_formation_a_jouter = MYSY_GV.MAINPAGE_QUERY_LIMIT_ROW - len(tab_training_inzone)
# print(" #### get_all_class : nb_formation_a_jouter "+str(nb_formation_a_jouter)+" "
# "MYSY_GV.MAINPAGE_QUERY_LIMIT_ROW = "+str(MYSY_GV.MAINPAGE_QUERY_LIMIT_ROW)+" len(tab_training_inzone) = "+
# str(len(tab_training_inzone) ))
alread_found = []
# print(str(tab_training_inzone))
for val in tab_training_inzone:
stud_obj = json.loads(val)
json_obj = json.dumps(stud_obj)
if (stud_obj['external_code']):
alread_found.append(str(stud_obj['external_code']))
# print(" stud_obj = "+str(stud_obj['external_code']))
user_recid = "None"
# Verification de la validité du token/mail dans le cas des partner en mode connecté
if (len(str(token)) > 0 and str(connection_type).strip() == "partner"):
retval = mycommon.check_partner_token_validity("", token)
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - La session de connexion n'est pas valide")
return "Err_Connexion", "La session de connexion n'est pas valide"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(token)
if user_recid is False:
mycommon.myprint(
str(inspect.stack()[0][3]) + " - Impossible de récupérer le token de l'utilisateur")
return False, " Impossible de récupérer le token de l'utilisateur"
"""
Travail à faire :
le bug actuel vient du fait que la 2ieme requete ci-dessous qui complete la liste des formation
ajoute les formations deja trouvée dans la requete d'en haute.
A faire : faire en sorte que la requete d'en dessous exclus les elements deja trouvée dans lreque en dessus.
"""
print(" alread_found = " + str(alread_found))
coll_name = MYSY_GV.dbname['myclass']
val_tmp = len(tab_training_inzone)
insertObject = []
"""
ORIG FOR
for x in coll_name.find({ "$or": [ {'valide':'1', 'locked':'0', 'isalaune':'1', 'published':'1'}, { 'coeur': 1, 'published':'1' } ] },
{"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0,
"valide": 0, "locked": 0, }).\
"""
connected_client_recid = ""
if (str(connection_type).strip() == "partner"):
connected_client_recid = user_recid
pipe = [{'$match':
{"$and": [{"$or": [{'valide': '1', 'locked': '0', 'isalaune': '1', 'published': '1'},
{'coeur': 1, 'published': '1'}]},
{'external_code': {'$nin': alread_found}},
{'display_rank': {'$nin': []}},
{'partner_owner_recid':partner_owner_recid}
]}
},
{'$project': {'indexed': 0, 'indexed_desc': 0, 'indexed_obj': 0, "indexed_title": 0,
"valide": 0, "locked": 0}},
{'$lookup':
{
'from': 'business_prices',
'let': {'partner_owner_recid': "$partner_owner_recid", 'programme': '$programme'},
'pipeline': [
{'$match':
{'$expr':
{'$and':
[
{'$eq': ["$partner_recid", "$$partner_owner_recid"]},
{'$eq': ["$client_recid", connected_client_recid]},
{'$eq': ["$valide", "1"]}
]
}
}
},
],
'as': 'business_prices'
}
},
{'$sort': {"display_rank": pymongo.DESCENDING, "price": pymongo.ASCENDING,
"date_update": pymongo.DESCENDING}},
{'$limit': nb_formation_a_jouter},
]
print(" ### get_all_class_Given_partner_owner_recid_No_Login pipe = ", pipe)
for x in coll_name.aggregate(pipe):
"""
for x in coll_name.find(
{"$and": [{"$or": [{'valide': '1', 'locked': '0', 'isalaune': '1', 'published': '1'},
{'coeur': 1, 'published': '1'}]},
{'external_code': {'$nin': alread_found}}
]},
{"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0,
"valide": 0, "locked": 0, }).\
limit(nb_formation_a_jouter).\
sort(
[("display_rank", pymongo.DESCENDING), ("price", pymongo.ASCENDING), ("date_update", pymongo.DESCENDING) ]):
"""
# print("AVANT ==> "+str(x['description']))
if ("description" in x.keys()):
val = x['description']
no_html = mycommon.cleanhtml(x['description'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
x['description'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
else:
x['description'] = no_html
# mycommon.myprint("APRES ==> " + str(x['description']))
if ("business_prices" in x.keys()):
# print(" ### business_prices = ", x['business_prices'], " len(x['business_prices']) = ", len(x['business_prices']))
if (len(x['business_prices']) > 0 and "discount" in x['business_prices'][0].keys()):
"""
Calcal du prix discounté
"""
# print(" ### discount = ", x['business_prices'][0]['discount'], " PRIX initial = ", x['price'])
local_discount = mycommon.tryFloat(str(x['business_prices'][0]['discount']))
local_initial_price = mycommon.tryFloat(str(x['price']))
local_discounted_price = round(local_initial_price - (local_initial_price * (local_discount / 100)),
2)
x['business_prices'][0]['discounted_price'] = str(local_discounted_price)
# print(" #### local_discounted_price = ", local_discounted_price)
user = x
user['id'] = str(val_tmp)
insertObject.append(JSONEncoder().encode(user))
# print(" 1111111 ")
# print(str(x))
mycommon.InsertStatistic(x, "summary", mydata)
tab_training_inzone.append(JSONEncoder().encode(user))
val_tmp = val_tmp + 1
# print(" ### insertObject = ", str(tab_training_inzone))
# return True, insertObject
return True, tab_training_inzone
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 récupérer les formations"
'''
Cette Fonction récupérer les formations dans la zone de l'utilisateur.
Par zone utilisateur j'entends : ville or pays
@ -364,7 +614,8 @@ def get_training_in_user_zone(diction):
# Dictionnaire des champs utilisables
field_list = ['token', 'user_ip', 'user_country_code', 'user_country_name', 'user_city',
'user_postal', 'user_latitude', 'user_longitude', 'user_state', 'search_text', 'certif',
'support', 'type', 'lang', 'price', 'distance', 'duration', 'cpf', 'connection_type']
'support', 'type', 'lang', 'price', 'distance', 'duration', 'cpf', 'connection_type',
'partner_owner_recid', 'subdomain']
incom_keys = diction.keys()