style(api): improve email template readability and clean up code formatting
This commit is contained in:
parent
282ffe4898
commit
5cb9015ab5
1 changed files with 156 additions and 150 deletions
144
api.py
144
api.py
|
|
@ -1050,8 +1050,6 @@ class MouvementStockResponse(BaseModel):
|
|||
nb_lignes: int = Field(..., description="Nombre de lignes")
|
||||
|
||||
|
||||
|
||||
|
||||
templates_signature_email = {
|
||||
"demande_signature": {
|
||||
"id": "demande_signature",
|
||||
|
|
@ -1073,7 +1071,7 @@ templates_signature_email = {
|
|||
<!-- Header -->
|
||||
<tr>
|
||||
<td style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; text-align: center; border-radius: 8px 8px 0 0;">
|
||||
<h1 style="color: #ffffff; margin: 0; font-size: 24px; font-weight: 600;">
|
||||
<h1 style="color: #000; margin: 0; font-size: 24px; font-weight: 600;">
|
||||
📝 Signature Électronique Requise
|
||||
</h1>
|
||||
</td>
|
||||
|
|
@ -1124,7 +1122,7 @@ templates_signature_email = {
|
|||
<table width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td align="center" style="padding: 10px 0 30px;">
|
||||
<a href="{{SIGNER_URL}}" style="display: inline-block; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #ffffff; text-decoration: none; padding: 16px 40px; border-radius: 6px; font-size: 16px; font-weight: 600; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);">
|
||||
<a href="{{SIGNER_URL}}" style="display: inline-block; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #000; text-decoration: none; padding: 16px 40px; border-radius: 6px; font-size: 16px; font-weight: 600; box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);">
|
||||
✍️ Signer le document
|
||||
</a>
|
||||
</td>
|
||||
|
|
@ -1179,10 +1177,9 @@ templates_signature_email = {
|
|||
"DATE",
|
||||
"MONTANT_TTC",
|
||||
"SIGNER_URL",
|
||||
"CONTACT_EMAIL"
|
||||
]
|
||||
"CONTACT_EMAIL",
|
||||
],
|
||||
},
|
||||
|
||||
"signature_confirmee": {
|
||||
"id": "signature_confirmee",
|
||||
"nom": "Confirmation de Signature",
|
||||
|
|
@ -1290,10 +1287,9 @@ templates_signature_email = {
|
|||
"NUMERO",
|
||||
"DATE_SIGNATURE",
|
||||
"TRANSACTION_ID",
|
||||
"CONTACT_EMAIL"
|
||||
]
|
||||
"CONTACT_EMAIL",
|
||||
],
|
||||
},
|
||||
|
||||
"relance_signature": {
|
||||
"id": "relance_signature",
|
||||
"nom": "Relance Signature en Attente",
|
||||
|
|
@ -1393,9 +1389,9 @@ templates_signature_email = {
|
|||
"NB_JOURS",
|
||||
"JOURS_RESTANTS",
|
||||
"SIGNER_URL",
|
||||
"CONTACT_EMAIL"
|
||||
]
|
||||
}
|
||||
"CONTACT_EMAIL",
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -1405,7 +1401,7 @@ async def universign_envoyer_avec_email(
|
|||
email: str,
|
||||
nom: str,
|
||||
doc_data: Dict, # Données du document (type, montant, date, etc.)
|
||||
session: AsyncSession
|
||||
session: AsyncSession,
|
||||
) -> Dict:
|
||||
import requests
|
||||
|
||||
|
|
@ -1419,7 +1415,7 @@ async def universign_envoyer_avec_email(
|
|||
auth=auth,
|
||||
json={
|
||||
"name": f"{doc_data.get('type_label', 'Document')} {doc_id}",
|
||||
"language": "fr"
|
||||
"language": "fr",
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
|
|
@ -1428,7 +1424,13 @@ async def universign_envoyer_avec_email(
|
|||
|
||||
logger.info(f"✅ Transaction Universign créée: {transaction_id}")
|
||||
|
||||
files = {"file": (f"{doc_data.get('type_label', 'Document')}_{doc_id}.pdf", pdf_bytes, "application/pdf")}
|
||||
files = {
|
||||
"file": (
|
||||
f"{doc_data.get('type_label', 'Document')}_{doc_id}.pdf",
|
||||
pdf_bytes,
|
||||
"application/pdf",
|
||||
)
|
||||
}
|
||||
response = requests.post(f"{api_url}/files", auth=auth, files=files, timeout=30)
|
||||
response.raise_for_status()
|
||||
file_id = response.json().get("id")
|
||||
|
|
@ -1460,9 +1462,7 @@ async def universign_envoyer_avec_email(
|
|||
response.raise_for_status()
|
||||
|
||||
response = requests.post(
|
||||
f"{api_url}/transactions/{transaction_id}/start",
|
||||
auth=auth,
|
||||
timeout=30
|
||||
f"{api_url}/transactions/{transaction_id}/start", auth=auth, timeout=30
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
|
|
@ -1486,7 +1486,7 @@ async def universign_envoyer_avec_email(
|
|||
10: "Commande",
|
||||
30: "Bon de Livraison",
|
||||
60: "Facture",
|
||||
50: "Avoir"
|
||||
50: "Avoir",
|
||||
}
|
||||
|
||||
variables = {
|
||||
|
|
@ -1496,7 +1496,7 @@ async def universign_envoyer_avec_email(
|
|||
"DATE": doc_data.get("date", datetime.now().strftime("%d/%m/%Y")),
|
||||
"MONTANT_TTC": f"{doc_data.get('montant_ttc', 0):.2f}",
|
||||
"SIGNER_URL": signer_url,
|
||||
"CONTACT_EMAIL": settings.smtp_from
|
||||
"CONTACT_EMAIL": settings.smtp_from,
|
||||
}
|
||||
|
||||
# Remplacer les variables dans le template
|
||||
|
|
@ -1533,16 +1533,13 @@ async def universign_envoyer_avec_email(
|
|||
"signer_url": signer_url,
|
||||
"statut": "ENVOYE",
|
||||
"email_log_id": email_log.id,
|
||||
"email_sent": True
|
||||
"email_sent": True,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Erreur Universign+Email: {e}")
|
||||
return {
|
||||
"error": str(e),
|
||||
"statut": "ERREUR",
|
||||
"email_sent": False
|
||||
}
|
||||
return {"error": str(e), "statut": "ERREUR", "email_sent": False}
|
||||
|
||||
|
||||
async def universign_statut(transaction_id: str) -> Dict:
|
||||
"""Récupération statut signature"""
|
||||
|
|
@ -2398,6 +2395,7 @@ async def commande_vers_facture(id: str, session: AsyncSession = Depends(get_ses
|
|||
logger.error(f"Erreur transformation: {e}")
|
||||
raise HTTPException(500, str(e))
|
||||
|
||||
|
||||
def normaliser_type_doc(type_doc: int) -> int:
|
||||
TYPES_AUTORISES = {0, 10, 30, 50, 60}
|
||||
|
||||
|
|
@ -2411,17 +2409,20 @@ def normaliser_type_doc(type_doc: int) -> int:
|
|||
|
||||
@app.post("/signature/universign/send", tags=["Signatures"])
|
||||
async def envoyer_signature_optimise(
|
||||
demande: SignatureRequest,
|
||||
session: AsyncSession = Depends(get_session)
|
||||
demande: SignatureRequest, session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
try:
|
||||
# Récupérer le document depuis Sage
|
||||
doc = sage_client.lire_document(demande.doc_id, normaliser_type_doc(demande.type_doc))
|
||||
doc = sage_client.lire_document(
|
||||
demande.doc_id, normaliser_type_doc(demande.type_doc)
|
||||
)
|
||||
if not doc:
|
||||
raise HTTPException(404, f"Document {demande.doc_id} introuvable")
|
||||
|
||||
# Générer PDF
|
||||
pdf_bytes = email_queue._generate_pdf(demande.doc_id, normaliser_type_doc(demande.type_doc))
|
||||
pdf_bytes = email_queue._generate_pdf(
|
||||
demande.doc_id, normaliser_type_doc(demande.type_doc)
|
||||
)
|
||||
|
||||
# Préparer les données du document pour l'email
|
||||
doc_data = {
|
||||
|
|
@ -2431,10 +2432,10 @@ async def envoyer_signature_optimise(
|
|||
10: "Commande",
|
||||
30: "Bon de Livraison",
|
||||
60: "Facture",
|
||||
50: "Avoir"
|
||||
50: "Avoir",
|
||||
}.get(demande.type_doc, "Document"),
|
||||
"montant_ttc": doc.get("total_ttc", 0),
|
||||
"date": doc.get("date", datetime.now().strftime("%d/%m/%Y"))
|
||||
"date": doc.get("date", datetime.now().strftime("%d/%m/%Y")),
|
||||
}
|
||||
|
||||
# Envoi Universign + Email automatique
|
||||
|
|
@ -2444,7 +2445,7 @@ async def envoyer_signature_optimise(
|
|||
email=demande.email_signataire,
|
||||
nom=demande.nom_signataire,
|
||||
doc_data=doc_data,
|
||||
session=session
|
||||
session=session,
|
||||
)
|
||||
|
||||
if "error" in resultat:
|
||||
|
|
@ -2468,13 +2469,12 @@ async def envoyer_signature_optimise(
|
|||
|
||||
# MAJ champ libre Sage
|
||||
sage_client.mettre_a_jour_champ_libre(
|
||||
demande.doc_id,
|
||||
demande.type_doc,
|
||||
"UniversignID",
|
||||
resultat["transaction_id"]
|
||||
demande.doc_id, demande.type_doc, "UniversignID", resultat["transaction_id"]
|
||||
)
|
||||
|
||||
logger.info(f"✅ Signature envoyée: {demande.doc_id} (Email: {resultat['email_sent']})")
|
||||
logger.info(
|
||||
f"✅ Signature envoyée: {demande.doc_id} (Email: {resultat['email_sent']})"
|
||||
)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
|
|
@ -2482,7 +2482,7 @@ async def envoyer_signature_optimise(
|
|||
"signer_url": resultat["signer_url"],
|
||||
"email_sent": resultat["email_sent"],
|
||||
"email_log_id": resultat.get("email_log_id"),
|
||||
"message": f"Demande de signature envoyée à {demande.email_signataire}"
|
||||
"message": f"Demande de signature envoyée à {demande.email_signataire}",
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
|
|
@ -2494,8 +2494,7 @@ async def envoyer_signature_optimise(
|
|||
|
||||
@app.post("/webhooks/universign", tags=["Signatures"])
|
||||
async def webhook_universign(
|
||||
request: Request,
|
||||
session: AsyncSession = Depends(get_session)
|
||||
request: Request, session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
try:
|
||||
payload = await request.json()
|
||||
|
|
@ -2533,8 +2532,11 @@ async def webhook_universign(
|
|||
template = templates_signature_email["signature_confirmee"]
|
||||
|
||||
type_labels = {
|
||||
0: "Devis", 10: "Commande", 30: "Bon de Livraison",
|
||||
60: "Facture", 50: "Avoir"
|
||||
0: "Devis",
|
||||
10: "Commande",
|
||||
30: "Bon de Livraison",
|
||||
60: "Facture",
|
||||
50: "Avoir",
|
||||
}
|
||||
|
||||
variables = {
|
||||
|
|
@ -2543,7 +2545,7 @@ async def webhook_universign(
|
|||
"NUMERO": signature_log.document_id,
|
||||
"DATE_SIGNATURE": datetime.now().strftime("%d/%m/%Y à %H:%M"),
|
||||
"TRANSACTION_ID": transaction_id,
|
||||
"CONTACT_EMAIL": settings.smtp_from
|
||||
"CONTACT_EMAIL": settings.smtp_from,
|
||||
}
|
||||
|
||||
sujet = template["sujet"]
|
||||
|
|
@ -2569,7 +2571,9 @@ async def webhook_universign(
|
|||
session.add(email_log)
|
||||
email_queue.enqueue(email_log.id)
|
||||
|
||||
logger.info(f"📧 Email de confirmation envoyé: {signature_log.email_signataire}")
|
||||
logger.info(
|
||||
f"📧 Email de confirmation envoyé: {signature_log.email_signataire}"
|
||||
)
|
||||
|
||||
elif event_type == "transaction.refused":
|
||||
# ❌ SIGNATURE REFUSÉE
|
||||
|
|
@ -2586,17 +2590,16 @@ async def webhook_universign(
|
|||
return {
|
||||
"status": "processed",
|
||||
"event": event_type,
|
||||
"transaction_id": transaction_id
|
||||
"transaction_id": transaction_id,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Erreur webhook Universign: {e}")
|
||||
return {"status": "error", "message": str(e)}
|
||||
|
||||
|
||||
@app.get("/admin/signatures/relances-auto", tags=["Admin"])
|
||||
async def relancer_signatures_automatique(
|
||||
session: AsyncSession = Depends(get_session)
|
||||
):
|
||||
async def relancer_signatures_automatique(session: AsyncSession = Depends(get_session)):
|
||||
try:
|
||||
from datetime import timedelta
|
||||
|
||||
|
|
@ -2604,12 +2607,11 @@ async def relancer_signatures_automatique(
|
|||
date_limite = datetime.now() - timedelta(days=7)
|
||||
|
||||
query = select(SignatureLog).where(
|
||||
SignatureLog.statut.in_([
|
||||
StatutSignatureEnum.EN_ATTENTE,
|
||||
StatutSignatureEnum.ENVOYE
|
||||
]),
|
||||
SignatureLog.statut.in_(
|
||||
[StatutSignatureEnum.EN_ATTENTE, StatutSignatureEnum.ENVOYE]
|
||||
),
|
||||
SignatureLog.date_envoi < date_limite,
|
||||
SignatureLog.nb_relances < 3 # Max 3 relances
|
||||
SignatureLog.nb_relances < 3, # Max 3 relances
|
||||
)
|
||||
|
||||
result = await session.execute(query)
|
||||
|
|
@ -2632,8 +2634,11 @@ async def relancer_signatures_automatique(
|
|||
template = templates_signature_email["relance_signature"]
|
||||
|
||||
type_labels = {
|
||||
0: "Devis", 10: "Commande", 30: "Bon de Livraison",
|
||||
60: "Facture", 50: "Avoir"
|
||||
0: "Devis",
|
||||
10: "Commande",
|
||||
30: "Bon de Livraison",
|
||||
60: "Facture",
|
||||
50: "Avoir",
|
||||
}
|
||||
|
||||
variables = {
|
||||
|
|
@ -2643,7 +2648,7 @@ async def relancer_signatures_automatique(
|
|||
"NB_JOURS": str(nb_jours),
|
||||
"JOURS_RESTANTS": str(jours_restants),
|
||||
"SIGNER_URL": signature.signer_url,
|
||||
"CONTACT_EMAIL": settings.smtp_from
|
||||
"CONTACT_EMAIL": settings.smtp_from,
|
||||
}
|
||||
|
||||
sujet = template["sujet"]
|
||||
|
|
@ -2675,7 +2680,9 @@ async def relancer_signatures_automatique(
|
|||
|
||||
nb_relances += 1
|
||||
|
||||
logger.info(f"📧 Relance envoyée: {signature.document_id} ({signature.nb_relances}/3)")
|
||||
logger.info(
|
||||
f"📧 Relance envoyée: {signature.document_id} ({signature.nb_relances}/3)"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Erreur relance signature {signature.id}: {e}")
|
||||
|
|
@ -2687,7 +2694,7 @@ async def relancer_signatures_automatique(
|
|||
"success": True,
|
||||
"signatures_verifiees": len(signatures_a_relancer),
|
||||
"relances_envoyees": nb_relances,
|
||||
"message": f"{nb_relances} email(s) de relance envoyé(s)"
|
||||
"message": f"{nb_relances} email(s) de relance envoyé(s)",
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
|
@ -4166,9 +4173,7 @@ async def commande_vers_livraison(
|
|||
):
|
||||
try:
|
||||
# Étape 1: Vérifier que la commande existe
|
||||
commande_existante = sage_client.lire_document(
|
||||
id, TypeDocumentSQL.BON_COMMANDE
|
||||
)
|
||||
commande_existante = sage_client.lire_document(id, TypeDocumentSQL.BON_COMMANDE)
|
||||
|
||||
if not commande_existante:
|
||||
raise HTTPException(404, f"Commande {id} introuvable")
|
||||
|
|
@ -4549,6 +4554,7 @@ async def statistiques_utilisateurs(session: AsyncSession = Depends(get_session)
|
|||
logger.error(f"❌ Erreur stats utilisateurs: {e}")
|
||||
raise HTTPException(500, str(e))
|
||||
|
||||
|
||||
@app.get("/modeles", tags=["PDF Sage-Like"])
|
||||
async def get_modeles_disponibles():
|
||||
"""Liste tous les modèles PDF disponibles"""
|
||||
|
|
@ -4564,8 +4570,10 @@ async def get_modeles_disponibles():
|
|||
async def get_document_pdf(
|
||||
numero: str,
|
||||
type_doc: int = Query(..., description="0=devis, 60=facture, etc."),
|
||||
modele: str = Query(None, description="Nom du modèle (ex: 'Facture client logo.bgc')"),
|
||||
download: bool = Query(False, description="Télécharger au lieu d'afficher")
|
||||
modele: str = Query(
|
||||
None, description="Nom du modèle (ex: 'Facture client logo.bgc')"
|
||||
),
|
||||
download: bool = Query(False, description="Télécharger au lieu d'afficher"),
|
||||
):
|
||||
try:
|
||||
# Récupérer le PDF (en bytes)
|
||||
|
|
@ -4573,7 +4581,7 @@ async def get_document_pdf(
|
|||
numero=numero,
|
||||
type_doc=type_doc,
|
||||
modele=modele,
|
||||
base64_encode=False # On veut les bytes bruts
|
||||
base64_encode=False, # On veut les bytes bruts
|
||||
)
|
||||
|
||||
# Retourner le PDF
|
||||
|
|
@ -4585,9 +4593,7 @@ async def get_document_pdf(
|
|||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": f'{disposition}; filename="{filename}"'
|
||||
}
|
||||
headers={"Content-Disposition": f'{disposition}; filename="{filename}"'},
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
|
|
|
|||
Loading…
Reference in a new issue