10/04/2026 - 18h

Signed-off-by: Cherif <cbalde@mysy-training.com>
master_Elyos_FI
Cherif 2026-04-10 18:15:08 +02:00
parent f31de6542d
commit 552c2b926b
9 changed files with 4700 additions and 64 deletions

View File

@ -4,14 +4,16 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="c6d0259a-16e1-410d-91a1-830590ee2a08" name="Changes" comment="04/04/26 - 20h">
<list default="true" id="c6d0259a-16e1-410d-91a1-830590ee2a08" name="Changes" comment="07/04/2026 - 14h">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Inscription_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/Inscription_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Ela_Spacy.py" beforeDir="false" afterPath="$PROJECT_DIR$/Ela_Spacy.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/GlobalVariable.py" beforeDir="false" afterPath="$PROJECT_DIR$/GlobalVariable.py" 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$/Session_Formation_Sequence.py" beforeDir="false" afterPath="$PROJECT_DIR$/Session_Formation_Sequence.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/email_inscription_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/email_inscription_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/emargement.py" beforeDir="false" afterPath="$PROJECT_DIR$/emargement.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/MySy_IA/mysy_ia.py" beforeDir="false" afterPath="$PROJECT_DIR$/MySy_IA/mysy_ia.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ela_index_bdd_classes.py" beforeDir="false" afterPath="$PROJECT_DIR$/ela_index_bdd_classes.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/help_articles.py" beforeDir="false" afterPath="$PROJECT_DIR$/help_articles.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/session_admission_fi.py" beforeDir="false" afterPath="$PROJECT_DIR$/session_admission_fi.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -455,7 +457,7 @@
<option name="project" value="LOCAL" />
<updated>1747251650255</updated>
</task>
<option name="localTasksCounter" value="558" />
<option name="localTasksCounter" value="559" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
@ -497,7 +499,6 @@
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="15/02/26 - 18h30" />
<MESSAGE value="16/02/26 - 18h30" />
<MESSAGE value="18/02/2026 - 18h" />
<MESSAGE value="21/02/26 - 20h" />
@ -522,6 +523,7 @@
<MESSAGE value="26/03/2026 - 12h" />
<MESSAGE value="23/03/26 - 20h" />
<MESSAGE value="04/04/26 - 20h" />
<option name="LAST_COMMIT_MESSAGE" value="04/04/26 - 20h" />
<MESSAGE value="07/04/2026 - 14h" />
<option name="LAST_COMMIT_MESSAGE" value="07/04/2026 - 14h" />
</component>
</project>

View File

@ -218,12 +218,12 @@ def Ela_Tokenize(sentence):
'''
status, sentence = Ela_Remove_Bad_Pattern(sentence)
if( status is False ):
return False
return False, False
#print(" AFTER Ela_Remove_Bad_Pattern " + str(sentence))
status, sentence = Ela_Remove_Ponct_Special_Caractere(sentence)
if (status is False):
return False
return False, False
doc = MYSY_GV.nlp(str(sentence).lower())
@ -880,17 +880,17 @@ def Ela_article_avis_list_to_mongo(tab_tokens, traning_id, source_field):
my_file.close()
# Making a Connection with MongoClient
client = MongoClient("mongodb://localhost:27017/")
#client = MongoClient("mongodb://localhost:27017/")
# database
db = client["cherifdb"]
#db = client["cherifdb"]
# collection
collection = db["elaindex_article_avis"]
#collection = db["elaindex_article_avis"]
data.reset_index(inplace=True)
data_dict = data.to_dict("records")
# Insert collection
collection.insert_many(data_dict)
MYSY_GV.dbname['elaindex_article_avis'].insert_many(data_dict)
data.to_csv("data_indexees_article_avis.csv")
return True
@ -899,3 +899,103 @@ def Ela_article_avis_list_to_mongo(tab_tokens, traning_id, source_field):
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False
def ela_index_article_help_record_field(lines, article_help_id, source_field = ""):
try:
'''
## Suppression de toutes les indexation qui existe de cette formation
'''
# check default value of parameter : source_field
if len(str(source_field)) == 0 :
source_field = 'default'
myquery = {"id_articles_help": article_help_id, "source_field":source_field}
delete_row = MYSY_GV.dbname['elaindex_articles_help'].delete_many(myquery)
mycommon.myprint(" elaindex Article HELP : - "+str(delete_row.deleted_count)+" documents deleted. Article_HELP ==> "+str(article_help_id)+" ")
'''
Ajout des indexe
'''
status, tab_tokens = Ela_Tokenize(lines)
if( status is False):
return False
status, tab_tokens2 = Ela_remove_stop_words(tab_tokens)
if (status is False):
return False
status, tab_tokens3 = Ela_remove_pronoun(tab_tokens2)
if (status is False):
return False
status, tab_tokens4 = Ela_stemmize_Class(tab_tokens3)
if (status is False):
return False
#tab_tokens4 = Ela_Remove_Noise_from_list(tab_tokens4)
#tab_tokens4 = Ela_remove_ponct(tab_tokens4)
# Enregistrement dans la base mongodb
Ela_article_help_list_to_mongo(tab_tokens4, article_help_id, source_field)
size_tab = len(tab_tokens4)
occurrences = Counter(tab_tokens4)
most_common = occurrences.most_common()
print(most_common)
return True
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
def Ela_article_help_list_to_mongo(tab_tokens, traning_id, source_field):
try:
# clear / truncate elaindex
#db.elaindex.remove({})
# Recherche des occurence d'une valeur
my_file = open("ela_output_article_help_file_pandas_2.txt", "w")
size_tab = len(tab_tokens)
occurrences = Counter(tab_tokens)
# insert the list to the set
list_set = set(tab_tokens)
# convert the set to the list
unique_list = (list(list_set))
final_lists = []
for tmp in unique_list:
moyenne = round(int(occurrences[str(tmp)]) / size_tab, 2)
final_lists.append([str(tmp), int(str(occurrences[str(tmp)])), str(moyenne), str(traning_id), str(source_field)])
print(final_lists)
data = pd.DataFrame(final_lists, columns=('mots', "occurence", 'moyenne', 'id_article_help', 'source_field'))
my_file.write(str(data))
my_file.close()
# Making a Connection with MongoClient
client = MongoClient("mongodb://localhost:27017/")
# database
#db = client["cherifdb"]
# collection
#collection = db["elaindex_article_help"]
data.reset_index(inplace=True)
data_dict = data.to_dict("records")
# Insert collection
MYSY_GV.dbname['elaindex_article_help'].insert_many(data_dict)
data.to_csv("data_indexees_article_help.csv")
return True
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

View File

@ -976,7 +976,7 @@ EMAIL_MAX_PJ = 5
"""
La clé API de OpenAI
"""
OPENAI_KEY = "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"
OPENAI_KEY = ("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")
"""
Variable interne pour le traitement

File diff suppressed because one or more lines are too long

View File

@ -30,7 +30,7 @@ client = OpenAI(
)
GPT_MODEL = "gpt-4-1106-preview" #"gpt-3.5-turbo-1106"
GPT_MODEL = "gpt-5.4-mini" # "gpt-4-1106-preview" #"gpt-3.5-turbo-1106"
def mysy_openai_improve_text(diction):

View File

@ -1,4 +1,4 @@
from bson import ObjectId
from pymongo import MongoClient
import Ela_Spacy as ls
import prj_common as mycommon
@ -618,8 +618,6 @@ def ela_index_all_classes_desc(partner_owner_recid):
# Making a Connection with MongoClient
try:
client = MongoClient("mongodb://localhost:27017/")
# database
db = client["cherifdb"]
# collection
collection = MYSY_GV.dbname["myclass"]
'''
@ -1036,6 +1034,7 @@ def ela_recherche_tokens_source_field(sentence, source_fied=""):
Cette fonction indexe les articles et avis.
important : se ra indexé que le titre de la formation.
apres avoir été indexés la champs "indexed" passe à 1
'''
def ela_index_all_articles_avis(partner_owner_recid):
# Making a Connection with MongoClient
@ -1069,6 +1068,47 @@ def ela_index_all_articles_avis(partner_owner_recid):
return False, "Impossible d'indexer les articles et avis ==> KO"
''''
Cette fonction indexe les articles de support.
important : se ra indexé que le titre de la formation et le champ : meta_description.
apres avoir été indexés la champs "indexed" passe à 1
'''
def ela_index_all_articles_help(partner_owner_recid):
# Making a Connection with MongoClient
try:
# collection
collection = MYSY_GV.dbname["articles_help"]
nb_class_indexed = 0
for doc in collection.find({'indexed': '0'}):
if ("title_formation" in doc.keys()):
chaine = doc["title_formation"]
mycommon.myprint(" Debut indexation de l'article : "+chaine)
retval = ela_index_articles_help( str(doc["_id"]), str(doc["partner_owner_recid"]) )
print(" apres : ela_index_class retval = " + str(retval), partner_owner_recid)
if (retval is False):
mycommon.myprint("IMPOSSIBLE d'indexer la formation = " + str(doc["external_code"]))
else:
nb_class_indexed = nb_class_indexed + 1
# retval = ls.ela_index_record_field(chaine, str(doc["external_code"]))
mycommon.myprint(str(nb_class_indexed) + " ont été indexes")
return True, str(nb_class_indexed) + " articles ont été indexes "
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 d'indexer les articles et avis ==> KO"
'''
Cette fonction indexe un article / avis
Par defaut sont pris en compte :
@ -1118,6 +1158,55 @@ def ela_index_articles_avis(titre_formation="", source_field = ""):
return False
'''
Cette fonction indexe un article de support
Par defaut sont pris en compte :
- le titre de la formation
- le meta_description
'''
def ela_index_articles_help(doc_id, partner_owner_recid):
try:
for doc in MYSY_GV.dbname["articles_help"].find({'_id':ObjectId(str(doc_id)), 'partner_owner_recid':str(partner_owner_recid)}):
# Indexation par defaut : champs TITRE FORMATION
#mycommon.myprint(" external_code = "+str(doc["external_code"])+" ==> "+str(chaine))
retval1 = ls.ela_index_article_help_record_field(doc["title_formation"], str(doc["_id"]))
### ----------------
# Indexation par defaut : champsmeta_description
retval2 = ls.ela_index_article_help_record_field(doc["meta_description"], str(doc["_id"]))
'''
# Apres indexation, on met a jour la formation pour
# mettre le champ "indexe" a 1.
'''
if (retval1 or retval2):
# mise à jour du champ "indexed"
myobjectif = {}
myobjectif['indexed'] = '1'
ret_val2 = MYSY_GV.dbname["articles_help"].find_one_and_update(
{'_id': ObjectId(str(doc_id)), 'partner_owner_recid': str(partner_owner_recid)},
{"$set": myobjectif},
return_document=ReturnDocument.AFTER
)
return True
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
'''
Cette fonction recherche une chaine de caractère
dans la table des articles et avis.
@ -1128,9 +1217,17 @@ Elle retourne le title de la formation
def ela_recherche_article_avis_tokens(sentence):
tab_training_id = []
tab_tokens = ls.Ela_Tokenize(sentence)
tab_tokens2 = ls.Ela_remove_stop_words(tab_tokens)
tab_tokens3 = ls.Ela_remove_pronoun(tab_tokens2)
retval1, tab_tokens = ls.Ela_Tokenize(sentence)
if( retval1 is False):
return retval1
retval2,tab_tokens2 = ls.Ela_remove_stop_words(tab_tokens)
if (retval2 is False):
return retval2
retval3,tab_tokens3 = ls.Ela_remove_pronoun(tab_tokens2)
if (retval3 is False):
return retval3
'''
note : 26/03 : Faire evolution la fonction ici pour
gerer les mots qui ne doivent pas etre racinisé comme le cas du mot "Responsive"
@ -1183,6 +1280,81 @@ def ela_recherche_article_avis_tokens(sentence):
tab_training_id.append(str(result["_id"]))
# print(result)
print("resultat tab_training_id = " + str(tab_training_id))
return tab_training_id
"""
Recherche indexe pour un article de support"""
def ela_recherche_article_help_tokens(sentence):
tab_training_id = []
retval_status, tab_tokens = ls.Ela_Tokenize(sentence)
if( retval_status is False):
return retval_status
retval_status2, tab_tokens2 = ls.Ela_remove_stop_words(tab_tokens)
if (retval_status2 is False):
return retval_status2
retval_status3, tab_tokens3 = ls.Ela_remove_pronoun(tab_tokens2)
if (retval_status3 is False):
return retval_status3
'''
note : 26/03 : Faire evolution la fonction ici pour
gerer les mots qui ne doivent pas etre racinisé comme le cas du mot "Responsive"
De manière plus globale, il faudrait exclure certains mot de la racinisation.
'''
tab_corrected_word = []
for mot in tab_tokens3:
mycommon.recherche_check_word_in_fr_dict(str(mot))
val = ls.correct_fr_word(str(mot))
if (val):
tab_corrected_word.append(str(val))
print("corrected word = " + str(tab_corrected_word))
status, tab_tokens4 = ls.Ela_stemmize(tab_corrected_word)
if( status is False):
return False
print(" VERIF APRES STEMISATION HELP BB: " + str(tab_tokens4))
tab_tokens4.sort()
'''
tab_tokens4 contient la liste des mots à rechercher.
En suite pour chaque mot de "tab_tokens4" on regarde dans la table "elaindex"
a quoi cela pourrait correspondre.
'''
#print(" mot recherché tab_tokens4 = " + str(tab_tokens4))
pipe2 = [{'$match': {'mots': {'$in': tab_tokens4}}},
{'$group': {
'_id': "$id_article_help",
'count_class': {'$sum': 1},
'sum_occurence': {'$sum': '$occurence'}
}
},
{'$sort': {'count_class': -1, 'sum_occurence': -1}},
{'$limit': MYSY_GV.QUERY_LIMIT_ROW}
]
print(" pipe2 help = ", pipe2)
# ici limit on rows
for result in MYSY_GV.dbname["elaindex_article_help"].aggregate(pipe2):
tab_training_id.append(str(result["_id"]))
print(result)
#print("resultat tab_training_id = " + str(tab_training_id))
return tab_training_id

View File

@ -11,6 +11,7 @@ import json
from bson import ObjectId
from unidecode import unidecode
import ela_index_bdd_classes
import ela_index_bdd_classes as ela_index
import logging
from datetime import datetime, date
@ -711,7 +712,7 @@ def add_help_article(diction):
'type_formation', 'qualite', 'avis', 'note', 'qualityrating','avisrating',
'comment', 'postedby', 'url_formation', 'user_recid', 'display_header_img',
'img_path', 'date_publication', 'meta_description', 'img_file_name', 'File', 'internal_url',
'video_path', 'video_path_name']
'video_path', 'video_path_name', 'a_retenir']
incom_keys = diction.keys()
for val in incom_keys:
@ -934,6 +935,15 @@ def add_help_article(diction):
mydata['meta_description'] = meta_description
a_retenir = ""
if ("a_retenir" in diction.keys()):
if diction['a_retenir']:
a_retenir = str(diction['a_retenir']).strip().lower()[0:1000]
mydata['a_retenir'] = a_retenir
mydata['valide'] = '1'
mydata['locked'] = '0'
mydata['indexed'] = '0'
@ -947,7 +957,12 @@ def add_help_article(diction):
coll_name = MYSY_GV.dbname['articles_help']
ret_val = coll_name.insert_one(mydata)
return True, " L'article/avis a été bien ajouté"
"""
On lance l'indexation de l'article
"""
retval = ela_index_bdd_classes.ela_index_articles_help(str(ret_val.inserted_id), my_partner['recid'])
return True, " L'article support a été bien ajouté"
except Exception as e:
@ -981,7 +996,7 @@ def update_help_article(diction):
'type_formation', 'qualite', 'avis', 'note', 'qualityrating', 'avisrating',
'comment', 'postedby', 'url_formation', 'user_recid', '_id','display_header_img',
'img_path', 'date_publication', 'meta_description','img_file_name', 'File',
'video_path', 'video_path_name'
'video_path', 'video_path_name', 'a_retenir', 'internal_url'
]
incom_keys = diction.keys()
@ -1160,6 +1175,13 @@ def update_help_article(diction):
meta_description = str(diction['title_formation']).strip().lower()[0:200]
mydata['meta_description'] = meta_description
a_retenir = ""
if ("a_retenir" in diction.keys()):
if diction['a_retenir']:
a_retenir = str(diction['a_retenir']).strip().lower()[0:1000]
mydata['a_retenir'] = a_retenir
mydata['valide'] = '0'
mydata['locked'] = '1'
@ -1183,7 +1205,13 @@ def update_help_article(diction):
upsert=False,
)
return True, "L'article/avis a été correctement mis à jour "
"""
On lance l'indexation de l'article
"""
if( ret_val):
retval = ela_index_bdd_classes.ela_index_articles_help(str(ret_val['_id']), my_partner['recid'])
return True, "L'article de support a été correctement mis à jour "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
@ -1264,14 +1292,13 @@ def recherche_help_article(diction):
return retval, message
tab_training = []
tab_training = ela_index.ela_recherche_article_avis_tokens(search_text)
tab_training = ela_index.ela_recherche_article_help_tokens(search_text)
'''
Pour analyser la recherche, decommenter les 2 lignes ci-dessous
'''
#mycommon.myprint(" pour phrase : #" + search_text + "#, voici la liste des formations")
#mycommon.myprint(tab_training)
mycommon.myprint(" pour phrase : #" + search_text + "#, voici la liste des articles")
mycommon.myprint(tab_training)
coll_name = MYSY_GV.dbname['articles_help']
'''
la valeur nb_result permettra de savoir si la requete a donnée un resultat.
@ -1279,45 +1306,20 @@ def recherche_help_article(diction):
nb_result = 0
insertObject = []
for x in MYSY_GV.dbname['articles_help'].find({"external_code": {"$in": tab_training}, 'valide':'1', 'locked':'0'},
{"indexed": 0, "valide": 0, "locked": 0, }):
mycommon.myprint(x)
user = x
insertObject.append(JSONEncoder().encode(user))
for val in tab_training:
for tmp in tab_training:
for x in coll_name.find({"_id": ObjectId(my_internal_id)},
{ "indexed": 0, "valide": 0, "locked": 0, }):
for x in MYSY_GV.dbname['articles_help'].find({"_id": ObjectId(tmp), 'valide':'1', 'locked':'0'},
{"indexed": 0, "valide": 0, "locked": 0, }):
nb_result = nb_result + 1
my_recid = {}
my_recid['user_rec_id'] = str(user_recid)
mydict_combined = {**diction, **x, **my_recid}
mydict_combined['update_date'] = str(datetime.now())
mydict_combined['type_view'] = "summary"
#if ("_id" in mydict_combined.keys()):
# mydict_combined['class_id'] = mydict_combined.pop('_id')
#mycommon.myprint(x)
user = x
val = x['qualite']
if (len(x['qualite']) > MYSY_GV.MAX_CARACT):
x['qualite'] = val[:MYSY_GV.MAX_CARACT] + " ..."
else:
x['qualite'] = val[:MYSY_GV.MAX_CARACT]
val = x['avis']
CLEANR = re.compile('<.*?>')
clean_avis = re.sub(CLEANR, '', str(val))
#print(" ### CLEANRCLEANR = "+str(CLEANR))
if (len(clean_avis) > MYSY_GV.MAX_CARACT):
x['avis'] = clean_avis[:MYSY_GV.MAX_CARACT] + " ..."
else:
x['avis'] = str(clean_avis)
if ("support_type" not in x.keys()):
x['support_type'] = ""
#print(user)
insertObject.append(mycommon.JSONEncoder().encode(user))
return True, insertObject

14
main.py
View File

@ -16347,6 +16347,20 @@ def Candidat_Relance_Given_Document():
"""
API permet d'inscire une liste de candidat a une promotion
"""
@app.route('/myclass/api/Candidat_Inscrire_To_Session/', methods=['POST','GET'])
@crossdomain(origin='*')
def Candidat_Inscrire_To_Session():
# On recupere le corps (payload) de la requete
payload = mycommon.strip_dictionary (request.form.to_dict())
print(" ### Candidat_Inscrire_To_Session payload = ", payload)
status, retval = session_admission_fi.Candidat_Inscrire_To_Session(payload)
return jsonify(status=status, message=retval)
"""

View File

@ -17,6 +17,7 @@ from bson import ObjectId
import re
from datetime import datetime, date
import apprenant_mgt
import partner_client
import prj_common as mycommon
import secrets
@ -2600,6 +2601,18 @@ def Get_Synthese_Candidat_Process_Admission(diction):
if ("rang" not in retval.keys() or retval['rang'] == ""):
retval['rang'] = "999"
if ("inscrit_session_id" not in retval.keys() ):
retval['inscrit_session_id'] = ""
inscrit_session_code = ""
if( "inscrit_session_id" in retval.keys() and retval['inscrit_session_id']):
local_session_data = MYSY_GV.dbname['session_formation'].find_one({'_id':ObjectId(retval['inscrit_session_id']), 'partner_owner_recid':str(my_partner['recid'])})
if( local_session_data and 'code_session' in local_session_data.keys()):
inscrit_session_code = local_session_data['code_session']
retval['inscrit_session_code'] = inscrit_session_code
age = relativedelta( date.today(), datetime.strptime(str(retval['date_naissance']), '%d/%m/%Y') )
retval['age'] = str(age.years)
@ -2898,3 +2911,338 @@ def Candidat_Relance_Given_Document(diction=None):
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, "Impossible d'envoyer l'email de relance "
"""
Inscrire une liste d'apprenant à une session de formation
Si une unité d'enseignement est fourni, alors l'incription
concernant uniquement cette ue (collection : inscription_liste_ue)
Algorithme :
1 - Création ou récupération du dossier de l'apprenant
2 - Inscription de l'apprenant à promotion concernée
"""
def Candidat_Inscrire_To_Session(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'list_candidat_id', 'admission_session_id', 'session_id',
'type_apprenant' , 'modefinancement',
'client_rattachement_id', 'tab_ue_ids']
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', 'list_candidat_id', 'admission_session_id', 'session_id',
'type_apprenant' ]
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 la liste des arguments ")
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
"""
S'il y a des ue, verifier la validité des ue
"""
my_ue_ids = ""
tab_ue_ids = []
if ("tab_ue_ids" in diction.keys()):
if diction['tab_ue_ids']:
my_ue_ids = diction['tab_ue_ids']
tab_ue_ids_work = str(my_ue_ids).split(",")
for tmp in tab_ue_ids_work:
if( tmp ):
tab_ue_ids.append(tmp)
for val in tab_ue_ids :
is_eu_count = MYSY_GV.dbname['unite_enseignement'].count_documents({'_id':ObjectId(str(val)),
'valide':'1',
'locked':'0',
'partner_owner_recid':str(my_partner['recid'])})
if( is_eu_count != 1):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'unité d'enseignement "+str(val)+" est invalide ")
return False, " L'unité d'enseignement "+str(val)+" est invalide "
# Verifier que le type d'apprenant est bien valide
type_apprenant = "0"
if( str(diction['type_apprenant']) not in MYSY_GV.INSCRIPTION_TYPE_APPRENANT ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le type d'apprenant est invalide ")
return False, " Le type d'apprenant est invalide "
else:
type_apprenant = str(diction['type_apprenant'])
# Verifier la validité du client, s'il ya un client
client_rattachement_id = ""
if ("client_rattachement_id" in diction.keys() and diction['client_rattachement_id']):
is_client_rattachement_id_exist = MYSY_GV.dbname['partner_client'].count_documents(
{'_id': ObjectId(diction['client_rattachement_id']),
'partner_owner_recid': str(
my_partner['recid']),
'valide': '1',
'locked': '0'})
if (is_client_rattachement_id_exist <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant du client n'est pas valide ")
return False, " L'identifiant du client n'est pas valide ",
client_rattachement_id = str(diction['client_rattachement_id'])
"""
Creation ou mise à jour dossier apprenant
"""
list_candidat_ids = []
if ("list_candidat_id" in diction.keys()):
if diction['list_candidat_id']:
my_list_candidat_id = diction['list_candidat_id']
list_candidat_id_work = str(my_list_candidat_id).split(",")
for tmp in list_candidat_id_work:
if (tmp):
is_valide_candidat_count = MYSY_GV.dbname['admission_session_inscrit'].count_documents({'_id':ObjectId(tmp),
'partner_owner_recid':str(my_partner['recid']),
'locked':'0',
'valide':'1'})
if( is_valide_candidat_count != 1):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant "+str(tmp)+" du candidat est invalide ")
return False, " L'identifiant "+str(tmp)+" du candidat est invalide "
candidat_data = MYSY_GV.dbname['admission_session_inscrit'].find_one(
{'_id': ObjectId(tmp),
'partner_owner_recid': str(my_partner['recid']),
'locked': '0',
'valide': '1'},
{'email': 1, })
is_candidat_exist_in_apprenant_count = MYSY_GV.dbname['apprenant'].count_documents(
{'email': candidat_data['email'],
'partner_owner_recid': str(my_partner['recid'])})
if (is_candidat_exist_in_apprenant_count > 1):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " Il existe déjà plusieurs apprenants ayant pour adresse email " + str(
candidat_data['email']))
return False, " Il existe déjà plusieurs apprenants ayant pour adresse email " + str(
candidat_data['email'])
list_candidat_ids.append(tmp)
# Verifier que la session de formation existe et est valide et qu'elle n'est pas completement facturée
is_session_existe = MYSY_GV.dbname['session_formation'].count_documents(
{'_id': ObjectId(str(diction['session_id'])),
'partner_owner_recid': str(my_partner['recid']),
'valide': '1',
'invoiced_statut': {'$ne': '2'},
})
if (is_session_existe <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant de la promotion / session de formation n'est pas valide ")
return False, " L'identifiant de la promotion / session de formation n'est pas valide ",
"""
Creation du dossier apprenant avec un mise à jour
"""
list_apprenant_id = []
for candidat_id in list_candidat_ids:
candidat_data = MYSY_GV.dbname['admission_session_inscrit'].find_one(
{'_id': ObjectId(candidat_id),
'partner_owner_recid': str(my_partner['recid']),
'locked': '0',
'valide': '1'}, {'_id':0, 'relances_document':0, 'rang':0, 'update_by':0, 'update_date':0, 'session_etape':0})
is_candidat_exist_in_apprenant_count = MYSY_GV.dbname['apprenant'].count_documents({'email':candidat_data['email'],
'partner_owner_recid':str(my_partner['recid'])})
if( is_candidat_exist_in_apprenant_count == 1):
# On fait une mise à jour du dossier apprenant
candidat_data['update_date'] = str(datetime.now())
candidat_data['update_by'] = str(my_partner['_id'])
elif( is_candidat_exist_in_apprenant_count == 0):
# Il s'agit d'une creation
candidat_data['creation_date'] = str(datetime.now())
candidat_data['creation_by'] = str(my_partner['_id'])
"""
Creation du matricule de l'apprenant
"""
# Récuperation de la sequence de l'objet "apprenant_matricule" dans la collection : "mysy_sequence"
retval_sequence_matricule_apprenant = MYSY_GV.dbname['mysy_sequence'].find_one(
{'related_mysy_object': 'apprenant_matricule',
'valide': '1', 'partner_owner_recid': str(
my_partner['recid'])})
if (retval_sequence_matricule_apprenant is None):
# Il n'y pas de sequence pour le partenaire, on va aller chercher la sequence par defaut
retval_sequence_matricule_apprenant = MYSY_GV.dbname['mysy_sequence'].find_one(
{'related_mysy_object': 'apprenant_matricule',
'valide': '1', 'partner_owner_recid': 'default'})
apprenant_matricule = ""
if (
retval_sequence_matricule_apprenant is None or "current_val" not in retval_sequence_matricule_apprenant.keys()):
mycommon.myprint(
" WARNING : Impossible de récupérer la sequence 'apprenant_matricule' pour créer le matricule")
else:
current_seq_value = str(retval_sequence_matricule_apprenant['current_val'])
new_sequence_value = int(mycommon.tryInt(current_seq_value)) + 1
new_sequance_data_to_update = {'current_val': new_sequence_value}
ret_val2 = MYSY_GV.dbname['mysy_sequence'].find_one_and_update(
{'_id': ObjectId(str(retval_sequence_matricule_apprenant['_id'])), 'valide': '1'},
{"$set": new_sequance_data_to_update},
return_document=ReturnDocument.AFTER,
upsert=False,
)
apprenant_matricule = retval_sequence_matricule_apprenant['prefixe'] + str(current_seq_value)
candidat_data['matricule'] = str(apprenant_matricule)
result = MYSY_GV.dbname['apprenant'].find_one_and_update(
{'email': candidat_data['email'],
'partner_owner_recid': str(my_partner['recid'])},
{"$set": candidat_data},
upsert=True,
return_document=ReturnDocument.AFTER
)
if( result and '_id' in result.keys()):
list_apprenant_id.append(result['_id'])
is_blocking_message = False
blocking_message = "Erreur : "
for apprenant_id in list_apprenant_id :
# Recuperer les données de l'apprenant
apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id': ObjectId(str(apprenant_id)),
'partner_owner_recid': str(my_partner['recid']),
'valide': '1',
'locked': '0'})
# Verifier que l'apprenant n'est pas inscrit à cette session
is_inscrit_session_count = MYSY_GV.dbname['inscription'].count_documents({'session_id':str(diction['session_id']),
'apprenant_id':str(apprenant_id)})
if( is_inscrit_session_count > 0 ):
is_blocking_message = True
blocking_message = "\n L'apprenant :" + str(apprenant_data['email']) + " est déjà inscrit à cette session "
if( is_blocking_message is True):
return False, blocking_message
is_warning_message = False
warning_message = "Warning : "
# field_list = ['token', '_id', 'session_id', 'type_apprenant' , 'modefinancement']
#print(" ### list_apprenant_id = ", list_apprenant_id)
for apprenant_id in list_apprenant_id:
# Recuperer les données de l'apprenant
apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id': ObjectId(str(apprenant_id)),
'partner_owner_recid': str(my_partner['recid']),
'valide': '1',
'locked': '0'})
local_diction = {}
local_diction['token'] = diction['token']
local_diction['_id'] = str(apprenant_id)
local_diction['session_id'] = diction['session_id']
local_diction['type_apprenant'] = diction['type_apprenant']
local_diction['modefinancement'] = diction['modefinancement']
local_diction['client_rattachement_id'] = client_rattachement_id
if( "tab_ue_ids" in diction.keys() ):
local_diction['tab_ue_ids'] = str(diction['tab_ue_ids'])
print(" ### local_diction inscription apprenant = ", local_diction)
local_status, local_retval = apprenant_mgt.Apprenant_Inscrire_Session(local_diction)
if( local_status is False ):
is_warning_message = True
warning_message = "\n impossible d'inscrire l'apprenant : " + str(apprenant_data['email']) + " "
"""
Mettre à jour le candidat pour dire qu'il a été inscrit
"""
for candidat_id in list_candidat_ids:
candidat_data = MYSY_GV.dbname['admission_session_inscrit'].find_one(
{'_id': ObjectId(candidat_id),
'partner_owner_recid': str(my_partner['recid']),
'locked': '0',
'valide': '1'}, {'_id':0, 'relances_document':0, 'rang':0, 'update_by':0, 'update_date':0, 'session_etape':0})
local_update_data = {}
local_update_data['inscrit_session_id'] = diction['session_id']
local_update_data['update_date'] = str(datetime.now())
local_update_data['update_by'] = str(my_partner['_id'])
local_update_data['inscrit_session_date'] = str(datetime.now())
ret_val2 = MYSY_GV.dbname['admission_session_inscrit'].find_one_and_update(
{'_id': ObjectId(candidat_id), 'partner_owner_recid': str(my_partner['recid']),},
{"$set": local_update_data},
return_document=ReturnDocument.AFTER,
upsert=False,
)
if (is_warning_message is True):
return True, " Les apprenants ont été inscrits avec les erreurs suivantes : \n " + str(warning_message)
return True, " Les apprenants ont été correctement inscrits "
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'inscrire les apprenants à la session de formation "