""" Ce fichier permet de gerer les apprenants. Un apprenant est crée apres la validation d'une inscription ou sans. """ import ast import xlsxwriter import jinja2 import pymongo from flask import send_file from pymongo import MongoClient import json from bson import ObjectId import re from datetime import datetime, date from xhtml2pdf import pisa import attached_file_mgt 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', 'date_naissance' ] 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']) + "' " if ("date_naissance" in diction.keys()): if diction['date_naissance']: date_naissance = str(diction['date_naissance']).strip() local_status = mycommon.CheckisDate(date_naissance) if (local_status is False): mycommon.myprint( str(inspect.stack()[0][ 3]) + " La date de naissance n'est pas au format 'jj/mm/aaaa' ") return False, " La date de naissance n'est pas au format 'jj/mm/aaaa' " # 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', 'date_naissance' ] 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 ", if ("date_naissance" in diction.keys()): if diction['date_naissance']: date_naissance = str(diction['date_naissance']).strip() local_status = mycommon.CheckisDate(date_naissance) if (local_status is False): mycommon.myprint( str(inspect.stack()[0][ 3]) + " La date de naissance n'est pas au format 'jj/mm/aaaa' ") return False, " La date de naissance n'est pas au format 'jj/mm/aaaa' " # 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'inscription 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) " # Suppression des pièces jointes associées local_diction = {'token':str(diction['token']), 'object_owner_id':str(diction['apprenant_id']), 'object_owner_collection':'apprenant'} local_status, local_retval = attached_file_mgt.Delete_Entity_Stored_Downloaded_File(local_diction) if( local_status is False ): return local_status, local_retval #Suppression des images de l'apprenant delete_qry = {'related_collection':'apprenant', 'related_collection_recid':str(diction['apprenant_id'])} ret_val = MYSY_GV.dbname['mysy_images'].delete_many(delete_qry ) # Suppression l'apprenant delete_qry_apprenant = {'_id':ObjectId(str(diction['apprenant_id'])),'partner_owner_recid':str(my_partner['recid']), 'valide':'1', 'locked':'0'} ret_val_apprenant = MYSY_GV.dbname['apprenant'].delete_many(delete_qry_apprenant) # /!\ Dans le cas ou il aurait des inscriptions annulé, on va supprimer ces lignes car l'apprenant a été supprimé qry_delete_canceled_inscription = {'apprenant_id':str(diction['apprenant_id']), 'status': '-1', 'partner_owner_recid':str(my_partner['recid'])} ret_val_cancelled_inscription = MYSY_GV.dbname['inscription'].delete_many(qry_delete_canceled_inscription) 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 " """ Suppressoin des apprenant en mass. Attention, on effectue controle global avant de supprimer """ def Delete_List_Apprenant(diction): try: diction = mycommon.strip_dictionary(diction) """ Verification des input acceptés """ field_list = ['token', 'list_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', 'list_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 list_apprenant_id = [] if ("list_apprenant_id" in diction.keys()): if diction['list_apprenant_id']: list_apprenant_id = str(diction['list_apprenant_id']).replace(",", ";").split(";") # Verifier que toutes les conditions sont reunion pour toute la liste d'apprenants is_blocking_message = False blocking_message = "Erreur : " for apprenant_id in list_apprenant_id: # Verifier que l'apprenant existe deja is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(str(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 ") is_blocking_message = True blocking_message = blocking_message + " \n L'identifiant de l'apprenant "+str(apprenant_id)+" n'est pas valide " 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'as pas d'inscription en cours ou valide """ is_apprenant_has_valide_inscription_count = MYSY_GV.dbname['inscription'].count_documents({'apprenant_id':str(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]) + " L'apprenant avec l'adress email : "+str(apprenant_data['email'])+" a "+str(is_apprenant_has_valide_inscription_count)+" inscription(s) en cours ou déjà validée(s) ") is_blocking_message = True blocking_message = blocking_message + " \n L'apprenant avec l'adress email : "+str(apprenant_data['email'])+" a "+str(is_apprenant_has_valide_inscription_count)+" inscription(s) en cours ou déjà validée(s) " if( is_blocking_message is True ): return False, blocking_message is_warning_message = False warning_message = "Warning : " for apprenant_id in list_apprenant_id: local_diction = {"token":str(diction['token']), "apprenant_id":str(apprenant_id)} 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_status, local_retval = Delete_Given_Apprenant(local_diction) if( local_status is False ): is_warning_message = True warning_message = "\n impossible de supprimer l'apprenant : "+str(apprenant_data['email'])+" " if( is_warning_message is True ): return True, " Les apprenants ont été supprimés avec les erreurs suivantes : \n "+str(warning_message) return True, " Les apprenants ont correctement supprimés " 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'}).sort([("_id", pymongo.DESCENDING), ]): 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 ("prenom" 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, filt_prenom, {'partner_owner_recid': str(my_partner['recid'])}]}}, {'$sort': {'_id': -1}}, ] print("#### Get_Apprenant_List_Partner_with_filter laa 01 : query = ", query) RetObject = [] cpt = 1 for retVal in MYSY_GV.dbname['apprenant'].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', 'client_rattachement_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', '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 ", # 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_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']) # 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_session_existe <= 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['civilite'] = apprenant_data['civilite'] new_data['prenom'] = apprenant_data['prenom'] new_data['telephone'] = apprenant_data['telephone'] new_data['modefinancement'] = str(diction['modefinancement']) new_data['client_rattachement_id'] = client_rattachement_id 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 " """ Inscrire une liste d'apprenant à une session de formation """ def Apprenant_Inscrire_Session_List(diction): try: diction = mycommon.strip_dictionary(diction) """ Verification des input acceptés """ field_list = ['token', 'list_apprenant_id', 'session_id', 'type_apprenant' , 'modefinancement', 'client_rattachement_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', 'list_apprenant_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 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_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']) # 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_session_existe <= 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 ", list_apprenant_id = [] if ("list_apprenant_id" in diction.keys()): if diction['list_apprenant_id']: list_apprenant_id = str(diction['list_apprenant_id']).replace(",", ";").split(";") is_blocking_message = False blocking_message = "Erreur : " for apprenant_id in list_apprenant_id : # Verifier que l'apprenant existe is_apprenant_exist = MYSY_GV.dbname['apprenant'].count_documents({'_id':ObjectId(str(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 ") is_blocking_message = True blocking_message = "\n L'identifiant de l'apprenant :"+str(apprenant_id)+" n'est pas valide " # 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'] 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 local_status, local_retval = 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']) + " " 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 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 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, 'client_rattachement_id':1}): user = val user['id'] = str(val_tmp) val_tmp = val_tmp + 1 client_rattachement_nom = ""; if ("client_rattachement_id" in val.keys() and val['client_rattachement_id']): client_rattachement_id_data = MYSY_GV.dbname['partner_client'].find_one( {'_id': ObjectId(str(val['client_rattachement_id'])), 'valide': '1', 'locked': '0', 'partner_recid': str(my_partner['recid'])}, {'nom': 1}) if (client_rattachement_id_data and "nom" in client_rattachement_id_data.keys()): client_rattachement_nom = str(client_rattachement_id_data["nom"]) user['client_rattachement_nom'] = str(client_rattachement_nom) 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 " """ Mise à jour tuteurs d'un apprenant """ def Update_Apprenant_Tuteurs(diction): try: return_message = "" field_list = ['token', '_id', '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', ] 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, "Impossible de mettre à jour stagiaire. Toutes les informations fournies ne sont pas valables" """ Verification de la liste 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, "Impossible de mettre à jour stagiaire, Toutes les informations necessaires n'ont pas été fournies" query_key = {} mytoken = "" if ("token" in diction.keys()): if diction['token']: mytoken = str(diction['token']).strip() # query_key['token'] = diction['token'] 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'])+"' est invalide ") return False, "L'adresse email '"+str(diction['tuteur1_email'])+"' est invalide" 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']) + "' est invalide ") return False, "L'adresse email '" + str(diction['tuteur2_email']) + "' est invalide" local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data({'token': mytoken}) if (local_status is not True): return local_status, my_partner data_update = diction my_id = str(diction['_id']) del data_update['token'] del data_update['_id'] data_update['date_update'] = str(datetime.now()) data_update['update_by'] = str(my_partner['_id']) result = MYSY_GV.dbname['apprenant'].find_one_and_update( {'_id':ObjectId(str(my_id)), 'partner_owner_recid':str(my_partner['recid'])}, {"$set": data_update}, upsert=False, return_document=ReturnDocument.AFTER ) if (result is None or "_id" not in result.keys()): mycommon.myprint( " Impossible de mettre à jour le tuteur (2) ") return False, " Impossible de mettre à jour le tuteur (2) " return True, " Le tuteur 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) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno)) return False, "Impossible de mettre à jour le tuteur " """ Fonction pour imprimer la fiche d'un apprenant (mode pdf). Cette fonction est prevu pour gérer le choix d'un modèle ou le modèle de courrier par defaut. /!\ si courrier_template_id = "default_pdf", alors on va chercher le modèle par defaut. """ def Print_Apprenant_PDF(diction): try: diction = mycommon.strip_dictionary(diction) """ Verification des input acceptés """ field_list = ['token', '_id', 'courrier_template_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 ", appenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id': ObjectId(str(diction['_id'])), 'partner_owner_recid': str(my_partner['recid']), 'valide': '1', 'locked': '0'}) # Recuperation du modele de courrier courrier_template_data = {} if( str(diction['courrier_template_id']) == "default_pdf" ): default_courrier_template_client_count = MYSY_GV.dbname['courrier_template'].count_documents( {'valide': '1', 'locked': '0', 'ref_interne': 'FICHE_APPRENANT', 'default_version': '1', 'edit_by_client': '0', 'type_doc': 'pdf', 'partner_owner_recid': str(my_partner['recid'])} ) qry = {'valide': '1', 'locked': '0', 'ref_interne': 'FICHE_APPRENANT', 'default_version': '1', 'edit_by_client': '0', 'type_doc': 'pdf', 'partner_owner_recid': str(my_partner['recid'])} if (default_courrier_template_client_count != 1): mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant du modèle de courrier est invalide 1 ") return False, " L'identifiant du modèle de courrier est invalide 1 " courrier_template_data = MYSY_GV.dbname['courrier_template'].find_one( {'valide': '1', 'locked': '0', 'ref_interne': 'FICHE_APPRENANT', 'default_version': '1', 'edit_by_client': '0', 'type_doc': 'pdf', 'partner_owner_recid': str(my_partner['recid'])} ) else : is_courrier_template_id_valide = MYSY_GV.dbname['courrier_template'].count_documents( {'_id': ObjectId(str(diction['courrier_template_id'])), 'valide': '1', 'type_doc': 'pdf', 'ref_interne': 'FICHE_APPRENANT', 'locked': '0', 'partner_owner_recid': str(my_partner['recid'])} ) if (is_courrier_template_id_valide != 1): mycommon.myprint(str(inspect.stack()[0][3]) + " L'identifiant du modèle de courrier est invalide ") return False, " L'identifiant du modèle de courrier est invalide " courrier_template_data = MYSY_GV.dbname['courrier_template'].find_one( {'_id': ObjectId(str(diction['courrier_template_id'])), 'valide': '1', 'type_doc': 'pdf', 'ref_interne': 'FICHE_APPRENANT', 'locked': '0', 'partner_owner_recid': str(my_partner['recid'])} ) """ Creation du dictionnaire d'information lié à l'apprenant. Pour cela on besoin de connaitre : - l'id de l'apprenant - list_session_id associé cet apprenant - list_client_id associé cet apprenant - """ tab_apprenant = [] tab_apprenant.append(appenant_data['_id']) tab_session = [] for val in MYSY_GV.dbname['inscription'].find({'apprenant_id':str(diction['_id']), 'partner_owner_recid':str(my_partner['recid'])}, {'session_id':1}): tab_session.append(ObjectId(str(val['session_id']))) tab_client = [] if( "client_rattachement_id" in appenant_data.keys() and appenant_data['client_rattachement_id']): for val in MYSY_GV.dbname['partner_client'].find({'_id':ObjectId(str(appenant_data['client_rattachement_id'])), 'valide':'1', 'locked':'0', 'partner_recid':str(my_partner['recid']) }, {'_id':1}): tab_client.append(val['_id']) local_diction = {} local_diction['token'] = diction['token'] local_diction['list_stagiaire_id'] = [] local_diction['list_session_id'] = tab_session local_diction['list_class_id'] = [] local_diction['list_client_id'] = tab_client local_diction['list_apprenant_id'] = tab_apprenant #print(" ### local_diction = ", local_diction) local_status, local_retval = mycommon.Get_Dictionnary_data_For_Template(local_diction) if (local_status is False): return local_status, local_retval convention_dictionnary_data = local_retval body = { "params": convention_dictionnary_data, } json_formatted_str = json.dumps(body, indent=2) #print(json_formatted_str) #print(convention_dictionnary_data) """ Creation du ficier PDF """ contenu_doc_Template = jinja2.Template(str(courrier_template_data['contenu_doc'])) sourceHtml = contenu_doc_Template.render(params=body["params"]) todays_date = str(date.today().strftime("%d/%m/%Y")) ts = datetime.now().timestamp() ts = str(ts).replace(".", "").replace(",", "")[-5:] orig_file_name = "Fiche_Apprenant_" + str(my_partner['recid']) + "_" + str(ts) + ".pdf" outputFilename = str(MYSY_GV.TEMPORARY_DIRECTORY) + "/" + str(orig_file_name) # open output file for writing (truncated binary) resultFile = open(outputFilename, "w+b") # convert HTML to PDF pisaStatus = pisa.CreatePDF( src=sourceHtml, # the HTML to convert dest=resultFile) # file handle to receive result # close output file resultFile.close() if os.path.exists(outputFilename): # print(" ### ok os.path.exists(outputFilename) "+str(outputFilename)) return True, send_file(outputFilename, as_attachment=True) # return True on success and False on errors print(pisaStatus.err, type(pisaStatus.err)) return True, " le fichier generé " 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'imprimer les données de l'apprenant " """ Recuperation de la liste des modèles de courrier pour les fiches d'apprenants """ def Get_List_Fiche_Apprenant(diction): try: 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, " La valeur '" + val + "' n'est pas presente dans liste" 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(diction) if (local_status is not True): return local_status, my_partner RetObject = [] val_tmp = 0 """ # Recuperation des documents (collection : courrier_template) de ce partenaire avec 'ref_interne' = 'CONVENTION_STAGIAIRE' 1 - On regarde le partenaire à des conventions qui sont personnalisées, si non 2 - On va sortir les conventions par defaut de MySy. /!\ : On ne melange pas les 2. c'est l'un ou l'autre """ for retval in MYSY_GV.dbname['courrier_template'].find({'ref_interne': 'FICHE_APPRENANT', 'valide': '1', 'locked': '0', 'partner_owner_recid': str(my_partner['recid'])}): user = retval val_tmp = val_tmp + 1 RetObject.append(mycommon.JSONEncoder().encode(user)) # Si aucune convention personnalisée, on va chercher les conventions mysy if (val_tmp == 0): for retval in MYSY_GV.dbname['courrier_template'].find({'ref_interne': 'FICHE_APPRENANT', 'valide': '1', 'locked': '0', 'partner_owner_recid': 'default'}): user = retval val_tmp = val_tmp + 1 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 modèles de fiche" """ Fonction permet d'exporter les apprenant dans un fichier excel """ def Export_Apprenant_To_Excel_From_from_List_Id(diction): try: diction = mycommon.strip_dictionary(diction) """ Verification des input acceptés """ field_list = ['token', 'tab_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") return False, " Les informations fournies sont incorrectes", """ Verification des champs obligatoires """ field_list_obligatoire = ['token', 'tab_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 tab_id = [] tab_id_tmp = str(diction['tab_id']).split(",") for val in tab_id_tmp: tab_id.append(ObjectId(str(val))) qery_match = {'_id': {'$in': tab_id}, 'partner_owner_recid': str(my_partner['recid']), 'valide': '1', 'locked': '0'} print(" #### qry = ", qery_match) list_class_datas = MYSY_GV.dbname['myclass'].find({'_id': {'$in': tab_id}, 'partner_owner_recid': str(my_partner['recid']), 'valide': '1', 'locked': '0'}, {'_id': 0, 'valide': 0, 'locked': 0}) pipe_qry = ([ {'$match': qery_match}, {'$project': {'_id': 0, 'valide': 0, 'locked': 0}}, {'$lookup': { 'from': 'partner_client', "let": {'client_rattachement_id': "$client_rattachement_id", 'partner_owner_recid': '$partner_owner_recid'}, 'pipeline': [ {'$match': {'$expr': {'$and': [ {'$eq': ["$_id", {'$convert': { 'input': "$$client_rattachement_id", 'to': "objectId", 'onError': {'error': 'true'}, 'onNull': {'isnull': 'true'} }}]}, {'$eq': ["$valide", "1"]}, {'$eq': ["$partner_recid", '$$partner_owner_recid']} ] } } }, {'$project': {'nom': 1, 'raison_sociale': 1, '_id': 0}}, ], 'as': 'partner_client' } }, ]) print(" #### pipe_qry_apprenant = ", pipe_qry) list_class_datas = MYSY_GV.dbname['apprenant'].aggregate(pipe_qry) # print(" ### list_class_datas = ", str(list_class_datas)) todays_date = str(datetime.today().strftime("%d/%m/%Y")) ts = datetime.now().timestamp() ts = str(ts).replace(".", "").replace(",", "")[-5:] orig_file_name = "Export_Apprenant_csv_" + str(my_partner['recid']) + "_" + str(ts) + ".xlsx" outputFilename = str(MYSY_GV.TEMPORARY_DIRECTORY) + "/" + str(orig_file_name) tab_exported_fields_header = ["nom", "email", "prenom", "civilite", "date_naissance", "telephone", "employeur", "client_rattachement_id", "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", "client_nom", "client_raison_sociale"] tab_exported_fields = ["nom", "email", "prenom", "civilite", "date_naissance", "telephone", "employeur", "client_rattachement_id", "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"] # Create a workbook and add a worksheet. workbook = xlsxwriter.Workbook(outputFilename) worksheet = workbook.add_worksheet() row = 0 column = 0 for header_item in tab_exported_fields_header: worksheet.write(row, column, header_item) column += 1 for class_data in list_class_datas: column = 0 row = row + 1 for local_fiels in tab_exported_fields: answers_record_JSON = ast.literal_eval(str(class_data)) if (str(local_fiels) in answers_record_JSON.keys()): local_status, local_retval = mycommon.IsFloat(str(answers_record_JSON[str(local_fiels)]).strip()) if (local_status is True): no_html = answers_record_JSON[str(local_fiels)] else: no_html = mycommon.cleanhtml(answers_record_JSON[str(local_fiels)]) else: no_html = "" worksheet.write(row, column, no_html) column += 1 if ("partner_client" in class_data.keys() and len(class_data['partner_client']) > 0): if ("nom" in class_data['partner_client'][0].keys()): no_html_formateur_nom = class_data['partner_client'][0]['nom'] worksheet.write(row, column, no_html_formateur_nom) column += 1 if ("raison_sociale" in class_data['partner_client'][0].keys()): no_html_formateur_raison_sociale = class_data['partner_client'][0]['raison_sociale'] worksheet.write(row, column, no_html_formateur_raison_sociale) column += 1 workbook.close() if os.path.exists(outputFilename): # print(" ### ok os.path.exists(outputFilename) "+str(outputFilename)) return True, send_file(outputFilename, as_attachment=True) return False, "Impossible de générer l'export csv des apprenants (2) " 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'exporter les apprenants "