Elyos_FI_Back_Office/partner_order.py

586 lines
27 KiB
Python

"""
Ce fichier permet de gerer les devis et les commandes d'un partenaires.
Pour précision, une commande a les status suivants :
- devis
- Commande
- Facturé
- Annulé
Une commande est defini par
order_header et order_lines comme suit :
order {order_header_ref:'xxx', order_header_amount:'yyyy', order_line[ {order_line1}, {order_line2}, ....,{}] }
"""
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
def Add_Partner_Order(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'order_header_client_id', 'order_header_description', 'order_header_comment', 'order_header_date_cmd', 'order_header_date_expiration',
'order_header_adr_fact_adresse', 'order_header_adr_fact_code_postal', 'order_header_adr_fact_ville','order_header_adr_fact_pays',
'order_header_adr_liv_adresse', 'order_header_adr_liv_code_postal', 'order_header_adr_liv_ville', 'order_header_adr_liv_pays'
'order_header_condition_paiement', 'order_header_ref_client', 'order_header_vendeur_id',
'order_header_ref_interne', 'order_header_total_ht', 'order_header_total_tax', 'order_header_total_ttc', 'order_header_status', 'order_header_type_reduction',
'order_header_type_reduction_valeur', 'order_header_montant_reduction', 'order_lines']
"""
/!\ A noter que "order_lines" est tableau [] qui peut contenir les keys suivantes : 'order_line_formation', 'order_line_qty', 'order_line_prix_unitaire', 'order_line_tax', 'order_line_type_reduction', 'order_line_type_valeur', 'order_line_montant_reduction'
ainsi, order_lines sera du style order_lines[ {order_line_formation:'xxx', order_line_qty:'2', etc }, {order_line_formation:'yyy', order_line_qty:'7', etc }, ....{}}
"""
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list:
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas autorisé")
return False, " Les informations fournies sont incorrectes",
"""
Verification des champs obligatoires
"""
field_list_obligatoire = ['token', "order_header_client", "order_header_date_cmd"]
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
# Recuperation des champs
data = {}
data['partner_owner_recid'] = my_partner['recid']
order_header_client_id = ""
if ("order_header_client_id" in diction.keys()):
if diction['order_header_client_id']:
order_header_client_id = diction['order_header_client_id']
# Verifier que le client existe bien pour ce partner
is_client_exist_count = MYSY_GV.dbname['partner_client'].count_documents({'_id':ObjectId(str(order_header_client_id)), 'valide':'1',
'locked':'0', 'partner_recid':str(my_partner['recid'])})
if( is_client_exist_count <= 0):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le client est invalide ")
return False, " - Le client est invalide "
data['order_header_client_id'] = diction['order_header_client_id']
order_header_description = ""
if ("order_header_description" in diction.keys()):
if diction['order_header_description']:
order_header_description = diction['order_header_description']
if (len(str(order_header_description)) > 500):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_description' fait plus de 500 caractères ")
return False, " - Le champ 'Description' fait plus de 500 caractères "
data['order_header_description'] = diction['order_header_description']
order_header_comment = ""
if ("order_header_comment" in diction.keys()):
if diction['order_header_comment']:
order_header_comment = diction['order_header_comment']
if (len(str(order_header_comment)) > 500):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_comment' fait plus de 500 caractères ")
return False, " - Le champ 'Commentaire' fait plus de 500 caractères "
data['order_header_comment'] = diction['order_header_comment']
order_header_condition_paiement = ""
if ("order_header_condition_paiement" in diction.keys()):
if diction['order_header_condition_paiement']:
order_header_condition_paiement = diction['order_header_condition_paiement']
if (len(str(order_header_condition_paiement)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_condition_paiement' fait plus de 255 caractères ")
return False, " - Le champ 'Condition de paiement' fait plus de 255 caractères "
data['order_header_condition_paiement'] = diction['order_header_condition_paiement']
order_header_ref_interne = ""
if ("order_header_ref_interne" in diction.keys()):
if diction['order_header_ref_interne']:
order_header_ref_interne = diction['order_header_ref_interne']
if (len(str(order_header_ref_interne)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_ref_interne' fait plus de 255 caractères ")
return False, " - Le champ 'ref_interne' fait plus de 255 caractères "
data['order_header_ref_interne'] = diction['order_header_ref_interne']
order_header_ref_externe = ""
if ("order_header_ref_externe" in diction.keys()):
if diction['order_header_ref_externe']:
order_header_ref_externe = diction['order_header_ref_externe']
if (len(str(order_header_ref_externe)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_ref_externe' fait plus de 255 caractères ")
return False, " - Le champ 'ref_externe' fait plus de 255 caractères "
data['order_header_ref_externe'] = diction['order_header_ref_externe']
order_header_vendeur_id = ""
if ("order_header_vendeur_id" in diction.keys()):
if diction['order_header_vendeur_id']:
order_header_vendeur_id = diction['order_header_vendeur_id']
# Verifier que l'employé vendeur existe bien pour ce partner
is_employee_exist_count = MYSY_GV.dbname['ressource_humaine'].count_documents(
{'_id': ObjectId(str(order_header_vendeur_id)), 'valide': '1',
'locked': '0', 'partner_recid': str(my_partner['recid'])})
if (is_employee_exist_count <= 0):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Le vendeur est invalide ")
return False, " - Le vendeur est invalide "
data['order_header_vendeur_id'] = diction['order_header_vendeur_id']
order_header_date_cmd = ""
if ("order_header_date_cmd" in diction.keys()):
if diction['order_header_date_cmd']:
order_header_date_cmd = str(diction['order_header_date_cmd'])[0:10]
local_status = mycommon.CheckisDate(order_header_date_cmd)
if (local_status is False):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " La date order_header_date_cmd n'est pas au format 'jj/mm/aaaa' ")
return False, "La date de la commande n'est pas au format 'jj/mm/aaaa'"
data['order_header_date_cmd'] = str(diction['order_header_date_cmd'])[0:10]
order_header_date_expiration = ""
if ("order_header_date_expiration" in diction.keys()):
if diction['order_header_date_expiration']:
order_header_date_cmd = str(diction['order_header_date_expiration'])[0:10]
local_status = mycommon.CheckisDate(order_header_date_cmd)
if (local_status is False):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " La date order_header_date_expiration n'est pas au format 'jj/mm/aaaa' ")
return False, "La date d'expiration de la commande n'est pas au format 'jj/mm/aaaa'"
data['order_header_date_expiration'] = str(diction['order_header_date_expiration'])[0:10]
## Verification de la cohérence des dates. order_header_date_cmd doit < order_header_date_expiration
if (datetime.strptime(str(diction['order_header_date_cmd'])[0:10], '%d/%m/%Y') >= datetime.strptime(str(diction['order_header_date_expiration'])[0:10], '%d/%m/%Y')):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - La date d'expiration " + str(diction['order_header_date_expiration'])[0:10] +" doit etre postérieure à la date de la commande " + str(diction['order_header_date_cmd'])[0:10] + " ")
return False, " - La date d'expiration " + str(diction['order_header_date_expiration'])[0:10] +" doit etre postérieure à la date de la commande " + str(diction['order_header_date_cmd'])[0:10] + " "
## Recuperation de l'adresse de facturation
order_header_adr_fact_adresse = ""
if ("order_header_adr_fact_adresse" in diction.keys()):
if diction['order_header_adr_fact_adresse']:
order_header_adr_fact_adresse = diction['order_header_adr_fact_adresse']
if (len(str(order_header_adr_fact_adresse)) > 500):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_fact_adresse' fait plus de 500 caractères ")
return False, " - Le champ 'adresse de facturation' fait plus de 500 caractères "
data['order_header_adr_fact_adresse'] = diction['order_header_adr_fact_adresse']
order_header_adr_fact_code_postal = ""
if ("order_header_adr_fact_code_postal" in diction.keys()):
if diction['order_header_adr_fact_code_postal']:
order_header_adr_fact_code_postal = diction['order_header_adr_fact_code_postal']
if (len(str(order_header_adr_fact_code_postal)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_fact_code_postal' fait plus de 255 caractères ")
return False, " - Le champ 'order_header_adr_fact_code_postal' fait plus de 255 caractères "
data['order_header_adr_fact_code_postal'] = diction['order_header_adr_fact_code_postal']
order_header_adr_fact_ville = ""
if ("order_header_adr_fact_ville" in diction.keys()):
if diction['order_header_adr_fact_ville']:
order_header_adr_fact_ville = diction['order_header_adr_fact_ville']
if (len(str(order_header_adr_fact_ville)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_fact_ville' fait plus de 255 caractères ")
return False, " - Le champ 'order_header_adr_fact_ville' fait plus de 255 caractères "
data['order_header_adr_fact_ville'] = diction['order_header_adr_fact_ville']
order_header_adr_fact_pays = ""
if ("order_header_adr_fact_pays" in diction.keys()):
if diction['order_header_adr_fact_pays']:
order_header_adr_fact_pays = diction['order_header_adr_fact_pays']
if (len(str(order_header_adr_fact_pays)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_fact_pays' fait plus de 255 caractères ")
return False, " - Le champ 'order_header_adr_fact_pays' fait plus de 255 caractères "
data['order_header_adr_fact_pays'] = diction['order_header_adr_fact_pays']
## Recuperation de l'adresse d'exécution de la formation
order_header_adr_liv_adresse = ""
if ("order_header_adr_liv_adresse" in diction.keys()):
if diction['order_header_adr_liv_adresse']:
order_header_adr_liv_adresse = diction['order_header_adr_liv_adresse']
if (len(str(order_header_adr_liv_adresse)) > 500):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_liv_adresse' fait plus de 500 caractères ")
return False, " - Le champ 'adresse d'exécution' fait plus de 500 caractères "
data['order_header_adr_liv_adresse'] = diction['order_header_adr_liv_adresse']
order_header_adr_liv_code_postal = ""
if ("order_header_adr_liv_code_postal" in diction.keys()):
if diction['order_header_adr_liv_code_postal']:
order_header_adr_liv_code_postal = diction['order_header_adr_liv_code_postal']
if (len(str(order_header_adr_liv_code_postal)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_liv_code_postal' fait plus de 255 caractères ")
return False, " - Le champ 'order_header_adr_liv_code_postal' fait plus de 255 caractères "
data['order_header_adr_liv_code_postal'] = diction['order_header_adr_liv_code_postal']
order_header_adr_liv_ville = ""
if ("order_header_adr_liv_ville" in diction.keys()):
if diction['order_header_adr_liv_ville']:
order_header_adr_liv_ville = diction['order_header_adr_liv_ville']
if (len(str(order_header_adr_liv_ville)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_liv_ville' fait plus de 255 caractères ")
return False, " - Le champ 'order_header_adr_liv_ville' fait plus de 255 caractères "
data['order_header_adr_liv_ville'] = diction['order_header_adr_liv_ville']
order_header_adr_liv_pays = ""
if ("order_header_adr_liv_pays" in diction.keys()):
if diction['order_header_adr_liv_pays']:
order_header_adr_liv_pays = diction['order_header_adr_liv_pays']
if (len(str(order_header_adr_liv_pays)) > 255):
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Le champ 'order_header_adr_liv_pays' fait plus de 255 caractères ")
return False, " - Le champ 'order_header_adr_liv_pays' fait plus de 255 caractères "
data['order_header_adr_liv_pays'] = diction['order_header_adr_liv_pays']
"""
Recuperation des lignes de commande
"""
data_order_lines = []
if( "order_lines" in diction.keys()):
for order_line in diction['order_lines']:
# Verifier les champs acceptés et champs obligatoires pour une ligne de commande
"""
Verification des input acceptés
"""
field_list = ['order_line_formation', 'order_line_qty', 'order_line_prix_unitaire',
'order_line_tax','order_line_type_reduction', 'order_line_type_valeur', 'order_line_montant_reduction']
incom_keys = order_line.keys()
for val in incom_keys:
if val not in field_list:
mycommon.myprint(str(
inspect.stack()[0][3]) + " Line de commande : Le champ '" + val + "' n'est pas autorisé")
return False, " Line de commande : Les informations fournies sont incorrectes",
"""
Verification des champs obligatoires
"""
field_list_obligatoire = ['order_line_formation', "order_line_qty", "order_line_prix_unitaire"]
for val in field_list_obligatoire:
if val not in order_line:
mycommon.myprint(
str(inspect.stack()[0][
3]) + " - Line de commande : La valeur '" + val + "' n'est pas presente dans liste ")
return False, " Line de commande : Les informations fournies sont incorrectes",
"""
/!\ : A present que tous les controles sont ok, on va proceder à la creation dans les table.
"""
### 1 - Creation de l'entete
# Rcuperation de la sequence de l'objet "lms_user_id" dans la collection : "mysy_sequence"
retval_sequence_order = MYSY_GV.dbname['mysy_sequence'].find_one({'related_mysy_object': 'partner_order_header',
'valide': '1', 'partner_owner_recid':str(my_partner['recid'])})
if (retval_sequence_order is None or "current_val" not in retval_sequence_order.keys()):
mycommon.myprint(" Impossible de recuperer la sequence 'retval_sequence_order' ")
return False, "Impossible de recuperer la sequence 'retval_sequence_order'"
current_seq_value = str(retval_sequence_order['current_val'])
new_sequence_value = int(mycommon.tryInt(current_seq_value)) + 1
# /!\ Affectation de la reference interne de la commande
diction['order_header_ref_interne'] = retval_sequence_order['prefixe']+str(current_seq_value)
print(" #### diction['order_header_ref_interne'] = ", str( diction['order_header_ref_interne']))
new_sequance_data_to_update = {'current_val': new_sequence_value}
ret_val2 = MYSY_GV.dbname['mysy_sequence'].find_one_and_update(
{'_id': ObjectId(str(retval_sequence_order['_id'])), 'valide': '1'},
{"$set": new_sequance_data_to_update},
return_document=ReturnDocument.AFTER,
upsert=False,
)
data['valide'] = '1'
data['locked'] = '0'
data['date_update'] = str(datetime.now())
inserted_id = ""
inserted_id = MYSY_GV.dbname['partner_order_header'].insert_one(data).inserted_id
if (not inserted_id):
mycommon.myprint(
" Impossible de créer l'entete de la commande ")
return False, "Impossible de créer l'entete de la commande "
### 2 - Creation des lignes
data_order_lines = []
if ("order_lines" in diction.keys()):
for order_line in diction['order_lines']:
order_line['order_header_id'] = str(inserted_id)
order_line['valide'] = '1'
order_line['locked'] = '0'
order_line['date_update'] = str(datetime.now())
order_line['partner_owner_recid'] = my_partner['recid']
inserted_line_id = ""
inserted_line_id = MYSY_GV.dbname['partner_order_line'].insert_one(data).inserted_id
if (not inserted_line_id):
mycommon.myprint(
" Impossible de créer la ligne la commande ")
return False, " Impossible de créer la ligne la commande "
return True, " La commande a été correctement créé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 créer la commande "
"""
Recuperation d'une commande donnée à partir du '_id'
"""
def Get_Given_Partner_Order(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:
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 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'] = str(my_partner['recid'])
data_cle['_id'] = ObjectId(str(diction['_id']))
data_cle['valide'] = "1"
data_cle['locked'] = "0"
RetObject = []
val_tmp = 1
#print(" ### data_cle = ", data_cle)
for retval in MYSY_GV.dbname['partner_order_header'].find(data_cle):
user = retval
user['id'] = str(val_tmp)
val_tmp = val_tmp + 1
# Recuperation des ligne associées
retval_line_data = []
for retval_line in MYSY_GV.dbname['partner_order_line'].find({'order_header_id':str(retval['_id']), 'partner_owner_recid':str(my_partner['recid']),
'valide':'1', 'locked':'0'}):
retval_line_data.append(retval_line)
RetObject.append(mycommon.JSONEncoder().encode(user))
#print(" ### RetObject = ", 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 recuperer les données de la commande "
"""
Recuperation d'un commande en partant de la reference interne et du token
"""
def Get_Given_Partner_Order_From_Internal_ref(diction):
try:
diction = mycommon.strip_dictionary(diction)
"""
Verification des input acceptés
"""
field_list = ['token', 'internal_ref']
incom_keys = diction.keys()
for val in incom_keys:
if val not in field_list:
mycommon.myprint(str(
inspect.stack()[0][3]) + " Le champ '" + val + "' n'existe pas")
return False, " Les informations fournies sont incorrectes",
"""
Verification des champs obligatoires
"""
field_list_obligatoire = ['token', 'internal_ref']
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'] = str(my_partner['recid'])
data_cle['order_header_ref_interne'] = str(diction['internal_ref'])
data_cle['valide'] = "1"
data_cle['locked'] = "0"
RetObject = []
val_tmp = 1
# print(" ### data_cle = ", data_cle)
for retval in MYSY_GV.dbname['partner_order_header'].find(data_cle):
user = retval
user['id'] = str(val_tmp)
val_tmp = val_tmp + 1
# Recuperation des ligne associées
retval_line_data = []
for retval_line in MYSY_GV.dbname['partner_order_line'].find(
{'order_header_id': str(retval['_id']), 'partner_owner_recid': str(my_partner['recid']),
'valide': '1', 'locked': '0'}):
retval_line_data.append(retval_line)
RetObject.append(mycommon.JSONEncoder().encode(user))
# print(" ### RetObject = ", 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 recuperer les données de la commande "