Ela_Back/partner_produit_service_mgt.py

769 lines
28 KiB
Python

"""
Ce fichier permet de gerer les produits et service qui peuvent etre ajouter à des devis et facture
Par exemple si dans la cadre d'une formation, on souhaite refacturer le deplacement de l'enseignant
ou si on facture des objets pédagogique.
/!\ : Un produit et service se differencient par le type de produit (produit ou service)
Un article (produit & service) est defini par :
code produit
Nom du produit
Type de produit?
Prix de vente?
Taxes à la vente?
famille
"""
import bson
import pymongo
from pymongo import MongoClient
import json
from bson import ObjectId
import re
from datetime import datetime
import prj_common as mycommon
import secrets
import inspect
import sys, os
import csv
import pandas as pd
from pymongo import ReturnDocument
import GlobalVariable as MYSY_GV
from math import isnan
import GlobalVariable as MYSY_GV
import ela_index_bdd_classes as eibdd
import email_mgt as email
import jinja2
from flask import send_file
from xhtml2pdf import pisa
from email.message import EmailMessage
from email.mime.text import MIMEText
from email import encoders
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
"""
Ajout d'un produit
"""
def Add_Partner_Produit_Service(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'code', 'nom', 'description', 'type', 'code_taxe',
'famille', 'prix_vente']
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', 'code', 'nom', ]
for val in field_list_obligatoire:
if val not in diction:
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans la liste des arguments ")
return False, " Les informations fournies sont incorrectes"
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
# Verifier que le prix est un floattant
if ("prix_vente" in diction.keys() and diction['prix_vente']):
local_price_status, local_status_retval = mycommon.IsFloat(str(diction['prix_vente']))
if (local_price_status is False):
return local_price_status, local_status_retval
# Verifier que ce code n'existe pas déjà
is_existe_class_categorie = MYSY_GV.dbname['partner_produit_service'].count_documents({'code':str(diction['code']),
'valide':'1',
'partner_owner_recid':str(my_partner['recid'])})
if( is_existe_class_categorie > 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Un produit avec le code '" + str(diction['code']) + "' existe déjà ")
return False, " Un produit avec le code '" + str(diction['code']) + "' existe déjà "
new_data = diction
del diction['token']
# Initialisation des champs non envoyés à vide
for val in field_list:
if val not in diction.keys():
new_data[str(val)] = ""
new_data['valide'] = "1"
new_data['locked'] = "0"
new_data['date_update'] = str(datetime.now())
new_data['update_by'] = str(my_partner['_id'])
new_data['partner_owner_recid'] = str(my_partner['recid'])
inserted_id = MYSY_GV.dbname['partner_produit_service'].insert_one(new_data).inserted_id
if (not inserted_id):
mycommon.myprint(
" Impossible de créer le produit (2) ")
return False, " Impossible de créer le produit (2) "
return True, " La produit a été correctement ajouté"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de créer le produit "
"""
Mise à jour d'un produit & service
"""
def Update_Partner_Produit_Service(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', '_id', 'code', 'nom', 'description', 'type', 'code_taxe',
'famille', 'prix_vente']
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 la liste des arguments ")
return False, " Les informations fournies sont incorrectes"
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
# Verifier que le prix est un floattant
if( "prix_vente" in diction.keys() and diction['prix_vente']):
local_price_status, local_status_retval = mycommon.IsFloat(str(diction['prix_vente']))
if( local_price_status is False ):
return local_price_status, local_status_retval
new_data = diction
# Verifier que le produit est valide
is_existe_produit = MYSY_GV.dbname['partner_produit_service'].count_documents(
{'_id': ObjectId(str(diction['_id'])),
'valide': '1',
'partner_owner_recid': str(my_partner['recid'])})
if (is_existe_produit < 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant du produit est invalide ")
return False, " L'identifiant du produit est invalide "
local_id = str(diction['_id'])
del diction['token']
del diction['_id']
new_data['date_update'] = str(datetime.now())
new_data['update_by'] = str(my_partner['_id'])
data_cle = {}
data_cle['partner_owner_recid'] = str(my_partner['recid'])
data_cle['_id'] = ObjectId(local_id)
data_cle['valide'] = "1"
data_cle['locked'] = "0"
result = MYSY_GV.dbname['partner_produit_service'].find_one_and_update(
data_cle,
{"$set": new_data},
upsert=False,
return_document=ReturnDocument.AFTER
)
if ("_id" not in result.keys()):
mycommon.myprint(
" Impossible de mettre à jour le produit (2) ")
return False, " Impossible de mettre à jour le produit (2) "
return True, " Le produit de formation a été correctement mis à jour"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de mettre à jour le produit "
"""
Suppression d'un produit
regles (a definir plus tard, mais à minima:
Si la condition (_id) n'est pas utiliser dans les collection
- partner_order_line
- partner_invoice_line
"""
def Delete_Partner_Produit_Service(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 la liste des arguments ")
return False, " Les informations fournies sont incorrectes"
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
# Verifier le produit existe
is_existe_produit = MYSY_GV.dbname['partner_produit_service'].count_documents(
{'_id': ObjectId(str(diction['_id'])),
'valide': '1',
'partner_owner_recid': str(my_partner['recid'])})
if (is_existe_produit < 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant du produit est invalide ")
return False, " L'identifiant du produit est invalide "
"""
Verifier que le produit n'est pas utilisé dans les collection
- partner_order_line
- partner_invoice_line
"""
is_product_in_order = MYSY_GV.dbname['partner_order_line'].count_documents({'partner_owner_recid':my_partner['recid'],
'valide':'1',
'partner_invoice_line_id':str(diction['_id'])})
if( is_product_in_order > 0 ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Ce produit est utilisée dans "+str(is_product_in_order)+" commande(s)/devis ")
return False, " Cette catégorie de formation est utilisée dans "+str(is_product_in_order)+" commande(s)/devis "
is_product_in_invoice = MYSY_GV.dbname['partner_invoice_line'].count_documents(
{'partner_owner_recid': my_partner['recid'],
'valide': '1',
'partner_invoice_line_id': str(diction['_id'])})
if (is_product_in_invoice > 0):
mycommon.myprint(
str(inspect.stack()[0][3]) + " Ce produit est utilisée dans " + str(
is_product_in_order) + " facture(s) ")
return False, " Cette catégorie de formation est utilisée dans " + str(
is_product_in_order) + " facture(s) "
delete = MYSY_GV.dbname['partner_produit_service'].delete_one({'_id': ObjectId(str(diction['_id'])),
'partner_owner_recid': str(my_partner['recid']),
}, )
return True, " Le produit a été correctement supprimé"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de supprimer le produit "
"""
Recuperer la liste des produits et services d'un partenaire
"""
def Get_List_Partner_Produit_Service(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 la liste des arguments ")
return False, " Les informations fournies sont incorrectes",
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
"""
Clés de mise à jour
"""
data_cle = {}
data_cle['partner_owner_recid'] = str(my_partner['recid'])
data_cle['valide'] = "1"
data_cle['locked'] = "0"
RetObject = []
val_tmp = 0
for retval in MYSY_GV.dbname['partner_produit_service'].find(data_cle).sort([("_id", pymongo.DESCENDING), ]):
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 produits "
"""
Recuperer la liste des produits et services d'un partenaire avec des filter
"""
def Get_List_Partner_Produit_Service_with_filter(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'code', 'nom' ]
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 la liste des arguments ")
return False, " Les informations fournies sont incorrectes",
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
filt_code = {}
if ("code" in diction.keys()):
filt_code = {'code': {'$regex': str(diction['code']), "$options": "i"}}
filt_nom = {}
if ("nom" in diction.keys()):
filt_nom = {'nom': {'$regex': str(diction['nom']), "$options": "i"}}
"""
Clés de mise à jour
"""
data_cle = {}
data_cle['partner_owner_recid'] = str(my_partner['recid'])
data_cle['valide'] = "1"
data_cle['locked'] = "0"
find_qry = {'$and': [
data_cle,
filt_nom, filt_code]}
print(" ### find_qry = ", find_qry)
RetObject = []
val_tmp = 0
for retval in MYSY_GV.dbname['partner_produit_service'].find(find_qry).sort([("_id", pymongo.DESCENDING), ]):
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 produits "
"""
Recuperer les données d'un produit
"""
def Get_Given_Partner_Produit_Service(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'existe pas")
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 la liste des arguments ")
return False, " Les informations fournies sont incorrectes",
"""
Verification de l'identité et autorisation de l'entité qui
appelle cette API
"""
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
"""
Clés de mise à jour
"""
data_cle = {}
data_cle['partner_owner_recid'] = str(my_partner['recid'])
data_cle['valide'] = "1"
data_cle['locked'] = "0"
data_cle['_id'] = ObjectId(str(diction['_id']))
RetObject = []
val_tmp = 0
for retval in MYSY_GV.dbname['partner_produit_service'].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 les données du produit "
""" Recuperation de l'image d'un produit
/!\ important : on prend le 'related_collection_recid' comme le '_id' de la collection inscription
"""
def getRecoded_Partner_Product_Image_from_front(diction=None):
try:
# Dictionnaire des champs utilisables
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'existe pas, requete annulée")
return False, " Impossible de récupérer les informations"
'''
Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente,
On controle que les champs obligatoires sont presents dans la liste
'''
field_list_obligatoire = ['token', '_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 la liste des arguments ")
return False, " Impossible de récupérer les informations"
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
qery_images = {'locked': '0', 'valide': '1', 'related_collection': 'partner_produit_service',
'related_collection_recid': str(diction['_id'])}
#print(" ### qery_images = ", qery_images)
RetObject = []
employee_images = {}
# Recuperation des image 'logo' et 'cachet' si le partenaire en a
for retVal in MYSY_GV.dbname['mysy_images'].find(qery_images):
if ('type_img' in retVal.keys()):
if (retVal['type_img'] == "user"):
employee_images['logo_img'] = retVal['img'].decode()
employee_images['logo_img_recid'] = retVal['recid']
RetObject.append(mycommon.JSONEncoder().encode(employee_images))
return True, RetObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de recupérer l'image de du produit "
"""
Cette fonction ajoute une image de profil d'un produit
"""
def Update_Partner_Product_Image(file_img=None, Folder=None, diction=None):
try:
# Dictionnaire des champs utilisables
'''
# Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés
# Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API
# Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste
# field_list.
'''
field_list = ['token', 'file_img_recid', '_id' ]
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list and val.startswith('my_') is False:
mycommon.myprint(str(inspect.stack()[0][3]) + " : Le champ '"+val + "' n'est pas autorisé ")
return False, " Le champ '" + val + "' n'est pas accepté "
'''
Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente,
On controle que les champs obligatoires sont presents dans la liste
'''
field_list_obligatoire = ['token']
for val in field_list_obligatoire:
if val not in diction:
mycommon.myprint(str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans la liste des arguments ")
return False, " La valeur '" + val + "' n'est pas presente dans la liste des arguments "
# recuperation des paramettre
token = ""
if ("token" in diction.keys()):
if diction['token']:
token = diction['token']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
_id = ""
if ("_id" in diction.keys()):
if diction['_id']:
_id = diction['_id']
if( file_img ):
recordimage_diction = {}
recordimage_diction['token'] = diction['token']
recordimage_diction['related_collection'] = "partner_produit_service"
recordimage_diction['type_img'] = "user"
recordimage_diction['related_collection_recid'] = str(_id)
recordimage_diction['image_recid'] = diction['file_img_recid']
local_status, local_message = mycommon.recordClassImage_v2(file_img, MYSY_GV.upload_folder, recordimage_diction)
if( local_status is False):
return local_status, local_message
return True, "L'image a été correctement enregistrée"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, "Impossible d'enregistrer l'image"
"""
Suppression d'un image d'un produit
"""
def DeleteImage_Partner_Product(diction=None):
try:
# Dictionnaire des champs utilisables
field_list = ['token', 'image_recid', ]
incom_keys = diction.keys()
'''
# Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés
# Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API
# Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste
# field_list.
'''
for val in incom_keys:
if str(val).lower() not in str(field_list).lower():
mycommon.myprint(
str(inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas accepté dans cette API")
return False, " Impossible de se connecter"
'''
Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente,
On controle que les champs obligatoires sont presents dans la liste
'''
field_list_obligatoire = ['token', 'image_recid']
for val in field_list_obligatoire:
if str(val).lower() not in diction:
mycommon.myprint(
str(inspect.stack()[0][3]) + " La valeur '" + val + "' n'est pas presente dans la liste des arguments des champs")
return False, "Impossible de se connecter"
mydata = {}
mytoken = ""
# recuperation des paramettre
if ("token" in diction.keys()):
if diction['token']:
mytoken = diction['token']
image_recid = ""
if ("image_recid" in diction.keys()):
if diction['image_recid']:
image_recid = diction['image_recid']
local_status, my_partner = mycommon.Check_Connexion_And_Return_Partner_Data(diction)
if (local_status is not True):
return local_status, my_partner
# " Lecture du fichier "
# print(" Lecture du fichier : " + saved_file + ". le token est :" + str(mytoken))
nb_line = 0
coll_name = MYSY_GV.dbname['mysy_images']
query_delete = {"recid": image_recid,}
ret_val = coll_name.delete_one({"recid": image_recid,}, )
print(" ### recordClassImage_v2 :L'image a été correctement supprimée ")
return True, "L'image a été correctement supprimée"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, "Impossible de supprimer l'image "