1558 lines
69 KiB
Python
1558 lines
69 KiB
Python
"""
|
|
Ce fichier permet de gerer les apprenants.
|
|
|
|
Un apprenant est crée apres la validation d'une inscription ou sans.
|
|
|
|
"""
|
|
import ast
|
|
|
|
import pymongo
|
|
from pymongo import MongoClient
|
|
import json
|
|
from bson import ObjectId
|
|
import re
|
|
from datetime import datetime, date
|
|
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
|
|
import ela_index_bdd_classes as eibdd
|
|
import email_mgt as email
|
|
import Inscription_mgt as Inscription_mgt
|
|
import Session_Formation as sf
|
|
|
|
"""
|
|
Ajout d'un apprenant.
|
|
La clé est l'adresse email
|
|
"""
|
|
|
|
# xxxx - log historique dans les fonction
|
|
def Add_Apprenant(diction):
|
|
try:
|
|
diction = mycommon.strip_dictionary(diction)
|
|
|
|
"""
|
|
Verification des input acceptés
|
|
"""
|
|
field_list = ['token', 'email', 'nom', 'prenom', 'telephone', 'opco', 'employeur', 'comment',
|
|
'client_rattachement_id', 'adresse', 'code_postal', 'ville', 'pays',
|
|
'tuteur1_nom', 'tuteur1_prenom', 'tuteur1_email', 'tuteur1_telephone', 'tuteur1_adresse',
|
|
'tuteur1_cp', 'tuteur1_ville', 'tuteur1_pays', 'tuteur1_include_com',
|
|
'tuteur2_nom', 'tuteur2_prenom', 'tuteur2_email', 'tuteur2_telephone', 'tuteur2_adresse',
|
|
'tuteur2_cp', 'tuteur2_ville', 'tuteur2_pays', 'tuteur2_include_com', 'civilite'
|
|
]
|
|
|
|
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','email', 'nom', 'prenom' ]
|
|
|
|
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
|
|
|
|
# Verifier que l'adresse email est valide
|
|
if( "email" in diction.keys() and diction['email']):
|
|
if( mycommon.isEmailValide(str(diction['email'])) is False ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email '"+str(diction['email'])+"' n'est pas valide")
|
|
return False, " L'adresse email '"+str(diction['email'])+"' n'est pas valide "
|
|
|
|
|
|
# Verifier qu'il n'y pas un apprenant avec le mail
|
|
qry = {'email':str(diction['email']),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1'}
|
|
|
|
print(" ### qry = ", qry)
|
|
|
|
is_apprenant_email_exist = MYSY_GV.dbname['apprenant'].count_documents({'email':str(diction['email']),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1'})
|
|
|
|
if(is_apprenant_email_exist > 0):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " Il y a déjà un apprenant avec la même adresse email : '" + str(diction['email']) + "' ")
|
|
return False, " Il y a déjà un apprenant avec la même adresse email : '" + str(diction['email']) + "' "
|
|
|
|
|
|
|
|
# Verifier l'adresse email du tuteur 1
|
|
if ("tuteur1_email" in diction.keys() and diction['tuteur1_email']):
|
|
if (mycommon.isEmailValide(str(diction['tuteur1_email'])) is False):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email '" + str(diction['tuteur1_email']) + "' n'est pas valide")
|
|
return False, " L'adresse email '" + str(diction['tuteur1_email']) + "' n'est pas valide ",
|
|
|
|
|
|
# Verifier l'adresse email du tuteur 2
|
|
if ("tuteur2_email" in diction.keys() and diction['tuteur2_email']):
|
|
if (mycommon.isEmailValide(str(diction['tuteur2_email'])) is False):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email '" + str(
|
|
diction['tuteur2_email']) + "' n'est pas valide")
|
|
return False, " L'adresse email '" + str(diction['tuteur2_email']) + "' n'est pas valide ",
|
|
|
|
|
|
# Verifier que le client_rattachement_id est valide
|
|
if ("client_rattachement_id" in diction.keys() and diction['client_rattachement_id']):
|
|
is_client_rattachement_id_valide = MYSY_GV.dbname['partner_client'].count_documents({'_id':ObjectId(str(diction['client_rattachement_id'])),
|
|
'valide':'1',
|
|
'locked':'0',
|
|
'partner_recid':str(my_partner['recid'])})
|
|
if( is_client_rattachement_id_valide <= 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 ",
|
|
|
|
|
|
|
|
# Verifier si un apprenant n'a pas deja ce meme email
|
|
is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'email':str(diction['email']),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1'})
|
|
|
|
if( is_apprenant_exist > 0 ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " Il existe déjà un apprenant avec la même adresse email. ")
|
|
return False, " Il existe déjà un apprenant avec la même adresse email. ",
|
|
|
|
|
|
new_data = diction
|
|
local_token = new_data['token']
|
|
|
|
# Initialisation des champs non envoyés à vide
|
|
for val in field_list:
|
|
if val not in diction.keys():
|
|
new_data[str(val)] = ""
|
|
|
|
|
|
new_data['valide'] = '1'
|
|
new_data['locked'] = '0'
|
|
new_data['partner_owner_recid'] = str(my_partner['recid'])
|
|
new_data['date_update'] = str(datetime.now())
|
|
new_data['update_by'] = str(my_partner['_id'])
|
|
|
|
todays_date = str(date.today().strftime("%d/%m/%Y"))
|
|
|
|
new_data['date_creation'] = str(todays_date)
|
|
|
|
del new_data['token']
|
|
inserted_id = MYSY_GV.dbname['apprenant'].insert_one(new_data).inserted_id
|
|
if (not inserted_id):
|
|
mycommon.myprint(
|
|
" Impossible de créer l'apprenant (1) ")
|
|
return False, " Impossible de créer l'apprenant (1) "
|
|
|
|
## Add to log history
|
|
now = str(datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
|
|
history_event_dict = {}
|
|
history_event_dict['token'] = local_token
|
|
history_event_dict['related_collection'] = "apprenant"
|
|
history_event_dict['related_collection_recid'] = str(inserted_id)
|
|
history_event_dict['action_date'] = str(now)
|
|
history_event_dict['action_description'] = "Creation"
|
|
local_status, local_retval = mycommon.Collection_Historique.Add_Historique_Event(history_event_dict)
|
|
if (local_status is False):
|
|
mycommon.myprint(
|
|
" WARNING : Impossible de logguer l'historique pour l'évènement : " + str(history_event_dict))
|
|
|
|
return True, "L'apprenant a été correctement ajouté "
|
|
|
|
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 créer l'apprenant "
|
|
|
|
|
|
"""
|
|
Mise à jour d'un apprenant.
|
|
La clé : _id
|
|
"""
|
|
def Update_Apprenant(diction):
|
|
try:
|
|
diction = mycommon.strip_dictionary(diction)
|
|
|
|
"""
|
|
Verification des input acceptés
|
|
"""
|
|
field_list = ['token', '_id', 'email', 'nom', 'prenom', 'telephone', 'opco', 'employeur', 'comment',
|
|
'client_rattachement_id', 'adresse', 'code_postal', 'ville', 'pays',
|
|
'tuteur1_nom', 'tuteur1_prenom', 'tuteur1_email', 'tuteur1_telephone', 'tuteur1_adresse',
|
|
'tuteur1_cp', 'tuteur1_ville', 'tuteur1_pays', 'tuteur1_include_com',
|
|
'tuteur2_nom', 'tuteur2_prenom', 'tuteur2_email', 'tuteur2_telephone', 'tuteur2_adresse',
|
|
'tuteur2_cp', 'tuteur2_ville', 'tuteur2_pays', 'tuteur2_include_com', 'civilite'
|
|
]
|
|
|
|
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
|
|
|
|
# Verifier que l'apprenant existe deja
|
|
is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(str(diction['_id'])),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1',
|
|
'locked':'0'})
|
|
if( is_apprenant_exist <= 0 ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant n'est pas valide ")
|
|
return False, " L'identifiant de l'apprenant n'est pas valide ",
|
|
|
|
|
|
# Verifier que l'adresse email est valide
|
|
if ("email" in diction.keys() and diction['email']):
|
|
if (mycommon.isEmailValide(str(diction['email'])) is False):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email '" + str(diction['email']) + "' n'est pas valide")
|
|
return False, " L'adresse email '" + str(diction['email']) + "' n'est pas valide ",
|
|
|
|
# Verifier l'adresse email du tuteur 1
|
|
if ("tuteur1_email" in diction.keys() and diction['tuteur1_email']):
|
|
if (mycommon.isEmailValide(str(diction['tuteur1_email'])) is False):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email '" + str(
|
|
diction['tuteur1_email']) + "' n'est pas valide")
|
|
return False, " L'adresse email '" + str(diction['tuteur1_email']) + "' n'est pas valide ",
|
|
|
|
# Verifier l'adresse email du tuteur 2
|
|
if ("tuteur2_email" in diction.keys() and diction['tuteur2_email']):
|
|
if (mycommon.isEmailValide(str(diction['tuteur2_email'])) is False):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email '" + str(
|
|
diction['tuteur2_email']) + "' n'est pas valide")
|
|
return False, " L'adresse email '" + str(diction['tuteur2_email']) + "' n'est pas valide ",
|
|
|
|
# Verifier que le client_rattachement_id est valide
|
|
if ("client_rattachement_id" in diction.keys() and diction['client_rattachement_id']):
|
|
is_client_rattachement_id_valide = MYSY_GV.dbname['partner_client'].count_documents(
|
|
{'_id': ObjectId(str(diction['client_rattachement_id'])),
|
|
'valide': '1',
|
|
'locked': '0',
|
|
'partner_recid': str(my_partner['recid'])})
|
|
if (is_client_rattachement_id_valide <= 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 ",
|
|
|
|
apprenant_id = str(diction['_id'])
|
|
stored_token = str(diction['token'])
|
|
new_data = diction
|
|
del new_data['token']
|
|
del new_data['_id']
|
|
|
|
new_data['valide'] = '1'
|
|
new_data['locked'] = '0'
|
|
new_data['date_update'] = str(datetime.now())
|
|
new_data['update_by'] = str(my_partner['_id'])
|
|
|
|
ret_val = MYSY_GV.dbname['apprenant'].find_one_and_update(
|
|
{'_id': ObjectId(str(apprenant_id)),
|
|
'partner_owner_recid':str(my_partner['recid'])},
|
|
{"$set": new_data},
|
|
upsert=False,
|
|
return_document=ReturnDocument.AFTER
|
|
)
|
|
|
|
if ret_val is None or ret_val['_id'] is None:
|
|
mycommon.myprint(str(inspect.stack()[0][3]) + " Impossible de mettre à jour l'apprenant (1) ")
|
|
return False, " Impossible de mettre à jour l'apprenant (1) "
|
|
|
|
## Add to log history
|
|
now = str(datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
|
|
history_event_dict = {}
|
|
history_event_dict['token'] = stored_token
|
|
history_event_dict['related_collection'] = "apprenant"
|
|
history_event_dict['related_collection_recid'] = apprenant_id
|
|
history_event_dict['action_date'] = str(now)
|
|
history_event_dict['action_description'] = "Mise à jour "
|
|
local_status, local_retval = mycommon.Collection_Historique.Add_Historique_Event(history_event_dict)
|
|
if (local_status is False):
|
|
mycommon.myprint(
|
|
" WARNING : Impossible de logguer l'historique pour l'évènement : " + str(history_event_dict))
|
|
|
|
|
|
return True, "L'apprenant a été correctement mise à 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 de mettre à jour l'apprenant "
|
|
|
|
|
|
"""
|
|
Recuperer les données detaillée d'un apprenant
|
|
"""
|
|
def Get_Given_Apprenant_Data(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
|
|
|
|
# Verifier que l'apprenant existe deja
|
|
is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(str(diction['_id'])),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1',
|
|
'locked':'0'})
|
|
if( is_apprenant_exist <= 0 ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant n'est pas valide ")
|
|
return False, " L'identifiant de l'apprenant n'est pas valide ",
|
|
|
|
RetObject = []
|
|
val_tmp = 1
|
|
for val in MYSY_GV.dbname['apprenant'].find({'_id':ObjectId(str(diction['_id'])),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1',
|
|
'locked':'0'}):
|
|
user = val
|
|
user['id'] = str(val_tmp)
|
|
val_tmp = val_tmp + 1
|
|
|
|
# Recuperer les données du client
|
|
if( "client_rattachement_id" in val.keys() and val['client_rattachement_id'] ):
|
|
client_data = MYSY_GV.dbname['partner_client'].find_one({'_id':ObjectId(str(val['client_rattachement_id'])),
|
|
'valide':'1',
|
|
'locked':'0'})
|
|
user['client_nom'] = client_data['nom']
|
|
|
|
RetObject.append(mycommon.JSONEncoder().encode(user))
|
|
|
|
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 les données de l'apprenant "
|
|
|
|
|
|
|
|
|
|
"""
|
|
Fonction pour supprimer un apprenant si toutes les conditions sont remplies.
|
|
|
|
Condition :
|
|
- pas d'inscription en cours ou validé
|
|
"""
|
|
def Delete_Given_Apprenant(diction):
|
|
try:
|
|
diction = mycommon.strip_dictionary(diction)
|
|
|
|
"""
|
|
Verification des input acceptés
|
|
"""
|
|
field_list = ['token', 'apprenant_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', 'apprenant_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
|
|
|
|
# Verifier que l'apprenant existe deja
|
|
is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(str(diction['apprenant_id'])),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1',
|
|
'locked':'0'})
|
|
if( is_apprenant_exist <= 0 ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant n'est pas valide ")
|
|
return False, " L'identifiant de l'apprenant n'est pas valide "
|
|
|
|
|
|
"""
|
|
Verifier que l'apprenant n'as pas d'incripiotn en cours ou valide
|
|
"""
|
|
is_apprenant_has_valide_inscription_count = MYSY_GV.dbname['inscription'].count_documents({'apprenant_id':str(diction['apprenant_id']),
|
|
'status': {'$in': ['0','1','2'], },
|
|
'partner_owner_recid':str(my_partner['recid'])})
|
|
|
|
if( is_apprenant_has_valide_inscription_count > 0 ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " Impossible de supprimer l'apprenant, il a "+str(is_apprenant_has_valide_inscription_count)+" inscription(s) en cours ou déjà validée(s) ")
|
|
return False, " Impossible de supprimer l'apprenant, il a "+str(is_apprenant_has_valide_inscription_count)+" inscription(s) en cours ou déjà validée(s) "
|
|
|
|
delete_retval = MYSY_GV.dbname['apprenant'].delete_one(
|
|
{'_id': ObjectId(str(diction['apprenant_id'])),
|
|
'partner_owner_recid':str(my_partner['recid'])}
|
|
)
|
|
|
|
return True, " L'apprenant a été correctement supprimé "
|
|
|
|
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 supprimer de l'apprenant "
|
|
|
|
|
|
|
|
"""
|
|
Récuperer la liste des apprenants d'un partenaire
|
|
"""
|
|
def Get_List_Partner_Apprenant(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'est pas autorisé")
|
|
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
|
|
|
|
RetObject = []
|
|
val_tmp = 1
|
|
for val in MYSY_GV.dbname['apprenant'].find({'partner_owner_recid': str(my_partner['recid']),
|
|
'valide': '1',
|
|
'locked': '0'}):
|
|
user = val
|
|
user['id'] = str(val_tmp)
|
|
val_tmp = val_tmp + 1
|
|
|
|
# Recuperer les données du client
|
|
if ("client_rattachement_id" in val.keys() and val['client_rattachement_id']):
|
|
client_data = MYSY_GV.dbname['partner_client'].find_one(
|
|
{'_id': ObjectId(str(val['client_rattachement_id'])),
|
|
'valide': '1',
|
|
'locked': '0'})
|
|
user['client_nom'] = client_data['nom']
|
|
|
|
RetObject.append(mycommon.JSONEncoder().encode(user))
|
|
|
|
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 apprenants "
|
|
|
|
|
|
"""
|
|
Recuperer la liste des apprenant avec des filtrer
|
|
"""
|
|
|
|
|
|
def Get_Apprenant_List_Partner_with_filter(diction):
|
|
try:
|
|
field_list = ['token', 'nom', 'prenom', 'email']
|
|
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é, Creation partenaire annulée")
|
|
return False, " Toutes les informations fournies ne sont pas valables"
|
|
|
|
"""
|
|
Verification de la liste 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, " Toutes les informations necessaires n'ont pas été fournies"
|
|
|
|
# Recuperation du recid du partner
|
|
mydata = {}
|
|
mytoken = ""
|
|
if ("token" in diction.keys()):
|
|
if diction['token']:
|
|
mytoken = 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
|
|
|
|
filt_email = {}
|
|
if ("email" in diction.keys()):
|
|
filt_email = {'email': {'$regex': str(diction['email']), "$options": "i"}}
|
|
|
|
filt_nom = {}
|
|
if ("nom" in diction.keys()):
|
|
filt_nom = {'nom': {'$regex': str(diction['nom']), "$options": "i"}}
|
|
|
|
filt_prenom = {}
|
|
if ("nom" in diction.keys()):
|
|
filt_prenom = {'prenom': {'$regex': str(diction['prenom']), "$options": "i"}}
|
|
|
|
filt_class_partner_recid = {'partner_owner_recid': str(my_partner['recid'])}
|
|
|
|
query = [{'$match': {'$and': [filt_email, filt_nom, {'partner_owner_recid': str(my_partner['recid'])}]}},
|
|
|
|
]
|
|
print("#### Get_Apprenant_List_Partner_with_filter laa 01 : query = ", query)
|
|
RetObject = []
|
|
cpt = 1
|
|
for retVal in MYSY_GV.dbname['inscription'].aggregate(query):
|
|
val = retVal
|
|
val['id'] = str(cpt)
|
|
cpt = cpt + 1
|
|
|
|
RetObject.append(mycommon.JSONEncoder().encode(val))
|
|
|
|
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) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
|
|
return False, "Impossible de récupérer la liste des apprenants"
|
|
|
|
|
|
"""
|
|
Inscrire un apprenant à un session de formation.
|
|
|
|
"""
|
|
def Apprenant_Inscrire_Session(diction):
|
|
try:
|
|
diction = mycommon.strip_dictionary(diction)
|
|
|
|
"""
|
|
Verification des input acceptés
|
|
"""
|
|
field_list = ['token', '_id', 'session_id', 'type_apprenant' , 'modefinancement']
|
|
|
|
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', '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 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
|
|
|
|
# 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 que l'apprenant existe
|
|
is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(str(diction['_id'])),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1',
|
|
'locked':'0'})
|
|
if( is_apprenant_exist <= 0 ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant n'est pas valide ")
|
|
return False, " L'identifiant de l'apprenant n'est pas valide ",
|
|
|
|
# Recuperer les données de l'apprenant
|
|
apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id': ObjectId(str(diction['_id'])),
|
|
'partner_owner_recid': str(my_partner['recid']),
|
|
'valide': '1',
|
|
'locked': '0'})
|
|
|
|
# Verifier que la session de formation existe et est valide
|
|
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',
|
|
})
|
|
|
|
if (is_apprenant_exist <= 0):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'identifiant de la session de formation n'est pas valide ")
|
|
return False, " L'identifiant de la session de formation n'est pas valide ",
|
|
|
|
# Recuperer les données de la session
|
|
session_data = MYSY_GV.dbname['session_formation'].find_one(
|
|
{'_id': ObjectId(str(diction['session_id'])),
|
|
'partner_owner_recid': str(my_partner['recid']),
|
|
'valide': '1',
|
|
})
|
|
|
|
|
|
new_data = {}
|
|
new_data['token'] = diction['token']
|
|
new_data['email'] = apprenant_data['email']
|
|
new_data['nom'] = apprenant_data['nom']
|
|
new_data['prenom'] = apprenant_data['prenom']
|
|
new_data['telephone'] = apprenant_data['telephone']
|
|
new_data['modefinancement'] = str(diction['modefinancement'])
|
|
|
|
|
|
new_data['apprenant_id'] = str(apprenant_data['_id'])
|
|
new_data['session_id'] = str(session_data['_id'])
|
|
new_data['class_internal_url'] = session_data['class_internal_url']
|
|
new_data['status'] = "1"
|
|
new_data['type_apprenant'] = str(type_apprenant)
|
|
|
|
|
|
new_data['inscription_validation_date'] = str(datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
|
|
#new_data['date_update'] = str(datetime.now())
|
|
#new_data['update_by'] = str(my_partner['_id'])
|
|
#new_data['partner_owner_recid'] = str(my_partner['recid'])
|
|
|
|
local_status, local_retval = Inscription_mgt.AddStagiairetoClass(new_data)
|
|
if( local_status is False ):
|
|
return local_status, local_retval
|
|
|
|
## Add to log history
|
|
now = str(datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
|
|
history_event_dict = {}
|
|
history_event_dict['token'] = diction['token']
|
|
history_event_dict['related_collection'] = "apprenant"
|
|
history_event_dict['related_collection_recid'] = str(diction['_id'])
|
|
history_event_dict['action_date'] = str(now)
|
|
history_event_dict['action_description'] = "Inscription session "+str(session_data["code_session"])
|
|
local_status, local_retval = mycommon.Collection_Historique.Add_Historique_Event(history_event_dict)
|
|
if (local_status is False):
|
|
mycommon.myprint(
|
|
" WARNING : Impossible de logguer l'historique pour l'évènement : " + str(history_event_dict))
|
|
|
|
return True, " L'apprenant a été correctement inscrit à la session de formation"
|
|
|
|
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 l'apprenant à la session de formation "
|
|
|
|
|
|
"""
|
|
Recuperation de la liste des inscriptions de cet apprenant
|
|
"""
|
|
def Get_Apprenant_List_Inscription(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
|
|
|
|
# Verifier que l'apprenant existe deja
|
|
is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(str(diction['_id'])),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
'valide':'1',
|
|
'locked':'0'})
|
|
if( is_apprenant_exist <= 0 ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant n'est pas valide ")
|
|
return False, " L'identifiant de l'apprenant n'est pas valide ",
|
|
|
|
RetObject = []
|
|
val_tmp = 1
|
|
|
|
|
|
for val in MYSY_GV.dbname['inscription'].find({'apprenant_id':str(diction['_id']),
|
|
'partner_owner_recid':str(my_partner['recid']),
|
|
}, {"_id":1, "class_internal_url":1,"session_id":1, 'status':1,
|
|
"inscription_validation_date":1, "modefinancement":1, "inscription_refuse_date":1,}):
|
|
user = val
|
|
user['id'] = str(val_tmp)
|
|
val_tmp = val_tmp + 1
|
|
local_diction = {'token':str(diction['token']), 'class_internal_url':str(val['class_internal_url']), 'session_id':str(val['session_id'])}
|
|
|
|
local_status, local_retval_str = sf.GetSessionFormation(local_diction)
|
|
if( local_status is False ):
|
|
return local_status, local_retval
|
|
|
|
|
|
local_retval = ast.literal_eval(local_retval_str[0])
|
|
|
|
if( local_retval and "title" in local_retval.keys()):
|
|
user['class_title'] = local_retval['title']
|
|
|
|
if (local_retval and "formateur_nom_prenom" in local_retval.keys()):
|
|
user['formateur_nom_prenom'] = local_retval['formateur_nom_prenom']
|
|
|
|
if (local_retval and "date_debut" in local_retval.keys()):
|
|
user['date_debut'] = local_retval['date_debut']
|
|
|
|
if (local_retval and "date_fin" in local_retval.keys()):
|
|
user['date_fin'] = local_retval['date_fin']
|
|
|
|
if (local_retval and "distantiel" in local_retval.keys()):
|
|
user['distantiel'] = local_retval['distantiel']
|
|
|
|
if (local_retval and "presentiel" in local_retval.keys()):
|
|
user['presentiel'] = local_retval['presentiel']
|
|
|
|
if (local_retval and "session_ondemande" in local_retval.keys()):
|
|
user['session_ondemande'] = local_retval['session_ondemande']
|
|
|
|
if (local_retval and "prix_session" in local_retval.keys()):
|
|
user['prix_session'] = local_retval['prix_session']
|
|
|
|
if (local_retval and "location_type" in local_retval.keys()):
|
|
user['location_type'] = local_retval['location_type']
|
|
|
|
if (local_retval and "is_bpf" in local_retval.keys()):
|
|
user['is_bpf'] = local_retval['is_bpf']
|
|
|
|
if (local_retval and "code_session" in local_retval.keys()):
|
|
user['code_session'] = local_retval['code_session']
|
|
|
|
|
|
RetObject.append(mycommon.JSONEncoder().encode(user))
|
|
|
|
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 les inscriptions de l'apprenant "
|
|
|
|
|
|
|
|
"""
|
|
Cette fonction ajoute ou met à jour une image de profil d'un apprenant
|
|
"""
|
|
def Add_Update_Apprenant_Image(file_img=None, Folder=None, diction=None):
|
|
try:
|
|
|
|
# Dictionnaire des champs utilisables
|
|
'''
|
|
# 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 = ['token', 'file_img_recid', 'apprenant_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, " Le champ '" + val + "' n'est pas accepté "
|
|
|
|
'''
|
|
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', 'file_img_recid', 'apprenant_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, " La valeur '" + val + "' n'est pas presente dans liste "
|
|
|
|
# recuperation des paramettre
|
|
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
|
|
|
|
# Verifier que l'apprenant est valide
|
|
is_apprenant_id_valide_count = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(diction['apprenant_id']),
|
|
'valide':'1',
|
|
'locked':'0',
|
|
'partner_owner_recid':str(my_partner['recid'])})
|
|
|
|
if( is_apprenant_id_valide_count != 1):
|
|
mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant est invalide ")
|
|
return False, " L'identifiant de l'apprenant est invalide "
|
|
|
|
apprenant_id_data = MYSY_GV.dbname['apprenant'].find_one(
|
|
{'_id': ObjectId(diction['apprenant_id']),
|
|
'valide': '1',
|
|
'locked': '0',
|
|
'partner_owner_recid': str(my_partner['recid'])})
|
|
|
|
if( file_img ):
|
|
recordimage_diction = {}
|
|
recordimage_diction['token'] = diction['token']
|
|
recordimage_diction['related_collection'] = "apprenant"
|
|
recordimage_diction['type_img'] = "user"
|
|
recordimage_diction['related_collection_recid'] = str(apprenant_id_data['_id'])
|
|
recordimage_diction['image_recid'] = diction['file_img_recid']
|
|
|
|
print(" ### recordimage_diction stagaire = ", recordimage_diction)
|
|
local_status, local_message = mycommon.recordClassImage_v2(file_img, MYSY_GV.upload_folder, recordimage_diction)
|
|
if( local_status is False):
|
|
return local_status, local_message
|
|
|
|
return True, "L'image du stagiaire a été correctement enregistrée"
|
|
|
|
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'enregistrer l'image de l'apprenant"
|
|
|
|
|
|
""" Recuperation de l'image d'un apprenant
|
|
|
|
/!\ important : on prend le 'related_collection_recid' comme le '_id' de la collection de l'apprenant
|
|
"""
|
|
def Get_Apprenant_Recorded_Image_from_front(diction=None):
|
|
try:
|
|
# Dictionnaire des champs utilisables
|
|
field_list = ['token', 'apprenant_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'existe pas, requete annulée")
|
|
return False, " Impossible de récupérer les informations"
|
|
|
|
'''
|
|
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', 'apprenant_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, " Impossible de récupérer les informations"
|
|
|
|
|
|
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
|
|
if (local_status is not True):
|
|
return local_status, my_partner
|
|
|
|
# Verifier que l'apprenant est valide
|
|
is_apprenant_id_valide_count = MYSY_GV.dbname['apprenant'].count_documents(
|
|
{'_id': ObjectId(diction['apprenant_id']),
|
|
'valide': '1',
|
|
'locked': '0',
|
|
'partner_owner_recid': str(my_partner['recid'])})
|
|
|
|
if (is_apprenant_id_valide_count != 1):
|
|
mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant de l'apprenant est invalide ")
|
|
return False, " L'identifiant de l'apprenant est invalide "
|
|
|
|
apprenant_id_data = MYSY_GV.dbname['apprenant'].find_one(
|
|
{'_id': ObjectId(diction['apprenant_id']),
|
|
'valide': '1',
|
|
'locked': '0',
|
|
'partner_owner_recid': str(my_partner['recid'])})
|
|
|
|
|
|
|
|
qery_images = {'locked': '0', 'valide': '1', 'related_collection': 'apprenant',
|
|
'related_collection_recid': str(apprenant_id_data['_id'])}
|
|
|
|
|
|
RetObject = []
|
|
partner_images = {}
|
|
# Recuperation des image 'logo' et 'cachet' si le partenaire en a
|
|
for retVal in MYSY_GV.dbname['mysy_images'].find(qery_images):
|
|
if ('type_img' in retVal.keys()):
|
|
if (retVal['type_img'] == "user"):
|
|
partner_images['logo_img'] = retVal['img'].decode()
|
|
partner_images['logo_img_recid'] = retVal['recid']
|
|
|
|
|
|
RetObject.append(mycommon.JSONEncoder().encode(partner_images))
|
|
|
|
return True, RetObject
|
|
|
|
except Exception as e:
|
|
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 de recupérer l'image de l'apprenant"
|
|
|
|
"""
|
|
Suppresion d'un image de l'apprenant
|
|
"""
|
|
def Delete_Apprenant_Image(diction=None):
|
|
try:
|
|
|
|
# Dictionnaire des champs utilisables
|
|
field_list = ['token', 'image_recid', ]
|
|
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 accepté dans cette API")
|
|
return False, " Le champ '" + val + "' n'est pas accepté "
|
|
|
|
'''
|
|
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', 'image_recid']
|
|
for val in field_list_obligatoire:
|
|
if str(val).lower() not in diction:
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " La valeur '" + val + "' n'est pas presente dans liste des champs")
|
|
return False, " La valeur '" + val + "' n'est pas presente dans liste "
|
|
|
|
mydata = {}
|
|
mytoken = ""
|
|
|
|
# recuperation des paramettre
|
|
if ("token" in diction.keys()):
|
|
if diction['token']:
|
|
mytoken = diction['token']
|
|
|
|
image_recid = ""
|
|
if ("image_recid" in diction.keys()):
|
|
if diction['image_recid']:
|
|
image_recid = diction['image_recid']
|
|
|
|
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
|
|
if (local_status is not True):
|
|
return local_status, my_partner
|
|
|
|
# " Lecture du fichier "
|
|
# print(" Lecture du fichier : " + saved_file + ". le token est :" + str(mytoken))
|
|
nb_line = 0
|
|
coll_name = MYSY_GV.dbname['mysy_images']
|
|
|
|
query_delete = {"recid": image_recid,}
|
|
|
|
|
|
ret_val = coll_name.delete_one({"recid": image_recid,}, )
|
|
|
|
|
|
|
|
#print(" ### recordClassImage_v2 :L'image a été correctement supprimée ")
|
|
return True, "L'image a été correctement supprimée"
|
|
|
|
|
|
except Exception as e:
|
|
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 de supprimer l'image "
|
|
|
|
|
|
"""
|
|
Cette fonction import des apprenants en mass avec un fichier csv (utf-8)
|
|
"""
|
|
|
|
def Add_Apprenant_mass(file=None, Folder=None, diction=None):
|
|
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 = ['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, " Verifier votre API, Toutes les informations techniques ne sont pas fournies"
|
|
|
|
'''
|
|
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, " Verifier votre API, Toutes les informations techniques ne sont pas fournies"
|
|
|
|
my_token = ""
|
|
if ("token" in diction.keys()):
|
|
if diction['token']:
|
|
my_token = diction['token']
|
|
|
|
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data({'token': str(diction['token'])})
|
|
if (local_status is not True):
|
|
return local_status, my_partner
|
|
|
|
|
|
status, saved_file = mycommon.Upload_Save_CSV_File(file, Folder)
|
|
if (status == False):
|
|
mycommon.myprint("Impossible de récupérer correctement le fichier à importer")
|
|
return False, "Impossible d'importer la liste des apprenants, le nom du fichier est incorrect "
|
|
|
|
|
|
nb_line = 0
|
|
|
|
local_controle_status, local_controle_message = Controle_Add_Apprenant_mass(saved_file, Folder, diction)
|
|
|
|
if (local_controle_status is False):
|
|
return local_controle_status, local_controle_message
|
|
|
|
df = pd.read_csv(saved_file, encoding='utf8', on_bad_lines='skip', sep=';', encoding_errors='ignore')
|
|
df = df.fillna('')
|
|
|
|
'''
|
|
# Verification que les noms des colonne sont bien corrects"
|
|
'''
|
|
field_list = ['token', 'nom', 'email', 'prenom', 'civilite', 'telephone', 'employeur', 'client_rattachement_email',
|
|
'adresse', 'code_postal',
|
|
'ville', 'pays', 'tuteur1_nom', 'tuteur1_prenom', 'tuteur1_email', 'tuteur1_telephone',
|
|
'tuteur2_nom', 'tuteur2_prenom',
|
|
'tuteur2_email', 'tuteur2_telephone', 'opco', 'comment', 'tuteur1_adresse', 'tuteur1_cp',
|
|
'tuteur1_ville', 'tuteur1_pays',
|
|
'tuteur1_include_com', 'tuteur2_adresse', 'tuteur2_cp', 'tuteur2_ville', 'tuteur2_pays',
|
|
'tuteur2_include_com']
|
|
|
|
# Controle du nombre de lignes dans le fichier.
|
|
total_rows = len(df)
|
|
if (total_rows > MYSY_GV.MAX_PARTICIPANT_BY_CSV):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " Le fichier comporte plus de " + str(
|
|
MYSY_GV.MAX_PARTICIPANT_BY_CSV) + " lignes.")
|
|
return False, " Le fichier comporte plus de " + str(MYSY_GV.MAX_PARTICIPANT_BY_CSV) + " lignes."
|
|
|
|
|
|
for val in df.columns:
|
|
if str(val).lower() not in field_list and val.startswith('my_') is False:
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3])+" : entete du fichier csv. '" + val + "' n'est pas acceptée")
|
|
return False, " Entete du fichier csv. La Colonne '" + val + "' n'est pas acceptée"
|
|
|
|
# Verification des champs obligatoires dans le fichier
|
|
field_list_obligatoire_file = ['prenom', 'nom', 'email', 'civilite']
|
|
|
|
for val in field_list_obligatoire_file:
|
|
if val not in df.columns:
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][
|
|
3]) + " : Le champ '" + val + "' n'est pas présent dans le fichier. Il est obligatoire")
|
|
return False, " Le champ '" + val + "' n'est pas présent dans le fichier. Il est obligatoire "
|
|
|
|
x = range(0, total_rows)
|
|
for n in x:
|
|
mydata = {}
|
|
mydata['prenom'] = str(df['prenom'].values[n])
|
|
mydata['nom'] = str(df['nom'].values[n])
|
|
mydata['email'] = str(df['email'].values[n])
|
|
mydata['civilite'] = str(df['civilite'].values[n])
|
|
|
|
|
|
telephone = ""
|
|
if ("telephone" in df.keys()):
|
|
if (str(df['telephone'].values[n])):
|
|
telephone = str(df['telephone'].values[n])
|
|
mydata['telephone'] = telephone
|
|
|
|
employeur = ""
|
|
if ("employeur" in df.keys()):
|
|
if (str(df['employeur'].values[n])):
|
|
employeur = str(df['employeur'].values[n])
|
|
mydata['employeur'] = employeur
|
|
|
|
adresse = ""
|
|
if ("adresse" in df.keys()):
|
|
if (str(df['adresse'].values[n])):
|
|
adresse = str(df['adresse'].values[n])
|
|
mydata['adresse'] = adresse
|
|
|
|
code_postal = ""
|
|
if ("code_postal" in df.keys()):
|
|
if (str(df['code_postal'].values[n])):
|
|
code_postal = str(df['code_postal'].values[n])
|
|
mydata['code_postal'] = code_postal
|
|
|
|
ville = ""
|
|
if ("ville" in df.keys()):
|
|
if (str(df['ville'].values[n])):
|
|
ville = str(df['ville'].values[n])
|
|
mydata['ville'] = ville
|
|
|
|
pays = ""
|
|
if ("pays" in df.keys()):
|
|
if (str(df['pays'].values[n])):
|
|
pays = str(df['pays'].values[n])
|
|
mydata['pays'] = pays
|
|
|
|
tuteur1_nom = ""
|
|
if ("tuteur1_nom" in df.keys()):
|
|
if (str(df['tuteur1_nom'].values[n])):
|
|
tuteur1_nom = str(df['tuteur1_nom'].values[n])
|
|
mydata['tuteur1_nom'] = tuteur1_nom
|
|
|
|
tuteur1_prenom = ""
|
|
if ("tuteur1_prenom" in df.keys()):
|
|
if (str(df['tuteur1_prenom'].values[n])):
|
|
tuteur1_prenom = str(df['tuteur1_prenom'].values[n])
|
|
mydata['tuteur1_prenom'] = tuteur1_prenom
|
|
|
|
tuteur1_email = ""
|
|
if ("tuteur1_email" in df.keys()):
|
|
if (str(df['tuteur1_email'].values[n])):
|
|
tuteur1_email = str(df['tuteur1_email'].values[n])
|
|
mydata['tuteur1_email'] = tuteur1_email
|
|
|
|
tuteur1_telephone = ""
|
|
if ("tuteur1_telephone" in df.keys()):
|
|
if (str(df['tuteur1_telephone'].values[n])):
|
|
tuteur1_telephone = str(df['tuteur1_telephone'].values[n])
|
|
mydata['tuteur1_telephone'] = tuteur1_telephone
|
|
|
|
tuteur2_nom = ""
|
|
if ("tuteur2_nom" in df.keys()):
|
|
if (str(df['tuteur2_nom'].values[n])):
|
|
tuteur2_nom = str(df['tuteur2_nom'].values[n])
|
|
mydata['tuteur2_nom'] = tuteur2_nom
|
|
|
|
tuteur2_prenom = ""
|
|
if ("tuteur2_prenom" in df.keys()):
|
|
if (str(df['tuteur2_prenom'].values[n])):
|
|
tuteur2_prenom = str(df['tuteur2_prenom'].values[n])
|
|
mydata['tuteur2_prenom'] = tuteur2_prenom
|
|
|
|
tuteur2_email = ""
|
|
if ("tuteur2_email" in df.keys()):
|
|
if (str(df['tuteur2_email'].values[n])):
|
|
tuteur2_email = str(df['tuteur2_email'].values[n])
|
|
mydata['tuteur2_email'] = tuteur2_email
|
|
|
|
tuteur2_telephone = ""
|
|
if ("tuteur2_telephone" in df.keys()):
|
|
if (str(df['tuteur2_telephone'].values[n])):
|
|
tuteur2_telephone = str(df['tuteur2_telephone'].values[n])
|
|
mydata['tuteur2_telephone'] = tuteur2_telephone
|
|
|
|
opco = ""
|
|
if ("opco" in df.keys()):
|
|
if (str(df['opco'].values[n])):
|
|
opco = str(df['opco'].values[n])
|
|
mydata['opco'] = opco
|
|
|
|
tuteur1_adresse = ""
|
|
if ("tuteur1_adresse" in df.keys()):
|
|
if (str(df['tuteur1_adresse'].values[n])):
|
|
tuteur1_adresse = str(df['tuteur1_adresse'].values[n])
|
|
mydata['tuteur1_adresse'] = tuteur1_adresse
|
|
|
|
tuteur1_cp = ""
|
|
if ("tuteur1_cp" in df.keys()):
|
|
if (str(df['tuteur1_cp'].values[n])):
|
|
tuteur1_cp = str(df['tuteur1_cp'].values[n])
|
|
mydata['tuteur1_cp'] = tuteur1_cp
|
|
|
|
tuteur1_ville = ""
|
|
if ("tuteur1_ville" in df.keys()):
|
|
if (str(df['tuteur1_ville'].values[n])):
|
|
tuteur1_ville = str(df['tuteur1_ville'].values[n])
|
|
mydata['tuteur1_ville'] = tuteur1_ville
|
|
|
|
tuteur1_pays = ""
|
|
if ("tuteur1_pays" in df.keys()):
|
|
if (str(df['tuteur1_pays'].values[n])):
|
|
tuteur1_pays = str(df['tuteur1_pays'].values[n])
|
|
mydata['tuteur1_pays'] = tuteur1_pays
|
|
|
|
tuteur1_include_com = ""
|
|
if ("tuteur1_include_com" in df.keys()):
|
|
if (str(df['tuteur1_include_com'].values[n])):
|
|
tuteur1_include_com = str(df['tuteur1_include_com'].values[n])
|
|
mydata['tuteur1_include_com'] = tuteur1_include_com
|
|
|
|
tuteur2_adresse = ""
|
|
if ("tuteur2_adresse" in df.keys()):
|
|
if (str(df['tuteur2_adresse'].values[n])):
|
|
tuteur2_adresse = str(df['tuteur2_adresse'].values[n])
|
|
mydata['tuteur2_adresse'] = tuteur2_adresse
|
|
|
|
tuteur2_cp = ""
|
|
if ("tuteur2_cp" in df.keys()):
|
|
if (str(df['tuteur2_cp'].values[n])):
|
|
tuteur2_cp = str(df['tuteur2_cp'].values[n])
|
|
mydata['tuteur2_cp'] = tuteur2_cp
|
|
|
|
tuteur2_ville = ""
|
|
if ("tuteur2_ville" in df.keys()):
|
|
if (str(df['tuteur2_ville'].values[n])):
|
|
tuteur2_ville = str(df['tuteur2_ville'].values[n])
|
|
mydata['tuteur2_ville'] = tuteur2_ville
|
|
|
|
tuteur2_pays = ""
|
|
if ("tuteur2_pays" in df.keys()):
|
|
if (str(df['tuteur2_pays'].values[n])):
|
|
tuteur2_pays = str(df['tuteur2_pays'].values[n])
|
|
mydata['tuteur2_pays'] = tuteur2_pays
|
|
|
|
tuteur2_include_com = ""
|
|
if ("tuteur2_include_com" in df.keys()):
|
|
if (str(df['tuteur2_include_com'].values[n])):
|
|
tuteur2_include_com = str(df['tuteur2_include_com'].values[n])
|
|
mydata['tuteur2_include_com'] = tuteur2_include_com
|
|
|
|
comment = ""
|
|
if ("comment" in df.keys()):
|
|
if (str(df['comment'].values[n])):
|
|
comment = str(df['comment'].values[n])
|
|
mydata['comment'] = comment
|
|
|
|
client_rattachement_id = ""
|
|
client_rattachement_email = ""
|
|
if ("client_rattachement_email" in df.keys()):
|
|
if (str(df['client_rattachement_email'].values[n])):
|
|
client_rattachement_email = str(df['client_rattachement_email'].values[n])
|
|
client_rattachement_data = MYSY_GV.dbname['partner_client'].find_one({'email':str(client_rattachement_email),
|
|
'valide':'1',
|
|
'locked':'0',
|
|
'partner_recid':str(my_partner['recid'])},
|
|
{'_id':1})
|
|
|
|
if( '_id' in client_rattachement_data.keys()):
|
|
client_rattachement_id = client_rattachement_data['_id']
|
|
|
|
|
|
|
|
mydata['client_rattachement_id'] = client_rattachement_id
|
|
|
|
|
|
clean_dict = {k: mydata[k] for k in mydata if (str(mydata[k]) != "nan")}
|
|
|
|
clean_dict['token'] = diction['token']
|
|
|
|
print("#### clean_dict ", clean_dict)
|
|
email_to_check = ""
|
|
if( "email" in clean_dict.keys() ):
|
|
"""
|
|
Si l'email existe on fait une mise à jour
|
|
Si non on fait une insertion
|
|
"""
|
|
is_exist_apprenant = MYSY_GV.dbname['apprenant'].count_documents({'email':str(clean_dict['email']),
|
|
'valide':'1',
|
|
'partner_owner_recid':str(my_partner['recid'])})
|
|
|
|
if( is_exist_apprenant <= 0 ):
|
|
status, retval = Add_Apprenant(clean_dict)
|
|
if (status is False):
|
|
return status, retval
|
|
else:
|
|
is_exist_apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'email': str(clean_dict['email']),
|
|
'valide': '1',
|
|
'partner_owner_recid': str(
|
|
my_partner['recid'])})
|
|
print(" ### is_exist_apprenant_data = ", is_exist_apprenant_data)
|
|
clean_dict['_id'] = str(is_exist_apprenant_data['_id'])
|
|
status, retval = Update_Apprenant(clean_dict)
|
|
if (status is False):
|
|
return status, retval
|
|
|
|
|
|
print(str(total_rows)+" participants ont été inserés")
|
|
|
|
return True, str(total_rows)+" apprenant ont été inserés / mis à jour"
|
|
|
|
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'importer les apprenants en masse "
|
|
|
|
|
|
"""
|
|
Controle du fichier et de sa cohérence
|
|
"""
|
|
def Controle_Add_Apprenant_mass(saved_file=None, Folder=None, diction=None):
|
|
try:
|
|
|
|
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data({'token': str(diction['token'])})
|
|
if (local_status is not True):
|
|
return local_status, my_partner
|
|
|
|
df = pd.read_csv(saved_file, encoding='utf8', on_bad_lines='skip', sep=';', encoding_errors='ignore')
|
|
df = df.fillna('')
|
|
|
|
total_rows = len(df)
|
|
|
|
field_list = ['nom', 'email', 'prenom', 'civilite', 'telephone', 'employeur', 'client_rattachement_email',
|
|
'adresse', 'code_postal',
|
|
'ville', 'pays', 'tuteur1_nom', 'tuteur1_prenom', 'tuteur1_email', 'tuteur1_telephone',
|
|
'tuteur2_nom', 'tuteur2_prenom',
|
|
'tuteur2_email', 'tuteur2_telephone', 'opco', 'comment', 'tuteur1_adresse', 'tuteur1_cp',
|
|
'tuteur1_ville', 'tuteur1_pays',
|
|
'tuteur1_include_com', 'tuteur2_adresse', 'tuteur2_cp', 'tuteur2_ville', 'tuteur2_pays',
|
|
'tuteur2_include_com', 'token']
|
|
|
|
x = range(0, total_rows)
|
|
for n in x:
|
|
mydata = {}
|
|
mydata['prenom'] = str(df['prenom'].values[n])
|
|
mydata['nom'] = str(df['nom'].values[n])
|
|
mydata['email'] = str(df['email'].values[n])
|
|
mydata['civilite'] = str(df['civilite'].values[n])
|
|
|
|
if (len(str(mydata['nom']).strip()) < 2):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " Le champ 'nom' de la ligne " + str(
|
|
n + 2) + " doit faire plus de deux caractères.")
|
|
return False, " Le champ 'nom' de la ligne " + str(
|
|
n + 2) + " doit faire plus de deux caractères. "
|
|
|
|
if (len(str(mydata['prenom']).strip()) < 2):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " Le champ 'prenom' de la ligne " + str(
|
|
n + 2) + " doit faire plus de deux caractères.")
|
|
return False, " Le champ 'prenom' de la ligne " + str(
|
|
n + 2) + " doit faire plus de deux caractères. "
|
|
|
|
if ( str(mydata['civilite']).lower() not in MYSY_GV.CIVILITE ):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " Le champ 'civilite' de la ligne " + str(
|
|
n + 2) + " est invalide ")
|
|
return False, " Le champ 'civilite' de la ligne " + str(
|
|
n + 2) + " est invalide. "
|
|
|
|
|
|
|
|
tuteur1_email = ""
|
|
if ("tuteur1_email" in df.keys() and df['tuteur1_email'].values[n]):
|
|
tuteur1_email = str(df['tuteur1_email'].values[n])
|
|
if (mycommon.isEmailValide(str(tuteur1_email)) is False):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email du tuteur1 '"+str(tuteur1_email)+"' de la ligne " + str(
|
|
n + 2) + " est invalide ")
|
|
return False, " L'adresse email du tuteur1 '"+str(tuteur1_email)+"' de la ligne " + str(
|
|
n + 2) + " est invalide "
|
|
|
|
tuteur2_email = ""
|
|
if ("tuteur2_email" in df.keys() and df['tuteur2_email'].values[n]):
|
|
tuteur2_email = str(df['tuteur2_email'].values[n])
|
|
if (mycommon.isEmailValide(str(tuteur2_email)) is False):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'adresse email du tuteur2 "+str(tuteur2_email)+" de la ligne " + str(
|
|
n + 2) + " est invalide ")
|
|
return False, " L'adresse email du tuteur2 "+str(tuteur2_email)+" de la ligne " + str(
|
|
n + 2) + " est invalide "
|
|
|
|
client_rattachement_id = ""
|
|
client_rattachement_email = ""
|
|
if ("client_rattachement_email" in df.keys()):
|
|
if (str(df['client_rattachement_email'].values[n])):
|
|
client_rattachement_email = str(df['client_rattachement_email'].values[n])
|
|
client_rattachement_data_count = MYSY_GV.dbname['partner_client'].count_documents(
|
|
{'email': str(client_rattachement_email),
|
|
'valide': '1',
|
|
'locked': '0',
|
|
'partner_recid': str(my_partner['recid'])})
|
|
|
|
if (client_rattachement_data_count < 0):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][
|
|
3]) + " L'email du client de rattachement de la ligne " + str(
|
|
n + 2) + " est invalide ")
|
|
return False, " L'email du client de rattachement de la ligne " + str(
|
|
n + 2) + " est invalide "
|
|
|
|
|
|
is_exist_apprenant_locked = MYSY_GV.dbname['apprenant'].count_documents({'email': str(mydata['email']),
|
|
'locked': '1',
|
|
'partner_owner_recid': str(
|
|
my_partner['recid'])})
|
|
|
|
if (is_exist_apprenant_locked > 0):
|
|
mycommon.myprint(
|
|
str(inspect.stack()[0][3]) + " L'apprenant avec l'adresse email : "+str(mydata['email'])+" de la ligne " + str(
|
|
n + 2) + " est verrouillé ")
|
|
return False, " L'apprenant avec l'adresse email : "+str(mydata['email'])+" de la ligne " + str(
|
|
n + 2) + " est verrouillé "
|
|
|
|
return True, str(total_rows) + " apprenants lus dans le fichier excel"
|
|
|
|
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 controler le fichier des apprenants "
|