"""
Ce fichier permets de créer les inscription des stagiaires à une formation
"""
import pymongo
from pymongo import MongoClient
import json
from bson import ObjectId
import re
from datetime import datetime
import prj_common as mycommon
import secrets
import inspect
import sys, os
import csv
import pandas as pd
from pymongo import ReturnDocument
import GlobalVariable as MYSY_GV
from math import isnan
import GlobalVariable as MYSY_GV
from datetime import timedelta
import email_inscription_mgt as email_session
from flask import send_file
import re
from xhtml2pdf import pisa
import jinja2
import ftplib
import pysftp

"""
Enregistrement d'un stagiaire

Voici les valeurs possibles du statut d'un stagiaire
# 0 ==> Preinscription
# 1 ==> Inscription validée
# -1 ==> Inscription annulée


"""
def AddStagiairetoClass(diction):
    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 = ['nom', 'prenom', 'email', 'telephone', 'modefinancement', 'opco',
                      'class_internal_url', 'session_id', 'employeur', 'status', 'price',
                      'inscription_validation_date']
        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list:
                mycommon.myprint(str(inspect.stack()[0][
                                         3]) + " - Creation partner account : Le champ  '" + val + "' n'est pas autorisé, Creation partenaire annulée")
                return False, "Impossible de créer le stagiaire. Toutes les informations fournies ne sont pas valables"

        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'prenom', 'email', 'telephone', 'modefinancement', 'opco',
                                  'class_internal_url', 'session_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 créer le stagiaire, Toutes les informations necessaires n'ont pas été fournies"

        mydata = {}

        session_id = ""
        if ("session_id" in diction.keys()):
            if diction['session_id']:
                mydata['session_id'] = diction['session_id']
                session_id = diction['session_id']

        """
        Recuperation des info de la session de formation
        """

        for tmp_val in  MYSY_GV.dbname['session_formation'].find({"formation_session_id":str(session_id)}):
            mydata['date_du'] = tmp_val['date_debut']
            mydata['date_au'] = tmp_val['date_fin']
            mydata['ville'] = tmp_val['ville']
            mydata['code_postal'] = tmp_val['code_postal']
            mydata['adresse'] = tmp_val['adresse']



        print(" #### mydata = "+str(mydata))

        if ("nom" in diction.keys()):
            if diction['nom']:
                mydata['nom'] = diction['nom']

        if ("prenom" in diction.keys()):
            if diction['prenom']:
                mydata['prenom'] = diction['prenom']

        if ("employeur" in diction.keys()):
            if diction['employeur']:
                mydata['employeur'] = diction['employeur']

        if ("telephone" in diction.keys()):
            if diction['telephone']:
                mydata['telephone'] = diction['telephone']

        if ("inscription_validation_date" in diction.keys()):
            if diction['inscription_validation_date']:
                mydata['inscription_validation_date'] = diction['inscription_validation_date']



        if ("email" in diction.keys()):
            if diction['email']:
                mydata['email'] = diction['email']
                regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
                if (not re.fullmatch(regex, str(diction['email']) ) ):
                    mycommon.myprint(
                        str(inspect.stack()[0][3]) + " l'adresse email "+str(diction['email'])+" est invalide")
                    return False, " l'adresse email  -"+str(diction['email'])+"- est invalide"


        if ("modefinancement" in diction.keys()):
            if diction['modefinancement']:
                mydata['modefinancement'] = diction['modefinancement']

        if ("opco" in diction.keys()):
            if diction['opco']:
                mydata['opco'] = diction['opco']



        if ("class_internal_url" in diction.keys()):
            if diction['class_internal_url']:
                mydata['class_internal_url'] = diction['class_internal_url']

        mydata['date_update'] = str(datetime.now())

        new_status = "0" # 0 ==> Preinscription, par defaut
        if ("status" in diction.keys()):
            if diction['status']:
                new_status = diction['status']
        mydata['status'] = str(new_status)

        new_price = "0"  # 0 ==>  par defaut
        if ("price" in diction.keys()):
            if diction['price']:
                new_price = diction['price']
        mydata['price'] = new_price

        coll_inscription = MYSY_GV.dbname['inscription']

        ## Verification si cette adresse n'est pas deja inscrite à cette session
        # print(" myquery pr demo_account = " + str(myquery))
        tmp = coll_inscription.count_documents({'email':str(mydata['email']),
                                                'session_id':str( mydata['session_id']),
                                                'class_internal_url':str(mydata['class_internal_url'])})

        if( tmp > 0 )   :
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - L'adresse email "+str(mydata['email'])+" est deja inscrite à la session du "
                                                                                        " "+str( mydata['session_id'])+ " ")

            return False, "Impossible de créer le stagiaire. l'adresse email "+str(mydata['email'])\
                   +" est deja inscrite à cette session de formation "

        ret_val = coll_inscription.insert_one(mydata)

        inserted_id = ret_val.inserted_id
        if( inserted_id ):
            # Le stagaire a bien ete inseré, on declenche l'envoi des emaisl
            print(" ### l'inscription est ok, il faut declenché l'envoi des email")
            ## Envoie de l'email de preinscription
            mail_data = {}
            mail_data['email'] = diction['email']
            mail_data['class_internal_url'] = diction['class_internal_url']
            mail_data['session_id'] = diction['session_id']

            print(" ### l'inscription est ok, il faut declenché l'envoi des email a "+str(mail_data))
            local_status, message = SendPre_InscriptionEmail(mail_data)
            if( local_status is False):
                mycommon.myprint(" WARNING : Impossible d'envoyer le mail de preinscriton à "+
                                 str(inspect.stack()[0][3]) + " - l'adresse email " + str(
                        mydata['email']) + " pour la session  " + str(mydata['session_id']) + " ")


        else:
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " - ret_val.inserted_id is null  ")
            return False, "Impossible de créer le stagiaire"

        return True, " Le stagiaire à bien été créé"


    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'ajouter le stagiaire"

"""
Mettre à jour les infomration d'un stgiaire

/!\ : on NE mets PAS à jour la session, juste les info du stagiaire

    # status :  0 ==> Preinscription
    # status : 1 ==> Inscription validée
    # status : -1 ==> Inscription annulée

"""
def UpdateStagiairetoClass(diction):
    try:
        field_list = ['token', 'email', 'nom', 'prenom', 'telephone', 'modefinancement', 'opco',
                      'status', 'class_internal_url', 'session_id', 'price', 'employeur', 'comment']
        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list:
                mycommon.myprint(str(inspect.stack()[0][
                                         3]) + " - Creation partner account : 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', 'email', 'class_internal_url', 'session_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 = diction['token']
                #query_key['token'] = diction['token']

        myemail = ""
        if ("email" in diction.keys()):
            if diction['email']:
                myemail = diction['email']
                query_key['email'] = diction['email']

        myinternal_url = ""
        if ("class_internal_url" in diction.keys()):
            if diction['class_internal_url']:
                myinternal_url = diction['class_internal_url']
                query_key['class_internal_url'] = diction['class_internal_url']

        mysession_id = ""
        if ("session_id" in diction.keys()):
            if diction['session_id']:
                mysession_id = diction['session_id']
                query_key['session_id'] = diction['session_id']




        partner_recid = mycommon.get_parnter_recid_from_token(mytoken)
        if (partner_recid is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de mettre à jour le stagiaire ")
            return False, "Impossible de mettre à jour le stagiaire "



        mydata = {}
        user_nom = ""

        if ("nom" in diction.keys()):
            if diction['nom']:
                mydata['nom'] = diction['nom']
                user_nom = diction['nom']

        if ("price" in diction.keys()):
            if diction['price']:
                mydata['price'] = diction['price']

        if ("employeur" in diction.keys()):
            if diction['employeur']:
                mydata['employeur'] = diction['employeur']

        user_prenom = ""
        if ("prenom" in diction.keys()):
            if diction['prenom']:
                mydata['prenom'] = diction['prenom']
                user_prenom = diction['prenom']

        if ("telephone" in diction.keys()):
            if diction['telephone']:
                mydata['telephone'] = diction['telephone']

        if ("modefinancement" in diction.keys()):
            if diction['modefinancement']:
                mydata['modefinancement'] = diction['modefinancement']

        if ("opco" in diction.keys()):
            if diction['opco']:
                mydata['opco'] = diction['opco']

        if ("price" in diction.keys()):
            if diction['price']:
                mydata['price'] = diction['price']

        new_status = ""
        if ("status" in diction.keys()):
            if diction['status']:
                mydata['status'] = diction['status']
                new_status = diction['status']


        if ("comment" in diction.keys()):
            if diction['comment']:
                mydata['comment'] = diction['comment']


        """
        Pour gerer la date de validation, differemment d'une simple mise à jour, 
        on recuperer le status actuellement en base, on verifie si le nouveau status != de status en base.
        
        Si il y a changement de status alors c'est une date de changement de status.
        """
        coll_inscription = MYSY_GV.dbname['inscription']

        local_retval = coll_inscription.find_one(query_key)
        old_status = local_retval['status']
        if( new_status != old_status ):
            # Il y a eu un changement de status
            if( new_status == "1"):
                mydata['inscription_validation_date'] =  str(datetime.now().strftime("%d/%m/%Y %H:%M:%S"))

            if (new_status == "-1"):
                mydata['inscription_refuse_date'] =  str(datetime.now().strftime("%d/%m/%Y %H:%M:%S"))


        ret_val2 = coll_inscription.find_one_and_update(query_key,
                                                  {"$set": mydata},
                                                  return_document=ReturnDocument.AFTER
                                                  )

        if (ret_val2 and ret_val2['_id']):
            
            """
            - Si le status == 1; alors il s'agit d'une validation d'une inscription.
            - Si le status == -1; alors il s'agit d'une refus  d'une inscription.
            
            Du coup, il faut envoyer le mail de confirmation de l'inscription:
            1 - recuperation des infos de la session 
            1 BIS - recuperation du title
            2 - Envoie de l'email
            """
            email_data = {}
            email_data['nom'] = user_nom
            email_data['prenom'] = user_prenom
            email_data['email'] = myemail

            if ("comment" in diction.keys()):
                if diction['comment']:
                    email_data['comment'] = diction['comment']

            # ici recup du titre
            for local_tmp_myclass in MYSY_GV.dbname['myclass'].find(
                    {'internal_url': str(myinternal_url)}):

                local_title = ""
                if ("title" in local_tmp_myclass.keys() and local_tmp_myclass['title']):
                    local_title = local_tmp_myclass['title']
                    email_data['title'] = local_title

            # ici recup des infos de la session
            local_query = {'formation_session_id':str(mysession_id)}
            print("### local_query = "+str(local_query))


            for local_tmp_session in MYSY_GV.dbname['session_formation'].find(local_query):

                local_date_du = ""
                if ("date_debut" in local_tmp_session.keys() and local_tmp_session['date_debut']):
                    local_date_du = local_tmp_session['date_debut']
                    email_data['date_du'] = local_date_du


                local_date_au = ""
                if ("date_fin" in local_tmp_session.keys() and local_tmp_session['date_fin']):
                    local_date_au = local_tmp_session['date_fin']
                    email_data['date_au'] = local_date_au

                adresse = ""
                if ("adresse" in local_tmp_session.keys() and local_tmp_session['adresse']):
                    local_adresse = local_tmp_session['adresse']
                    email_data['adresse'] = local_adresse

                if ( diction['status'] == "1" ):
                    # Il s'agit d'envoyer le message de confirmation d'une inscription
                    local_status, local_message = email_session.incription_training_confirmation_mail(email_data)

                elif ( diction['status'] == "-1" ):
                    # Il s'agit d'envoyer le message de refus d'une inscription
                    local_status, local_message = email_session.incription_training_refused_mail(email_data)


                mycommon.myprint(" Les données du stagiaire ont été correctement mise à jour")
                return True, "Les données du stagiaire ont été correctement mise à jour"


        else:
            mycommon.myprint(" Impossible de mettre à jour les données du stagiaire 1")
            return False, "Impossible de mettre à jour les données du stagiaire "


    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 les informations du stagiaire"



"""
Recuperation d'un stagiaire
"""
def GetStagiaire(diction):
    try:
        field_list = ['nom', 'adr_street', 'adr_city']
        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list:
                mycommon.myprint(str(inspect.stack()[0][
                                         3]) + " - Creation partner account : Le champ  '" + val + "' n'est pas autorisé, Creation partenaire annulée")
                return False, "Impossible de recuperer  le stagiaire. Toutes les informations fournies ne sont pas valables"

        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['nom', 'email', 'pwd', ]
        for val in field_list_obligatoire:
            if val not in diction:
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " -  : La valeur '" + val + "' n'est pas presente dans liste ")
                return False, "Impossible de recuperer  le stagiaire, Toutes les informations necessaires n'ont pas été fournies"


        return True

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, "Impossible de recuperer  le stagiaire"


"""
Recuperation de liste des stagiaire d'une formation
# status :  0 ==> Preinscription
# status : 1 ==> Inscription validée
# status : -1 ==> Inscription annulée
"""
def GetAllClassStagiaire(diction):
    try:
        field_list = ['token', 'class_internal_url', 'session_id', 'status']
        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list:
                mycommon.myprint(str(inspect.stack()[0][
                                         3]) + " - Creation partner account : Le champ  '" + val + "' n'est pas autorisé, Creation partenaire annulée")
                return False, "de recuperer la liste des stagiaires . Toutes les informations fournies ne sont pas valables"

        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = ['token', 'class_internal_url', 'session_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 recuperer la liste des stagiaires, 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']

        partner_recid = mycommon.get_parnter_recid_from_token(mytoken)
        if (partner_recid is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de recuperer la liste des stagiaires, ")
            return False, "Impossible de recuperer la liste des stagiaires, Les informations d'identification sont incorrectes "

        class_internal_url = ""
        if ("class_internal_url" in diction.keys()):
            if diction['class_internal_url']:
                class_internal_url = diction['class_internal_url']

        session_id = ""
        if ("session_id" in diction.keys()):
            if diction['session_id']:
                session_id = diction['session_id']

        status = ""
        if ("status" in diction.keys()):
            if diction['status']:
                status = diction['status']


        ## Recuperation de toutes les stagiaire rattaché à cette session
        coll_session = MYSY_GV.dbname['inscription']
        myquery = {}
        myquery['session_id'] = session_id
        myquery['class_internal_url'] = class_internal_url

        if(len(status) > 0 ):
            myquery['status'] = status


        RetObject = []
        val_tmp = 1

        #print(" #### myquery = "+str(myquery))

        for retval in coll_session.find(myquery):
            user = retval
            user['id'] = str(val_tmp)
            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) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, "Impossible de recuperer la liste des stagiaires de la formation"


"""
Cette fonction envoie l'email de confirmation  d'une inscription a une formation.

Ceci est mis en "mode function" pour permettre aux utilisateur de renvoyer 
autant de fois que souhaité  la confirmation d'inscription
"""
def SendInscriptionConfirmation(diction):
    try:
        """
       Verification de la liste des champs obligatoires
       """
        field_list_obligatoire = ['token', 'email', 'class_internal_url', 'session_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 d'envoyer la confirmation d'inscription"

        mytoken = ""
        if ("token" in diction.keys()):
            if diction['token']:
                mytoken = diction['token']

        partner_recid = mycommon.get_parnter_recid_from_token(mytoken)
        if (partner_recid is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de recuperer le recid du partenaire")
            return False, " Impossible d'envoyer le mail de confirmation"


        data_mail = {}
        # 1 - Recuperation des données de la formation
        local_class = MYSY_GV.dbname['myclass'].find({'internal_url':str(diction['class_internal_url'])})
        data_mail['title'] = local_class[0]['title']


        # 2 - Recuperation des données de l'inscription
        local_session = MYSY_GV.dbname['inscription'].find({'session_id':str(diction['session_id']),
                                                            'email':str(diction['email'])})


        data_mail['nom'] = local_session[0]['nom']
        data_mail['prenom'] = local_session[0]['prenom']
        data_mail['email'] = local_session[0]['email']
        data_mail['date_du'] = local_session[0]['date_du']
        data_mail['date_au'] = local_session[0]['date_au']
        data_mail['adresse'] = local_session[0]['adresse']

        local_status, local_message = email_session.incription_training_confirmation_mail(data_mail)

        return local_status, "La confirmation d'inscription a bien ete envoyé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'envoyer la confirmation d'inscription"


"""
Cette fonction envoie les pre-inscritpions
"""
def SendPre_InscriptionEmail(diction):
    try:
        """
       Verification de la liste des champs obligatoires
       """
        field_list_obligatoire = [ 'email', 'class_internal_url', 'session_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 d'envoyer la pre-inscription "


        data_mail = {}
        # 1 - Recuperation des données de la formation
        local_class = MYSY_GV.dbname['myclass'].find({'internal_url':str(diction['class_internal_url'])})
        data_mail['title'] = local_class[0]['title']
        partner_recid = local_class[0]['partner_owner_recid']

        # 1-BIS : Recuperation des donnees de l'editeur de la formation
        local_partner = MYSY_GV.dbname['partnair_account'].find_one({'recid':str(partner_recid)})
        data_mail['partner_mail'] = local_partner['email']



        # 2 - Recuperation des données de l'inscription
        local_session = MYSY_GV.dbname['inscription'].find({'session_id':str(diction['session_id']),
                                                            'email':str(diction['email'])})


        data_mail['nom'] = local_session[0]['nom']
        data_mail['prenom'] = local_session[0]['prenom']
        data_mail['email'] = local_session[0]['email']
        data_mail['date_du'] = local_session[0]['date_du']
        data_mail['date_au'] = local_session[0]['date_au']
        data_mail['adresse'] = local_session[0]['adresse']
        data_mail['employeur'] = local_session[0]['employeur']
        data_mail['telephone'] = local_session[0]['telephone']



        # Envoi de l'email de confirmation au demandeur de la formation
        local_status, local_message = email_session.Pre_incription_training_confirmation_mail(data_mail)


        # Envoi de l'email de notification au formateur
        local_status, local_message = email_session.Notification_partner_Pre_incription_mail(data_mail)

        return local_status, "La confirmation de la pre-inscription a bien ete envoyé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'envoyer la confirmation d'inscription"


"""
Cette fonction retour en CSV la liste
des personnes inscrites à une session de formation
"""
def DownloadParticipantsList(diction):
    try:

        """
        Verification de la liste des champs obligatoires
        """
        field_list_obligatoire = field_list = ['token',  'session_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 generer la liste des participants. les informations sont incompletes"

        # Recuperation du recid du partner
        mydata = {}
        mytoken = ""
        if ("token" in diction.keys()):
            if diction['token']:
                mytoken = diction['token']

        partner_recid = mycommon.get_parnter_recid_from_token(mytoken)
        if (partner_recid is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de recuperer la liste des stagiaires, ")
            return False, "Impossible de recuperer la liste des stagiaires, Les informations d'identification sont incorrectes "


        session_id = ""
        if ("session_id" in diction.keys()):
            if diction['session_id']:
                session_id = diction['session_id']


        # Recuperation des données de la session
        local_session = MYSY_GV.dbname['session_formation'].find_one({'formation_session_id':session_id})


        if (local_session is None):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - Cette de formation n'a pas d'informations detaillées ")
            return False, " Cette de formation n'a pas d'informations detaillées "

        # Recuperation des données de la formation
        local_formation = MYSY_GV.dbname['myclass'].find_one({'internal_url':str(local_session['class_internal_url'])})
        if (local_formation is None):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - Cette de formation n'a pas d'informations detaillées (2) ")
            return False, " Cette de formation n'a pas d'informations detaillées (2) "

        ## Recuperation de toutes les stagiaire rattaché à cette session
        coll_session = MYSY_GV.dbname['inscription']
        myquery = {}
        myquery['session_id'] = session_id


        RetObject = []

        for retval in coll_session.find(myquery, { 'session_id':0}):

            local_data = {}
            local_data['titre_formation'] = local_formation['title']
            local_data['debut_session'] = local_session ['date_debut']
            local_data['fin_session'] = local_session['date_fin']




            local_data['prenom'] = retval['prenom']
            local_data['nom'] = retval['nom']
            local_data['email'] = retval['email']
            local_data['telephone'] = retval['telephone']
            local_data['date inscription'] = str(retval['_id'].generation_time.strftime("%m/%d/%Y, %H:%M"))

            adresse = ""
            if ("adresse" in retval.keys()):
                if (retval['adresse']):
                    adresse = retval['adresse']
            local_data['adresse'] = adresse

            formateur = ""
            if ("formateur" in local_session.keys()):
                if (local_session['formateur']):
                    formateur = local_session['formateur']
            local_data['formateur'] = formateur

            code_postal = ""
            if ("code_postal" in retval.keys()):
                if (retval['code_postal']):
                    code_postal = retval['code_postal']
            local_data['code_postal'] = code_postal

            ville = ""
            if ("ville" in retval.keys()):
                if (retval['ville']):
                    ville = retval['ville']
            local_data['ville'] = ville

            employeur = ""
            if ("employeur" in retval.keys()):
                if (retval['employeur']):
                    employeur = retval['employeur']
            local_data['employeur'] = employeur

            financement = ""
            if ("modefinancement" in retval.keys()):
                if (retval['modefinancement']):
                    financement = retval['modefinancement']
            local_data['financement'] = financement

            opco = ""
            if ("opco" in retval.keys()):
                if (retval['opco']):
                    opco = retval['opco']
            local_data['opco'] = opco

            if '_id' in local_data:
                del local_data['_id']

            if( retval['status'] == "1"):
                local_data['status'] = "inscrit"

            elif (retval['status'] == "0"):
                local_data['status'] = "en attente"

            elif (retval['status'] == "-1"):
                local_data['status'] = "refusé"

            if ("inscription_validation_date" in retval.keys()):
                if( retval['inscription_validation_date']):
                    local_data['inscription_validation_date'] = retval['inscription_validation_date']

            if ("inscription_refuse_date" in retval.keys()):
                if (retval['inscription_refuse_date']):
                    local_data['inscription_refuse_date'] = retval['inscription_refuse_date']

            RetObject.append(local_data)

        # Expand the cursor and construct the DataFrame
        df = pd.DataFrame(list(RetObject))

        file_name_tmp = mycommon.create_token_urlsafe()
        file_name = ''.join(char for char in file_name_tmp if char.isalnum())

        #print("#### filename = "+str(file_name))

        df.to_excel(MYSY_GV.TEMPORARY_DIRECTORY+"/"+str(file_name)+".xlsx",  index=False)
        if os.path.exists(MYSY_GV.TEMPORARY_DIRECTORY+"/"+str(file_name)+".xlsx"):
            path = MYSY_GV.TEMPORARY_DIRECTORY+"/"+str(file_name)+".xlsx"
            return True, send_file(path, as_attachment=True)
        else:
            return False, False


    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'envoyer la confirmation d'inscription"


""" Import des inscriptions en masse
Avec l'import d'un fichier csv
"""
def AddStagiairetoClass_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','session_id']
        incom_keys = diction.keys()
        for val in incom_keys:
            if val not in field_list:
                mycommon.myprint(str(inspect.stack()[0][3]) + "  Le champ  '" + val + "' n'existe pas, Creation participants annulée")
                return False, " Verifier votre API"

        '''
        Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente,
        On controle que les champs obligatoires sont presents dans la liste 
        '''
        field_list_obligatoire = ['token', 'session_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, " Verifier votre API"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_token = diction['token']

        session_id = ""
        if ("session_id" in diction.keys()):
            if diction['session_id']:
                session_id = diction['session_id']

        if(len(str(session_id).strip()) <= 0 ):
            mycommon.myprint(
                str(inspect.stack()[0][3]) + " La session de formation est vide : Impossible d'importer la liste des participants ")
            return False, "la session de formation est incorrecte. Impossible d'importer la liste des participants"


        partner_recid = mycommon.get_parnter_recid_from_token(my_token)
        if (partner_recid is False):
            mycommon.myprint(str(inspect.stack()[0][3]) + " - partner_recid KO : Impossible d'importer la liste des participants ")
            return False, "les information de connexion sont incorrectes. Impossible d'importer la liste des participants"

        status, saved_file = mycommon.Upload_Save_CSV_File(file, Folder)
        if (status == False):
            return False, "Impossible d'importer la liste des participants, le nom du fichier est incorrect "

        #" Lecture du fichier "
        #print(" Lecture du fichier : "+saved_file)
        nb_line = 0

        df = pd.read_csv(saved_file, encoding='utf8',  on_bad_lines='skip', sep=';')

        # Dictionnaire des champs utilisables
        '''
        # Verification que les noms des colonne sont bien corrects"
        '''
        field_list = ['prenom', 'nom', 'employeur', 'telephone', 'email', 'modefinancement',
                      'opco', 'status', 'prix']


        # 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."


        #print(df.columns)
        for val in df.columns:
            if str(val).lower()  not in field_list:
                mycommon.myprint(
                    str(inspect.stack()[0][3])+" : entete du fichier csv. '" + val + "' n'est pas acceptée")
                return False, " Entete du fichier csv. '" + val + "' n'est pas acceptée"

        # Verification des champs obligatoires dans le fichier
        field_list_obligatoire_file = ['prenom', 'nom',  'email', 'modefinancement', 'status', 'prix']

        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 "


        # Recuperation des info de la session.
        session_data = MYSY_GV.dbname['session_formation'].find_one({'formation_session_id':str(session_id)})
        if( session_data is None ):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + " La session de formation n'existe pas : Impossible d'importer la liste des participants ")
            return False, "la session de formation n'existe pas. Impossible d'importer la liste des participants"

        #print(" #### session_data = ",session_data)

        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['employeur'] = str(df['employeur'].values[n])
            mydata['telephone'] = str(df['telephone'].values[n])
            mydata['email'] = str(df['email'].values[n])
            mydata['session_id'] = str(session_id)

            modefinancement = ""
            if ("modefinancement" in df.keys()):
                if (str(df['modefinancement'].values[n])):
                    modefinancement = str(df['modefinancement'].values[n])
            mydata['modefinancement'] = modefinancement


            opco = ""
            if ("opco" in df.keys()):
                if (str(df['opco'].values[n])):
                    opco = str(df['opco'].values[n])
            mydata['opco'] = opco


            mydata['status'] = str(df['status'].values[n]).strip()
            if( str(mydata['status']) != "0" and str(mydata['status']) != "1" and str(mydata['status']) != "2"):
                mycommon.myprint(
                    str(inspect.stack()[0][3]) + " Le champs 'status' de ligne " + str(n) + " est incorrecte. Valeurs acceptées : 0,1,2")
                return False, " Le champs status de ligne " + str(n) + " est incorrecte. Valeurs acceptées : 0,1,2"


            if( str(df['status'].values[n]).strip() == "1"):
                mydata['inscription_validation_date'] = str(datetime.now().strftime("%d/%m/%Y %H:%M:%S"))

            mydata['class_internal_url'] = str(session_data['class_internal_url'])


            local_price = str(df['prix'].values[n]).strip()
            local_status, new_price = mycommon.IsFloat(local_price)
            if( local_status is False ):
                mycommon.myprint(
                    str(inspect.stack()[0][ 3]) + " Le champs 'prix' de ligne " + str( n) + " est incorrecte.")
                return False, " Le champs prix de ligne " + str(n) + " est incorrecte. "

            mydata['price'] = local_price


            clean_dict = {k: mydata[k] for k in mydata if ( str(mydata[k]) != "nan") }

            print( "####  clean_dict ", clean_dict)
            status, retval =  AddStagiairetoClass(clean_dict)

            if( status is False ):
                return status, retval

        print(str(total_rows)+" participants ont été inserés")

        return True, str(total_rows)+" participants ont été inserées / Mises à 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 participants  en masse "


"""
Cette fonction permet d'imprimer/telecharger la fichier d'un inscrit à une session.
Cette fonction va utiliser un template pour imprimer le modele
"""
def PrintAttendeeDetail_perSession(diction):
    try:
        field_list_obligatoire = ['session_id', 'token', 'attendee_email']

        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 d'imprimer la fiche detaillée"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_token = diction['token']

        # Recuperation 	du 	recid 	du 	partenaire
        partner_recid = mycommon.get_parnter_recid_from_token(str(my_token))
        if partner_recid is False:
            mycommon.myprint(str(inspect.stack()[0][3]) + " -  Impossible d'imprimer la fiche detaillée")
            return False, " Les informations d'identification sont invalides"

        RetObject = []
        # Recuperation des infos de la formation
        local_Insc_retval = MYSY_GV.dbname['inscription'].find_one({'session_id': str(diction['session_id']),
                                                                    'email': str(diction['attendee_email'])})
        my_retrun_dict = {}

        my_retrun_dict['session_id'] = local_Insc_retval['session_id']
        my_retrun_dict['date_du'] = local_Insc_retval['date_du']
        my_retrun_dict['date_au'] = local_Insc_retval['date_au']
        my_retrun_dict['ville'] = local_Insc_retval['ville']
        my_retrun_dict['code_postal'] = local_Insc_retval['code_postal']

        my_retrun_dict['adresse'] = local_Insc_retval['adresse']
        my_retrun_dict['nom'] = local_Insc_retval['nom']
        my_retrun_dict['prenom'] = local_Insc_retval['prenom']
        my_retrun_dict['employeur'] = local_Insc_retval['employeur']
        my_retrun_dict['telephone'] = local_Insc_retval['telephone']

        my_retrun_dict['email'] = local_Insc_retval['email']
        my_retrun_dict['modefinancement'] = local_Insc_retval['modefinancement']
        my_retrun_dict['opco'] = local_Insc_retval['opco']
        my_retrun_dict['class_internal_url'] = local_Insc_retval['class_internal_url']
        my_retrun_dict['status'] = local_Insc_retval['status']

        my_retrun_dict['price'] = local_Insc_retval['price']

        if ("inscription_validation_date" in local_Insc_retval.keys()):
            my_retrun_dict['inscription_validation_date'] = local_Insc_retval['inscription_validation_date']

        if ("eval_eval" in local_Insc_retval.keys()):
            my_retrun_dict['evaluation'] = local_Insc_retval['eval_eval']

        if ("eval_note" in local_Insc_retval.keys()):
            my_retrun_dict['note_eval'] = local_Insc_retval['eval_note']

        if ("eval_date" in local_Insc_retval.keys()):
            my_retrun_dict['date_eval'] = str(local_Insc_retval['eval_date'])[0:10]

        v = local_Insc_retval['_id'].generation_time
        my_retrun_dict['created_date'] = str(v.strftime("%d/%m/%Y"))

        my_retrun_dict['date_impression'] = str(datetime.today().strftime("%d/%m/%Y"))

        # Recuperation des infotrmations de la formation
        local_formation = MYSY_GV.dbname['myclass'].find_one(
            {'internal_url': str(local_Insc_retval['class_internal_url'])})

        my_local_title = ""
        if ("class_title" in local_formation.keys()):
            if local_formation['class_title']:
                my_retrun_dict['class_title'] = local_formation['title']
                my_local_title = local_formation['title']

        """
        if( my_local_title == "" ):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + "  Impossible d'imprimer la fiche detaillée : le title de session est absent ")
            return False, " Impossible d'imprimer la fiche detaillée : le title de session est absent "
        """



        # Recuperation du formation depuis la collection "session_formation"
        tmp_val = MYSY_GV.dbname['session_formation'].find_one({'formation_session_id':str(local_Insc_retval['session_id']), 'valide':'1'})
        if( tmp_val is None):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + "  Impossible d'imprimer la fiche detaillée : code session erronée ")
            return False, "  Impossible d'imprimer la fiche detaillée : code session erronée  "

        my_trainer = ""
        if ("formateur" in tmp_val.keys()):
            if tmp_val['formateur']:
                my_trainer = tmp_val['formateur']
                my_retrun_dict['formateur'] = tmp_val['formateur']

        if (my_trainer == ""):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + "  Impossible d'imprimer la fiche detaillée : Aucun formateur designé pour la session")
            return False, " Impossible d'imprimer la fiche detaillée : Aucun formateur designé pour la session"


        my_retrun_dict['partner'] = local_formation['institut_formation']
        my_retrun_dict['img_url'] = local_formation['img_url']



        ##############################
        # Recuperation des fiches de presence
        tab_presences = []
        for val_tmp in MYSY_GV.dbname['emargement'].find({'session_id':str(local_Insc_retval['session_id']),
                                                          'email':str(local_Insc_retval['email'])}).sort([("date", pymongo.ASCENDING)]):
            local_tmp = {}
            local_tmp['email'] = val_tmp['email']
            local_tmp['matin'] = val_tmp['matin']
            local_tmp['apresmidi'] = val_tmp['apresmidi']
            local_tmp['date'] = val_tmp['date']

            tab_presences.append(local_tmp)


        #print(" ### tab_presences =",tab_presences)

        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/fiche_detail_stagiaire_tpl.html"
        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {
            "data": my_retrun_dict,
            "presences": tab_presences
        }

        # print(" ### body = " + str(body))

        sourceHtml = template.render(json_data=body["data"], presences=body["presences"])
        orig_file_name = "fichier_presence.pdf"
        outputFilename = str(MYSY_GV.EMARGEMENT_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()

        # print(" ### outputFilename = "+str(outputFilename))
        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()
        print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False,  " Impossible d'imprimer la fiche detaillée"


""" Creation d'un evaluation sur une formation
Les infos d'evaluation sont rattachées à la collection inscription.

eval_date :
eval_note :
eval_eval :
eval_pedagogie :

"""
def Evaluation_Class(diction):
    try:

        field_list_obligatoire = ['inscription_id', 'eval_note', 'eval_eval',  'eval_pedagogie']
        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"



        note = str(diction['eval_note']).strip()
        if( mycommon.IsFloat( note ) is False ):
            mycommon.myprint(
                str(inspect.stack()[0][
                        3]) + "  La note d'evalution est incorrecte ")
            return False, " La note d'evalution est incorrecte "

        mydata = {}
        mydata['eval_date'] = str(datetime.now())
        mydata['eval_note'] = str(diction['eval_note']).strip()
        mydata['eval_eval'] = str(diction['eval_eval']).strip()
        mydata['eval_pedagogie'] = str(diction['eval_pedagogie']).strip()

        ret_val = MYSY_GV.dbname['inscription'].find_one_and_update({'_id': ObjectId(str(str(diction['inscription_id']).strip())),},
                                                       {"$set": mydata},
                                                       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 d'enregistrer l'evaluation ")
            return False, " Impossible d'enregistrer l'evaluation "

        return  True, " L'evaluation a bien été enregistré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 créer l'evaluation"

"""
Cette fonction verifie si un token d'evaluation est valide.

Un token est valide si : 
token = ObjectId existe
internal_url et le objectId sont coherents (meme ligne dans la collection)
L'evaluation n'a pas deja ete faite.

"""
def MySyckeckEvaluationToken(diction):
    try:
        field_list_obligatoire = ['eval_token', 'class_internal_url']
        for val in field_list_obligatoire:
            if val not in diction:
                mycommon.myprint(
                    str(inspect.stack()[0][
                            3]) + "  La valeur '" + val + "' n'est pas presente dans liste ")
                return False, " Les informations fournies sont incorrectes"

        eval_token = ""
        if ("eval_token" in diction.keys()):
            if diction['eval_token']:
                eval_token = diction['eval_token']

        internal_url = ""
        if ("class_internal_url" in diction.keys()):
            if diction['class_internal_url']:
                internal_url = diction['class_internal_url']

        local_qry = {'class_internal_url':internal_url,  '_id': ObjectId(eval_token), "eval_date":{"$exists":False}   }

        #print(" ###  local_qry =",local_qry)
        tmp_count = MYSY_GV.dbname['inscription'].count_documents({'class_internal_url':internal_url,
                                                                   '_id': ObjectId(eval_token), "eval_date":{"$exists":False}   } )

        if (tmp_count != 1):
            mycommon.myprint(str(inspect.stack()[0][3]) + " "+str(tmp_count)+" est different de 1. impossible de faire l'evaluation")
            return False, " Impossible de faire l'evaluation. Verifier les informations fournies"


        return True, "Ok"

    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 verifier la validé du token"


"""
Cette fonction envoie l'email de demande d'evaluation
"""
def SendTrainingEvaluationEmail(diction):
    try:
        field_list_obligatoire = ['session_id', 'token', 'attendee_email']

        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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_token = diction['token']

        # Recuperation 	du 	recid 	du 	partenaire
        partner_recid = mycommon.get_parnter_recid_from_token(str(my_token))
        if partner_recid is False:
            mycommon.myprint(str(inspect.stack()[0][3]) + " -  Impossible d'imprimer la fiche detaillée")
            return False, "  Les informations fournies sont incorrectes"

        # Verifier qui la formation n'a pas deja été evaluée
        tmp_count = MYSY_GV.dbname['inscription'].count_documents({'session_id': str(diction['session_id']),
                                                                    'email': str(diction['attendee_email']),
                                                      "eval_date": {"$exists": True}})

        if (tmp_count > 0):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Vous avez deja evalué cette formation")
            return False, "  Vous avez deja evalué cette formation"


        RetObject = []
        # Recuperation des infos de la formation
        local_Insc_retval = MYSY_GV.dbname['inscription'].find_one({'session_id': str(diction['session_id']),
                                                                    'email': str(diction['attendee_email'])})

        my_retrun_dict = {}

        my_retrun_dict['token_eval'] = local_Insc_retval['_id']
        my_retrun_dict['session_id'] = local_Insc_retval['session_id']
        my_retrun_dict['date_du'] = local_Insc_retval['date_du']
        my_retrun_dict['date_au'] = local_Insc_retval['date_au']
        my_retrun_dict['ville'] = local_Insc_retval['ville']
        my_retrun_dict['code_postal'] = local_Insc_retval['code_postal']
        my_retrun_dict['internal_url'] = local_Insc_retval['class_internal_url']

        my_retrun_dict['adresse'] = local_Insc_retval['adresse']
        my_retrun_dict['nom'] = local_Insc_retval['nom']
        my_retrun_dict['prenom'] = local_Insc_retval['prenom']
        my_retrun_dict['employeur'] = local_Insc_retval['employeur']
        my_retrun_dict['telephone'] = local_Insc_retval['telephone']

        my_retrun_dict['email'] = local_Insc_retval['email']

        # Recuperation des infotrmations de la formation
        print(" ## str(local_Insc_retval['class_internal_url']) = ",str(local_Insc_retval['class_internal_url']) )
        local_formation = MYSY_GV.dbname['myclass'].find_one(
            {'internal_url': str(local_Insc_retval['class_internal_url'])})
        my_retrun_dict['title'] = local_formation['title']

        # Envoi de l'email de notification au formateur
        local_status, local_message = email_session.Evaluation_training_confirmation_mail(my_retrun_dict)

        return local_status, str(local_message)

    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 d'envoyer la demande d'evaluation"




"""
Cette fonction envoie le certificat d'un stagiaire
"""
def SendAttendeeCertification(diction):
    try:

        field_list_obligatoire = ['session_id', 'token', 'attendee_email']

        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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_token = diction['token']

        # Recuperation 	du 	recid 	du 	partenaire
        partner_recid = mycommon.get_parnter_recid_from_token(str(my_token))
        if partner_recid is False:
            mycommon.myprint(str(inspect.stack()[0][3]) + " -  Impossible d'imprimer la fiche detaillée")
            return False, "  Les informations fournies sont incorrectes"

        # Verifier qui la formation n'a pas deja été evaluée
        tmp_count = MYSY_GV.dbname['inscription'].count_documents({'session_id': str(diction['session_id']),
                                                                   'email': str(diction['attendee_email']),
                                                                   "certification_send_date": {"$exists": True}})

        if (tmp_count > 0):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Vous avez deja envoyé le certificat")
            return False, "  Vous avez deja envoyé le certificat"

        # Recuperation du type/nom de la certifcation depuis la collecion "session_formation"
        session_formation = MYSY_GV.dbname['session_formation'].find_one({'formation_session_id': str(diction['session_id']),
                                                                    'valide': "1"})

        if( session_formation['attestation_certif'] is None ):
            mycommon.myprint(str(inspect.stack()[0][3]) + " impossible de trouver le modele d'attestation")
            return False, "  impossible de trouver le modele d'attestation"

        date_fin_session = str(session_formation['date_fin'] )[0:10]
        local_status = mycommon.CheckisDate(date_fin_session)
        if( local_status is False ):
            mycommon.myprint(str(inspect.stack()[0][3]) + " La date de fin de session de formation est incorrecte.")
            return False, "  La date de fin de session de formation est incorrecte."

        mytoday = datetime.today().strftime("%d/%m/%Y")

        if (datetime.strptime(str(date_fin_session).strip(), '%d/%m/%Y') > datetime.strptime(str(mytoday).strip(), '%d/%m/%Y')):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Vous ne pouvez pas delivrer de certificat avant la date de fin de la session de formation ")
            return False, "  Vous ne pouvez pas delivrer de certificat avant la date de fin de la session de formation "

        attestation_certificat = MYSY_GV.dbname['attestation_certificat'].find_one({'nom': str(session_formation['attestation_certif']),
                                                                    'valide': "1"})

        my_retrun_dict = {}

        my_retrun_dict['attestation_tmpl'] = attestation_certificat['template_name']

        # Recuperation des info de l'inscrit
        local_Insc_retval = MYSY_GV.dbname['inscription'].find_one({'session_id': str(diction['session_id']),
                                                                    'email': str(diction['attendee_email'])})

        if (local_Insc_retval is None):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Impossible de recuperer les données de l'inscrit")
            return False, "  Impossible de recuperer les données de l'inscrit"

        my_retrun_dict['date_du'] = local_Insc_retval['date_du']
        my_retrun_dict['date_au'] = local_Insc_retval['date_au']
        my_retrun_dict['ville'] = local_Insc_retval['ville']
        my_retrun_dict['code_postal'] = local_Insc_retval['code_postal']
        my_retrun_dict['internal_url'] = local_Insc_retval['class_internal_url']

        my_retrun_dict['inscription_id'] = local_Insc_retval['_id']


        my_retrun_dict['adresse'] = local_Insc_retval['adresse']
        my_retrun_dict['nom'] = local_Insc_retval['nom']
        my_retrun_dict['prenom'] = local_Insc_retval['prenom']
        my_retrun_dict['employeur'] = local_Insc_retval['employeur']
        my_retrun_dict['telephone'] = local_Insc_retval['telephone']
        my_retrun_dict['formateur'] = session_formation['formateur']
        my_retrun_dict['email'] = local_Insc_retval['email']

        # Recuperation des infotrmations de la formation
        print(" ## str(local_Insc_retval['class_internal_url']) = ", str(local_Insc_retval['class_internal_url']))
        local_formation = MYSY_GV.dbname['myclass'].find_one(
            {'internal_url': str(local_Insc_retval['class_internal_url'])})
        my_retrun_dict['title'] = local_formation['title']

        # Envoi de l'email de notification au formateur
        local_status, local_message = email_session.SendAttestion_to_attendee_by_email(my_retrun_dict)

        return local_status, str(local_message)

    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 d'envoyer l'attestation"


""" Cette fonction imprime l'attestation 
"""


def PrintAttendeeCertification(diction):
    try:

        field_list_obligatoire = ['session_id', 'token', 'attendee_email']

        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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_token = diction['token']

        # Recuperation 	du 	recid 	du 	partenaire
        partner_recid = mycommon.get_parnter_recid_from_token(str(my_token))
        if partner_recid is False:
            mycommon.myprint(str(inspect.stack()[0][3]) + " -  Impossible d'imprimer la fiche detaillée")
            return False, "  Les informations fournies sont incorrectes"

        # Verifier qui la formation n'a pas deja été evaluée
        tmp_count = MYSY_GV.dbname['inscription'].count_documents({'session_id': str(diction['session_id']),
                                                                   'email': str(diction['attendee_email']),
                                                                   "certification_send": {"$exists": True}})

        if (tmp_count > 0):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Vous avez deja evalué cette formation")
            return False, "  Vous avez deja envoyé le certificat"

        # Recuperation du type/nom de la certifcation depuis la collecion "session_formation"
        session_formation = MYSY_GV.dbname['session_formation'].find_one(
            {'formation_session_id': str(diction['session_id']),
             'valide': "1"})

        if (session_formation['attestation_certif'] is None):
            mycommon.myprint(str(inspect.stack()[0][3]) + " impossible de trouver le modele d'attestation")
            return False, "  impossible de trouver le modele d'attestation"

        attestation_certificat = MYSY_GV.dbname['attestation_certificat'].find_one(
            {'nom': str(session_formation['attestation_certif']),
             'valide': "1"})

        my_retrun_dict = {}

        my_retrun_dict['attestation_tmpl'] = attestation_certificat['template_name']

        # Recuperation des info de l'inscrit
        local_Insc_retval = MYSY_GV.dbname['inscription'].find_one({'session_id': str(diction['session_id']),
                                                                    'email': str(diction['attendee_email'])})

        if (local_Insc_retval is None):
            mycommon.myprint(str(inspect.stack()[0][3]) + " Impossible de recuperer les données de l'inscrit")
            return False, "  Impossible de recuperer les données de l'inscrit"

        my_retrun_dict['date_du'] = local_Insc_retval['date_du']
        my_retrun_dict['date_au'] = local_Insc_retval['date_au']
        my_retrun_dict['ville'] = local_Insc_retval['ville']
        my_retrun_dict['code_postal'] = local_Insc_retval['code_postal']
        my_retrun_dict['internal_url'] = local_Insc_retval['class_internal_url']

        my_retrun_dict['formateur'] = session_formation['formateur']

        my_retrun_dict['adresse'] = local_Insc_retval['adresse']
        my_retrun_dict['nom'] = local_Insc_retval['nom']
        my_retrun_dict['prenom'] = local_Insc_retval['prenom']
        my_retrun_dict['employeur'] = local_Insc_retval['employeur']
        my_retrun_dict['telephone'] = local_Insc_retval['telephone']

        my_retrun_dict['email'] = local_Insc_retval['email']

        # Recuperation des infotrmations de la formation
        print(" ## str(local_Insc_retval['class_internal_url']) = ", str(local_Insc_retval['class_internal_url']))
        local_formation = MYSY_GV.dbname['myclass'].find_one(
            {'internal_url': str(local_Insc_retval['class_internal_url'])})
        my_retrun_dict['title'] = local_formation['title']

        templateLoader = jinja2.FileSystemLoader(searchpath="./")
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = "Template/"+str(my_retrun_dict['attestation_tmpl'])+".html"
        template = templateEnv.get_template(TEMPLATE_FILE)
        # This data can come from database query
        body = {
            "data": my_retrun_dict,

        }

        # print(" ### body = " + str(body))

        sourceHtml = template.render(json_data=body["data"])
        orig_file_name = "Attestation_.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()

        # print(" ### outputFilename = "+str(outputFilename))
        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()
        print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
        return False, " Impossible d'envoyer l'attestation"


"""
Cette fonction recuperer la liste des evaluations d'une session de formation
"""
def GetListEvaluation_Session(diction):
    try:
        field_list_obligatoire = ['session_id', '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"

        my_token = ""
        if ("token" in diction.keys()):
            if diction['token']:
                my_token = diction['token']

        # Recuperation 	du 	recid 	du 	partenaire
        partner_recid = mycommon.get_parnter_recid_from_token(str(my_token))
        if partner_recid is False:
            mycommon.myprint(str(inspect.stack()[0][3]) + " -  Impossible de recuperer la liste des evaluations")
            return False, "  Les informations fournies sont incorrectes"

        RetObject = []
        val_tmp = 1
        # Recuperation des infos de la formation
        for local_Insc_retval in MYSY_GV.dbname['inscription'].find({'session_id': str(diction['session_id'])}):
            user = {}
            user['id'] = str(val_tmp)
            val_tmp = val_tmp + 1
            user['session_id'] = local_Insc_retval['session_id']
            user['email'] = local_Insc_retval['email']
            user['nom'] = local_Insc_retval['nom']
            user['prenom'] = local_Insc_retval['prenom']


            if ("eval_date" in diction.keys()):
                if diction['eval_date']:
                    user['eval_date'] = local_Insc_retval['eval_date']

            if ("eval_date" in diction.keys()):
                if diction['eval_date']:
                    user['eval_date'] = local_Insc_retval['eval_date']

            if ("eval_eval" in diction.keys()):
                if diction['eval_eval']:
                    user['eval_eval'] = local_Insc_retval['eval_eval']
            else:
                user['eval_eval'] = "Aucune Evalution"

            if ("eval_note" in diction.keys()):
                if diction['eval_note']:
                    user['eval_note'] = local_Insc_retval['eval_note']
            else:
                user['eval_note'] = "Aucune Note"


            if ("eval_pedagogie" in diction.keys()):
                if diction['eval_pedagogie']:
                    user['eval_pedagogie'] = local_Insc_retval['eval_pedagogie']


            RetObject.append(mycommon.JSONEncoder().encode(user))


        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 recuperer la liste des evaluations"