Elyos_FI_Back_Office/class_mgt.py

5866 lines
253 KiB
Python

'''
Ce fichier traite tout ce qui est liée à la gestion des formations
'''
import ast
import hashlib
import xlsxwriter
import pymongo
from flask import send_file
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
import ela_index_bdd_classes as eibdd
import email_mgt as email
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
return json.JSONEncoder.default(self, o)
'''
Cette fonction ajoute une formation
elle verifie le token de l'entité qui ajoute la formation.
/!\ : Le champ 'source' permet de savoir le système qui est la source de creation de cette info.
Par exemple : les formations créer depuis le LMS ou les formations envoyées par une
application tiers car on est sur des API.
'''
def add_class(diction):
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 = ['external_code', 'title', 'description', 'institut_formation', 'distantiel', 'presentiel',
'price', 'url','duration', 'duration_unit', 'token', 'plus_produit', 'mots_cle','domaine',
'internal_url', 'zone_diffusion', 'metier', 'published', 'img_url', 'objectif',
'programme', 'prerequis', 'note', 'cpf', 'certif', 'class_inscription_url', 'pourqui',
'support', 'img_banner_detail_class', 'source', 'lms_class_code', 'formateur_id',
'class_level', 'methode_pedagogique', 'condition_handicape', 'suivi_eval', 'class_id',
'version', 'categorie']
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])+" - Creation formation : Le champ '" + val + "' n'est pas autorisé, Creation formation annulée")
return False, " Le champ '" + val + "' n'est pas autorisé, Creation formation annulée ", False
'''
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 = ['external_code', 'title', 'description', 'distantiel', 'presentiel', '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", False
'''
Verification si le token et l'email sont valident
'''
# recuperation des paramettre
mydata = {}
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verification de la validité du token
'''
Important : pour créer une formation, il faut obligatoirement avoir un token.
PAS DE CREATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT LES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - La session de connexion n'est pas valide")
return False, "Les informations d'identification ne sont pas valident", False
# Recuperation du recid du partenaire
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid du partenaire")
return False, " Les informations d'identification sont incorrectes", False
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
part_status, part_pack, part_pack_nb_training_auto = mycommon.Partner_Get_pack_nbTraining(user_recid)
if( part_status is False):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le pack et le nombre de formation du partenaire")
return False, "Votre pack / abonnement ne permet pas de créer les formations. Verifiez votre abonnement ", False
"""
Recuperation du nombre de formations actif de ce partner
"""
part_status2, part_nb_active_training = mycommon.Get_partner_nb_active_training(user_recid)
if (part_status2 is False):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - Impossible de récupérer le pack et le nombre de formation du partenaire")
return False, " Les informations d'identification sont incorrectes", False
mydata['partner_owner_recid'] = user_recid
class_internal_url = ""
class_internal_url_source = ""
if ("internal_url" in diction.keys()):
if diction['internal_url']:
class_internal_url = diction['internal_url']
class_internal_url_source = diction['internal_url']
class_source = ""
if ("source" in diction.keys()):
if diction['source']:
mydata['source'] = diction['source']
class_source = diction['source']
# On ne prend que les valeurs de lms_class_code qui semble cohérent (taille > 2), si non on met vide
lms_class_code = ""
if ("lms_class_code" in diction.keys() and diction['lms_class_code'] and len(str(diction['lms_class_code'])) > 2):
if diction['lms_class_code']:
mydata['lms_class_code'] = diction['lms_class_code']
lms_class_code = diction['lms_class_code']
'''
Si l'internal_url reste à vide, alors le système va créer une internal url de la formation
/!\ : Il faut aller verifier si il a une formation ayant le meme code externe si oui récupérer son internal_url.
Si a chaque fois on créer un nouveau "internal_url", on va perdre les url à chaque mise à jour par excel.
Oui pire, si on modifie le tritre, c'est mort.... :(
'''
exist_class = MYSY_GV.dbname['myclass'].find_one({'external_code':str(diction['external_code']).strip(),
'valide':'1'})
if( exist_class and exist_class['internal_url'] and len(str(exist_class['internal_url'])) > 5):
class_internal_url = str(exist_class['internal_url'])
else :
# On est dans le cas ou la formation N'existe PAS, donc on fait un controle par rappart au nombre dans le pack.
"""
/!\ : Pour le controle du nombre de formation acheté Versus Ajout d'une nouvelle formation
l'utilisateur peut mettre à jour la formation autant de fois qu'il souhaite, *
MAIS il ne peut pas ajouter une formation s'il a atteint le nombre autororisé
Algo :
1 - verifier si la formation à ajouter/mettre à jour existe en base,
- Si elle n'existe pas, alors c'est un ajout, donc controle.
- Si la formation existe deja, alors pas de controle
"""
# Verification si la formation existe en en base
if (mycommon.tryInt(part_nb_active_training) >= mycommon.tryInt(part_pack_nb_training_auto)):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - Impossible d'ajouter la formation "+str(diction['title'])+" - Vous avez atteint le nombre maximum de formations autorisées")
return False, " - Impossible d'ajouter la formation "+str(diction['title'])+" Vous avez atteint le nombre maximum de formations autorisées (" + str(
part_pack_nb_training_auto) + "" \
"). La formation '" + str(
diction['external_code']) + "' n'a pas été enregistrée", False
status, class_internal_url = mycommon.CreateInternalUrl(diction['title'])
mydata['internal_url'] = class_internal_url
"""
Si j'ai deja un "class_internal_url_source" et j'ai une source = "mysy_lms", alors ceci veut dire
qu'il s'agit d'une formation poussée par le LMS
"""
if(len(str(class_internal_url_source)) > 0 and class_source == "mysy_lms"):
mydata['internal_url'] = class_internal_url_source
#print(" ### Il s'agit class_internal_url_source = ", class_internal_url_source, " ### class_source = ", class_source)
if ("external_code" in diction.keys()):
if diction['external_code']:
mydata['external_code'] = diction['external_code']
if ("title" in diction.keys()):
if diction['title']:
mydata['title'] = diction['title']
note = "1"
if ("note" in diction.keys()):
if diction['note']:
note = diction['note']
mydata['note'] = note
cpf = "0"
if ("cpf" in diction.keys()):
if diction['cpf']:
cpf = diction['cpf']
mydata['cpf'] = diction['cpf']
class_level = "0"
if ("class_level" in diction.keys()):
if diction['class_level']:
class_level = diction['class_level']
mydata['class_level'] = class_level
if ("class_inscription_url" in diction.keys()):
if diction['class_inscription_url']:
mydata['class_inscription_url'] = diction['class_inscription_url']
formateur_id = ""
if ("formateur_id" in diction.keys() and diction['formateur_id']):
formateur_id = diction['formateur_id']
# Verification de la validité du formateur (collection employé)
is_formateur_id_ok = MYSY_GV.dbname['ressource_humaine'].count_documents(
{'_id': ObjectId(str(formateur_id)),
'partner_recid': str(user_recid),
'valide': '1',
'locked': '0'
})
if (is_formateur_id_ok <= 0):
mycommon.myprint(str(inspect.stack()[0][3]) + " - L'identifiant du formateur est invalide")
return False, " L'identifiant du formateur est invalide ", False
mydata['formateur_id'] = formateur_id
certif = "0"
if ("certif" in diction.keys()):
if diction['certif']:
certif = diction['certif']
mydata['certif'] = certif
objectif = ""
if ("objectif" in diction.keys()):
if diction['objectif']:
objectif = diction['objectif']
if (len(mycommon.cleanhtml(diction['objectif'])) > MYSY_GV.CLASS_ZONE_OBJECTIF_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'objectif' de la formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_OBJECTIF_LIMIT) + " caractères")
return False, " le champ 'objectif' de la formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_OBJECTIF_LIMIT) + " caractères", False
mydata['objectif'] = objectif
programme = ""
if ("programme" in diction.keys()):
if diction['programme']:
programme = diction['programme']
if(len(mycommon.cleanhtml(diction['programme'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'Progamme' de La formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'Progamme' de La formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
mydata['programme'] = programme
methode_pedagogique = ""
if ("methode_pedagogique" in diction.keys()):
if diction['methode_pedagogique']:
methode_pedagogique = diction['methode_pedagogique']
if (len(mycommon.cleanhtml(diction['methode_pedagogique'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'methode pedagogique' de La formation " + str(
mydata['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'methode pedagogique' de La formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
mydata['methode_pedagogique'] = methode_pedagogique
condition_handicape = ""
if ("condition_handicape" in diction.keys()):
if diction['condition_handicape']:
condition_handicape = diction['condition_handicape']
if (len(mycommon.cleanhtml(diction['condition_handicape'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'condition handicape' de La formation " + str(
mydata['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'condition handicape' de La formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
mydata['condition_handicape'] = condition_handicape
suivi_eval = ""
if ("suivi_eval" in diction.keys()):
if diction['suivi_eval']:
suivi_eval = diction['suivi_eval']
if (len(mycommon.cleanhtml(diction['suivi_eval'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'suivi et evaluation' de La formation " + str(
mydata['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'suivi et evaluation' de La formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
mydata['suivi_eval'] = suivi_eval
prerequis = ""
if ("prerequis" in diction.keys()):
if diction['prerequis']:
prerequis = diction['prerequis']
mydata['prerequis'] = prerequis
if ("description" in diction.keys()):
if diction['description']:
mydata['description'] = diction['description']
if (len(mycommon.cleanhtml(diction['description'])) > MYSY_GV.CLASS_ZONE_DESCRIP_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'description' de La formation " + str(
diction['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_DESCRIP_LIMIT) + " caractères")
return False, " le champ 'description' de La formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_DESCRIP_LIMIT) + " caractères", False
metier = ""
if ("metier" in diction.keys()):
if diction['metier']:
metier = diction['metier']
"""
Verifier la validé du métier
"""
is_valide_metier = MYSY_GV.dbname['class_metier'].count_documents(
{'_id': ObjectId(str(diction['metier'])),
'valide': '1',
'locked': '0'})
if (is_valide_metier <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le métier de formation n'est pas valide ")
return False, " Le métier de formation n'est pas valide ", False
mydata['metier'] = metier
myprki = ""
if ("pourqui" in diction.keys()):
if diction['pourqui']:
myprki = diction['pourqui']
mydata['pourqui'] = myprki
mysupport = ""
if ("support" in diction.keys()):
if diction['support']:
mysupport = str(diction['support']).lower().strip()
mydata['support'] = mysupport
if ("img_banner_detail_class" in diction.keys()):
if diction['img_banner_detail_class']:
mydata['img_banner_detail_class'] = diction['img_banner_detail_class']
if ("published" in diction.keys()):
if diction['published']:
mydata['published'] = diction['published']
if ("plus_produit" in diction.keys()):
if diction['plus_produit']:
mydata['plus_produit'] = diction['plus_produit']
if ("institut_formation" in diction.keys()):
if diction['institut_formation']:
mydata['institut_formation'] = diction['institut_formation']
my_presentiel = "0"
my_distantiel = "0"
if ("distantiel" in diction.keys()):
if diction['distantiel']:
my_distantiel = diction['distantiel']
if ("presentiel" in diction.keys()):
if diction['presentiel']:
my_presentiel = diction['presentiel']
mydata['presentiel'] = {'presentiel': my_presentiel, 'distantiel': my_distantiel}
if ("price" in diction.keys()):
if diction['price']:
mydata['price'] = mycommon.tryFloat(str(diction['price']))
if ("url" in diction.keys()):
if diction['url']:
mydata['url'] = diction['url']
if ("duration" in diction.keys()):
if diction['duration']:
mydata['duration'] = float(str(diction['duration']))
if ("plus_produit" in diction.keys()):
if diction['plus_produit']:
mydata['plus_produit'] = diction['plus_produit']
local_mots_cle = ""
if ("mots_cle" in diction.keys()):
if diction['mots_cle']:
mydata['mots_cle'] = diction['mots_cle']
local_mots_cle = diction['mots_cle']
'''
Verification du nombre de mots clée : limite MYSY_GV.MAX_KEYWORD (3)
'''
local_val = mydata['mots_cle'];
if (local_val.endswith(';')):
local_val = local_val[:-1]
nb_keyword = local_val.split(";")
if(len(str(local_val).strip()) > 0 and len(nb_keyword) > 0 ):
for local_nb_keyword in nb_keyword:
if (len(str(local_nb_keyword).strip()) <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation " + str(
mydata['external_code']) + " contient des valeurs vides")
return False, " La formation " + str(
mydata['external_code']) + " contient des valeurs vides", False
nb_keyword = local_val.split(";")
if( len(nb_keyword) > MYSY_GV.MAX_KEYWORD ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation "+str(mydata['external_code'])+" a plus de "+ str(MYSY_GV.MAX_KEYWORD)+" mots clés")
return False, " La formation "+str(mydata['external_code'])+" a plus de "+ str(MYSY_GV.MAX_KEYWORD)+" mots clés", False
domaine = ""
if ("domaine" in diction.keys()):
if diction['domaine']:
domaine = diction['domaine']
"""
Verifier la validé du domaine
"""
is_valide_domaine = MYSY_GV.dbname['class_domaine'].count_documents({'_id':ObjectId(str(diction['domaine'])),
'valide':'1',
'locked':'0'})
if( is_valide_domaine <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le domaine de formation n'est pas valide ")
return False, " Le domaine de formation n'est pas valide ", False
mydata['domaine'] = domaine
version = ""
if ("version" in diction.keys()):
if diction['version']:
version = diction['version']
mydata['version'] = version
categorie = ""
if ("categorie" in diction.keys()):
if diction['categorie']:
categorie = diction['categorie']
"""
Verifier la validé de la catégoeir
"""
is_valide_categorie = MYSY_GV.dbname['class_categorie'].count_documents(
{'_id': ObjectId(str(diction['categorie'])),
'valide': '1',
'locked': '0'})
if (is_valide_categorie <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La catégorie de formation n'est pas valide ")
return False, " La catégorie de formation n'est pas valide ", False
mydata['categorie'] = categorie
# Traitement de l'url imag
if ("img_url" in diction.keys()):
if diction['img_url']:
# Verifier si l'image existe
status_tmp, img = mycommon.TryUrlImage(str(diction['img_url']))
if( status_tmp is False):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : l'url de l'image de la formation " + str(
mydata['external_code']) + " est incorrecte ")
return False, " l'url de l'image de la formation " + str(mydata['external_code']) + " est incorrecte ", False
mydata['img_url'] = diction['img_url']
else:
mydata['img_url'] = ""
if ("duration_unit" in diction.keys()):
if (diction['duration_unit'] not in MYSY_GV.CLASS_DURATION_UNIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'duration_unit' contient une valeur erronées."
" Les valeurs acceptées sont " + str(
MYSY_GV.CLASS_DURATION_UNIT) + " ")
return False, " : le champ 'duration_unit' contient une valeur erronées." \
" Les valeurs acceptées sont " + str(MYSY_GV.CLASS_DURATION_UNIT), False
mydata['duration_unit'] = diction['duration_unit']
else:
mydata['duration_unit'] = "jour"
if ("zone_diffusion" in diction.keys()):
if diction['zone_diffusion'] and len(str(diction['zone_diffusion'])) > 0:
tmp_str2 = str(diction['zone_diffusion']).lower().replace(",", ";").replace("\r\n", "")
if (not tmp_str2.endswith(";")):
tmp_str2 = tmp_str2 + ";"
#print("tmp_str2 = " + tmp_str2)
if (";" not in tmp_str2):
mycommon.myprint(str(inspect.stack()[0][3]) + " - la zone de diffusion de la formation : A" + str(
diction['external_code']) + " est incorrecte")
return False, "La zone de diffusion de la formation " + str(diction['external_code']) + " est incorrecte ", False
tmp_str = tmp_str2.split(";") #==> ce qui va donner un tableau de : Country_Code-City : ['fr-paris', 'fr-marseille', 'bn-cotonou']
cpt = 0
tab_country = []
tab_city = []
for val in tmp_str:
#print(" val = "+str(val))
if( len(str(val)) <= 0 ):
continue
if( "-" not in str(val)):
mycommon.myprint(str(inspect.stack()[0][3]) + " - la zone de diffusion de la formation : B" + str( diction['external_code']) + " est incorrecte")
return False, "La zone de diffusion de la formation " + str(diction['external_code']) + " est incorrecte", False
tab_val = len(val.split("-"))
if( len(val.split("-")) != 1 and len(val.split("-")) != 2 ):
mycommon.myprint( str(inspect.stack()[0][3]) + " - la zone de diffusion de la formation : C" + str(diction['external_code'])+" est incorrecte")
return False, "La zone de diffusion de la formation " + str(diction['external_code'])+" est incorrecte", False
if( val.split("-")[0]):
tab_country.append(val.split("-")[0])
else:
tab_country.append("")
if(val.split("-")[1]):
tab_city.append(val.split("-")[1])
else:
tab_city.append("")
mydata['zone_diffusion'] = {'country':tab_country, 'city':tab_city}
"""
Update du 22/10/2023 - Gestion des champs spécifiques ajoutés par le partenaire
"""
# Recuperation des champs spécifiques se trouvant dans le dictionnaire. ils commencent tous par 'my_'
for val in diction.keys():
if (val.startswith('my_')):
if (MYSY_GV.dbname['base_specific_fields'].count_documents(
{'partner_owner_recid': str(user_recid),
'related_collection': 'myclass',
'field_name': str(val),
'valide': '1',
'locked': '0'}) != 1):
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas autorisé ")
return False, " Les informations fournies sont incorrectes", False
mydata[str(val)] = diction[str(val)]
mydata['valide'] = '1'
mydata['locked'] = '0'
mydata['indexed'] = '0'
mydata['indexed_title'] = '0'
mydata['indexed_desc'] = '0'
mydata['indexed_obj'] = '0'
mydata['update_by'] = str(my_partner['_id'])
# A supprimer apres (a reflechir .... me tate)
mydata['freeacces'] = '1'
mydata['isalaune'] = '1'
# fin à supprimer
# Create internal ref. of class
mydata['internal_code'] = mycommon.Create_internal_call_ref()
""" Gestion des ajout pr les compte utilisateur de type demo """
coll_partner_account = MYSY_GV.dbname['partnair_account']
myquery = {"recid": str(mydata['partner_owner_recid']), "active": "1",
"demo_account": "1"}
#print(" myquery pr demo_account = " + str(myquery))
tmp = coll_partner_account.count_documents(myquery)
if (tmp > 0):
mydata['display_rank'] = str(MYSY_GV.DEMO_RANKING_VALUE)
mydata['isalaune'] = "1"
#print(" myquery pr demo_account 222 = " + str(tmp))
else:
# Ce n'est pas un compte demo, il faut donc récupérer le display rank tu pack - part_pack
coll_pack = MYSY_GV.dbname['pack']
local_tmp = coll_pack.find({'code_pack': str(part_pack).lower()})
if (local_tmp[0] and "ranking" in local_tmp[0].keys()):
if local_tmp[0]['ranking']:
#print(" ### le ranking du pack est " + str(local_tmp[0]['ranking']))
##mydata['display_rank'] = str(local_tmp[0]['ranking'])
## for demo only
mydata['display_rank'] = "999"
coll_name = MYSY_GV.dbname['myclass']
'''
Verification si cette formation exite deja .
la clé est : external_code
'''
#tmp = coll_name.find({'external_code': str(mydata['external_code'])}).count()
tmp = coll_name.count_documents({'external_code': str(mydata['external_code'])})
#mycommon.myprint(" TMP = " + str(tmp))
'''if (tmp > 0):
mycommon.myprint(str(inspect.stack()[0][3])+" -la formation avec l'external code " + str(mydata['external_code']) + "' existe deja, impossible de créer la formation ")
return False, "la formation avec l'external code " + str(mydata['external_code']) + "' existe deja. Impossible de créer la formation "
'''
#print(" ### Add_Class mydata = ", mydata)
#coll_name.insert_one(mydata)
ret_val = coll_name.find_one_and_update(
{'external_code': str(mydata['external_code']), },
{"$set": mydata},
upsert=True,
return_document=ReturnDocument.AFTER
)
if ret_val and ret_val['_id']:
#Indexation Title de la nouvelle formation ajoutée
training_to_index_title = {}
training_to_index_title['internal_url'] = mydata['internal_url']
training_to_index_title['reindex_all'] = '0'
training_to_index_title['partner_owner_recid'] = str(user_recid)
eibdd.ela_index_given_classes_title(training_to_index_title)
# Indexation Title des mots clées
if( local_mots_cle.strip() != ""):
print(" ### DEBUT indexation mot clée", )
eibdd.ela_index_class_key_word(mydata['external_code'], "keyword", user_recid)
return True, "La formation a bien été ajoutée", str(ret_val['_id'])
else:
mycommon.myprint(" Impossible d'ajouter la formation "+str(str(mydata['external_code'])))
return False, " Impossible d'ajouter la formation "+str(str(mydata['external_code'])), 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'ajouter la formation"+ str(e), False
'''
cette fontion met à jour une formation
la clé est : class_id et ou class_inscription_url
seules les formations "valide" et non "locked" sont modifiable
'''
def update_class(diction):
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 = ['external_code', 'title', 'description', 'institut_formation', 'distantiel',
'presentiel','price', 'url', 'duration', 'token','plus_produit', 'mots_cle',
'domaine', 'internal_code', 'internal_url','zone_diffusion', 'metier',
'published', 'img_url', 'objectif', 'programme', 'prerequis', 'note',
'cpf', 'certif', 'class_inscription_url','pourqui', 'support', 'img_banner_detail_class',
'duration_unit', 'source', 'lms_class_code', 'formateur_id', 'class_level','methode_pedagogique',
'condition_handicape', 'suivi_eval', 'class_id', 'version', 'categorie']
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 accepté, Creation formation annulée")
return False, " Impossible de mettre à jour la formation", False
'''
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 = ['internal_url', '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, " Impossible de mettre à jour la formation", False
# recuperation des paramettre
mydata = {}
my_external_code = ""
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verifier la validité du token
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
# Verification de la validité du token
'''
Important : pour modifier une formation, il faut obligatoirement avoir un token.
PAS DE CREATION / MODIFICATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT CELLES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token ne sont pas valident")
return False, "L'email ou le token ne sont pas valident", False
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid de l'utilisateur")
return False, " Les informations d'identification sont incorrectes", False
partner_recid = user_recid
my_internal_code = ""
if ("internal_code" in diction.keys()):
my_internal_code = diction['internal_code']
my_internal_url = ""
if ("internal_url" in diction.keys()):
my_internal_url = diction['internal_url']
# On ne prend que les valeurs de lms_class_code qui semble cohérent (taille > 2), si non on met vide
lms_class_code = ""
if ("lms_class_code" in diction.keys()):
if(len(str(diction['lms_class_code'])) > 2 ):
mydata['lms_class_code'] = diction['lms_class_code']
else:
mydata['lms_class_code'] = ""
if ("class_level" in diction.keys()):
mydata['class_level'] = diction['class_level']
source = ""
if ("source" in diction.keys()):
mydata['source'] = diction['source']
formateur_id = ""
if ("formateur_id" in diction.keys() and diction['formateur_id']):
formateur_id = diction['formateur_id']
# Verification de la validité du formateur (collection employé)
is_formateur_id_ok = MYSY_GV.dbname['ressource_humaine'].count_documents(
{'_id': ObjectId(str(formateur_id)),
'partner_recid': str(user_recid),
'valide': '1',
'locked': '0'
})
if (is_formateur_id_ok <= 0):
mycommon.myprint(str(inspect.stack()[0][3]) + " - L'identifiant du formateur est invalide")
return False, " L'identifiant du formateur est invalide ", False
mydata['formateur_id'] = formateur_id
if ("external_code" in diction.keys()):
my_external_code = diction['external_code']
mydata['external_code'] = diction['external_code']
if ("title" in diction.keys()):
mydata['title'] = diction['title']
if ("class_inscription_url" in diction.keys()):
mydata['class_inscription_url'] = diction['class_inscription_url']
if ("note" in diction.keys()):
mydata['note'] = diction['note']
if ("objectif" in diction.keys()):
mydata['objectif'] = diction['objectif']
if (len(mycommon.cleanhtml(diction['objectif'])) > MYSY_GV.CLASS_ZONE_OBJECTIF_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'objectif' de La formation " + str(
diction['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_OBJECTIF_LIMIT) + " caractères")
return False, " le champ 'objectif' de La formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_OBJECTIF_LIMIT) + " caractères", False
if ("programme" in diction.keys()):
mydata['programme'] = diction['programme']
if (len(mycommon.cleanhtml(diction['programme'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'Progamme' de La formation " + str(
diction['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'Progamme' de La formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
if ("methode_pedagogique" in diction.keys()):
mydata['methode_pedagogique'] = diction['methode_pedagogique']
if (len(mycommon.cleanhtml(diction['methode_pedagogique'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'methode pedagogique' de La formation " + str(
diction['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'methode pedagogique' de La formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
if ("condition_handicape" in diction.keys()):
mydata['condition_handicape'] = diction['condition_handicape']
if (len(mycommon.cleanhtml(diction['condition_handicape'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'condition handicape' de La formation " + str(
diction['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'condition handicape' de La formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
if ("suivi_eval" in diction.keys()):
mydata['suivi_eval'] = diction['suivi_eval']
if (len(mycommon.cleanhtml(diction['suivi_eval'])) > MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'suivi et evaluation' de La formation " + str(
diction['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères")
return False, " le champ 'suivi et evaluation' de La formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_PROGRAM_LIMIT) + " caractères", False
if ("cpf" in diction.keys()):
mydata['cpf'] = diction['cpf']
if ("pourqui" in diction.keys()):
mydata['pourqui'] = diction['pourqui']
if ("support" in diction.keys()):
mydata['support'] = str(diction['support']).lower().strip()
if ("img_banner_detail_class" in diction.keys()):
mydata['img_banner_detail_class'] = diction['img_banner_detail_class']
if ("certif" in diction.keys()):
mydata['certif'] = diction['certif']
if ("prerequis" in diction.keys()):
mydata['prerequis'] = diction['prerequis']
if ("img_url" in diction.keys()):
if diction['img_url']:
# Verifier si l'image existe
status_tmp, img = mycommon.TryUrlImage(str(diction['img_url']))
if (status_tmp is False):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : l'url de l'image de la formation " + str(my_internal_code) + " est incorrecte ")
return False, " l'url de l'image de la formation " + str(my_internal_code) + " est incorrecte ", False
mydata['img_url'] = diction['img_url']
if ("description" in diction.keys()):
mydata['description'] = diction['description']
#print(" #### ",mycommon.cleanhtml(diction['description']))
#print(" ### len =", len(mycommon.cleanhtml(diction['description'])))
if (len(mycommon.cleanhtml(diction['description'])) > MYSY_GV.CLASS_ZONE_DESCRIP_LIMIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'description' de La formation " + str(
diction['external_code']) + " a plus de " + str(
MYSY_GV.CLASS_ZONE_DESCRIP_LIMIT) + " caractères")
return False, " le champ 'description' de La formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.CLASS_ZONE_DESCRIP_LIMIT) + " caractères", False
if ("metier" in diction.keys()):
mydata['metier'] = diction['metier']
if( diction['metier'] ):
"""
Verifier la validé du métier
"""
is_valide_metier = MYSY_GV.dbname['class_metier'].count_documents(
{'_id': ObjectId(str(diction['metier'])),
'valide': '1',
'locked': '0'})
if (is_valide_metier <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le métier de formation n'est pas valide ")
return False, " Le métier de formation n'est pas valide ", False
if ("published" in diction.keys()):
mydata['published'] = diction['published']
if ("institut_formation" in diction.keys()):
mydata['institut_formation'] = diction['institut_formation']
my_presentiel = "0"
my_distantiel = "0"
if ("distantiel" in diction.keys()):
my_distantiel = diction['distantiel']
if ("presentiel" in diction.keys()):
my_presentiel = diction['presentiel']
mydata['presentiel'] = {'presentiel': my_presentiel, 'distantiel': my_distantiel}
if ("price" in diction.keys()):
if( diction['price']):
mydata['price'] = mycommon.tryFloat(str(diction['price']))
if ("url" in diction.keys()):
mydata['url'] = diction['url']
if ("duration" in diction.keys()):
mydata['duration'] = mycommon.tryFloat(str(diction['duration']))
if ("duration_unit" in diction.keys()):
if ( diction['duration_unit'] not in MYSY_GV.CLASS_DURATION_UNIT) :
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'duration_unit' contient une valeur erronées."
" Les valeurs acceptées sont " + str(MYSY_GV.CLASS_DURATION_UNIT) + " ")
return False, " : le champ 'duration_unit' contient une valeur erronées." \
" Les valeurs acceptées sont " + str(MYSY_GV.CLASS_DURATION_UNIT), False
mydata['duration_unit'] = diction['duration_unit']
else:
mydata['duration_unit'] = "jour"
if ("plus_produit" in diction.keys()):
mydata['plus_produit'] = diction['plus_produit']
if ("mots_cle" in diction.keys()):
mots_cle = diction['mots_cle']
if (mots_cle.endswith(';')):
mots_cle = mots_cle[:-1]
nb_keyword = mots_cle.split(";")
if(len(str(mots_cle).strip()) > 0 and len(nb_keyword) > 0 ):
for local_nb_keyword in nb_keyword:
if (len(str(local_nb_keyword).strip()) <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation " + str(
diction['external_code']) + " contient des valeurs vides (1)")
return False, " La formation " + str(diction['external_code']) + " contient des valeurs vides", False
if (len(nb_keyword) > MYSY_GV.MAX_KEYWORD):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation " + str(
diction['external_code']) + " a plus de " + str(MYSY_GV.MAX_KEYWORD) + " mots clés")
return False, " La formation " + str(diction['external_code']) + " a plus de " + str(
MYSY_GV.MAX_KEYWORD) + " mots clés", False
mydata['mots_cle'] =mots_cle
if ("domaine" in diction.keys()):
mydata['domaine'] = diction['domaine']
if (diction['domaine']):
"""
Verifier la validé du domaine
"""
is_valide_domaine = MYSY_GV.dbname['class_domaine'].count_documents(
{'_id': ObjectId(str(diction['domaine'])),
'valide': '1',
'locked': '0'})
if (is_valide_domaine <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le domaine de formation n'est pas valide ")
return False, " Le domaine de formation n'est pas valide ", False
if ("version" in diction.keys()):
mydata['version'] = diction['version']
if ("categorie" in diction.keys()):
mydata['categorie'] = diction['categorie']
if (diction['categorie']):
"""
Verifier la validé de la catégorie
"""
is_valide_categorie = MYSY_GV.dbname['class_categorie'].count_documents(
{'_id': ObjectId(str(diction['categorie'])),
'valide': '1',
'locked': '0'})
if (is_valide_categorie <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La catégorie de formation n'est pas valide ")
return False, " La catégorie de formation n'est pas valide ", False
if ("zone_diffusion" in diction.keys()):
if(len(str(diction['zone_diffusion'])) == 0 ):
mydata['zone_diffusion'] = {}
else:
tmp_str2 = str(diction['zone_diffusion']).lower().replace(",", ";").replace("\r\n", "")
if( not tmp_str2.endswith(";")):
tmp_str2 = tmp_str2+";"
#print("tmp_str2 = " + tmp_str2)
if (";" not in tmp_str2):
mycommon.myprint(str(inspect.stack()[0][3]) + " - la zone de diffusion de la formation 0: " + str(
my_external_code) + " est incorrecte")
return False, "La zone de diffusion de la formation " + str(my_external_code) + " est incorrecte", False
tmp_str = tmp_str2.split(";") #==> ce qui va donner un tableau de : Country_Code-City : ['fr-paris', 'fr-marseille', 'bn-cotonou']
cpt = 0
tab_country = []
tab_city = []
for val in tmp_str:
if (len(str(val)) <= 0):
continue
if( "-" not in str(val)):
mycommon.myprint(str(inspect.stack()[0][3]) + " - la zone de diffusion de la formation 1: " + str( my_external_code) + " est incorrecte")
return False, "La zone de diffusion de la formation " + str(my_external_code) + " est incorrecte", False
tab_val = len(val.split("-"))
if( len(val.split("-")) != 1 and len(val.split("-")) != 2 ):
mycommon.myprint( str(inspect.stack()[0][3]) + " - la zone de diffusion de la formation 2: " + str(my_external_code)+" est incorrecte")
return False, "La zone de diffusion de la formation " + str(my_external_code)+" est incorrecte", False
if( val.split("-")[0]):
tab_country.append(val.split("-")[0])
else:
tab_country.append("")
if(val.split("-")[1]):
tab_city.append(val.split("-")[1])
else:
tab_city.append("")
mydata['zone_diffusion'] = {'country':tab_country, 'city':tab_city}
mydata['date_update'] = str(datetime.now())
mydata['update_by'] = str(my_partner['recid'])
# Recuperation des champs spécifiques se trouvant dans le dictionnaire. ils commencent tous par 'my_'
for val in diction.keys():
if (val.startswith('my_')):
if (MYSY_GV.dbname['base_specific_fields'].count_documents(
{'partner_owner_recid': str(partner_recid),
'related_collection': 'myclass',
'field_name': str(val),
'valide': '1',
'locked': '0'}) != 1):
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas autorisé ")
return False, " Les informations fournies sont incorrectes", False
mydata[str(val)] = diction[str(val)]
# A supprimer apres (a reflechir .... me tate)
mydata['freeacces'] = '1'
mydata['isalaune'] = '1'
# fin à supprimer
mydata['indexed'] = '0'
mydata['indexed_title'] = '0'
mydata['indexed_desc'] = '0'
mydata['indexed_obj'] = '0'
mydata['date_update'] = str(datetime.now())
mydata['update_by'] = str(my_partner['_id'])
""" Gestion des ajout pr les compte utilisateur de type demo """
coll_partner_account = MYSY_GV.dbname['partnair_account']
myquery = {"recid": str(user_recid), "active": "1",
"demo_account": "1"}
#print(" myquery pr demo_account = " + str(myquery))
tmp = coll_partner_account.count_documents(myquery)
if (tmp > 0):
mydata['display_rank'] = str(MYSY_GV.DEMO_RANKING_VALUE)
mydata['isalaune'] = "1"
#print(" myquery pr demo_account 222 = " + str(tmp))
else:
#Ce n'est pas un compte demo, il faut donc récupérer le display rank tu pack - part_pack
part_status, part_pack, part_pack_nb_training_auto = mycommon.Partner_Get_pack_nbTraining(user_recid)
if (part_status is False):
mycommon.myprint(str(inspect.stack()[0][
3]) + " - Impossible de récupérer le pack et le nombre de formation du partenaire")
return False, "Votre pack / abonnement ne permet pas de créer les formations. Verifiez votre abonnement ", False
coll_pack = MYSY_GV.dbname['pack']
local_tmp = coll_pack.find({'code_pack':str(part_pack).lower()})
if (local_tmp[0] and "ranking" in local_tmp[0].keys()):
if local_tmp[0]['ranking']:
print(" ### le ranking du pack est "+str(local_tmp[0]['ranking']) )
#mydata['display_rank'] = str(local_tmp[0]['ranking'])
## For demo only
mydata['display_rank'] = "999"
coll_name = MYSY_GV.dbname['myclass']
#print(" ### Update class : internal_url = ", str(my_internal_url), " -- partner_owner_recid = ", partner_recid)
#print(" ### mydata = ", mydata)
# seules les formations avec locked = 0 et valide=1 sont modifiables
ret_val = coll_name.find_one_and_update({'internal_url': str(my_internal_url), 'partner_owner_recid':partner_recid, 'locked': '0', 'valide': '1',
'_id':ObjectId(str(diction['class_id']))},
{"$set": mydata},
upsert=False,
return_document=ReturnDocument.AFTER
)
if (ret_val and ret_val['_id']):
nb_doc = str(ret_val['_id'])
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a bin ete mise à jour =" + str(nb_doc))
# Indexation Title de la nouvelle formation ajoutée
training_to_index_title = {}
training_to_index_title['internal_url'] = ret_val['internal_url']
training_to_index_title['reindex'] = '1'
training_to_index_title['partner_owner_recid'] = str(partner_recid)
eibdd.ela_index_given_classes_title(training_to_index_title)
# Indexation Title des mots clées
eibdd.ela_index_given_classes_keywords(training_to_index_title)
return True, " La formation a été mise à jour", str(ret_val['_id'])
else:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de mettre à jour la formation : "+str(my_external_code) )
return False, "Impossible de mettre à jour la formation "+str(my_external_code), 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 de mettre à jour la formation ", False
'''
Desactivation d'une formation
Disable a training, set mydata['valide'] = '0'
'''
def disable_class(diction):
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 = ['internal_url', '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, Creation formation annulée")
return False, " Impossible de mettre à jour la formation"
'''
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 = ['internal_url', '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, " Impossible de mettre à jour la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verification de la validité du token
'''
Important : pour modifier une formation, il faut obligatoirement avoir un token.
PAS DE CREATION / MODIFICATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT CELLES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token ne sont pas valident")
return False, "L'email ou le token ne sont pas valident"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid de l'utilisateur")
return False, " Les informations d'identification sont incorrectes"
partner_recid = user_recid
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
mydata['date_update'] = str(datetime.now())
mydata['valide'] = '0'
coll_name = MYSY_GV.dbname['myclass']
# seules les formations avec locked = 0 et valide=1 sont modifiables
ret_val = coll_name.find_one_and_update(
{'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '0',
'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
if (ret_val and ret_val['_id']):
nb_doc = str(ret_val['_id'])
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a bin ete mise à jour =" + str(nb_doc))
return True, " La formation "+str(my_internal_url)+"a été desactivée"
else:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de desactivier : " +str(my_internal_url) )
return False, " Impossible de desactivier la formation : "+str(my_internal_url)
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 desactivier la formation "
'''
reactivation d'une formation
Enable a training set mydata['valide'] = '1'
'''
def enable_class(diction):
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 = ['internal_url', '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, Creation formation annulée")
return False, " Impossible de mettre à jour la formation"
'''
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 = ['internal_url', '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, " Impossible de mettre à jour la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verification de la validité du token
'''
Important : pour modifier une formation, il faut obligatoirement avoir un token.
PAS DE CREATION / MODIFICATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT CELLES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token ne sont pas valident")
return False, "L'email ou le token ne sont pas valident"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid de l'utilisateur")
return False, " Les informations d'identification sont incorrectes"
partner_recid = user_recid
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
mydata['date_update'] = str(datetime.now())
mydata['valide'] = '1'
coll_name = MYSY_GV.dbname['myclass']
# seules les formations avec locked = 0 et valide=1 sont modifiables
ret_val = coll_name.find_one_and_update(
{'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '0',
'valide': '0'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
if (ret_val and ret_val['_id']):
nb_doc = str(ret_val['_id'])
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a bien ete reactivée =" + str(nb_doc))
return True, " La formation " + str(my_internal_url) + "a été reactivée"
else:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de desactivier : " + str(my_internal_url))
return False, " Impossible de reactivée la formation : " + str(my_internal_url)
except Exception as e:
mycommon.myprint(str(inspect.stack()[0][3])+" - " +str(e))
return False, " Impossible de reactiver la formation"
'''
Desactivation d'une formation
unlock a training set mydata['locked'] = '0'
'''
def unlock_class(diction):
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 = ['internal_url', '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, Creation formation annulée")
return False, " Impossible de mettre à jour la formation"
'''
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 = ['internal_url', '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, " Impossible de mettre à jour la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verification de la validité du token
'''
Important : pour modifier une formation, il faut obligatoirement avoir un token.
PAS DE CREATION / MODIFICATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT CELLES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token ne sont pas valident")
return False, "L'email ou le token ne sont pas valident"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid de l'utilisateur")
return False, " Les informations d'identification sont incorrectes"
partner_recid = user_recid
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
mydata['date_update'] = str(datetime.now())
mydata['locked'] = '0'
coll_name = MYSY_GV.dbname['myclass']
# seules les formations avec locked = 1 et valide=1 sont 'unlockable'
ret_val = coll_name.find_one_and_update(
{'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '1',
'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
if (ret_val and ret_val['_id']):
nb_doc = str(ret_val['_id'])
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a bien ete debloquée =" + str(nb_doc))
return True, " La formation " + str(my_internal_url) + "a été debloquée"
else:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de debloquer : " + str(my_internal_url))
return False, " Impossible de debloquer la formation : " + str(my_internal_url)
except Exception as e:
mycommon.myprint(str(inspect.stack()[0][3])+" - " +str(e))
return False, " Impossible de mettre à jour la formation"
'''
Verrouillage d'une formation
lock a training set mydata['locked'] = '1'
'''
def lock_class(diction):
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 = ['internal_url', '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, Creation formation annulée")
return False, " Impossible de mettre à jour la formation"
'''
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 = ['internal_url', '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, " Impossible de mettre à jour la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verification de la validité du token
'''
Important : pour modifier une formation, il faut obligatoirement avoir un token.
PAS DE CREATION / MODIFICATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT CELLES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token ne sont pas valident")
return False, "L'email ou le token ne sont pas valident"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid de l'utilisateur")
return False, " Les informations d'identification sont incorrectes"
partner_recid = user_recid
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
mydata['date_update'] = str(datetime.now())
mydata['locked'] = '1'
coll_name = MYSY_GV.dbname['myclass']
# seules les formations avec locked = 1 et valide=1 sont 'unlockable'
print( "str(my_internal_url) = "+str(my_internal_url)+" --- partner_recid = "
+partner_recid+" mydata = "+str(mydata))
ret_val = coll_name.find_one_and_update(
{'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '0',
'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
if (ret_val and ret_val['_id']):
nb_doc = str(ret_val['_id'])
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a bien ete verrouillée =" + str(nb_doc))
return True, " La formation " + str(my_internal_url) + "a été verrouillée"
else:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de verrouiller la formation : " + str(my_internal_url))
return False, " Impossible de verrouiller la formation : " + str(my_internal_url)
except Exception as e:
mycommon.myprint(str(inspect.stack()[0][3]) + " - " + str(e))
return False, " Impossible de mettre à jour la formation"
'''
Cette fonction publie une formation
elle met la valeur "published" à 1
'''
def pusblish_class(diction):
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 = ['internal_url', '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, Creation formation annulée")
return False, " Impossible de mettre à jour la formation"
'''
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 = ['internal_url', '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, " Impossible de mettre à jour la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verification de la validité du token
'''
Important : pour modifier une formation, il faut obligatoirement avoir un token.
PAS DE CREATION / MODIFICATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT CELLES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token ne sont pas valident")
return False, "L'email ou le token ne sont pas valident"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid de l'utilisateur")
return False, " Les informations d'identification sont incorrectes"
partner_recid = user_recid
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
mydata['date_update'] = str(datetime.now())
mydata['published'] = '1'
coll_name = MYSY_GV.dbname['myclass']
# seules les formations avec locked = 1 et valide=1 sont 'publiable'
print( "str(my_internal_url) = "+str(my_internal_url)+" --- partner_recid = "
+partner_recid+" mydata = "+str(mydata))
'''
ret_val = coll_name.find_one_and_update(
{'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '0',
'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
'''
ret_val = coll_name.update_many( {'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '0',
'valide': '1'}, {"$set": mydata}, )
if (ret_val.matched_count > 0):
nb_doc = str(my_internal_url)
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a bien ete publiée =" + str(nb_doc))
return True, " La formation " + str(my_internal_url) + "a été publiée"
else:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de publier la formation : " + str(my_internal_url))
return False, " Impossible de publier la formation : " + str(my_internal_url)
except Exception as e:
mycommon.myprint(str(inspect.stack()[0][3]) + " - " + str(e))
return False, " Impossible de publier la formation"
'''
Cette fonction Depublie une formation
1 - Elle met "published" à 0
'''
def unpublish_class(diction):
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 = ['internal_url', '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, Creation formation annulée")
return False, " Impossible de mettre à jour la formation"
'''
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 = ['internal_url', '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, " Impossible de depublier la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
# Verification de la validité du token
'''
Important : pour modifier une formation, il faut obligatoirement avoir un token.
PAS DE CREATION / MODIFICATION DE FORMATION EN MODE NON CONNECTE.
CONCERNANT CELLES CREEES PAR NOS SYSTEME AUTOMATIQUE, IL FAUDRA LEUR PASSER UNE VALEUR MALGRE TOUT
'''
retval = mycommon.check_partner_token_validity("", str(mydata['token']))
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token ne sont pas valident")
return False, "L'email ou le token ne sont pas valident"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(str(mydata['token']))
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le recid de l'utilisateur")
return False, " Les informations d'identification sont incorrectes"
partner_recid = user_recid
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
mydata['date_update'] = str(datetime.now())
mydata['published'] = '0'
coll_name = MYSY_GV.dbname['myclass']
# seules les formations avec locked = 1 et valide=1 sont 'depupliable'
print( " str(my_internal_url) = "+str(my_internal_url)+" partner_recid = "+partner_recid+
" mydata = "+str(mydata) )
'''
ret_val = coll_name.find_one_and_update(
{'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '0',
'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
'''
ret_val = coll_name.update_many(
{'internal_url': str(my_internal_url), 'partner_owner_recid': partner_recid, 'locked': '0',
'valide': '1'}, {"$set": mydata}, )
if (ret_val.matched_count > 0):
nb_doc = str(my_internal_url)
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a bien ete depubliée =" + str(nb_doc))
return True, " La formation " + str(my_internal_url) + "a été depubliée"
else:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de depublier la formation : " + str(my_internal_url))
return False, " Impossible de depublier la formation : " + str(my_internal_url)
except Exception as e:
mycommon.myprint(str(inspect.stack()[0][3])+" - " +str(e))
return False, " Impossible de depublier la formation"
'''
cette fonction recherche et retour une formation.
la clé est : l'external code.
- le token du partenaire
Seules les formations "locked = 0 et valide = 1" sont recuperables par l'API
'''
def get_class(diction):
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 = ['internal_url', 'token', 'title', 'valide', 'locked', 'user_ip', 'user_country_code', 'user_country_name', 'user_city',
'user_postal', 'user_latitude', 'user_longitude', 'user_state', 'connection_type']
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, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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, " Impossible de récupérer la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
my_token = ""
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
client_connected_recid = ""
connection_type = ""
if ("connection_type" in diction.keys()):
if diction['connection_type']:
connection_type = diction['connection_type']
'''
Gestion des filters.
'''
internal_url_crit = {}
if ("internal_url" in diction.keys()):
if diction['internal_url']:
internal_url_crit['internal_url'] = diction['internal_url']
title_crit = {}
if ("title" in diction.keys()):
if diction['title']:
title_crit['title'] = diction['title']
coll_name = MYSY_GV.dbname['myclass']
# verifier que le token et l'email sont ok
coll_token = MYSY_GV.dbname['user_token']
# Verification de la validité du token dans le cas des user en mode connecté
'''
/!\ Important : si le token est vide, alors c'est une recherche faite en mode non-connecté.
on doit l'accepter.
le controle de la validé du token est faite que ce dernier n'est pas vide.
'''
user_recid = "None"
coll_search_result = MYSY_GV.dbname['user_recherche_result']
# Verification de la validité du token/mail dans le cas des user en mode connecté
if (len(str(my_token)) > 0 and str(connection_type).strip() == "user"):
retval = mycommon.check_token_validity("", my_token)
if retval is False:
mycommon.myprint( str(inspect.stack()[0][3])+" - La session de connexion n'est pas valide")
return False, " Impossible de récupérer la formation"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_user_recid_from_token(my_token)
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3])+" - Impossible de récupérer le token de l'utilisateur")
return False, " Impossible de récupérer la formation"
# Verification de la validité du token/mail dans le cas des partner en mode connecté
if (len(str(my_token)) > 0 and str(connection_type).strip() == "partner"):
retval = mycommon.check_partner_token_validity("", my_token)
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - La session de connexion n'est pas valide")
return "Err_Connexion", "La session de connexion n'est pas valide"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(my_token)
if user_recid is False:
mycommon.myprint(
str(inspect.stack()[0][3]) + " - Impossible de récupérer le token du partenaire")
return False, " Impossible de récupérer le token du partenaire"
RetObject = []
filt_external_code = {}
internal_url = ""
if ("internal_url" in diction.keys()):
filt_external_code = {'internal_url':str(diction['internal_url'])}
internal_url = str(diction['internal_url'])
#print(' ICICICIC '+str(filt_external_code))
#print(" #### internal_url = ", internal_url)
qry_02 = {'valide':'1','locked':'0','internal_url':internal_url, 'published':'1'}
#print(" #### qty_02 = ", qry_02)
# Recuperation des info du partenaire propriaitaire comme : ces certification (qualiopi, datadock, etc) et son nom
tmp_class_data = MYSY_GV.dbname['myclass'].find_one({'valide':'1','locked':'0','internal_url':internal_url, 'published':'1'},
{"_id": 1, "partner_owner_recid": 1, } )
if( tmp_class_data is None or tmp_class_data["partner_owner_recid"] is None):
#print(' ### tmp_class_data =', str(tmp_class_data ))
mycommon.myprint(str(inspect.stack()[0][3]) + " - impossible de récupérer les données du partenaire - laa ")
return False, " Cette formation est indisponible "
#print(" ### la formation concernee est : ", tmp_class_data)
qry = {'active':'1','locked':'0','recid':str(tmp_class_data["partner_owner_recid"]) }
tmp_partenaire_data = MYSY_GV.dbname['partnair_account'].find_one(qry)
if (tmp_partenaire_data is None or tmp_partenaire_data["_id"] is None):
mycommon.myprint(str(inspect.stack()[0][3]) + " - impossible de récupérer les données du partenaire (2) ")
return False, " Cette formation est indisponible (2) "
filt_title = {}
if ("title" in diction.keys()):
filt_title = {'title': {'$regex': str(diction['title']), "$options": "i"}}
print(" #### avant requete get partner_owner_recid laa yy= "+str(user_recid)+
" internal_url = "+str(my_internal_url)+
" filt_title = "+str(filt_title))
text_size = 0
"""
# Pour facilité l'affichage du front, on va créer une variable qui liste le nombre de pavé existant.
A date la liste des champs est : description, plus_produit, objectif, programme, prerequis, session, pourqui
"""
nb_pave_a_afficher = 0
connected_client_recid = ""
if (str(connection_type).strip() == "partner"):
connected_client_recid = user_recid
pipe = [
{'$match': {'internal_url': internal_url, 'published': '1'}},
{'$project': { 'indexed': 0, 'indexed_desc': 0, 'indexed_obj': 0, "indexed_title": 0, "valide": 0,
"locked": 0}},
{'$lookup':
{
'from': 'business_prices',
'let': {'partner_owner_recid': "$partner_owner_recid", 'programme': '$programme'},
'pipeline': [
{'$match':
{'$expr':
{'$and':
[
{'$eq': ["$partner_recid", "$$partner_owner_recid"]},
{'$eq': ["$client_recid", connected_client_recid]},
{'$eq': ["$valide", "1"]}
]
}
}
},
],
'as': 'business_prices'
}
}
]
print(" ### pipe myclass = ", pipe)
for retVal in coll_name.aggregate(pipe):
"""
for retVal in coll_name.find({'valide':'1','locked':'0','internal_url':internal_url, 'published':'1'},
{"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0,
"valide": 0, "locked": 0, "partner_owner_recid": 0, }
).limit(1):
"""
print('#### ICI retVal = '+str(retVal))
if ("business_prices" in retVal.keys()):
if(len(retVal['business_prices']) > 0 and "discount" in retVal['business_prices'][0].keys() ):
"""
Calcal du prix discounté
"""
#print(" ### discount = ", x['business_prices'][0]['discount'], " PRIX initial = ", x['price'])
local_discount = mycommon.tryFloat(str(retVal['business_prices'][0]['discount']))
local_initial_price = mycommon.tryFloat(str(retVal['price']))
local_discounted_price = round( local_initial_price - (local_initial_price * (local_discount/100)), 2)
retVal['business_prices'][0]['discounted_price'] = str(local_discounted_price)
#print(" #### local_discounted_price = ", local_discounted_price)
my_recid = {}
my_recid['user_rec_id'] = str(user_recid)
mydict_combined = {**diction, **retVal, **my_recid}
mydict_combined['date_update'] = str(datetime.now())
mydict_combined['type_view'] = "detail"
if ("_id" in mydict_combined.keys()):
mydict_combined['class_id'] = mydict_combined.pop('_id')
#mycommon.myprint("COMBINED = " + str(mydict_combined))
'''
Statistique : Insertion du recherche - resultat '''
ret_val_tmp = coll_search_result.insert_one(mydict_combined)
if (ret_val_tmp is False):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de mettre à jour la table des resultat"
" d'une recherche de formation. Voir _id = ")
return False, "Impossible de faire un affichage detaillé "
# Cette varible compte le nombre de certificat dont dispose le partenaire.
# Cette information est utilisée pour savoir les taille à afficher sur le front
nb_partner_certificat = 0
if( "isdatadock" in tmp_partenaire_data.keys() and tmp_partenaire_data['isdatadock']):
retVal['isdatadock'] = tmp_partenaire_data['isdatadock']
if (tmp_partenaire_data['isdatadock'] == "1"):
nb_partner_certificat = nb_partner_certificat + 1
if ("isqualiopi" in tmp_partenaire_data.keys() and tmp_partenaire_data['isqualiopi']):
retVal['isqualiopi'] = tmp_partenaire_data['isqualiopi']
if (tmp_partenaire_data['isqualiopi'] == "1"):
nb_partner_certificat = nb_partner_certificat + 1
if ("iscertitrace" in tmp_partenaire_data.keys() and tmp_partenaire_data['iscertitrace']):
retVal['iscertitrace'] = tmp_partenaire_data['iscertitrace']
if( tmp_partenaire_data['iscertitrace'] == "1"):
nb_partner_certificat = nb_partner_certificat + 1
if ("isbureaucertitrace" in tmp_partenaire_data.keys() and tmp_partenaire_data['isbureaucertitrace']):
retVal['isbureaucertitrace'] = tmp_partenaire_data['isbureaucertitrace']
if (tmp_partenaire_data['isbureaucertitrace'] == "1"):
nb_partner_certificat = nb_partner_certificat + 1
if ("iscertifvoltaire" in tmp_partenaire_data.keys() and tmp_partenaire_data['iscertifvoltaire']):
retVal['iscertifvoltaire'] = tmp_partenaire_data['iscertifvoltaire']
if (tmp_partenaire_data['iscertifvoltaire'] == "1"):
nb_partner_certificat = nb_partner_certificat + 1
retVal['nb_partner_certificat'] = str(nb_partner_certificat)
if ("nom" in tmp_partenaire_data.keys() and tmp_partenaire_data['nom']):
retVal['nom_partenaire'] = tmp_partenaire_data['nom']
if ("website" in tmp_partenaire_data.keys() and tmp_partenaire_data['website']):
retVal['website_partenaire'] = tmp_partenaire_data['website']
if ("description" in retVal.keys()):
tmp_str = retVal['description']
no_html = mycommon.cleanhtml(retVal['description'])
nb_pave_a_afficher = nb_pave_a_afficher + 1
text_size = text_size + len(str(no_html))
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['description'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("objectif" in retVal.keys()):
tmp_str = retVal['objectif']
no_html = mycommon.cleanhtml(retVal['objectif'])
text_size = text_size + len(str(no_html))
nb_pave_a_afficher = nb_pave_a_afficher + 1
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['objectif'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("pourqui" in retVal.keys() and retVal['pourqui']):
nb_pave_a_afficher = nb_pave_a_afficher + 1
if ("programme" in retVal.keys()):
tmp_str = retVal['programme']
no_html = mycommon.cleanhtml( retVal['programme'])
text_size = text_size + len(str(no_html))
nb_pave_a_afficher = nb_pave_a_afficher + 1
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['programme'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("methode_pedagogique" in retVal.keys()):
tmp_str = retVal['methode_pedagogique']
no_html = mycommon.cleanhtml( retVal['methode_pedagogique'])
text_size = text_size + len(str(no_html))
nb_pave_a_afficher = nb_pave_a_afficher + 1
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['methode_pedagogique'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("condition_handicape" in retVal.keys()):
tmp_str = retVal['condition_handicape']
no_html = mycommon.cleanhtml( retVal['condition_handicape'])
text_size = text_size + len(str(no_html))
nb_pave_a_afficher = nb_pave_a_afficher + 1
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['condition_handicape'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("suivi_eval" in retVal.keys()):
tmp_str = retVal['suivi_eval']
no_html = mycommon.cleanhtml( retVal['suivi_eval'])
text_size = text_size + len(str(no_html))
nb_pave_a_afficher = nb_pave_a_afficher + 1
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['suivi_eval'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("pedagogie" in retVal.keys()):
tmp_str = retVal['pedagogie']
no_html = mycommon.cleanhtml(retVal['pedagogie'])
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['pedagogie'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
#retVal["text_size"] = str(text_size)
retVal["text_size"] = "1600"
"""
Verifier s'il y a des session des formations actives
"""
localmyquery = {}
localmyquery['class_internal_url'] = internal_url
localmyquery['valide'] = "1"
localmyquery['session_status'] = "true"
count_localmyquery = MYSY_GV.dbname['session_formation'].count_documents(localmyquery)
if( count_localmyquery > 0 ):
nb_pave_a_afficher = nb_pave_a_afficher + 1
print(" ### nb_pave_a_afficher , SESSION ")
retVal["nb_pave_a_afficher"] = str(nb_pave_a_afficher)
#print(" #### Pour la formation :",internal_url, " text_size = ", str(text_size))
#mycommon.myprint(" #### "+str(retVal))
user = retVal
RetObject.append(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 formation"
'''
Cette API retour une formation "coup de coeur".
elle effectue les controles necessaires et retour la formation
'''
def get_class_coup_de_coeur(diction):
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 = ['internal_url', 'token', 'title', 'valide', 'locked', 'user_ip', 'user_country_code', 'user_country_name', 'user_city',
'user_postal', 'user_latitude', 'user_longitude', 'user_state']
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, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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, " Impossible de récupérer la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
my_token = ""
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
coll_name = MYSY_GV.dbname['myclass']
RetObject = []
filt_external_code = {}
internal_url = ""
if ("internal_url" in diction.keys()):
internal_url = str(diction['internal_url'])
for retVal in coll_name.find({'valide':'1','locked':'0','internal_url':internal_url, 'coeur':'1', 'published':'1'},
{"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0,
"valide": 0, "locked": 0, "partner_owner_recid": 0, }
):
print(" retval "+str(retVal))
if ("description" in retVal.keys()):
tmp_str = retVal['description']
if (len(retVal['description']) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['description'] = tmp_str[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("objectif" in retVal.keys()):
tmp_str = retVal['objectif']
if (len(retVal['objectif']) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['objectif'] = tmp_str[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("programme" in retVal.keys()):
tmp_str = retVal['programme']
if (len(retVal['programme']) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['programme'] = tmp_str[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("pedagogie" in retVal.keys()):
tmp_str = retVal['pedagogie']
if (len(retVal['pedagogie']) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['pedagogie'] = tmp_str[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
#mycommon.myprint(str(retVal))
user = retVal
RetObject.append(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 formation"
'''
cette fonction recherche et retour une formation dont le proprietaire est le partenaire "partenaire_rec_id"
la clé est : l'external code.
- le token du partenaire. le token permet d'aller chercher le "rec_id"
Seules les formations "locked = 0 et valide = 1" sont recuperables par l'API
'''
def get_partner_class(diction):
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 = ['internal_url', 'token', 'title', 'valide', 'locked', 'external_code']
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])+ " - get_partner_class : Le champ '" + val + "' n'existe pas, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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, " Impossible de récupérer la formation"
# recuperation des paramettre
mydata = {}
my_external_code = ""
my_token = ""
my_internal_url = ""
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
if ("external_code" in diction.keys()):
if diction['external_code']:
my_external_code = diction['external_code']
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
# Verifier la validité du token
retval = mycommon.check_partner_token_validity("", my_token)
if retval is False:
return "Err_Connexion", " La session de connexion n'est pas valide"
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
user_recid = str(my_partner['recid'])
'''
Gestion des filters.
'''
internal_url_crit = {}
if ("internal_url" in diction.keys()):
if diction['internal_url']:
internal_url_crit['internal_url'] = diction['internal_url']
external_code_crit = {}
if ("external_code" in diction.keys()):
if diction['external_code']:
external_code_crit['external_code'] = diction['external_code']
title_crit = {}
if ("title" in diction.keys()):
if diction['title']:
title_crit['title'] = diction['title']
coll_name = MYSY_GV.dbname['myclass']
# verifier que le token et l'email sont ok
coll_token = MYSY_GV.dbname['user_token']
# Verification de la validité du token dans le cas des user en mode connecté
'''
/!\ Important : le token ne doit jamais etre vide car cette fonction a pour objectif
de retourner les formations edité par un partenaire.
Il dont obligatoirement est en mode connecté
'''
user_recid = "None"
# Verification de la validité du token/mail dans le cas des user en mode connecté
if (len(str(my_token)) > 0):
retval = mycommon.check_partner_token_validity("", my_token)
if retval is False:
mycommon.myprint( str(inspect.stack()[0][3])+" - La session de connexion n'est pas valide")
return False, " Impossible de récupérer la formation"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(my_token)
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3])+" - Impossible de récupérer le token de l'utilisateur")
return False, " Impossible de récupérer la formation"
if (len(str(my_token)) <= 0):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token est vide")
return False, " Impossible de récupérer la formation"
RetObject = []
filt_external_code= {}
if ("external_code" in diction.keys()):
filt_external_code = {'external_code':str(diction['external_code'])}
#print(" GRRRRRRRRRRRRR "+str(filt_external_code))
filt_title = {}
if ("title" in diction.keys()):
filt_title = {'title': str(diction['title'])}
filt_internal_url = {}
if ("internal_url" in diction.keys()):
filt_internal_url = {'internal_url': str(diction['internal_url'])}
#print(" filt_internal_url GRRRRRRRRRRRRRRRRRRRRrr "+str(filt_internal_url))
"""
print(" ATTTTENNTION : GESTION DU CAS OU LA PERSONNE QUI CHERCHE LE COURS EST UN UTILISATEUR : PB avec : partner_owner_recid ")
print(" #### avant requete get partner_owner_recid ="+str(user_recid)+
" filt_external_code = "+str(filt_external_code)+
" filt_internal_url = " + str(filt_internal_url) +
" filt_title = "+str(filt_title))
"""
val_tmp = 1
nb_hour_per_day = mycommon.Get_Partner_Hour_Per_Day(str(my_partner['recid']))
if (nb_hour_per_day is False):
nb_hour_per_day = "7"
currency = mycommon.Get_Partner_Currency(str(my_partner['recid']))
if (currency is False):
currency = ""
for retVal in coll_name.find( {"$and":[ {'valide':'1'},{'locked':'0'},
{'partner_owner_recid':user_recid} ,
filt_external_code, filt_title, filt_internal_url]},
{ 'indexed':0, 'indexed_desc':0,
'indexed_obj':0, 'indexed_title':0, }
).sort([("_id", pymongo.DESCENDING), ]):
#print(" #### retVal = ", retVal)
if ("title" not in retVal.keys()):
retVal['title'] = ""
if ("domain" not in retVal.keys()):
retVal['domain'] = ""
if ("metier" not in retVal.keys()):
retVal['metier'] = ""
if ("version" not in retVal.keys()):
retVal['version'] = ""
if ("categorie" not in retVal.keys()):
retVal['categorie'] = ""
if ("duration" not in retVal.keys()):
retVal['duration'] = ""
if ("duration_unit" not in retVal.keys()):
retVal['duration_unit'] = ""
if ("pourqui" not in retVal.keys()):
retVal['pourqui'] = ""
if ("presentiel" not in retVal.keys()):
retVal['presentiel'] = {'presentiel':'0', 'distantiel':'0'}
if ("price" not in retVal.keys()):
retVal['price'] = "0"
if ("description" not in retVal.keys()):
retVal['description'] = ""
if ("published" not in retVal.keys()):
retVal['published'] = "0"
if ("lms_class_code" not in retVal.keys()):
retVal['lms_class_code'] = "0"
# Recuperation des données du formateur
formateur_nom_prenom = ""
# Si il y a un code formateur_id, alors on va recuperer les nom et prenom du formation
if ("formateur_id" in retVal.keys() and retVal['formateur_id']):
formateur_data = MYSY_GV.dbname['ressource_humaine'].find_one(
{'_id': ObjectId(str(retVal['formateur_id'])),
'valide': '1',
'locked': '0',
'partner_recid': str(my_partner['recid'])
})
if (formateur_data and "nom" in formateur_data.keys() and "prenom" in formateur_data.keys()):
formateur_nom_prenom = str(formateur_data['nom']) + " " + str(formateur_data['prenom'])
retVal['formateur_nom_prenom'] = formateur_nom_prenom
# Recuperation des données du niveau de class
class_level_description = ""
# Si il y a un code class_level, alors on va recuperer la description
if ("class_level" in retVal.keys() and retVal['class_level']):
class_level_data = MYSY_GV.dbname['class_niveau_formation'].find_one(
{'code': str(retVal['class_level']),
'valide': '1',
'locked': '0',
'partner_owner_recid': 'default'
})
if (class_level_data and "description" in class_level_data.keys()):
class_level_description = str(class_level_data['description'])
retVal['class_level_description'] = class_level_description
# Recuperer le nombre de session pour cette formation
nb_session_formation_count = MYSY_GV.dbname['session_formation'].count_documents({'class_internal_url':str(retVal['internal_url']),
'valide':'1',
'partner_owner_recid':str(my_partner['recid'])})
retVal['nb_session_formation'] = nb_session_formation_count
user = retVal
user['id'] = str(val_tmp)
'''
Pour des facilité d'affichage coté front
on va reformater le champ "zone_diffusion" de sorte à le renvoyer
sous la forme "code_pays-ville"
'''
i = 0
tmp_zone_diffusion = ""
if( "zone_diffusion" in user.keys()):
if( user['zone_diffusion'] and user['zone_diffusion']["city"]):
for tmp_val in user['zone_diffusion']["city"]:
tmp_zone_diffusion = tmp_zone_diffusion + str(user['zone_diffusion']["country"][i])+"-"+str(user['zone_diffusion']["city"][i])+";"
i = i+1
user['zone_diffusion_str'] = str(tmp_zone_diffusion[:-1])
if ("duration" in user.keys() and "duration_unit" in user.keys() and str(user['duration_unit']) == "jour" ):
duration_in_hour = mycommon.tryFloat(user['duration']) * mycommon.tryFloat(nb_hour_per_day)
if (duration_in_hour):
user['duration_in_hour'] = str(duration_in_hour)
else:
user['duration_in_hour'] = ""
user['currecny'] = currency
RetObject.append(JSONEncoder().encode(user))
val_tmp = val_tmp + 1
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 formation"
"""
Cette fonction recherche des formations avec une recherche large (like %value%)
"""
def find_partner_class_like(diction):
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 = ['internal_url', 'token', 'title', 'valide', 'locked', 'external_code']
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]) + " - get_partner_class : Le champ '" + val + "' n'existe pas, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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, " Impossible de récupérer la formation"
# recuperation des paramettre
mydata = {}
my_external_code = ""
my_token = ""
my_internal_url = ""
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
if ("external_code" in diction.keys()):
if diction['external_code']:
my_external_code = diction['external_code']
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
'''
Gestion des filters.
'''
internal_url_crit = {}
if ("internal_url" in diction.keys()):
if diction['internal_url']:
internal_url_crit['internal_url'] = diction['internal_url']
external_code_crit = {}
if ("external_code" in diction.keys()):
if diction['external_code']:
external_code_crit['external_code'] = diction['external_code']
title_crit = {}
if ("title" in diction.keys()):
if diction['title']:
title_crit['title'] = diction['title']
coll_name = MYSY_GV.dbname['myclass']
# verifier que le token et l'email sont ok
coll_token = MYSY_GV.dbname['user_token']
# Verification de la validité du token dans le cas des user en mode connecté
'''
/!\ Important : le token ne doit jamais etre vide car cette fonction a pour objectif
de retourner les formations edité par un partenaire.
Il dont obligatoirement est en mode connecté
'''
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
user_recid = "None"
# Verification de la validité du token/mail dans le cas des user en mode connecté
if (len(str(my_token)) > 0):
retval = mycommon.check_partner_token_validity("", my_token)
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - La session de connexion n'est pas valide")
return False, " Impossible de récupérer la formation"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(my_token)
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le token de l'utilisateur")
return False, " Impossible de récupérer la formation"
if (len(str(my_token)) <= 0):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token est vide")
return False, " Impossible de récupérer la formation"
RetObject = []
filt_external_code = {}
if ("external_code" in diction.keys()):
filt_external_code = {'external_code':{'$regex': str(diction['external_code']), "$options": "i"}}
# print(" GRRRRRRRRRRRRR "+str(filt_external_code))
filt_title = {}
if ("title" in diction.keys()):
filt_title = {'title': {'$regex': str(diction['title']), "$options": "i"}}
filt_internal_url = {}
if ("internal_url" in diction.keys()):
filt_internal_url = {'internal_url': {'$regex': str(diction['internal_url']), "$options": "i"}}
# print(" filt_internal_url GRRRRRRRRRRRRRRRRRRRRrr "+str(filt_internal_url))
find_partner_class_like_local_qry = {"$and": [{'valide': '1'}, {'locked': '0'},
{'partner_owner_recid': user_recid},
filt_external_code, filt_title, filt_internal_url]}
#print(" ##### find_partner_class_like_local_qry = ", find_partner_class_like_local_qry)
"""
Recuperation du nombre d'heure par jour depuis la confif du partner
"""
nb_hour_per_day = mycommon.Get_Partner_Hour_Per_Day(str(my_partner['recid']))
if( nb_hour_per_day is False):
nb_hour_per_day = "7"
currency = mycommon.Get_Partner_Currency(str(my_partner['recid']))
if (currency is False):
currency = ""
val_tmp = 1
for retVal in coll_name.find({"$and": [{'valide': '1'}, {'locked': '0'},
{'partner_owner_recid': user_recid},
filt_external_code, filt_title, filt_internal_url]},
{'programme':0, 'objectif': 0, 'indexed': 0, 'indexed_desc': 0,
'indexed_obj': 0, 'indexed_title': 0, }
).sort([("_id", pymongo.DESCENDING), ]):
#mycommon.myprint(str(retVal))
user = retVal
if ("title" not in retVal.keys()):
retVal['title'] = ""
if ("domain" not in retVal.keys()):
retVal['domain'] = ""
if ("duration" not in retVal.keys()):
retVal['duration'] = ""
if ("duration_unit" not in retVal.keys()):
retVal['duration_unit'] = ""
if ("pourqui" not in retVal.keys()):
retVal['pourqui'] = ""
if ("presentiel" not in retVal.keys()):
retVal['presentiel'] = {'presentiel':'0', 'distantiel':'0'}
if ("metier" not in retVal.keys()):
retVal['metier'] = ""
if ("version" not in retVal.keys()):
retVal['version'] = ""
if ("categorie" not in retVal.keys()):
retVal['categorie'] = ""
if ("price" not in retVal.keys()):
retVal['price'] = "0"
if ("description" not in retVal.keys()):
retVal['description'] = ""
if ("published" not in retVal.keys()):
retVal['published'] = "0"
if ("lms_class_code" not in retVal.keys()):
retVal['lms_class_code'] = "0"
# Recuperer le nombre de session pour cette formation
nb_session_formation_count = MYSY_GV.dbname['session_formation'].count_documents(
{'class_internal_url': str(retVal['internal_url']),
'valide': '1',
'partner_owner_recid': str(my_partner['recid'])})
retVal['nb_session_formation'] = nb_session_formation_count
user['id'] = str(val_tmp)
'''
Pour des facilité d'affichage coté front
on va reformater le champ "zone_diffusion" de sorte à le renvoyer
sous la forme "code_pays-ville"
'''
i = 0
tmp_zone_diffusion = ""
if ("zone_diffusion" in user.keys()):
if (user['zone_diffusion'] and user['zone_diffusion']["city"]):
for tmp_val in user['zone_diffusion']["city"]:
tmp_zone_diffusion = tmp_zone_diffusion + str(user['zone_diffusion']["country"][i]) + "-" + str(
user['zone_diffusion']["city"][i]) + ";"
i = i + 1
user['zone_diffusion_str'] = str(tmp_zone_diffusion[:-1])
if ("duration" in user.keys() and "duration_unit" in user.keys() and str(user['duration_unit']) == "jour" ):
duration_in_hour = mycommon.tryFloat(user['duration']) * mycommon.tryFloat(nb_hour_per_day)
if(duration_in_hour ):
user['duration_in_hour'] = str(duration_in_hour)
else:
user['duration_in_hour'] = ""
user['currecny'] = currency
RetObject.append(JSONEncoder().encode(user))
val_tmp = val_tmp + 1
#print(" #### return find_partner_class_like = : ", str(RetObject))
return True, RetObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la formation"
"""
Cette fonction retourne la liste des formations
d'un parenaire mais seulement les champs :
- _id
- external_code,
- internal_code
- internal_url
"""
def Get_Partner_All_Class_Few_Fields(diction):
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]) + " - get_partner_class : Le champ '" + val + "' n'existe pas, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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, " Impossible de récupérer la formation"
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
RetObject = []
val_tmp = 0
for retVal in MYSY_GV.dbname['myclass'].find(
{'partner_owner_recid': my_partner['recid'],
'valide':'1',
'locked':'0'},
{'_id': 1, 'external_code': 1, 'internal_code': 1, 'internal_url': 1, }
).sort([("_id", pymongo.DESCENDING), ]):
# mycommon.myprint(str(retVal))
user = retVal
user['id'] = str(val_tmp)
RetObject.append(JSONEncoder().encode(user))
val_tmp = val_tmp + 1
# print(" #### return find_partner_class_like = : ", str(RetObject))
return True, RetObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la liste des formations"
"""
Cette fonction retrourne
- le code externe,
- internal_url
des formations d'un partner
"""
def get_partner_class_external_code(diction):
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 = ['internal_url', 'token', 'title', 'valide', 'locked', 'external_code']
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]) + " - get_partner_class : Le champ '" + val + "' n'existe pas, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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, " Impossible de récupérer la formation"
# recuperation des paramettre
mydata = {}
my_external_code = ""
my_token = ""
my_internal_url = ""
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
if ("external_code" in diction.keys()):
if diction['external_code']:
my_external_code = diction['external_code']
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
'''
Gestion des filters.
'''
internal_url_crit = {}
if ("internal_url" in diction.keys()):
if diction['internal_url']:
internal_url_crit['internal_url'] = diction['internal_url']
external_code_crit = {}
if ("external_code" in diction.keys()):
if diction['external_code']:
external_code_crit['external_code'] = diction['external_code']
title_crit = {}
if ("title" in diction.keys()):
if diction['title']:
title_crit['title'] = diction['title']
coll_name = MYSY_GV.dbname['myclass']
# verifier que le token et l'email sont ok
coll_token = MYSY_GV.dbname['user_token']
# Verification de la validité du token dans le cas des user en mode connecté
'''
/!\ Important : le token ne doit jamais etre vide car cette fonction a pour objectif
de retourner les formations edité par un partenaire.
Il dont obligatoirement est en mode connecté
'''
user_recid = "None"
# Verification de la validité du token/mail dans le cas des user en mode connecté
if (len(str(my_token)) > 0):
retval = mycommon.check_partner_token_validity("", my_token)
if retval is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - La session de connexion n'est pas valide")
return False, " Impossible de récupérer la formation"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(my_token)
if user_recid is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " - Impossible de récupérer le token de l'utilisateur")
return False, " Impossible de récupérer la formation"
if (len(str(my_token)) <= 0):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le token est vide")
return False, " Impossible de récupérer la formation"
RetObject = []
filt_external_code = {}
if ("external_code" in diction.keys()):
filt_external_code = {'external_code': str(diction['external_code']), "$options": "i"}
# print(" GRRRRRRRRRRRRR "+str(filt_external_code))
filt_title = {}
if ("title" in diction.keys()):
filt_title = {'title': {'$regex': str(diction['title']), "$options": "i"}}
filt_internal_url = {}
if ("internal_url" in diction.keys()):
filt_internal_url = {'internal_url': {'$regex': str(diction['internal_url']), "$options": "i"}}
# print(" filt_internal_url GRRRRRRRRRRRRRRRRRRRRrr "+str(filt_internal_url))
print(
" ATTTTENNTION : GESTION DU CAS OU LA PERSONNE QUI CHERCHE LE COURS EST UN UTILISATEUR : PB avec : partner_owner_recid ")
print(" #### avant requete get partner_owner_recid =" + str(user_recid) +
" filt_external_code = " + str(filt_external_code) +
" filt_internal_url = " + str(filt_internal_url) +
" filt_title = " + str(filt_title))
val_tmp = 1
for retVal in coll_name.find_one({"$and": [{'valide': '1'}, {'locked': '0'},
{'partner_owner_recid': user_recid},
filt_external_code, filt_title, filt_internal_url]},
{'external_code':1, 'internal_url':1},
).sort([("external_code",pymongo.ASCENDING),]).sort([("_id", pymongo.DESCENDING), ]):
# mycommon.myprint(str(retVal))
user = retVal
user['id'] = str(val_tmp)
'''
Pour des facilité d'affichage coté front
on va reformater le champ "zone_diffusion" de sorte à le renvoyer
sous la forme "code_pays-ville"
'''
i = 0
tmp_zone_diffusion = ""
if ("zone_diffusion" in user.keys()):
if (user['zone_diffusion'] and user['zone_diffusion']["city"]):
for tmp_val in user['zone_diffusion']["city"]:
tmp_zone_diffusion = tmp_zone_diffusion + str(user['zone_diffusion']["country"][i]) + "-" + str(
user['zone_diffusion']["city"][i]) + ";"
i = i + 1
user['zone_diffusion_str'] = str(tmp_zone_diffusion[:-1])
RetObject.append(JSONEncoder().encode(user))
val_tmp = val_tmp + 1
# print(str(RetObject))
return True, RetObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la formation"
def get_class_global_search(search_string):
try:
mycommon.myprint(" search_string", search_string)
coll_name = MYSY_GV.dbname['myclass']
val = re.compile(r".*"+search_string+".*")
my_regex = "/.*"+search_string+".*/"
insertObject = []
for x in coll_name.find({'myindex': { '$regex': re.compile(r".*"+search_string+".*") }}):
mycommon.myprint(x)
user = x
insertObject.append(JSONEncoder().encode(user))
#mycommon.myprint(" insertObject = ", insertObject)
return insertObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False
def get_all_class_by_attribut(attribut, value):
try:
mycommon.myprint(" attribut", attribut, " value = ",value)
coll_name = MYSY_GV.dbname['myclass']
insertObject = []
for x in coll_name.find({attribut: value}, {"_id": 0}):
mycommon.myprint(x)
user = x
insertObject.append(JSONEncoder().encode(user))
#mycommon.myprint(" insertObject = ", insertObject)
return insertObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False
'''
Cette fontion import un fichier excel de formation
'''
def add_class_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]) + " - Creation formation : Le champ '" + val + "' n'existe pas, Creation formation annulée")
return False, " Le champ '" + val + "' n'existe pas, Creation formation annulée"
'''
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, " Les informations de connexion sont invalides"
# Verifier la validité du token
my_token = ""
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
retval = mycommon.check_partner_token_validity("", my_token)
if retval is False:
return "Err_Connexion", " La session de connexion n'est pas valide"
status, saved_file = mycommon.Upload_Save_CSV_File(file, Folder)
if (status == False):
return False, "Impossible d'inserer les formations en masse, le nom du fichier est incorrect "
#" Lecture du fichier "
#print(" Lecture du fichier : "+saved_file)
nb_line = 0
""""
update du 31/08/23 : Controle de l'integrité du fichier avant import
"""
local_controle_status, local_controle_message = Controle_add_class_mass(saved_file, Folder, diction)
if (local_controle_status is False):
return local_controle_status, local_controle_message
print(" #### local_controle_message = ", local_controle_message)
df = pd.read_csv(saved_file, encoding='utf8', on_bad_lines='skip', sep=';', encoding_errors='ignore')
df = df.fillna('')
# Dictionnaire des champs utilisables
'''
# Verification que les noms des colonne sont bien corrects"
'''
field_list = ['external_code', 'titre', 'description', 'formateur', 'institut_formation',
'distantiel', 'presentiel', 'prix', 'domaine', 'url','duree', 'duree_unite', 'plus_produit',
'mots_cle', 'zone_diffusion', 'metier', 'publie', 'img_url',
'objectif', 'programme', 'prerequis', 'formateur', 'note', 'cpf', 'certif',
'class_inscription_url', 'pourqui', 'support', 'img_banner_detail_class', 'formateur_email',
'methode_pedagogique', 'condition_handicape', 'suivi_eval', 'version', 'categorie']
total_rows = len(df)
#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. La Colonne '" + val + "' n'est pas acceptée"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(diction['token'])
if user_recid is False:
mycommon.myprint(
str(inspect.stack()[0][3]) + " - Impossible de récupérer le token du partenaire")
return False, " Les informations d'identification sont incorrectes"
x = range(0, total_rows)
ignored_line = ""
nb_inserted_line = 0
for n in x:
mydata = {}
if ("external_code" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'external_code' pour la formation à la ligne "+str(n+2))
return False, " Absence de 'external_code' pour la formation à la ligne "+str(n+2)
if ("titre" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'titre' pour la formation à la ligne "+str(n+2))
return False, " Absence de 'titre' pour la formation à la ligne "+str(n+2)
if ("domaine" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'domaine' pour la formation à la ligne "+str(n+2))
return False, " Absence de 'domaine' pour la formation à la ligne "+str(n+2)
if ("description" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'description' pour la formation à la ligne "+str(n+2))
return False, " Absence de 'description' pour la formation à la ligne "+str(n+2)
nb_inserted_line = nb_inserted_line + 1
# Si une ligne n'a aucune information obligatoire, alors on ignore la ligne
if (str(df['external_code'].values[n]) == "nan" or str(df['titre'].values[n]) == "nan"):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - La ligne " + str(n + 2)+" a été ignorée")
ignored_line = str(n + 2)+" , "+str(ignored_line)
nb_inserted_line = nb_inserted_line - 1
continue
mydata['external_code'] = str(df['external_code'].values[n]).strip()
mydata['title'] = str(df['titre'].values[n]).strip()
tmp_desc = str(df['description'].values[n]).strip()
tmp_desc = mycommon.format_MySy_Text_Tag(tmp_desc)
mydata['description'] = tmp_desc
"""
Recuperer l'_id du domaine
"""
domaine_data = MYSY_GV.dbname['class_domaine'].find_one(
{'code': str(df['domaine'].values[n]).strip(),
'valide': '1',
'locked': '0'})
if (domaine_data is None):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le domaine de formation n'est pas valide ")
return False, " Le domaine de formation n'est pas valide "
mydata['domaine'] = str(domaine_data['_id'])
institut_formation = ""
if ("institut_formation" in df.keys()):
if (str(df['institut_formation'].values[n])):
institut_formation = str(df['institut_formation'].values[n]).strip()
mydata['institut_formation'] = institut_formation
version = ""
if ("version" in df.keys()):
if (str(df['version'].values[n])):
version = str(df['version'].values[n]).strip()
mydata['version'] = version
categorie_id = ""
if ("categorie" in df.keys()):
if (str(df['categorie'].values[n])):
categorie = str(df['categorie'].values[n]).strip()
"""
Recuperer l'_id de la catégorie
"""
categorie_data = MYSY_GV.dbname['class_categorie'].find_one(
{'code': str(df['domaine'].values[n]).strip(),
'valide': '1',
'locked': '0'})
if (categorie_data is None):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La catégorie de formation n'est pas valide ")
return False, " La catégorie de formation n'est pas valide "
categorie_id = str(categorie_data['_id'])
mydata['categorie'] = categorie_id
#mydata['duration'] = float(str(df['duree'].values[n]))
url = ""
if ("url" in df.keys()):
if (str(df['url'].values[n])):
url = str(df['url'].values[n]).strip()
mydata['url'] = url
duration = "0"
if ("duree" in df.keys()):
if (str(df['duree'].values[n])):
duration = str(df['duree'].values[n]).strip()
mydata['duration'] = duration
plus_produit = ""
if ("plus_produit" in df.keys()):
if (str(df['plus_produit'].values[n])):
plus_produit = str(df['plus_produit'].values[n]).strip()
plus_produit = mycommon.format_MySy_Text_Tag(plus_produit)
mydata['plus_produit'] = plus_produit
presentiel = "0"
if ("presentiel" in df.keys()):
if (str(df['presentiel'].values[n])):
presentiel = str(df['presentiel'].values[n]).strip()
mydata['presentiel'] = presentiel
distantiel = "0"
if ("distantiel" in df.keys()):
if (str(df['distantiel'].values[n])):
distantiel = str(df['distantiel'].values[n]).strip()
mydata['distantiel'] = distantiel
price = "0"
if ("prix" in df.keys()):
if (str(df['prix'].values[n])):
price = str(df['prix'].values[n]).strip()
mydata['price'] = price
metier_id = ""
if ("metier" in df.keys()):
if (str(df['metier'].values[n])):
metier = str(df['metier'].values[n]).strip()
"""
Recuperer l'_id de la catégorie
"""
metier_data = MYSY_GV.dbname['class_metier'].find_one(
{'code': str(df['metier'].values[n]).strip(),
'valide': '1',
'locked': '0'})
if (metier_data is None):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le metier de formation n'est pas valide ")
return False, " Le métier de formation n'est pas valide "
metier_id = str(metier_data['_id'])
mydata['metier'] = metier_id
published = "1"
if ("published" in df.keys()):
if (str(df['published'].values[n])):
published = str(df['published'].values[n]).strip()
mydata['published'] = published
mycpf = "0"
if ("cpf" in df.keys()):
if (str(df['cpf'].values[n])):
mycpf = str(df['cpf'].values[n]).strip()
mydata['cpf'] = mycpf
class_inscription_url = ""
if ("class_inscription_url" in df.keys()):
if (str(df['class_inscription_url'].values[n])):
class_inscription_url = str(df['class_inscription_url'].values[n]).strip()
mydata['class_inscription_url'] = class_inscription_url
certif = "0"
if ("certif" in df.keys()):
if (str(df['certif'].values[n])):
certif = str(df['certif'].values[n]).strip()
mydata['certif'] = certif
objectif = ""
if ("objectif" in df.keys()):
if (str(df['objectif'].values[n])):
objectif = str(df['objectif'].values[n]).strip()
objectif = mycommon.format_MySy_Text_Tag(objectif)
mydata['objectif'] = objectif
note = ""
if ("note" in df.keys()):
if (str(df['note'].values[n])):
note = str(df['note'].values[n]).strip()
mydata['note'] = note
programme = ""
if ("programme" in df.keys()):
if (str(df['programme'].values[n])):
programme = str(df['programme'].values[n]).strip()
programme = mycommon.format_MySy_Text_Tag(programme)
mydata['programme'] = programme
methode_pedagogique = ""
if ("methode_pedagogique" in df.keys()):
if (str(df['methode_pedagogique'].values[n])):
methode_pedagogique = str(df['methode_pedagogique'].values[n]).strip()
methode_pedagogique = mycommon.format_MySy_Text_Tag(methode_pedagogique)
mydata['methode_pedagogique'] = methode_pedagogique
condition_handicape = ""
if ("condition_handicape" in df.keys()):
if (str(df['condition_handicape'].values[n])):
condition_handicape = str(df['condition_handicape'].values[n]).strip()
condition_handicape = mycommon.format_MySy_Text_Tag(condition_handicape)
mydata['condition_handicape'] = condition_handicape
suivi_eval = ""
if ("suivi_eval" in df.keys()):
if (str(df['suivi_eval'].values[n])):
suivi_eval = str(df['suivi_eval'].values[n]).strip()
suivi_eval = mycommon.format_MySy_Text_Tag(suivi_eval)
mydata['suivi_eval'] = suivi_eval
prerequis = ""
if ("prerequis" in df.keys()):
if (str(df['prerequis'].values[n])):
prerequis = str(df['prerequis'].values[n]).strip()
prerequis = mycommon.format_MySy_Text_Tag(prerequis)
mydata['prerequis'] = prerequis
pourqui = ""
if ("pourqui" in df.keys()):
if (str(df['pourqui'].values[n])):
pourqui = str(df['pourqui'].values[n]).strip()
pourqui = mycommon.format_MySy_Text_Tag(pourqui)
mydata['pourqui'] = pourqui
# Verifier que l'adresse email du formateur est valide
formateur_email = ""
formateur_id = ""
if ("formateur_email" in df.keys()):
if (str(df['formateur_email'].values[n]) and str(df['formateur_email'].values[n]).strip() != ""):
formateur_email = str(df['formateur_email'].values[n]).strip()
if (mycommon.isEmailValide(formateur_email) is False):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide.")
return False, " L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide."
is_formateur_email_ok = MYSY_GV.dbname['ressource_humaine'].count_documents({'email': formateur_email,
'valide': '1',
'locked': '0',
'partner_recid': str(
user_recid)})
if (is_formateur_email_ok <= 0):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide (2).")
return False, " L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide (2)."
formateur_data = MYSY_GV.dbname['ressource_humaine'].find_one({'email': formateur_email,
'valide': '1',
'locked': '0',
'partner_recid': str(
user_recid)})
formateur_id = str(formateur_data['_id'])
mydata['formateur_id'] = formateur_id
support = ""
if ("support" in df.keys()):
if (str(df['support'].values[n])):
support = str(df['support'].values[n]).strip()
mydata['support'] = support
img_banner_detail_class = ""
if ("img_banner_detail_class" in df.keys()):
if (str(df['img_banner_detail_class'].values[n])):
img_banner_detail_class = str(df['img_banner_detail_class'].values[n]).strip()
mydata['img_banner_detail_class'] = img_banner_detail_class
if ("duree_unite" in df.keys()):
if (str(df['duree_unite'].values[n]).strip() not in MYSY_GV.CLASS_DURATION_UNIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'duration_unit' contient une valeur erronées."
" Les valeurs acceptées sont " + str(
MYSY_GV.CLASS_DURATION_UNIT) + " ")
return False, " : le champ 'duration_unit' contient une valeur erronées." \
" Les valeurs acceptées sont " + str(MYSY_GV.CLASS_DURATION_UNIT)
mydata['duration_unit'] = str(df['duree_unite'].values[n]).strip()
else:
mydata['duration_unit'] = "jour"
'''
Verification de l'image
'''
if ("img_url" in df.keys()):
mydata['img_url'] = str(df['img_url'].values[n]).strip()
if (str(df['img_url'].values[n]) == 'nan'):
mydata['img_url'] = ""
#print(" ### mydata['img_url'] = '"+str(mydata['img_url'])+"' ")
if( len(str(mydata['img_url'])) > 0 ):
# Verifier si l'image existe
status_tmp, img = mycommon.TryUrlImage(str(mydata['img_url']))
if (status_tmp is False):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : l'url de l'image de la formation " + str(
mydata['external_code']) + " est incorrecte ")
return False, " l'url de l'image de la formation " + str(mydata['external_code']) + " est incorrecte "
'''
Verification du nombre de mots clée : limite MYSY_GV.MAX_KEYWORD (3)
'''
mots_cle = ""
if ("mots_cle" in df.keys()):
if (str(df['mots_cle'].values[n])):
mots_cle = str(df['mots_cle'].values[n]).strip()
if( mots_cle.endswith(';')):
mots_cle = mots_cle[:-1]
nb_keyword = mots_cle.split(";")
if(len(str(mots_cle).strip()) > 0 and len(nb_keyword) > 0 ):
for local_nb_keyword in nb_keyword:
if(len(str(local_nb_keyword).strip()) <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation " + str(
mydata['external_code']) + " contient des valeur vide (2)")
return False, " La formation " + str(mydata['external_code']) + " contient des valeurs vides"
if( len(nb_keyword) > MYSY_GV.MAX_KEYWORD ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation "+str(mydata['external_code'])+" a plus de "+ str(MYSY_GV.MAX_KEYWORD)+" mots clés")
return False, " La formation "+str(mydata['external_code'])+" a plus de "+ str(MYSY_GV.MAX_KEYWORD)+" mots clés"
mydata['mots_cle'] = mots_cle
'''
Traitement de la zone de diffusion
'''
zone_diffusion = ""
if ("zone_diffusion" in df.keys()):
if(str(df['zone_diffusion'].values[n])):
zone_diffusion =str(df['zone_diffusion'].values[n]).strip()
mydata['zone_diffusion'] = zone_diffusion
'''
Traitement des date et lieu de la formation
date_lieu = ""
if ("date_lieu" in df.keys()):
if(str(df['date_lieu'].values[n])):
date_lieu =str(df['date_lieu'].values[n]).strip()
mydata['date_lieu'] = date_lieu
'''
if ("token" in diction.keys()):
if diction['token']:
mydata['token'] = diction['token']
clean_dict = {k: mydata[k] for k in mydata if ( str(mydata[k]) != "nan") }
status, retval, class_id = add_class(clean_dict)
if( status is False ):
return status, retval
message_ignored_line = ""
if( ignored_line ):
message_ignored_line = " ATTENTION - Les lignes [" + str(ignored_line) + "] ont été ignorées. car les toutes informations obligatoires ne sont pas fournies"
return True, str(nb_inserted_line)+" formation(s) insérée(s) / mise(s) à jour. "+str(message_ignored_line)
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'inserer les formations en masse -" + str(e)
"""
Fonction qui permet de controler le fichier a importer avant import
"""
def Controle_add_class_mass(saved_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]) + " - Creation formation : Le champ '" + val + "' n'existe pas, Creation formation annulée")
return False, " Le champ '" + val + "' n'existe pas, Creation formation annulée"
'''
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"
# " 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=';', encoding_errors='ignore')
df = df.fillna('')
# Dictionnaire des champs utilisables
'''
# Verification que les noms des colonne sont bien corrects"
'''
field_list = ['external_code', 'titre', 'description', 'formateur', 'institut_formation',
'distantiel', 'presentiel', 'prix', 'domaine', 'url', 'duree', 'duree_unite', 'plus_produit',
'mots_cle', 'zone_diffusion', 'metier', 'publie', 'img_url',
'objectif', 'programme', 'prerequis', 'formateur', 'note', 'cpf', 'certif',
'class_inscription_url', 'pourqui', 'support', 'img_banner_detail_class', 'formateur_email' ,'methode_pedagogique',
'condition_handicape', 'suivi_eval', 'version', 'categorie']
total_rows = len(df)
# 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. La Colonne '" + val + "' n'est pas acceptée"
# Recuperation du recid de l'utilisateur
user_recid = mycommon.get_parnter_recid_from_token(diction['token'])
if user_recid is False:
mycommon.myprint(
str(inspect.stack()[0][3]) + " - Impossible de récupérer le token du partenaire")
return False, " Les informations d'identification sont incorrectes"
x = range(0, total_rows)
ignored_line = ""
nb_inserted_line = 0
for n in x:
mydata = {}
if ("external_code" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'external_code' pour la formation à la ligne " + str(n + 2))
return False, " Absence de 'external_code' pour la formation à la ligne " + str(n + 2)
if ("titre" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'titre' pour la formation à la ligne " + str(n + 2))
return False, " Absence de 'titre' pour la formation à la ligne " + str(n + 2)
if ("domaine" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'domaine' pour la formation à la ligne " + str(n + 2))
return False, " Absence de 'domaine' pour la formation à la ligne " + str(n + 2)
if ("description" not in df.keys()):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Absence de 'description' pour la formation à la ligne " + str(n + 2))
return False, " Absence de 'description' pour la formation à la ligne " + str(n + 2)
nb_inserted_line = nb_inserted_line + 1
# Si une ligne n'a aucune information obligatoire, alors on ignore la ligne
if (str(df['external_code'].values[n]) == "nan" or str(df['titre'].values[n]) == "nan"):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - La ligne " + str(n + 2) + " a été ignorée")
ignored_line = str(n + 2) + " , " + str(ignored_line)
nb_inserted_line = nb_inserted_line - 1
continue
mydata['external_code'] = str(df['external_code'].values[n]).strip()
mydata['title'] = str(df['titre'].values[n]).strip()
mydata['domaine'] = str(df['domaine'].values[n]).strip()
# Verifier que l'external code et le titre on bien des valeurs
if(len(str(mydata['external_code']).strip()) < 2):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - Le code externe '" + str(
mydata['external_code']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 2 caractères.")
return False, " - Le code externe '" + str(
mydata['external_code']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 2 caractères."
# Verifier que le titre a plus 5 caractères
if (len(str(mydata['title']).strip()) < 5):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - Le titre '" + str(
mydata['title']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 5 caractères.")
return False, " - Le titre '" + str(
mydata['title']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 5 caractères."
tmp_desc = str(df['description'].values[n]).strip()
tmp_desc = mycommon.format_MySy_Text_Tag(tmp_desc)
mydata['description'] = tmp_desc
# Verifier que la description a plus 5 caractères
if (len(str(mydata['description']).strip()) < 5):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - La description '" + str(
mydata['description']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 5 caractères.")
return False, " -La description '" + str(
mydata['description']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 5 caractères."
"""
Verifier que le domaine est bien dans la liste acceptée
"""
print(" domaine a tester = ", str(mydata['domaine']).strip())
count_domaine = MYSY_GV.dbname['class_domaine'].count_documents(
{'code': str(mydata['domaine']).strip(), 'valide': '1', 'locked': '0',
})
if (count_domaine <= 0):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - Le domaine '" + str(mydata['domaine']) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas autorisé. Verifier la liste des domaines autorisés")
return False, " - Le domaine '" + str(mydata['domaine']) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas autorisé. Verifier la liste des domaines autorisés"
formateur = ""
institut_formation = ""
if ("institut_formation" in df.keys()):
if (str(df['institut_formation'].values[n])):
institut_formation = str(df['institut_formation'].values[n]).strip()
mydata['institut_formation'] = institut_formation
version = ""
if ("version" in df.keys()):
if (str(df['version'].values[n])):
version = str(df['version'].values[n]).strip()
mydata['version'] = version
categorie = ""
if ("categorie" in df.keys()):
if (str(df['categorie'].values[n])):
categorie = str(df['categorie'].values[n]).strip()
count_categorie = MYSY_GV.dbname['class_categorie'].count_documents(
{'code': str(mydata['categorie']).strip(), 'valide': '1', 'locked': '0',
})
if (count_categorie <= 0):
mycommon.myprint(str(
inspect.stack()[0][
3]) + " - La catégorie '" + str(
mydata['categorie']) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas autorisée. Verifier la liste des catégories autorisés")
return False, " - La catégorie '" + str(
mydata['categorie']) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas autorisée. Verifier la liste des catégories autorisés"
mydata['categorie'] = categorie
# Verifier que l'adresse email du formateur est valide
formateur_email = ""
formateur_id = ""
if ("formateur_email" in df.keys()):
if (str(df['formateur_email'].values[n]) and str(df['formateur_email'].values[n]).strip() != ""):
formateur_email = str(df['formateur_email'].values[n]).strip()
if (mycommon.isEmailValide(formateur_email) is False):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide.")
return False, " L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide."
is_formateur_email_ok = MYSY_GV.dbname['ressource_humaine'].count_documents(
{'email': formateur_email,
'valide': '1',
'locked': '0',
'partner_recid': str(
user_recid)})
if (is_formateur_email_ok <= 0):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide (2).")
return False, " L'email du formateur '" + str(
formateur_email) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas valide (2)."
formateur_data = MYSY_GV.dbname['ressource_humaine'].find_one({'email': formateur_email,
'valide': '1',
'locked': '0',
'partner_recid': str(
user_recid)})
formateur_id = str(formateur_data['_id'])
mydata['formateur_id'] = formateur_id
# mydata['duration'] = float(str(df['duree'].values[n]))
url = ""
if ("url" in df.keys()):
if (str(df['url'].values[n])):
url = str(df['url'].values[n]).strip()
mydata['url'] = url
duration = "0"
if ("duree" in df.keys()):
if (str(df['duree'].values[n])):
duration = str(df['duree'].values[n]).strip()
mydata['duration'] = duration
plus_produit = ""
if ("plus_produit" in df.keys()):
if (str(df['plus_produit'].values[n])):
plus_produit = str(df['plus_produit'].values[n]).strip()
plus_produit = mycommon.format_MySy_Text_Tag(plus_produit)
mydata['plus_produit'] = plus_produit
presentiel = "0"
if ("presentiel" in df.keys()):
if (str(df['presentiel'].values[n])):
presentiel = str(df['presentiel'].values[n]).strip()
mydata['presentiel'] = presentiel
distantiel = "0"
if ("distantiel" in df.keys()):
if (str(df['distantiel'].values[n])):
distantiel = str(df['distantiel'].values[n]).strip()
mydata['distantiel'] = distantiel
price = "0"
if ("prix" in df.keys()):
if (str(df['prix'].values[n])):
price = str(df['prix'].values[n]).strip()
mydata['price'] = price
metier = ""
if ("metier" in df.keys()):
if (str(df['metier'].values[n])):
metier = str(df['metier'].values[n]).strip()
"""
Verifier que le metier est bien dans la liste acceptée
"""
count_metier = MYSY_GV.dbname['class_metier'].count_documents(
{'code': str(metier).strip(), 'valide': '1', 'locked': '0'})
if (count_metier <= 0):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - Le metier '" + str(
metier) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas autorisé. Verifier la liste des domaines autorisés")
return False, " - Le metier '" + str(metier) + "' pour la formation à la ligne " + str(
n + 2) + " n'est pas autorisé. Verifier la liste des domaines autorisés"
mydata['metier'] = metier
published = "1"
if ("published" in df.keys()):
if (str(df['published'].values[n])):
published = str(df['published'].values[n]).strip()
mydata['published'] = published
mycpf = "0"
if ("cpf" in df.keys()):
if (str(df['cpf'].values[n])):
mycpf = str(df['cpf'].values[n]).strip()
mydata['cpf'] = mycpf
class_inscription_url = ""
if ("class_inscription_url" in df.keys()):
if (str(df['class_inscription_url'].values[n])):
class_inscription_url = str(df['class_inscription_url'].values[n]).strip()
mydata['class_inscription_url'] = class_inscription_url
certif = "0"
if ("certif" in df.keys()):
if (str(df['certif'].values[n])):
certif = str(df['certif'].values[n]).strip()
mydata['certif'] = certif
objectif = ""
if ("objectif" in df.keys()):
if (str(df['objectif'].values[n])):
objectif = str(df['objectif'].values[n]).strip()
objectif = mycommon.format_MySy_Text_Tag(objectif)
mydata['objectif'] = objectif
# Verifier que l'objectif a plus 5 caractères
if (len(str(mydata['objectif']).strip()) < 5):
mycommon.myprint(str(
inspect.stack()[0][3]) + " - L'objectif '" + str(
mydata['objectif']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 5 caractères.")
return False, " - L'objectif '" + str(
mydata['objectif']) + "' pour la formation à la ligne " + str(
n + 2) + " doit avoir plus de 5 caractères."
note = ""
if ("note" in df.keys()):
if (str(df['note'].values[n])):
note = str(df['note'].values[n]).strip()
mydata['note'] = note
programme = ""
if ("programme" in df.keys()):
if (str(df['programme'].values[n])):
programme = str(df['programme'].values[n]).strip()
programme = mycommon.format_MySy_Text_Tag(programme)
mydata['programme'] = programme
prerequis = ""
if ("prerequis" in df.keys()):
if (str(df['prerequis'].values[n])):
prerequis = str(df['prerequis'].values[n]).strip()
prerequis = mycommon.format_MySy_Text_Tag(prerequis)
mydata['prerequis'] = prerequis
pourqui = ""
if ("pourqui" in df.keys()):
if (str(df['pourqui'].values[n])):
pourqui = str(df['pourqui'].values[n]).strip()
pourqui = mycommon.format_MySy_Text_Tag(pourqui)
mydata['pourqui'] = pourqui
support = ""
if ("support" in df.keys()):
if (str(df['support'].values[n])):
support = str(df['support'].values[n]).strip()
mydata['support'] = support
img_banner_detail_class = ""
if ("img_banner_detail_class" in df.keys()):
if (str(df['img_banner_detail_class'].values[n])):
img_banner_detail_class = str(df['img_banner_detail_class'].values[n]).strip()
mydata['img_banner_detail_class'] = img_banner_detail_class
if ("duree_unite" in df.keys()):
if (str(df['duree_unite'].values[n]).strip() not in MYSY_GV.CLASS_DURATION_UNIT):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : le champ 'duration_unit' contient une valeur erronées."
" Les valeurs acceptées sont " + str(
MYSY_GV.CLASS_DURATION_UNIT) + " ")
return False, " : le champ 'duration_unit' contient une valeur erronées." \
" Les valeurs acceptées sont " + str(MYSY_GV.CLASS_DURATION_UNIT)
mydata['duration_unit'] = str(df['duree_unite'].values[n]).strip()
else:
mydata['duration_unit'] = "jour"
'''
Verification de l'image
'''
if ("img_url" in df.keys()):
mydata['img_url'] = str(df['img_url'].values[n]).strip()
if (str(df['img_url'].values[n]) == 'nan'):
mydata['img_url'] = ""
# print(" ### mydata['img_url'] = '"+str(mydata['img_url'])+"' ")
if (len(str(mydata['img_url'])) > 0):
# Verifier si l'image existe
status_tmp, img = mycommon.TryUrlImage(str(mydata['img_url']))
if (status_tmp is False):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : l'url de l'image de la formation " + str(
mydata['external_code']) + " est incorrecte ")
return False, " l'url de l'image de la formation " + str(
mydata['external_code']) + " est incorrecte "
'''
Verification du nombre de mots clée : limite MYSY_GV.MAX_KEYWORD (3)
'''
mots_cle = ""
if ("mots_cle" in df.keys()):
if (str(df['mots_cle'].values[n])):
mots_cle = str(df['mots_cle'].values[n]).strip()
if (mots_cle.endswith(';')):
mots_cle = mots_cle[:-1]
nb_keyword = mots_cle.split(";")
if (len(str(mots_cle).strip()) > 0 and len(nb_keyword) > 0):
for local_nb_keyword in nb_keyword:
if (len(str(local_nb_keyword).strip()) <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation " + str(
mydata['external_code']) + " contient des valeur vide (2)")
return False, " La formation " + str(mydata['external_code']) + " contient des valeurs vides"
if (len(nb_keyword) > MYSY_GV.MAX_KEYWORD):
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La formation " + str(
mydata['external_code']) + " a plus de " + str(MYSY_GV.MAX_KEYWORD) + " mots clés")
return False, " La formation " + str(mydata['external_code']) + " a plus de " + str(
MYSY_GV.MAX_KEYWORD) + " mots clés"
mydata['mots_cle'] = mots_cle
'''
Traitement de la zone de diffusion
'''
zone_diffusion = ""
if ("zone_diffusion" in df.keys()):
if (str(df['zone_diffusion'].values[n])):
zone_diffusion = str(df['zone_diffusion'].values[n]).strip()
return True, str(nb_inserted_line) + " formation(s) controlée(s) "
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 à importer "
'''
Cette fonction retourne les formations par metier
- la thématique est defini par un nouveau champ appelé "metier"
'''
def get_class_by_metier(diction):
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 = ['metier', 'token','user_ip', 'user_country_code',
'user_country_name', 'user_city', 'user_postal', 'user_latitude', 'user_longitude', 'user_state']
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, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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', 'metier']
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 la formation"
# recuperation des paramettre
mydata = {}
my_metier = ""
my_token = ""
if ("metier" in diction.keys()):
if diction['metier']:
my_metier = str(diction['metier']).lower()
if ("token" in diction.keys()):
if diction['token']:
my_token = diction['token']
coll_name = MYSY_GV.dbname['myclass']
RetObject = []
for retVal in coll_name.find({'valide': '1', 'locked': '0', 'metier': str(my_metier), 'published':'1'},
{"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0,
"valide": 0, "locked": 0, "partner_owner_recid": 0, }
).sort([("display_rank", pymongo.DESCENDING), ("price", pymongo.ASCENDING), ("date_update", pymongo.DESCENDING), ]):
#print(" retval " + str(retVal))
if ("description" in retVal.keys()):
tmp_str = retVal['description']
no_html = mycommon.cleanhtml(retVal['description'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
retVal['description'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
if ("objectif" in retVal.keys()):
tmp_str = retVal['objectif']
no_html = mycommon.cleanhtml(retVal['objectif'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
retVal['objectif'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
if ("programme" in retVal.keys()):
tmp_str = retVal['programme']
no_html = mycommon.cleanhtml(retVal['programme'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
retVal['programme'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
if ("methode_pedagogique" in retVal.keys()):
tmp_str = retVal['methode_pedagogique']
no_html = mycommon.cleanhtml(retVal['methode_pedagogique'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
retVal['methode_pedagogique'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
if ("condition_handicape" in retVal.keys()):
tmp_str = retVal['condition_handicape']
no_html = mycommon.cleanhtml(retVal['condition_handicape'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
retVal['condition_handicape'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
if ("suivi_eval" in retVal.keys()):
tmp_str = retVal['suivi_eval']
no_html = mycommon.cleanhtml(retVal['suivi_eval'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
retVal['suivi_eval'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
if ("pedagogie" in retVal.keys()):
tmp_str = retVal['pedagogie']
no_html = mycommon.cleanhtml(retVal['pedagogie'])
if (len(no_html) > MYSY_GV.MAX_CARACT):
retVal['pedagogie'] = no_html[:MYSY_GV.MAX_CARACT] + " ..."
# mycommon.myprint(str(retVal))
user = retVal
RetObject.append(JSONEncoder().encode(user))
# print(" 22222 ")
retVal_for_stat = retVal
retVal_for_stat['search_by_metier'] = str(my_metier)
mycommon.InsertStatistic(retVal_for_stat, "summary", mydata)
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 les formations par metier"
"""
Cette fonction modifier le ranking des formations d'un partenaire en masse.
Par exemple, lorqu'il change d'abonnement et passe
du standard au gold, toutes ses formation prenne le ranking des golds.
/!\ : Si le compte utilisateur est un compte de demo, le display_ranking prendra
une valeur max de 50. ceci pour que ses formations soient visibles tout de suite.
"""
def UpdataPartnerRankingClass(diction):
try:
'''
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 = ['partnaire_recid', 'new_pack_name']
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 le rang des formations"
# Recuperation du rang associé au pack
new_ranking_value = ""
coll_pack = MYSY_GV.dbname["pack"]
tmp = coll_pack.count_documents({"code_pack":str(diction["new_pack_name"]).lower()})
if( tmp <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - le pack "+str(diction["new_pack_name"]).lower()+ " n'est pas paramettré corretement")
return False, "Impossible de mettre à jour le rang des formations"
ranking_tab = None
ranking_tab = coll_pack.find({"code_pack":str(diction["new_pack_name"]).lower()})
if( ranking_tab and ranking_tab[0] and ranking_tab[0]["ranking"] ):
new_ranking_value = str(ranking_tab[0]["ranking"])
else:
mycommon.myprint(
str(inspect.stack()[0][3]) + " - le pack " + str(
diction["new_pack_name"]) + " n'est pas paramettré corretement - V2")
return False, "Impossible de mettre à jour le rang des formations"
"""
Verification si le compte utilisateur est un compte de demo, ceci pour mettre
le display ranking aux max de 50
"""
coll_partner_account = MYSY_GV.dbname['partnair_account']
myquery = {"recid": str(diction['partnaire_recid']), "active": "1",
"demo_account": "1"}
#print(" myquery pr demo_account = "+str(myquery))
tmp = coll_partner_account.count_documents(myquery)
if (tmp > 0):
new_ranking_value = MYSY_GV.DEMO_RANKING_VALUE
#print(" myquery pr demo_account 222 = " + str(tmp))
coll_class = MYSY_GV.dbname['myclass']
now = datetime.now()
update_data = {"display_rank":str(new_ranking_value), "date_update":str(now)}
if( tmp > 0 ):
update_data['isalaune'] = "1"
ret_val = coll_class.update_many(
{"partner_owner_recid": str(diction['partnaire_recid']), "valide":"1"},
{"$set": update_data}, )
mycommon.myprint(
str(inspect.stack()[0][3]) + " - Le RANKING de "+str(ret_val.matched_count)+" ont été mise à jour avec la valeur "+str(update_data))
return True, " Mise à jour du display_rank OK"
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 rang des formations"
"""
Cette fonction retourne les X formations du meme organisme de formations
associé à une formation données : current_internal_code
limit : X
condition : internal_url != current_internal_code
partner_owner_recid = current_partner_owner_recid
"""
def get_associated_class_of_partnair(diction):
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 = ['internal_url', 'token', 'title', 'valide', 'locked', 'user_ip', 'user_country_code', 'user_country_name', 'user_city',
'user_postal', 'user_latitude', 'user_longitude', 'user_state']
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, Creation formation annulée")
return False, " Impossible de récupérer la formation"
'''
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 = ['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, " Impossible de récupérer la formation"
# recuperation des paramettre
mydata = {}
my_internal_url = ""
my_token = ""
if ("internal_url" in diction.keys()):
if diction['internal_url']:
my_internal_url = diction['internal_url']
coll_name = MYSY_GV.dbname['myclass']
# verifier que le token et l'email sont ok
coll_token = MYSY_GV.dbname['user_token']
# Verification de la validité du token dans le cas des user en mode connecté
'''
/!\ Important : si le token est vide, alors c'est une recherche faite en mode non-connecté.
on doit l'accepter.
le controle de la validé du token est faite que ce dernier n'est pas vide.
'''
partner_recid = "None"
# Recuperation du partner_owner_recid de la formation
query = {'internal_url':my_internal_url}
tmp = coll_name.count_documents(query)
if( tmp <= 0 ):
mycommon.myprint(str(inspect.stack()[0][3]) + " - La valeur : internal_url '" + my_internal_url + "' est KOO dans la myclass")
return False, " Impossible de récupérer la formation"
tmp_val = coll_name.find_one({'internal_url':my_internal_url},{'partner_owner_recid':1})
#print(str(tmp_val))
if( tmp_val and tmp_val['partner_owner_recid']):
partner_recid = tmp_val['partner_owner_recid']
else:
mycommon.myprint(str(inspect.stack()[0][
3]) + " - La valeur :tmp_val and tmp_val[0] and tmp_val[0]['partner_owner_recid'] est KOO dans la myclass")
return False, " Impossible de récupérer la formation"
RetObject = []
filt_external_code = {}
internal_url = ""
if ("internal_url" in diction.keys()):
filt_external_code = {'internal_url':str(diction['internal_url'])}
internal_url = str(diction['internal_url'])
#print(' ICICICIC '+str(filt_external_code))
filt_title = {}
if ("title" in diction.keys()):
filt_title = {'title': {'$regex': str(diction['title']), "$options": "i"}}
print(" #### avant requete get partner_owner_recid laa zz="+str(partner_recid)+
" internal_url = "+str(my_internal_url)+
" filt_title = "+str(filt_title))
for retVal in coll_name.find({'valide':'1','locked':'0','internal_url': { '$ne': internal_url },
'partner_owner_recid':partner_recid, 'published':'1'},
{"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0,
"valide": 0, "locked": 0, "partner_owner_recid": 0, }
).limit(MYSY_GV.LIMIT_ASSOCIATED_TRAINING):
if ("description" in retVal.keys()):
tmp_str = retVal['description']
no_html = mycommon.cleanhtml(retVal['description'])
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['description'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("objectif" in retVal.keys()):
tmp_str = retVal['objectif']
no_html = mycommon.cleanhtml(retVal['objectif'])
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['objectif'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("programme" in retVal.keys()):
tmp_str = retVal['programme']
no_html = mycommon.cleanhtml(retVal['programme'])
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['programme'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
if ("pedagogie" in retVal.keys()):
tmp_str = retVal['pedagogie']
no_html = mycommon.cleanhtml(retVal['pedagogie'])
if (len(no_html) > MYSY_GV.MAX_CARACT_DETAIL):
retVal['pedagogie'] = no_html[:MYSY_GV.MAX_CARACT_DETAIL] + " ..."
#mycommon.myprint(str(retVal))
user = retVal
RetObject.append(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 formation"
"""
Cette fonction est utilisée pour la demande d'information sur une formation.
Depuis le site, lorqu'un utilisateur souhaite se renseigner sur une formation.
c'est la fonction : "je me renseigne"
"""
def RenseignementClass(diction):
try:
field_list = ['nom', 'prenom', 'email', 'telephone', 'employeur',
'message', 'class_internal_url',
'raison_sociale', 'siret', 'email_requester', 'telephone_requester',
'nom_requester', 'prenom_requester', 'nb_person_info',
'prenom_requester', 'nom_requester', 'telephone_requester',
'email_requester', 'siret', 'raison_sociale', 'is_company', 'class_sales_price']
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"
field_list_obligatoire = ['is_company']
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 informations de la formation et du formation (adresse email)
"""
local_class_info = MYSY_GV.dbname['myclass'].find_one({'internal_url':str(diction['class_internal_url'])})
if( not local_class_info['partner_owner_recid'] ):
mycommon.myprint( str(inspect.stack()[0][3]) + " - Impossible de récupérer les informations de la formation ")
return False, " Impossible de récupérer les informations de la formation "
local_partner_info = MYSY_GV.dbname['partnair_account'].find_one({'recid': str(local_class_info['partner_owner_recid'])})
if (not local_partner_info['email']):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - Impossible de récupérer les informaton du formateur ")
return False, " Impossible de récupérer les informaton du formateur "
diction['class_title'] = local_class_info['title']
diction['email_partnair'] = local_partner_info['email']
diction['partner_owner_recid'] = local_class_info['partner_owner_recid']
"""
On insert le lead dans la collection : lead_website
Cela permettra par la suite de créer le devis si besoin
ou de relancer
"""
new_lead_data = diction
new_lead_data['valide'] = "1"
new_lead_data['locked'] = "0"
new_lead_data['date_update'] = str(datetime.now())
new_lead_data['update_by'] = "auto"
inserted_invoice_id = MYSY_GV.dbname['lead_website'].insert_one(new_lead_data).inserted_id
diction['lead_website_id'] = str(inserted_invoice_id)
#print(" #### diction demande info = "+str(diction))
if( "is_company" in diction.keys() and diction['is_company'] == "0"):
# Verifier les champ obligatoires
field_list_obligatoire = ['nom', 'prenom',
'telephone', 'email', 'class_internal_url', ]
for val in field_list_obligatoire :
if( val not in diction.keys() or len(str(diction[str(val)])) <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Les champs obligatoires ne sont pas renseignés ")
return False, " Les champs obligatoires ne sont pas renseignés "
# Verifier que l'adresse email est valide
if (mycommon.isEmailValide(str(diction['email']).strip()) is False):
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 "
email.EmailDemandeInfoClass(diction)
elif( "is_company" in diction.keys() and diction['is_company'] == "1"):
# Verifier les champ obligatoires
field_list_obligatoire = ['raison_sociale', 'siret',
'email_requester', 'telephone_requester', 'nom_requester',
'prenom_requester', 'nb_person_info', 'class_internal_url', 'class_sales_price']
for val in field_list_obligatoire:
if (val not in diction.keys() or len(str(diction[str(val)])) <= 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Les champs obligatoires ne sont pas renseignés ")
return False, " Les champs obligatoires ne sont pas renseignés "
# Verifier que l'adresse email est valide
if (mycommon.isEmailValide(str(diction['email_requester']).strip()) is False):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " L'adresse email " + str(diction['email_requester']) + " est invalide ")
return False, " L'adresse email " + str(diction['email_requester']) + " est invalide "
email.EmailDemandeInfoClass_For_Cpny_With_Quotation_Option(diction)
return True, " La demande d'information a bien été envoyée"
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'envoyer la demande d'information pour une formation"
"""
Cette fonction supprime definitivement une formation.
/!\ : Une formation n'est supprimable que si :
1 - Il n'y a aucune session à venir. toutes les sessions sont passée.
2 - Si il y a des sessions, alors impossible de la supprimer. Proposer plus tard la notion d'archivage
3 - Dans la suppression, aller supprimer les champs dans la collection "elaindex"
"""
def delete_Class(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'class_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', 'class_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']
# Verifier la validité du 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 qu'une seule formation sera supprimée
Myclass_Data_count = MYSY_GV.dbname['myclass'].count_documents({'_id': ObjectId(str(diction['class_id'])),
'partner_owner_recid': str(my_partner['recid'])})
if( Myclass_Data_count <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation est invalide ")
return False, " La formation est invalide ",
if( Myclass_Data_count > 1 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - L'identifiant fourni correspond à plusieurs formation. Suppression annulée ")
return False, " L'identifiant fourni correspond à plusieurs formation. Suppression annulée",
# Receprer le 'internal_url_"
Myclass_Data = MYSY_GV.dbname['myclass'].find_one({'_id':ObjectId(str(diction['class_id'])),
'partner_owner_recid':str(my_partner['recid'])})
if( Myclass_Data is None):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation est invalide ")
return False, " La formation est invalide ",
# Verifier qu'il n'y a pas de session associée à cette formation
existe_Session_count = MYSY_GV.dbname['session_formation'].count_documents({'class_internal_url':str(Myclass_Data['internal_url']),
'partner_owner_recid':str(my_partner['recid']),
'valide':'1'})
if( existe_Session_count > 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a "+str(existe_Session_count)+" session(s) valide(s). Suppression impossible")
return False, " La formation a "+str(existe_Session_count)+" session(s) valide(s). Suppression impossible"
delete_doc = MYSY_GV.dbname['myclass'].delete_many({'_id':ObjectId(str(diction['class_id'])),
'partner_owner_recid':str(my_partner['recid'])})
if( delete_doc.deleted_count > 0 ):
return True, " La formation a été correctement supprimée"
else:
# Une formation a été supprimer, maintenant il faut supprimer les champs associés dans la collection "elaindex"
qry_elaindex_to_delete = {"partner_owner_recid":str(my_partner['recid']), "id_formation":str(Myclass_Data['external_code'])}
MYSY_GV.dbname['elaindex'].delete_many(qry_elaindex_to_delete)
return True, " Aucune formation supprimée"
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 la formation "
"""
Fonction de suppression des formations en masse, si les conditions sont reunies
"""
def delete_list_Class(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'list_class_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', 'list_class_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']
# Verifier la validité du 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_class_id = []
if ("list_class_id" in diction.keys()):
if diction['list_class_id']:
list_class_id = str(diction['list_class_id']).replace(",", ";").split(";")
for class_id in list_class_id :
# Receprer la liste des 'internal_url_"
Myclass_Data = MYSY_GV.dbname['myclass'].find_one({'_id':ObjectId(str(class_id)),
'partner_owner_recid':str(my_partner['recid'])})
if( Myclass_Data is None):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation avec l'identifiant "+str(class_id)+ " est invalide ")
return False, "La formation avec l'identifiant "+str(class_id)+ "est invalide ",
# Verifier qu'il n'y a pas de session associée à cette formation
existe_Session_count = MYSY_GV.dbname['session_formation'].count_documents({'class_internal_url':str(Myclass_Data['internal_url']),
'partner_owner_recid':str(my_partner['recid']),
'valide':'1'})
if( existe_Session_count > 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation avec le code externe "+str(Myclass_Data['external_code'])+" a "+str(existe_Session_count)+" session(s) valide(s). Suppression impossible")
return False, "La formation avec le code externe "+str(Myclass_Data['external_code'])+" a "+str(existe_Session_count)+" session(s) valide(s). Suppression impossible"
for class_id in list_class_id :
# Receprer la liste des 'internal_url_"
Myclass_Data = MYSY_GV.dbname['myclass'].find_one({'_id':ObjectId(str(class_id)),
'partner_owner_recid':str(my_partner['recid'])})
# Une formation va etre supprimée, maintenant il faut supprimer les champs associés dans la collection "elaindex"
qry_elaindex_to_delete = {"partner_owner_recid": str(my_partner['recid']),
"id_formation": str(Myclass_Data['external_code'])}
MYSY_GV.dbname['elaindex'].delete_many(qry_elaindex_to_delete)
delete_doc = MYSY_GV.dbname['myclass'].delete_many({'_id':ObjectId(str(class_id)),
'partner_owner_recid':str(my_partner['recid'])})
return True, " La liste des formations a été supprimée"
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 la liste des formations "
"""
Cette fonction supprime definitivement une formation, en utilisant l'internal_url
/!\ : Une formation n'est supprimable que si :
1 - Il n'y a aucune session à venir. toutes les sessions sont passée.
2 - Si il y a des sessions, alors impossible de la supprimer. Proposer plus tard la notion d'archivage
3 - Dans la suppression, aller supprimer les champs dans la collection "elaindex"
"""
def delete_Class_by_internal_url(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'class_internal_url', ]
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', '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",
"""
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']
# Verifier la validité du 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 qu'une seule formation sera supprimée
Myclass_Data_count = MYSY_GV.dbname['myclass'].count_documents({'internal_url': str(diction['class_internal_url']),
'partner_owner_recid': str(my_partner['recid'])})
if( Myclass_Data_count <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation est invalide ")
return False, " La formation est invalide ",
if( Myclass_Data_count > 1 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - L'identifiant fourni correspond à plusieurs formation. Suppression annulée ")
return False, " L'identifiant fourni correspond à plusieurs formation. Suppression annulée",
# Receprer le 'internal_url_"
Myclass_Data = MYSY_GV.dbname['myclass'].find_one({'internal_url': str(diction['class_internal_url']),
'partner_owner_recid':str(my_partner['recid'])})
if( Myclass_Data is None):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation est invalide ")
return False, " La formation est invalide ",
# Verifier qu'il n'y a pas de session associée à cette formation
existe_Session_count = MYSY_GV.dbname['session_formation'].count_documents({'class_internal_url':str(Myclass_Data['internal_url']),
'partner_owner_recid':str(my_partner['recid']),
'valide':'1'})
if( existe_Session_count > 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La formation a "+str(existe_Session_count)+" session(s) valide(s). Suppression impossible")
return False, " La formation a "+str(existe_Session_count)+" session(s) valide(s). Suppression impossible"
delete_doc = MYSY_GV.dbname['myclass'].delete_many({'_id':ObjectId(str(Myclass_Data['_id'])),
'partner_owner_recid':str(my_partner['recid'])})
if( delete_doc.deleted_count > 0 ):
return True, " La formation a été correctement supprimée"
else:
# Une formation a été supprimer, maintenant il faut supprimer les champs associés dans la collection "elaindex"
qry_elaindex_to_delete = {"partner_owner_recid":str(my_partner['recid']), "id_formation":str(Myclass_Data['external_code'])}
MYSY_GV.dbname['elaindex'].delete_many(qry_elaindex_to_delete)
return True, " Aucune formation supprimée"
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 la formation "
"""
Cette fonction retourne une formation, prenant en argument le l'internal_url
"""
def get_Class_From_Internal_Url(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'internal_url']
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', '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",
"""
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
qry = {'valide': '1', 'locked': '0', 'internal_url':str(diction['internal_url']),
'partner_owner_recid':str(my_partner['recid'])}
for retval in MYSY_GV.dbname['myclass'].find({'valide': '1', 'locked': '0', 'internal_url':str(diction['internal_url']),
'partner_owner_recid':str(my_partner['recid'])}):
user = retval
user['id'] = str(val_tmp)
val_tmp = val_tmp + 1
RetObject.append(mycommon.JSONEncoder().encode(user))
#print(" RetObject = ", 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 la formation "
"""
Pour facilité la communication pr l'ingestion du des formation scrappées,
Cette fonction va retouner la formation avec la clé qui est un url
/!\ : on ne fais pas de controle de recid (car c'est le bot admin qui doit l'utiliser (revoir cette logique plus tard)
"""
def get_Class_From_Url(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'url']
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', '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",
"""
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 retval in MYSY_GV.dbname['myclass'].find({'valide': '1', 'locked': '0', 'url':str(diction['url']), }):
user = retval
user['id'] = str(val_tmp)
val_tmp = val_tmp + 1
RetObject.append(mycommon.JSONEncoder().encode(user))
#print(" RetObject = ", 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 la formation "
"""
Fonction de duplication d'une formation en prenant l'_id
"""
def Duplicate_Class(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
# Verification de l'existence de la formation
is_Class_Valide = MYSY_GV.dbname["myclass"].count_documents({'_id':ObjectId(str(diction['_id'])),
'locked':'0', 'valide':'1',
'partner_owner_recid':my_partner['recid']})
if( is_Class_Valide <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - L'identification de la formation n'est pas valide ")
return False, " L'identification de la formation n'est pas valide"
class_to_duplicate = MYSY_GV.dbname["myclass"].find_one({'_id':ObjectId(str(diction['_id'])),
'locked':'0', 'valide':'1',
'partner_owner_recid':my_partner['recid']},
{'_id': 0}
)
# Creation de la variable aleatoire en se basant sur le datetime now
suffix = hashlib.md5(str(datetime.now()).encode()).hexdigest()
i = 1
new_title = str(class_to_duplicate['title']) + "_dup"
new_internal_code = str(class_to_duplicate['internal_code'])+"_dup_" + str(suffix[0:i])
new_internal_url = str(class_to_duplicate['internal_url'])+"_dup_" + str(suffix[0:i])
new_external_code = str(class_to_duplicate['external_code'])+"_dup_" + str(suffix[0:i])
# Verifier qu'il n'existe pas de formation avec le nouvel internal url, ni le nouvel internal_code
# Les nouveau codes doivent etre unique quelque soit le 'partner_owner_recid'
is_exite_class_with_new_internal_url = 1
while( is_exite_class_with_new_internal_url > 0):
is_exite_class_with_new_internal_url = MYSY_GV.dbname['myclass'].count_documents({'$or':[{'internal_url':str(new_internal_url)},
{'internal_code':str(new_internal_code)}
]})
i = i + 1
new_title = str(class_to_duplicate['title']) + "_dup_"+str(i)
new_internal_code = str(class_to_duplicate['internal_code']) + "_dup_" + str(suffix[0:i])
new_internal_url = str(class_to_duplicate['internal_url']) + "_dup_" + str(suffix[0:i])
new_external_code = str(class_to_duplicate['external_code']) + "_dup_" + str(suffix[0:1])
print(" FINAL DUPLICATE DATA = ")
print(" ### new_title = ", new_title)
print(" ### new_internal_code = ", new_internal_code)
print(" ### new_internal_url = ", new_internal_url)
print(" ### new_external_code = ", new_external_code)
new_class = class_to_duplicate
new_class['title'] = new_title
new_class['internal_code'] = new_internal_code
new_class['internal_url'] = new_internal_url
new_class['external_code'] = new_external_code
inserted = MYSY_GV.dbname['myclass'].insert_one(new_class)
if (not inserted.inserted_id):
mycommon.myprint(
" Impossible de dupliquer la formation")
return False, " Impossible de dupliquer la formation "
# Indexation Title de la nouvelle formation ajoutée
training_to_index_title = {}
training_to_index_title['internal_url'] = new_external_code['internal_url']
training_to_index_title['reindex_all'] = '0'
training_to_index_title['partner_owner_recid'] = str(my_partner['recid'])
eibdd.ela_index_given_classes_title(training_to_index_title)
# Indexation Title des mots clées
if (str(new_external_code['mots_cle']).strip() != ""):
eibdd.ela_index_class_key_word(new_external_code['external_code'], "keyword", str(my_partner['recid']))
return True, " La formation a été dupliquée"
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 dupliquer la formation"
"""
Fonction de duplication d'une formation en prenant l'internal_url
"""
def Duplicate_Class_from_internal_url(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'internal_url']
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', '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"
"""
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
# Verification de l'existence de la formation
is_Class_Valide = MYSY_GV.dbname["myclass"].count_documents({'internal_url':str(diction['internal_url']),
'locked':'0', 'valide':'1',
'partner_owner_recid':my_partner['recid']})
if( is_Class_Valide <= 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - L'identification de la formation n'est pas valide ")
return False, " L'identification de la formation n'est pas valide"
class_to_duplicate = MYSY_GV.dbname["myclass"].find_one({'internal_url':str(diction['internal_url']),
'locked':'0', 'valide':'1',
'partner_owner_recid':my_partner['recid']},
{'_id':0}
)
# Creation de la variable aleatoire en se basant sur le datetime now
suffix = hashlib.md5(str(datetime.now()).encode()).hexdigest()
i = 1
new_title = str(class_to_duplicate['title']) + "_dup"
new_internal_code = str(class_to_duplicate['internal_code']) + "_dup_" + str(suffix[0:i])
new_internal_url = str(class_to_duplicate['internal_url']) + "_dup_" + str(suffix[0:i])
new_external_code = str(class_to_duplicate['external_code']) + "_dup_" + str(suffix[0:i])
# Verifier qu'il n'existe pas de formation avec le nouvel internal url, ni le nouvel internal_code
# Les nouveau codes doivent etre unique quelque soit le 'partner_owner_recid'
is_exite_class_with_new_internal_url = MYSY_GV.dbname['myclass'].count_documents(
{'$or': [{'internal_url': str(new_internal_url)},
{'internal_code': str(new_internal_code)}
]})
while (is_exite_class_with_new_internal_url > 0):
#print(" #### qry = ", qry)
new_title = str(class_to_duplicate['title']) + "_dup_" + str(i)
new_internal_code = str(class_to_duplicate['internal_code']) + "_dup_" + str(suffix[0:i])
new_internal_url = str(class_to_duplicate['internal_url']) + "_dup_" + str(suffix[0:i])
new_external_code = str(class_to_duplicate['external_code']) + "_dup_" + str(suffix[0:i])
i = i + 1
"""print(" FINAL DUPLICATE DATA MASSE= ")
print(" ### new_title = ", new_title)
print(" ### new_internal_code = ", new_internal_code)
print(" ### new_internal_url = ", new_internal_url)
print(" ### new_external_code = ", new_external_code)
"""
new_class = class_to_duplicate
new_class['title'] = new_title
new_class['internal_code'] = new_internal_code
new_class['internal_url'] = new_internal_url
new_class['external_code'] = new_external_code
inserted = MYSY_GV.dbname['myclass'].insert_one(new_class)
if (not inserted.inserted_id):
mycommon.myprint(
" Impossible de dupliquer la formation")
return False, " Impossible de dupliquer la formation "
# Indexation Title de la nouvelle formation ajoutée
training_to_index_title = {}
training_to_index_title['internal_url'] = new_class['internal_url']
training_to_index_title['reindex_all'] = '0'
training_to_index_title['partner_owner_recid'] = str(my_partner['recid'])
eibdd.ela_index_given_classes_title(training_to_index_title)
# Indexation Title des mots clées
if (str(new_class['mots_cle']).strip() != ""):
eibdd.ela_index_class_key_word(new_class['external_code'], "keyword", str(my_partner['recid']))
return True, " La formation a été dupliquée"
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 dupliquer la formation"
"""
Liste de deroulante des niveaux de formation
"""
def Get_List_Class_Niveau_Formation(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token',]
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list and val.startswith('my_') is False:
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'existe pas")
return False, " Les informations fournies sont incorrectes",
"""
Verification des champs obligatoires
"""
field_list_obligatoire = ['token',]
for val in field_list_obligatoire:
if val not in diction:
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans liste ")
return False, " Les informations fournies sont incorrectes",
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
"""
Clés de mise à jour
"""
data_cle = {}
data_cle['partner_owner_recid'] = "default"
data_cle['valide'] = "1"
data_cle['locked'] = "0"
#print(" ### Get_Partner_List_Partner_Client data_cle = ", data_cle)
RetObject = []
val_tmp = 1
for retval in MYSY_GV.dbname['class_niveau_formation'].find(data_cle):
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) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la liste des types des niveaux de formation"
"""
Fonction permet d'exporter les formations dans un fichier Excel
"""
def Export_Class_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, 'internal_code':0,
'freeacces':0, 'indexed':0,
'indexed_desc':0, 'indexed_obj':0,
'indexed_title':0, 'isalaune':0,
'valide':0, 'locked':0})
pipe_qry = ([
{'$match': qery_match},
{'$project':{'_id':0, 'internal_code':0,'freeacces':0, 'indexed':0, 'indexed_desc':0, 'indexed_obj':0, 'indexed_title':0, 'isalaune':0,'valide':0, 'locked':0}},
{'$lookup': {
'from': 'ressource_humaine',
"let": {'formateur_id': "$formateur_id", 'partner_owner_recid': '$partner_owner_recid'},
'pipeline': [
{'$match':
{'$expr':
{'$and':
[
{'$eq': ["$_id", {'$convert': {
'input': "$$formateur_id",
'to': "objectId",
'onError': {'error': 'true'},
'onNull': {'isnull': 'true'}
}}]},
{'$eq': ["$valide", "1"]},
{'$eq': ["$partner_recid", '$$partner_owner_recid']}
]
}
}
},
{'$project':{'nom':1, 'prenom':1, '_id':0}},
],
'as': 'ressource_humaine'
}
},
])
#print(" #### pipe_qry = ", pipe_qry)
list_class_datas = MYSY_GV.dbname['myclass'].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_Formation_csv_" + str(my_partner['recid']) + "_" + str(ts) + ".xlsx"
outputFilename = str(MYSY_GV.TEMPORARY_DIRECTORY) + "/" + str(orig_file_name)
tab_exported_fields_header = ["external_code", "certif", "cpf", "title", "description", "objectif", "domaine",
"duration", "duration_unit", "institut_formation", "metier", "mots_cle",
"note",
"plus_produit", "pourqui", "prerequis", "price", "programme", "published", "support",
"presentiel", "distantiel", "formateur_nom", "formateur_prenom" ]
tab_exported_fields = ["external_code", "certif", "cpf", "title", "description", "objectif", "domaine",
"duration", "duration_unit", "institut_formation", "metier", "mots_cle",
"note",
"plus_produit", "pourqui", "prerequis", "price", "programme", "published", "support",]
# 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( "presentiel" in class_data.keys()):
no_html_presentiel = class_data['presentiel']['presentiel']
worksheet.write(row, column, no_html_presentiel)
column += 1
no_html_distantiel = class_data['presentiel']['distantiel']
worksheet.write(row, column, no_html_distantiel)
column += 1
if( "ressource_humaine" in class_data.keys() and len(class_data['ressource_humaine'])> 0 ):
if( "nom" in class_data['ressource_humaine'][0].keys() ):
no_html_formateur_nom = class_data['ressource_humaine'][0]['nom']
worksheet.write(row, column, no_html_formateur_nom)
column += 1
if ("prenom" in class_data['ressource_humaine'][0].keys()):
no_html_formateur_prenom = class_data['ressource_humaine'][0]['prenom']
worksheet.write(row, column, no_html_formateur_prenom)
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 formation (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 formations "
"""
Cette fontcion permet d'ajouter ou mettre à jour une unité d'enseignement (UE) à une formation.
A l'ajout d'une UE, les info necessaires sont :
- Le crédit associé (numérique)
- pres_dist_hyp : Présentiel/ distantiel/ hybride,
- Est_note (oui / non) pour savoir cette unité doit être notée
/!\ :
on gere en mode nesred field, c'est a dire que les compétence dont directement ajouté à la collection myclass comme suit:
myclass:
{
'_id':xxxxxx
'title':yyyyy
...........
...........
'list_unite_enseignement':[
{ue1}
{ue2}
{ue3}
....
}
}
"""
def Add_Update_UE_To_Class(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'class_id', 'ue_id', 'credit', 'pres_dist_hyp', 'is_noted', ]
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', 'class_id', 'ue_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
mydata = {}
mydata = diction
del mydata['token']
# Initialisation des champs non envoyés à vide
for val in field_list:
if val not in diction.keys():
mydata[str(val)] = ""
# Verifier que UE est valide
is_ue_exist_count = MYSY_GV.dbname['unite_enseignement'].count_documents({'partner_owner_recid':my_partner['recid'],
'valide':'1',
'_id':ObjectId(str(diction['ue_id'])),
'locked':'0'
})
if( is_ue_exist_count != 1 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant de l'UE est invalide ")
return False, " L'identifiant de l'UE est invalide "
# Verifier que la formation est valide
is_class_exist_count = MYSY_GV.dbname['myclass'].count_documents(
{'partner_owner_recid': my_partner['recid'],
'valide': '1',
'locked': '0',
'_id':ObjectId(str(diction['class_id']))})
if (is_class_exist_count != 1 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant de la formation est invalide ")
return False, " L'identifiant de la formation est invalide "
is_class_exist_data = MYSY_GV.dbname['myclass'].find_one(
{'partner_owner_recid': my_partner['recid'],
'valide': '1',
'locked': '0',
'_id': ObjectId(str(diction['class_id']))})
local_status, local_retval = mycommon.IsFloat(str(diction['credit']))
if( local_status is False ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La valeur 'crédit' est invalide ")
return False, " La valeur 'crédit' est invalide "
"""
pres_dist_hyp prend les valeurs suivantes :
- 0 : presentiel
- 1 : distanciel
- 2 : hybride
"""
if( str(diction['pres_dist_hyp']) not in ['', '0', '1', '2']):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La valeur 'type formation' est invalide ")
return False, " La valeur 'type formation' est invalide "
if (str(diction['is_noted']) not in [ '0', '1']):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La valeur 'est noté' est invalide ")
return False, " La valeur 'est noté' est invalide "
"""
Verifier que le ue_id existe deja pour cette formation, au quel cas c'est un update qu'on fait
si non c'est un create
"""
is_ue_id_existe_class = 0
if( "list_unite_enseignement" in is_class_exist_data.keys()):
is_ue_id_existe_class = MYSY_GV.dbname['myclass'].count_documents({'list_unite_enseignement._id':str(diction['ue_id']),
'_id': ObjectId(str(diction['class_id'])),
'partner_owner_recid': my_partner[
'recid'],
'valide': '1',
'locked': '0',
})
if (is_ue_id_existe_class > 0):
# L'UE existe dans la formation, on autorise la mise à jour
update = MYSY_GV.dbname['myclass'].update_one({'_id': ObjectId(str(diction['class_id'])),
'partner_owner_recid': str(
my_partner['recid']),
'valide': '1',
'locked': '0',
'list_unite_enseignement._id': str(
diction['ue_id'])},
{'$set':
{
'list_unite_enseignement.$[xxx].credit': str(
diction['credit']),
'list_unite_enseignement.$[xxx].pres_dist_hyp': str(
diction['pres_dist_hyp']),
'list_unite_enseignement.$[xxx].is_noted': str(
diction['is_noted']),
'list_unite_enseignement.$[xxx].date_update': str(
datetime.now()),
'list_unite_enseignement.$[xxx].update_by': str(
my_partner['_id']),
}
},
upsert=False,
array_filters=[
{"xxx._id": str(diction['ue_id'])}
]
)
return True, " La compétence a été mise à jour"
else:
# l'UE n'existe pas pour cette formation, on fait une creation
# Il s'agit de la creation d'une competence
new_data = {}
new_data['date_update'] = str(datetime.now())
new_data['valide'] = "1"
new_data['update_by'] = str(my_partner['_id'])
new_data['locked'] = "0"
new_data['credit'] = str(diction['credit'])
new_data['pres_dist_hyp'] = str(diction['pres_dist_hyp'])
new_data['is_noted'] = str(diction['is_noted'])
new_data['_id'] = str(diction['ue_id'])
insert = MYSY_GV.dbname['myclass'].update_one({'_id': ObjectId(str(diction['class_id'])),
'partner_owner_recid': str(
my_partner['recid']),
'valide': '1',
'locked': '0',
},
{
'$push': {
"list_unite_enseignement": {
'$each': [new_data]
}
}
},
)
return True, " L'UE a été correctement ajoutée à la 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'ajouter L'UE à la formation "
"""
Cette fonction permet de supprimer une UE d'une formation.
/!\ : Pour rappel, on est en mode nested json sur la collection myclass
"""
def Delete_UE_From_Class(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'class_id', 'ue_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', 'class_id', 'ue_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
mydata = {}
mydata = diction
del mydata['token']
# Initialisation des champs non envoyés à vide
for val in field_list:
if val not in diction.keys():
mydata[str(val)] = ""
# Verifier que UE est valide
is_ue_exist_count = MYSY_GV.dbname['unite_enseignement'].count_documents({'partner_owner_recid':my_partner['recid'],
'valide':'1',
'_id':ObjectId(str(diction['ue_id'])),
'locked':'0'
})
if( is_ue_exist_count != 1 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant de l'UE est invalide ")
return False, " L'identifiant de l'UE est invalide "
# Verifier que la formation est valide
is_class_exist_count = MYSY_GV.dbname['myclass'].count_documents(
{'partner_owner_recid': my_partner['recid'],
'valide': '1',
'locked': '0',
'_id':ObjectId(str(diction['class_id']))})
if (is_class_exist_count != 1 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant de la formation est invalide ")
return False, " L'identifiant de la formation est invalide "
is_class_exist_data = MYSY_GV.dbname['myclass'].find_one(
{'partner_owner_recid': my_partner['recid'],
'valide': '1',
'locked': '0',
'_id': ObjectId(str(diction['class_id']))})
if ("list_unite_enseignement" in is_class_exist_data.keys()):
delete = MYSY_GV.dbname['myclass'].update_one({'_id': ObjectId(str(diction['class_id'])),
'partner_owner_recid': str(
my_partner['recid']),
'valide': '1',
'locked': '0',
'list_unite_enseignement._id': str(diction['ue_id'])},
{'$pull': {'list_unite_enseignement': {
"_id": str(diction['ue_id'])}}}
)
return True, " L'UE a été correctement suppimée de la 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 de supprimer L'UE de la formation "