13/05/2024 - 18h30

master
cherif 2024-05-13 18:38:55 +02:00
parent 3ce781ec1b
commit fa4c081614
8 changed files with 4762 additions and 51 deletions

View File

@ -1,13 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="c6d0259a-16e1-410d-91a1-830590ee2a08" name="Changes" comment="ddsdfsd">
<list default="true" id="c6d0259a-16e1-410d-91a1-830590ee2a08" name="Changes" comment="12/05/2024 - 21h30">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Job_Cron.py" beforeDir="false" afterPath="$PROJECT_DIR$/Job_Cron.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Log/log_file.log" beforeDir="false" afterPath="$PROJECT_DIR$/Log/log_file.log" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Session_Formation.py" beforeDir="false" afterPath="$PROJECT_DIR$/Session_Formation.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/class_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/class_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/partner_order.py" beforeDir="false" afterPath="$PROJECT_DIR$/partner_order.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/prj_common.py" beforeDir="false" afterPath="$PROJECT_DIR$/prj_common.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/partner_base_setup.py" beforeDir="false" afterPath="$PROJECT_DIR$/partner_base_setup.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/partner_client.py" beforeDir="false" afterPath="$PROJECT_DIR$/partner_client.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -77,13 +79,6 @@
<option name="presentableId" value="Default" />
<updated>1680804787304</updated>
</task>
<task id="LOCAL-00247" summary="20/03/2024 - 22h30dss">
<created>1711148467159</created>
<option name="number" value="00247" />
<option name="presentableId" value="LOCAL-00247" />
<option name="project" value="LOCAL" />
<updated>1711148467160</updated>
</task>
<task id="LOCAL-00248" summary="20/03/2024 - 22h30dss">
<created>1711149396482</created>
<option name="number" value="00248" />
@ -420,7 +415,14 @@
<option name="project" value="LOCAL" />
<updated>1715528112770</updated>
</task>
<option name="localTasksCounter" value="296" />
<task id="LOCAL-00296" summary="12/05/2024 - 21h30">
<created>1715541456510</created>
<option name="number" value="00296" />
<option name="presentableId" value="LOCAL-00296" />
<option name="project" value="LOCAL" />
<updated>1715541456510</updated>
</task>
<option name="localTasksCounter" value="297" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
@ -462,7 +464,6 @@
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="17/04/2024 - 21h04" />
<MESSAGE value="18/04/2024 - 21h50" />
<MESSAGE value="19/04/2024 - 22h22" />
<MESSAGE value="20/04/2024 - 13h" />
@ -487,6 +488,7 @@
<MESSAGE value="gdf" />
<MESSAGE value="dd" />
<MESSAGE value="ddsdfsd" />
<option name="LAST_COMMIT_MESSAGE" value="ddsdfsd" />
<MESSAGE value="12/05/2024 - 21h30" />
<option name="LAST_COMMIT_MESSAGE" value="12/05/2024 - 21h30" />
</component>
</project>

View File

@ -2,6 +2,7 @@
Ce fichier permet de gerer les crons et differents job
"""
import ast
from calendar import monthrange
import bson
import pymongo
@ -15,6 +16,8 @@ from datetime import datetime, date, timedelta
import module_editique
import partner_base_setup
import partner_client
import partner_order
import prj_common as mycommon
import secrets
@ -413,4 +416,660 @@ def Cron_Quotation_Relance():
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, str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)
return False, str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)
"""
Cron de facturation automatique des inscriptions
Contrôle avant facturation :
Après la facturation, on ajout sur la ligne dinscription, la liste des factures. On remplit aussi les champs : invoice et invoice_date.
A la prochaine facturation, comme on est sur une facturation mensuelle, le système va vérifier que la ligne en question na pas été facturée le mois en cours.
"""
def Cron_Monthly_Invoice_Inscription():
try:
todays_date = str(date.today().strftime("%d/%m/%Y"))
todays_date_ISODATE = datetime.strptime(str(todays_date), '%d/%m/%Y')
"""
1 - Recuprer la liste des client facturation mensuelle automatique
"""
list_clients = []
for client_data in MYSY_GV.dbname['partner_client'].find({'valide':'1',
'locked':'0',
'invoice_automatique':'mois'}):
list_clients.append(str(client_data['_id']))
print(" Client à factuer : ", str(client_data['nom']) )
qery_match = {'$and': [{"valide": '1', },
{
'mysy_session_start_date': {'$lte': todays_date_ISODATE},
},
{
'mysy_session_end_date': {'$gte': todays_date_ISODATE, },
},
]}
pipe_qry = [
{"$addFields": {
"mysy_session_start_date": {
'$dateFromString': {
'dateString': '$date_debut',
'format': "%d/%m/%Y"
}
}
}
},
{"$addFields": {
"mysy_session_end_date": {
'$dateFromString': {
'dateString': '$date_fin',
'format': "%d/%m/%Y"
}
}
}
},
{'$match': qery_match},
{'$lookup': {
'from': 'inscription',
'let': {'session_id': {'$toString': '$_id'}, 'session_partner_owner_recid': '$partner_owner_recid'},
'pipeline': [
{'$match':
{'$expr':
{'$and':
[
{'$eq': ['$session_id', '$$session_id']},
{'$eq': ['$partner_owner_recid', '$$session_partner_owner_recid']},
{'$eq': ['$status', '1']},
{'$eq': ["$client_rattachement_id", str(client_data['_id'])]}
]
}
}
},
],
'as': 'inscription_collection'
}
},
]
#print(" ### Cron_Monthly_Invoice_Inscription pipe_qry = ", pipe_qry)
data_for_invoicing = {}
data_for_invoicing['list_client'] = []
data_for_invoicing['list_session'] = []
data_for_invoicing['detail_data'] = []
list_session = []
list_client = []
for val in MYSY_GV.dbname['session_formation'].aggregate(pipe_qry):
#print(" #### val = ", val)
if( str(client_data['_id']) not in list_client ):
list_client.append(str(client_data['_id']))
if (str(val['code_session']) not in list_session):
list_session.append(str(val['code_session']))
for inscrit_data in val['inscription_collection'] :
"""
Verifier que la ligne d'inscription n'as pas été facturé le mois en cours
"""
inscription_allready_invoiced = "0"
if( "invoiced_date" in inscrit_data.keys() and inscrit_data['invoiced_date'] ):
today_yearmonth =str(datetime.now().strftime("%Y%m"))
last_invoiced_date = datetime.strptime(str(inscrit_data['invoiced_date'])[0:10], '%Y-%m-%d')
last_invoiced_yearmonth = str(last_invoiced_date.strftime("%Y%m"))
if(str(today_yearmonth) == str(last_invoiced_yearmonth)):
inscription_allready_invoiced = 1
print(" Cette inscription a a déjà ete facturé le "+str(last_invoiced_date))
"""
# On va aller prendre toutes les incriptions qui n'ont pas été facturées le mois en cours
"""
if( inscription_allready_invoiced == "0"):
local_node = {}
local_node['client_id'] = str(client_data['_id'])
local_node['client_nom'] = str(client_data['nom'])
local_node['client_raison_sociale'] = str(client_data['raison_sociale'])
local_node['nb_inscrit_to_invoice'] = str(len(val['inscription_collection']))
if( "_id" in val.keys() ):
local_node['session_id'] = str(val['_id'])
if ("code_session" in val.keys()):
local_node['code_session'] = val['code_session']
if ("titre" in val.keys()):
local_node['session_titre'] = val['titre']
class_title = ""
class_internal_url = ""
if( "class_internal_url" in val.keys() and val['class_internal_url']):
class_internal_url = val['class_internal_url']
class_data = MYSY_GV.dbname['myclass'].find_one({'internal_url':str(val['class_internal_url']),
'partner_owner_recid':str(val['partner_owner_recid']),
'valide':'1',
'locked':'0'})
if( class_data and "title" in class_data.keys() ):
class_title = class_data['title']
local_node['class_title'] = class_title
local_node['class_internal_url'] = class_internal_url
if ("date_debut" in val.keys()):
local_node['session_date_debut'] = val['date_debut']
if ("date_debut" in val.keys()):
local_node['session_date_debut'] = val['date_debut']
if ("date_fin" in val.keys()):
local_node['session_date_fin'] = val['date_fin']
if ("prix_session" in val.keys()):
local_node['prix_session'] = val['prix_session']
if ("price_by" in val.keys()):
local_node['price_by'] = val['price_by']
local_node['inscription_id'] = str(inscrit_data['_id'])
### data Inscription
local_node['apprenant_id'] = str(inscrit_data['_id'])
if ("_id" in inscrit_data.keys()):
local_node['apprenant_id'] = str(inscrit_data['_id'])
# Si on a une apprenant_id, on va aller chercher les données de l'apprenant
if( "apprenant_id" in inscrit_data.keys() and inscrit_data['apprenant_id']):
apprenant_data = MYSY_GV.dbname['apprenant'].find_one({'_id':ObjectId(str(inscrit_data['apprenant_id'])),
'partner_owner_recid':str(val['partner_owner_recid'])})
if (apprenant_data and "email" in apprenant_data.keys()):
local_node['apprenant_email'] = apprenant_data['email']
if (apprenant_data and "civilite" in apprenant_data.keys()):
local_node['apprenant_civilite'] = apprenant_data['civilite']
if (apprenant_data and "prenom" in apprenant_data.keys()):
local_node['apprenant_prenom'] = apprenant_data['prenom']
if (apprenant_data and "nom" in apprenant_data.keys()):
local_node['apprenant_nom'] = apprenant_data['nom']
else:
# Situation anormale car toutes inscription validée à forcement un dossier apprenant. mais on fait pour se couvrir de bug
local_node['inscription_email'] = ""
local_node['inscription_civilite'] = ""
local_node['inscription_prenom'] = ""
local_node['inscription_nom'] = ""
local_node['partner_owner_recid'] = str(client_data['partner_recid'])
data_for_invoicing['detail_data'].append(local_node)
data_for_invoicing['list_client'] = list_client
data_for_invoicing['list_session'] = list_session
print(" ### le tableau a facturer est : ")
print(data_for_invoicing)
if( len(data_for_invoicing['detail_data']) > 0 ):
print(" DEBUT FACTURATION")
local_invoice_status, local_invoice_retval = Invoice_Data_From_Tab(data_for_invoicing)
if( local_invoice_status is False):
return local_invoice_status, local_invoice_retval
else:
print(" FACTURATION REUSSI")
return True, ""
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, str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)
"""
Cette fonction prend le tableau des data à factuer et créer les facture dans les
tables et met à jour les inscriptions
"""
def Invoice_Data_From_Tab(diction):
try:
todays_date_mode_2 = str(date.today().strftime("%Y-%m-%d"))
print( " ### diction FACTURATION= ", diction)
field_list_obligatoire = ['list_client', 'list_session', 'detail_data', ]
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"
field_list_detail_data_obligatoire = ['client_id', 'session_id', 'code_session', 'prix_session', 'price_by', 'nb_inscrit_to_invoice',
'apprenant_id', 'apprenant_email', 'apprenant_prenom', 'apprenant_nom', 'partner_owner_recid', 'class_internal_url']
for val in field_list_detail_data_obligatoire:
for tmp in diction['detail_data']:
if val not in tmp:
mycommon.myprint(
str(inspect.stack()[0][3]) + " : La valeur '" + val + "' n'est pas presente dans 'detail_data' ")
return False, "La valeur '" + val + "' n'est pas presente dans 'detail_data' "
data_array = diction['detail_data']
tab_ligne_a_facturer = []
ref_interne_facture = ""
"""
Calcul des totaux à facturer
"""
montant_total_ht = 0
for session_data in diction['list_session'] :
montant_total_ht_session = 0
nb_participant = 0
prix_session = 0
price_by_session = ""
liste_participant = ""
class_intenal_url_session = ""
partner_owner_recid = ""
for local_data in diction['detail_data']:
if( local_data['code_session'] == session_data ) :
if( "prix_session" in local_data.keys() and local_data['prix_session'] and
"price_by" in local_data.keys() and local_data['price_by'] ):
prix_insc = str(local_data['prix_session'])
price_by = str(local_data['price_by'])
if( price_by not in MYSY_GV.TRAINING_PRICE):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La valeur '" + price_by + "' n'est pas valide ")
return False, " La valeur '" + price_by + "' n'est pas valide "
local_isfloat_status, local_isfloat_retval = mycommon.IsFloat(prix_insc)
if(local_isfloat_status is False ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " La valeur '" + prix_insc + "' n'est pas valide ")
return False, " La valeur '" + prix_insc + "' n'est pas valide "
nb_participant = mycommon.tryInt(local_data['nb_inscrit_to_invoice'])
prix_session = local_isfloat_retval
price_by_session = price_by
liste_participant = str(local_data['apprenant_prenom'])+" "+str(local_data['apprenant_nom'])+str(local_data['apprenant_email'])+"\n"+liste_participant
class_intenal_url_session = local_data['class_internal_url']
partner_owner_recid = local_data['partner_owner_recid']
if( price_by_session == "perstagiaire"):
montant_total_ht_session = montant_total_ht_session + (prix_session * nb_participant )
elif( price_by_session == "persession"):
montant_total_ht_session = montant_total_ht_session + prix_session
montant_total_ht = montant_total_ht + montant_total_ht_session
partner_invoice_line_data = {}
list_partner_invoice_line_champ = ['order_line_formation', 'order_line_qty', 'order_line_prix_unitaire',
'order_line_tax', 'order_line_tax_amount',
'order_line_montant_toutes_taxes',
'order_line_montant_hors_taxes', 'order_line_type_reduction',
'order_line_type_valeur', 'order_line_montant_reduction',
'order_header_ref_interne',
'order_line_comment', 'order_header_id', 'valide', 'locked',
'date_update',
'partner_owner_recid', 'invoice_header_ref_interne', 'invoice_line_type',
'invoice_date', 'invoice_header_id']
# PreRemplir les champs
for val in list_partner_invoice_line_champ:
partner_invoice_line_data[str(val)] = ""
partner_invoice_line_data['order_line_formation'] = class_intenal_url_session
partner_invoice_line_data['order_line_qty'] = str(nb_participant)
partner_invoice_line_data['order_line_prix_unitaire'] = str(prix_session)
partner_invoice_line_data['order_line_montant_hors_taxes'] = str(montant_total_ht_session)
partner_invoice_line_data['order_line_comment'] = str(liste_participant)
partner_invoice_line_data['invoice_line_type'] = "facture"
partner_invoice_line_data['code_session'] = session_data
partner_invoice_line_data['update_by'] = "auto"
partner_invoice_line_data['valide'] = "1"
partner_invoice_line_data['locked'] = "0"
partner_invoice_line_data['partner_owner_recid'] = str(partner_owner_recid)
if( "order_line_formation" in partner_invoice_line_data.keys() and partner_invoice_line_data['order_line_formation'] and
"order_line_qty" in partner_invoice_line_data.keys() and partner_invoice_line_data['order_line_qty'] ):
tab_ligne_a_facturer.append(partner_invoice_line_data)
print(" ### montant_total_ht = ", montant_total_ht)
"""
1 - recuperation des données du client
"""
client_data = MYSY_GV.dbname['partner_client'].find_one({'_id':ObjectId(str(diction['list_client'][0])),
'valide':'1',
'locked':'0',
'partner_recid':str(str(data_array[0]['partner_owner_recid']))})
if( client_data is None ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " L'identifiant du client "+str(data_array[0]['client_id'])+" est invalide ")
return False, " L'identifiant du client "+str(data_array[0]['client_id'])+" est invalide "
local_status, my_partner = mycommon.Get_Connected_User_Partner_Data_From_RecID( str(data_array[0]['partner_owner_recid']))
if (local_status is not True):
return local_status, my_partner
# Recuperation des contacts de communication du client
local_diction = {}
local_diction['token'] = str(my_partner['token'])
local_diction['_id'] = str(client_data['_id'])
print(" ##### local_diction = ", local_diction)
local_status, partner_client_contact_communication = partner_client.Get_Partner_Client_Communication_Contact(
local_diction)
if (local_status is False):
mycommon.myprint(" Impossible de récupérer les contacts de communication du client ")
return False, " Impossible de récupérer les contacts de communication du client "
partner_invoice_header_data = {}
list_partner_invoice_header_champ = ['order_header_client_id', 'order_header_ref_interne',
'order_header_email_client', 'order_header_origin',
'order_header_ref_client', 'order_header_vendeur_id',
'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', 'valide',
'locked', 'date_update',
'order_header_montant_reduction', 'order_header_tax',
'order_header_tax_amount', 'total_header_hors_taxe_after_header_reduction',
'total_header_hors_taxe_before_header_reduction',
'total_header_toutes_taxes', 'total_lines_hors_taxe_after_lines_reduction',
'total_lines_hors_taxe_before_lines_reduction',
'total_lines_montant_reduction', 'invoice_header_ref_interne',
'invoice_header_type', 'invoice_date', 'update_by']
# PreRemplir les champs
for val in list_partner_invoice_header_champ:
partner_invoice_header_data[str(val)] = ""
partner_invoice_header_data['order_header_client_id'] = str(client_data['_id'])
"""
Recuperation des conditions de paiement depuis le client
"""
ction_paiement_code = ""
ction_paiement_desc = ""
ction_paiement_depart = "facture"
ction_paiement_nb_jour = "0"
if ("invoice_condition_paiement_id" in client_data.keys() and client_data[
'invoice_condition_paiement_id']):
ction_paiement_data = MYSY_GV.dbname['base_partner_paiement_condition'].find_one(
{'partner_owner_recid': my_partner['recid'],
'valide': '1',
'locked': '0',
'_id': ObjectId(str(client_data['invoice_condition_paiement_id']))})
if (ction_paiement_data and "code" in ction_paiement_data.keys() and ction_paiement_data['code']):
ction_paiement_code = ction_paiement_data['code']
if (ction_paiement_data and "description" in ction_paiement_data.keys() and ction_paiement_data[
'description']):
ction_paiement_desc = ction_paiement_data['description']
if (ction_paiement_data and "nb_jour" in ction_paiement_data.keys() and ction_paiement_data['nb_jour'] and
"depart" in ction_paiement_data.keys() and ction_paiement_data['depart']):
ction_paiement_nb_jour = ction_paiement_data['nb_jour']
ction_paiement_depart = ction_paiement_data['depart']
nb_jour_int = mycommon.tryInt(str(ction_paiement_nb_jour))
today = datetime.today()
date_echance = datetime.today()
if (str(ction_paiement_depart) == "mois"):
days_in_month = lambda dt: monthrange(dt.year, dt.month)[1]
first_day_next_month = today.replace(day=1) + timedelta(days_in_month(today))
date_echance = first_day_next_month + timedelta(days=nb_jour_int)
else:
date_echance = today + timedelta(days=nb_jour_int)
date_echance = date_echance.strftime("%d/%m/%Y")
partner_invoice_header_data['invoice_date_echeance'] = str(date_echance)
partner_invoice_header_data['order_header_condition_paiement_code'] = str(ction_paiement_code)
partner_invoice_header_data['order_header_condition_paiement_description'] = str(ction_paiement_desc)
partner_invoice_header_data['order_header_ref_interne'] = "Fact_Auto_" + str(todays_date_mode_2)
order_header_email_client = ""
if ("email" in client_data.keys()):
order_header_email_client = client_data['email']
partner_invoice_header_data['order_header_email_client'] = order_header_email_client
order_header_origin = "session_id_" + str(client_data['_id'])
partner_invoice_header_data['order_header_origin'] = order_header_origin
order_header_adr_fact_adresse = ""
if ("invoice_adresse" in client_data.keys()):
order_header_adr_fact_adresse = client_data['invoice_adresse']
partner_invoice_header_data['order_header_adr_fact_adresse'] = order_header_adr_fact_adresse
order_header_adr_fact_ville = ""
if ("invoice_ville" in client_data.keys()):
order_header_adr_fact_ville = client_data['invoice_adresse']
partner_invoice_header_data['order_header_adr_fact_ville'] = order_header_adr_fact_ville
order_header_adr_fact_code_postal = ""
if ("invoice_code_postal" in client_data.keys()):
order_header_adr_fact_code_postal = client_data['invoice_code_postal']
partner_invoice_header_data['order_header_adr_fact_code_postal'] = order_header_adr_fact_code_postal
order_header_adr_fact_pays = ""
if ("invoice_pays" in client_data.keys()):
order_header_adr_fact_pays = client_data['invoice_pays']
partner_invoice_header_data['order_header_adr_fact_pays'] = order_header_adr_fact_pays
order_header_montant_reduction = "0"
partner_invoice_header_data['order_header_montant_reduction'] = order_header_montant_reduction
partner_invoice_header_data['total_header_hors_taxe_before_header_reduction'] = str(montant_total_ht)
# Recupération de la TVA de l'entité qui facture
taux_tva_statuts, taux_tva_retval = partner_base_setup.Get_Given_Partner_Basic_Setup(
{'token': str(my_partner['token']), 'config_name': 'tva'})
if (taux_tva_statuts is False):
mycommon.myprint(str(inspect.stack()[0][3]) + " Facturation : Impossible de récupérer le taux de TVA ")
return False, " Facturation : Impossible de récupérer le taux de TVA "
tmp = ast.literal_eval(taux_tva_retval[0])
taux_tva_retval = tmp['config_value']
tva_status, tva_value = mycommon.IsFloat(str(taux_tva_retval))
if (tva_status is False):
mycommon.myprint(str(inspect.stack()[0][3]) + " Facturation : Le taux de TVA est invalide ")
return False, " Facturation : Le taux de TVA est invalide "
partner_invoice_header_data['order_header_tax'] = taux_tva_retval
partner_invoice_header_data['order_header_tax_amount'] = str(round(tva_value * montant_total_ht / 100, 2))
partner_invoice_header_data['total_header_toutes_taxes'] = str(
round(montant_total_ht + (tva_value * montant_total_ht) / 100, 2))
partner_invoice_header_data['invoice_header_type'] = "facture"
# Récuperation de la sequence de l'objet "partner_invoice_header" dans la collection : "mysy_sequence"
retval_sequence_invoice = MYSY_GV.dbname['mysy_sequence'].find_one(
{'partner_invoice_header': 'partner_order_header',
'valide': '1', 'partner_owner_recid': str(
my_partner['recid'])})
if (retval_sequence_invoice is None):
# Il n'y pas de sequence pour le partenaire, on va aller chercher la sequence par defaut
retval_sequence_invoice = MYSY_GV.dbname['mysy_sequence'].find_one(
{'related_mysy_object': 'partner_invoice_header',
'valide': '1', 'partner_owner_recid': 'default'})
if (retval_sequence_invoice is None or "current_val" not in retval_sequence_invoice.keys()):
# Il n'y aucune sequence meme par defaut.
mycommon.myprint(" Facture : Impossible de récupérer la sequence 'retval_sequence_invoice' ")
return False, "Facture : Impossible de récupérer la sequence 'retval_sequence_invoice' ", False
current_seq_value = str(retval_sequence_invoice['current_val'])
new_sequence_value = int(mycommon.tryInt(current_seq_value)) + 1
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_invoice['_id'])), 'valide': '1'},
{"$set": new_sequance_data_to_update},
return_document=ReturnDocument.AFTER,
upsert=False,
)
invoice_date_time = str(datetime.now().strftime("%d/%m/%Y"))
"""
Verifier qu'il n'y pas une facture du partenaire avec le meme ref interne
"""
is_already_invoice_ref_exist = MYSY_GV.dbname['partner_invoice_header'].count_documents(
{'partner_invoice_header': str(my_partner['recid']),
'valide': '1',
'invoice_header_ref_interne': str(retval_sequence_invoice['prefixe'] + str(current_seq_value))})
if (is_already_invoice_ref_exist > 0):
mycommon.myprint(" Facture : Il existe déjà une facture avec la même ref. interne : " + str(
retval_sequence_invoice['prefixe'] + str(current_seq_value)))
return False, " Facture : Il existe déjà une facture avec la même ref. interne : " + str(
retval_sequence_invoice['prefixe'] + str(current_seq_value)), False
partner_invoice_header_data['invoice_header_ref_interne'] = retval_sequence_invoice['prefixe'] + str(
current_seq_value)
partner_invoice_header_data['invoice_header_type'] = "facture"
partner_invoice_header_data['invoice_date'] = invoice_date_time
partner_invoice_header_data['update_by'] = str(my_partner['_id'])
partner_invoice_header_data['valide'] = "1"
partner_invoice_header_data['locked'] = "0"
partner_invoice_header_data['partner_owner_recid'] = str(my_partner['recid'])
partner_invoice_header_data['date_update'] = str(datetime.now())
ref_interne_facture = retval_sequence_invoice['prefixe'] + str(
current_seq_value)
print(" #### partner_invoice_header_data = ", partner_invoice_header_data)
inserted_invoice_id = MYSY_GV.dbname['partner_invoice_header'].insert_one(
partner_invoice_header_data).inserted_id
if (not inserted_invoice_id):
mycommon.myprint(" Facture : Impossible de créer l'entête de la facture ")
return False, " Facture : Impossible de créer l'entête de la facture "
"""
Création des lignes de facture.
Pour memo, dans la collection : partner_invoice_line
order_line_formation = titre formation
order_line_qty = nb participants
order_line_comment = la liste des personnes participans
"""
for line in tab_ligne_a_facturer :
if( "order_line_formation" in line.keys() and line['order_line_formation'] and
"order_line_qty" in line.keys() and line['order_line_qty']):
line['invoice_header_id'] = str(inserted_invoice_id)
line['invoice_header_ref_interne'] = partner_invoice_header_data[
'invoice_header_ref_interne']
line['update_by'] = str(my_partner['_id'])
line['valide'] = "1"
line['locked'] = "0"
line['partner_owner_recid'] = str(my_partner['recid'])
print(" #### partner_invoice_line_data = ", line)
inserted_invoice_id = MYSY_GV.dbname['partner_invoice_line'].insert_one(
line).inserted_id
if (not inserted_invoice_id):
mycommon.myprint(" Facture : Impossible de créer les lignes de la facture " + str(
partner_invoice_header_data['invoice_header_ref_interne']))
return False, " Facture : Impossible de créer les lignes de la facture " + str(
partner_invoice_header_data['invoice_header_ref_interne'])
"""
Mettre à jour les inscrit avec le numero de facture
"""
ref_facture = ref_interne_facture
for val in diction['detail_data']:
if( "inscription_id" in val.keys() and val['inscription_id']):
node = {}
node['invoiced_date'] = str(date.today().strftime("%Y-%m-%d"))
node['invoiced_ref'] = str(ref_interne_facture)
inscription_data = MYSY_GV.dbname['inscription'].find_one({'_id':ObjectId(str(val['inscription_id']))})
local_list_facture = []
if( "list_facture" in inscription_data.keys() and inscription_data['list_facture']):
inscription_data['list_facture'] .append(node)
else:
inscription_data['list_facture'] = []
inscription_data['list_facture'] .append(node)
inscription_data['invoiced_date'] = str(date.today().strftime("%Y-%m-%d"))
inscription_data['invoiced_ref'] = str(ref_interne_facture)
del inscription_data['_id']
update_attendee_data = MYSY_GV.dbname['inscription'].find_one_and_update(
{'_id':ObjectId(str(val['inscription_id']))},
{"$set": inscription_data},
upsert=False,
return_document=ReturnDocument.AFTER
)
else:
mycommon.myprint(" Impossible de récupérer les invoice_condition_paiement_id du client ")
return False, " Impossible de récupérer les invoice_condition_paiement_id du client "
print(" FACTION CREE = ", ref_interne_facture)
return True, ""
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, str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno)

File diff suppressed because it is too large Load Diff

View File

@ -8269,7 +8269,7 @@ def Prepare_and_Send_Facture_From_Session_By_Inscription_Id(tab_files, Folder, d
tab_my_inscription_ids_Object.append(ObjectId(str(my_inscription_id)))
print(" éééé tab_my_inscription_ids_Object = ", tab_my_inscription_ids_Object)
# Verifier que la session est valide
is_session_valide = MYSY_GV.dbname['session_formation'].count_documents(
{'_id': ObjectId(str(diction['session_id'])),
@ -8727,8 +8727,8 @@ def Invoice_Partner_From_Session_By_Inscription_Id( diction):
tab_apprenant.append(ObjectId(str(val['apprenant_id'])))
print(" ### tab_participant = ", tab_participant)
print(" ### tab_apprenant = ", tab_apprenant)
#print(" ### tab_participant = ", tab_participant)
#print(" ### tab_apprenant = ", tab_apprenant)
# Recuperations des info de la session de formation
session_data = MYSY_GV.dbname['session_formation'].find_one({'_id': ObjectId(str(diction['session_id']))})

View File

@ -346,6 +346,19 @@ def add_class(diction):
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
@ -443,6 +456,18 @@ def add_class(diction):
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 = ""
@ -455,6 +480,21 @@ def add_class(diction):
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
@ -888,6 +928,20 @@ def update_class(diction):
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']
@ -964,11 +1018,39 @@ def update_class(diction):
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()):
@ -3119,21 +3201,23 @@ def add_class_mass(file=None, Folder=None, diction=None):
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()
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'})
"""
Verifier que le domaine est bien dans la liste acceptée
"""
count_domaine = MYSY_GV.dbname['liste_domaine_metier'].count_documents({'domaine': str(mydata['domaine']).lower(), '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"
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'])
@ -3149,11 +3233,28 @@ def add_class_mass(file=None, Folder=None, diction=None):
version = str(df['version'].values[n]).strip()
mydata['version'] = version
categorie = ""
categorie_id = ""
if ("categorie" in df.keys()):
if (str(df['categorie'].values[n])):
categorie = str(df['categorie'].values[n]).strip()
mydata['categorie'] = categorie
"""
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]))
@ -3200,22 +3301,27 @@ def add_class_mass(file=None, Folder=None, diction=None):
mydata['price'] = price
metier = ""
metier_id = ""
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_domaine = MYSY_GV.dbname['liste_domaine_metier'].count_documents(
{'metier': str(metier).lower(), 'valide': '1', 'locked': '0'})
if (count_domaine <= 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"
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
mydata['metier'] = metier_id
published = "1"
@ -3620,8 +3726,10 @@ def Controle_add_class_mass(saved_file=None, Folder=None, diction=None):
"""
Verifier que le domaine est bien dans la liste acceptée
"""
count_domaine = MYSY_GV.dbname['liste_domaine_metier'].count_documents(
{'domaine': str(mydata['domaine']).lower(), 'valide': '1', 'locked': '0'})
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][
@ -3644,10 +3752,25 @@ def Controle_add_class_mass(saved_file=None, Folder=None, diction=None):
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
@ -3740,9 +3863,9 @@ def Controle_add_class_mass(saved_file=None, Folder=None, diction=None):
"""
Verifier que le metier est bien dans la liste acceptée
"""
count_domaine = MYSY_GV.dbname['liste_domaine_metier'].count_documents(
{'metier': str(metier).lower(), 'valide': '1', 'locked': '0'})
if (count_domaine <= 0):
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(

View File

@ -9190,6 +9190,8 @@ if __name__ == '__main__':
"""
/!\ Dasactivé en dev pour pas consommer de ressource pr rien.
"""
"""
scheduler = BackgroundScheduler()
# Create the job
@ -9203,6 +9205,7 @@ if __name__ == '__main__':
# /!\ IMPORTANT /!\ : Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
"""
app.run(host='localhost', port=MYSY_GV.MYSY_PORT_DEV, debug=True, threaded=True)
# Create the background scheduler

View File

@ -313,7 +313,7 @@ def Get_Given_Partner_Basic_Setup(diction):
"""
Verification des champs obligatoires
"""
field_list_obligatoire = ['token','config_name', 'related_collection' ]
field_list_obligatoire = ['token','config_name', ]
for val in field_list_obligatoire:
if val not in diction:
mycommon.myprint(
@ -333,6 +333,13 @@ def Get_Given_Partner_Basic_Setup(diction):
if (local_status is not True):
return local_status, my_partner
related_collection = ""
if( "related_collection" in diction.keys() and diction['related_collection']) :
related_collection = diction['related_collection']
if( str(diction['config_name']) not in MYSY_GV.PARTNER_BASE_CONFIG_NAME ):
mycommon.myprint(
str(inspect.stack()[0][3]) + " - La valeur '" + str(diction['config_name']) + "' n'est pas valide ")
@ -344,12 +351,13 @@ def Get_Given_Partner_Basic_Setup(diction):
param_retval_value = ""
qry_tva = {'partner_owner_recid':str(my_partner['recid']), 'valide':'1',
'locked':'0', 'config_name':str(diction['config_name'])}
'locked':'0', 'config_name':str(diction['config_name']),
'related_collection':str(related_collection)}
#print(" ### qry_tva = ", qry_tva)
print(" ### qry_tva = ", qry_tva)
for New_retVal in MYSY_GV.dbname['base_partner_setup'].find({'partner_owner_recid':str(my_partner['recid']), 'valide':'1',
'locked':'0', 'config_name':str(diction['config_name']),
'related_collection':str(diction['related_collection'])}):
'related_collection':str(related_collection)}):
user = New_retVal
param_retval_value = str(New_retVal['config_value'])
@ -358,10 +366,17 @@ def Get_Given_Partner_Basic_Setup(diction):
Si la valeur est vide, alors on va aller chercher la configuration par default
"""
if( str(param_retval_value).strip() == ""):
qry_tva2 = {'partner_owner_recid': "default", 'valide': '1',
'locked': '0', 'config_name': str(diction['config_name']),
'related_collection':str(related_collection)}
print(" ### qry_tva2 = ", qry_tva2)
for New_retVal in MYSY_GV.dbname['base_partner_setup'].find(
{'partner_owner_recid': "default", 'valide': '1',
'locked': '0', 'config_name': str(diction['config_name']),
'related_collection':str(diction['related_collection'])}):
'related_collection':str(related_collection)}):
user = New_retVal
param_retval_value = str(New_retVal['config_value'])

View File

@ -41,7 +41,7 @@ def Add_Partner_Client(diction):
'invoice_email', 'invoice_nom', 'invoice_siret',
'invoice_tva', 'invoice_condition_paiement_id', 'invoice_adresse', 'invoice_ville',
'invoice_code_postal', 'invoice_pays', "client_type_id",
'is_fournisseur', 'is_client', 'is_financeur', 'is_company']
'is_fournisseur', 'is_client', 'is_financeur', 'is_company', 'invoice_automatique']
print(" diction = ", diction)
@ -151,6 +151,12 @@ def Add_Partner_Client(diction):
is_company = diction['is_company']
data['is_company'] = is_company
invoice_automatique = ""
if ("invoice_automatique" in diction.keys()):
if diction['invoice_automatique']:
invoice_automatique = diction['invoice_automatique']
data['invoice_automatique'] = invoice_automatique
is_fournisseur = ""
if ("is_fournisseur" in diction.keys() and diction['is_fournisseur']):
@ -500,7 +506,7 @@ def Update_Partner_Client(diction):
'invoice_email', 'invoice_nom', 'invoice_siret',
'invoice_tva','invoice_condition_paiement_id', 'invoice_adresse', 'invoice_ville',
'invoice_code_postal', 'invoice_pays', 'client_type_id',
'is_fournisseur', 'is_client', 'is_financeur', 'is_company']
'is_fournisseur', 'is_client', 'is_financeur', 'is_company', 'invoice_automatique']
incom_keys = diction.keys()
for val in incom_keys:
@ -581,6 +587,11 @@ def Update_Partner_Client(diction):
nom = diction['nom']
data_update['nom'] = diction['nom']
if ("invoice_automatique" in diction.keys()):
data_update['invoice_automatique'] = diction['invoice_automatique']
# Le nom est un champ obligatoire
if( str(nom).strip() == ""):
mycommon.myprint(str(inspect.stack()[0][
@ -1186,6 +1197,9 @@ def Get_Given_Partner_Client_From_Id(diction):
user['client_type_code'] = client_type_data['code']
if( "invoice_automatique" not in retval.keys() ):
user['invoice_automatique'] = ""
RetObject.append(mycommon.JSONEncoder().encode(user))
#print(" ### RetObject = ", RetObject)