09/07/23 - 21h

master
cherif 2023-07-09 20:44:25 +02:00
parent f7f538c346
commit c0c4efd6b2
5 changed files with 1016 additions and 15 deletions

View File

@ -1,12 +1,10 @@
<?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="08/07/23 - 20h">
<list default="true" id="c6d0259a-16e1-410d-91a1-830590ee2a08" name="Changes" comment="09/07/23 - 16h">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" 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$/appel_offre.py" beforeDir="false" afterPath="$PROJECT_DIR$/appel_offre.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ela_factures_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/ela_factures_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/email_mgt.py" beforeDir="false" afterPath="$PROJECT_DIR$/email_mgt.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/strype_payement.py" beforeDir="false" afterPath="$PROJECT_DIR$/strype_payement.py" afterDir="false" />
</list>
@ -359,7 +357,14 @@
<option name="project" value="LOCAL" />
<updated>1688846277129</updated>
</task>
<option name="localTasksCounter" value="42" />
<task id="LOCAL-00042" summary="09/07/23 - 16h">
<created>1688911052399</created>
<option name="number" value="00042" />
<option name="presentableId" value="LOCAL-00042" />
<option name="project" value="LOCAL" />
<updated>1688911052400</updated>
</task>
<option name="localTasksCounter" value="43" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
@ -374,7 +379,6 @@
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="29/04/23 - 21h" />
<MESSAGE value="05/05/23 - 21h" />
<MESSAGE value="12/05/23 - 19h" />
<MESSAGE value="13/05/23 - 17h" />
@ -399,6 +403,7 @@
<MESSAGE value="05/07/23 - 12h" />
<MESSAGE value="05/07/23 - 20h" />
<MESSAGE value="08/07/23 - 20h" />
<option name="LAST_COMMIT_MESSAGE" value="08/07/23 - 20h" />
<MESSAGE value="09/07/23 - 16h" />
<option name="LAST_COMMIT_MESSAGE" value="09/07/23 - 16h" />
</component>
</project>

File diff suppressed because one or more lines are too long

View File

@ -29,6 +29,7 @@ from dateutil.relativedelta import relativedelta
import class_mgt as class_mgt
import strype_payement as Stripe
import code_promo_mgt as code_promo_mgt
import time
class JSONEncoder(json.JSONEncoder):
def default(self, o):
@ -446,6 +447,22 @@ def get_payement_mode(diction):
"""
Cette fonction crée une facture dans la collecion : factures.
/!\ : update du 09/07/2023 :
Apres la creation de la commande, une recap de la facture à venir est envoyé, ceci à titre d'information.
Le système recupere les informations depuis la plateforme strype. MAIS pour eviter des soucis de sychronisation,
c'est à dire recuperer les infos, alors que strype n'a pas fini sa mise à jour, on a desynchroniser complement
la finalisation de la commande et l'envoie des données de facture.
Pour ce faire, un va positionner un flag sur le partenaire pour dire :
"send_pre_invoice_data" à '1', "date_time_pre_invoice_created" à date_time_now.
Ensuite un job va tourner (frequence à definir) pour traiter tous les client
dont : "send_pre_invoice_data" = 1 et "date_time_pre_invoice_created" <= now() - 5 min.
Ainsi on laisse 5 minutes à strype pour bien se mettre à jour
"""
def createOrder(diction):
try:
@ -858,7 +875,18 @@ def createOrder(diction):
# Facturation de la commande
print(" ######## lancement de la facturation total_ttc_float = " + str(total_ttc_float))
if (total_ttc_float > 0 or len(str(discount_code)) > 2):
CreateInvoice(new_data)
local_invoice_status, local_invoice_retval = CreateInvoice(new_data)
if( local_invoice_status == False):
return False, local_invoice_retval, None
else:
# La facture a bien été créée, on va mettre à jour le client/partenaire avec les champ : "send_pre_invoice_data" à '1', "date_time_pre_invoice_created" à date_time_now.
ret_val_local = MYSY_GV.dbname['partnair_account'].find_one_and_update({"recid":str(user_recid), 'active':'1', 'locked':'0'},
{"$set": {'send_pre_invoice_data':'1', 'datetime_pre_invoice_created':str(datetime.now())}},
upsert=False,
return_document=ReturnDocument.AFTER
)
# Apres la facturation, on met à jour le display_ranking des formations du partenaire.
tmp_diction = {"partnaire_recid":str(user_recid), "new_pack_name":str(mypack)}
@ -908,14 +936,14 @@ def CreateInvoice(diction):
if val not in diction:
mycommon.myprint(str(inspect.stack()[0][
3]) + " - Le champ '" + val + "' n'existe pas, Creation facture annulée")
return False, " Impossible de créer la facture"
return False, " Impossible de créer la facture (1)"
order_id = ""
status_tmp, last_invoice_id = Get_Last_Invoice_ID()
if( status_tmp is False):
mycommon.myprint(str(inspect.stack()[0][
3]) + " Impossible de recuperer Get_Last_Invoice_ID ")
return False, " Impossible de créer la facture"
return False, " Impossible de créer la facture (2)"
#print(" ######## last_invoice_id = "+str(last_invoice_id))
last_invoice_id = last_invoice_id + 1
@ -955,14 +983,14 @@ def CreateInvoice(diction):
#print(" ### next_invoice_date = "+str(next_invoice_date))
elif (local_status is False):
#print(" ### IMPOSSIBLE DE FACTURER la COMMANDE")
return False
return False, ""
if (local_status and str(diction['periodicite']).lower() == "annuel"):
next_invoice_date = (tmp_date + relativedelta(years=+1)).date()
#print(" ### next_invoice_date = " + str(next_invoice_date))
elif (local_status is False):
#print(" ### IMPOSSIBLE DE FACTURER la COMMANDE")
return False
return False, ""
@ -985,7 +1013,7 @@ def CreateInvoice(diction):
mycommon.myprint(
" Impression de mettre à jour la date de la prochaine facturation de la commande : ° " + str(diction['order_id']) + " ")
return True,
return True, " ok"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
@ -1150,10 +1178,10 @@ def convertHtmlToPdf(diction):
# return True on success and False on errors
print(pisaStatus.err, type(pisaStatus.err))
""" update du 09/07/23 - test envoie info prochaine facture"""
""" update du 09/07/23 - test envoie info prochaine facture
local_diction = {}
local_diction['recid'] = diction['client_recid']
email.Strip_Get_Customer_Upcoming_Invoice(local_diction)
email.Strip_Get_Customer_Upcoming_Invoice(local_diction) """
return True

35
main.py
View File

@ -1,3 +1,5 @@
import atexit
from flask import make_response, request, current_app, Flask, jsonify
from functools import update_wrapper
import json
@ -40,6 +42,7 @@ import tools_cherif.tools_cherif as tools_cherif
import business_prices as business_prices
import lms_chamilo.mysy_lms as mysy_lms
import code_promo_mgt as code_promo_mgt
from apscheduler.schedulers.background import BackgroundScheduler
app = Flask(__name__)
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
@ -3091,6 +3094,26 @@ def Strip_Get_Customer_Upcoming_Invoice():
return jsonify(status=localStatus, message=message)
"""
Cette API est job qui envoie a une frequence données
les infos de prefacturation aux clients/partner.
Les conditions :
"send_pre_invoice_data" : '1',
"datetime_pre_invoice_created" < date_time_now + 5 min.
"""
@app.route('/myclass/api/Cron_Strip_Get_Customer_Abonnement_Data/', methods=['POST','GET'])
@crossdomain(origin='*')
def Cron_Strip_Get_Customer_Abonnement_Data():
# On recupere le corps (payload) de la requete
payload = mycommon.strip_dictionary (request.form.to_dict())
print(" ### Cron_Strip_Get_Customer_Abonnement_Data : payload = ",payload)
localStatus, message = Stripe.Cron_Strip_Get_Customer_Abonnement_Data()
return jsonify(status=localStatus, message=message)
if __name__ == '__main__':
print(" debut api")
context = SSL.Context(SSL.SSLv23_METHOD)
@ -3109,6 +3132,15 @@ if __name__ == '__main__':
mycommon.myprint("++ FLASK PORT " + str(MYSY_GV.MYSY_PORT_DEV) + " ++")
mycommon.myprint("++ LMS_BAS_URL " + str(MYSY_GV.LMS_BAS_URL) + " ++")
app.run(host='localhost', port=MYSY_GV.MYSY_PORT_DEV, debug=True, threaded=True)
scheduler = BackgroundScheduler()
scheduler.add_job(func=Cron_Strip_Get_Customer_Abonnement_Data, trigger="interval", seconds=30)
scheduler.start()
mycommon.myprint("++ LANCEMENT JOB Cron_Strip_Get_Customer_Abonnement_Data TOUTES LES 60 sec ++")
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
elif (MYSY_GV.MYSY_ENV == "REC"):
mycommon.myprint(" ++++ ENVIRONNEMENT DEVELOPPEMENT ++++")
@ -3120,3 +3152,6 @@ if __name__ == '__main__':

View File

@ -16,7 +16,7 @@ import prj_common as mycommon
import inspect
import sys, os
import time
from datetime import datetime
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import email_mgt as email_mgt
import lms_chamilo.mysy_lms as mysy_lms
@ -1355,3 +1355,58 @@ def Strip_Get_Customer_Abonnement_Data(diction):
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de recuperer les données de l'abonnement "
"""
Cette fonction est un job qui va aller chercher tous les client/partner
pour lesquels il faut envoyer les elements de facturation
"send_pre_invoice_data" : '1',
"datetime_pre_invoice_created" < date_time_now + 5 min.
"""
def Cron_Strip_Get_Customer_Abonnement_Data():
try:
query = {}
query['send_pre_invoice_data'] = '1'
query['datetime_pre_invoice_created'] = { '$lte' : str( datetime.now() - timedelta(minutes=5) )}
#{}: {"$lte" :1355414400} #datetime.datetime.now() - datetime.timedelta(minutes=5)
query['locked'] = '0'
query['active'] = '1'
print(" ### query = ", query)
cpt = 0
cpt_erreur = 0
cpt_ok = 0
for val in MYSY_GV.dbname['partnair_account'].find(query):
cpt = cpt + 1
data = {}
data['recid'] = val['recid']
local_status, local_retval = email_mgt.Strip_Get_Customer_Upcoming_Invoice(data)
if( local_status is False):
cpt_erreur = cpt_erreur +1
mycommon.myprint(
str(inspect.stack()[0][3]) + " - WARNING : impossible d'envoyer les elements de prefacturation pour le recid : "+str(val['recid']))
else:
cpt_ok = cpt_ok + 1
# Les elements ont bien ete envoyé, alors on fait la mise à jour du partenaire en mettant : "send_pre_invoice_data" : '2', (2 veut dire que c'est fait)
ret_val_local = MYSY_GV.dbname['partnair_account'].find_one_and_update(
{"recid": str(val['recid']), 'active': '1', 'locked': '0'},
{"$set": {'send_pre_invoice_data': '2', 'datetime_pre_invoice_created': str(datetime.now())}},
upsert=False,
return_document=ReturnDocument.AFTER
)
return True, "Envoie des données de prefacturation : - "+str(cpt)+ " clients ==> A traiter. - "+str(cpt_ok)+ " clients==> traiter OKK. - "+str(cpt_erreur)+ " clients ==> traiter ERREUR. "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de recuperer les données de l'abonnement "