Added create, update and transformation workflow for livraisons
This commit is contained in:
parent
fc7216fe2f
commit
5c374892d0
2 changed files with 494 additions and 1448 deletions
|
|
@ -4480,8 +4480,459 @@ class SageConnector:
|
||||||
|
|
||||||
raise RuntimeError(f"Erreur Sage: {error_message}")
|
raise RuntimeError(f"Erreur Sage: {error_message}")
|
||||||
|
|
||||||
|
def creer_livraison_enrichi(self, livraison_data: dict) -> Dict:
|
||||||
|
"""
|
||||||
|
➕ Création d'une livraison (type 30 = Bon de livraison)
|
||||||
|
|
||||||
|
✅ Gestion identique aux commandes/devis
|
||||||
|
"""
|
||||||
|
if not self.cial:
|
||||||
|
raise RuntimeError("Connexion Sage non établie")
|
||||||
|
|
||||||
|
logger.info(f"🚀 Début création livraison pour client {livraison_data['client']['code']}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._com_context(), self._lock_com:
|
||||||
|
transaction_active = False
|
||||||
|
try:
|
||||||
|
self.cial.CptaApplication.BeginTrans()
|
||||||
|
transaction_active = True
|
||||||
|
logger.debug("✅ Transaction Sage démarrée")
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Création document LIVRAISON (type 30)
|
||||||
|
process = self.cial.CreateProcess_Document(settings.SAGE_TYPE_BON_LIVRAISON)
|
||||||
|
doc = process.Document
|
||||||
|
|
||||||
|
try:
|
||||||
|
doc = win32com.client.CastTo(doc, "IBODocumentVente3")
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
logger.info("📄 Document livraison créé")
|
||||||
|
|
||||||
|
# Date
|
||||||
|
import pywintypes
|
||||||
|
|
||||||
|
if isinstance(livraison_data["date_livraison"], str):
|
||||||
|
date_obj = datetime.fromisoformat(livraison_data["date_livraison"])
|
||||||
|
elif isinstance(livraison_data["date_livraison"], date):
|
||||||
|
date_obj = datetime.combine(livraison_data["date_livraison"], datetime.min.time())
|
||||||
|
else:
|
||||||
|
date_obj = datetime.now()
|
||||||
|
|
||||||
|
doc.DO_Date = pywintypes.Time(date_obj)
|
||||||
|
logger.info(f"📅 Date définie: {date_obj.date()}")
|
||||||
|
|
||||||
|
# Client (CRITIQUE)
|
||||||
|
factory_client = self.cial.CptaApplication.FactoryClient
|
||||||
|
persist_client = factory_client.ReadNumero(livraison_data["client"]["code"])
|
||||||
|
|
||||||
|
if not persist_client:
|
||||||
|
raise ValueError(f"Client {livraison_data['client']['code']} introuvable")
|
||||||
|
|
||||||
|
client_obj = self._cast_client(persist_client)
|
||||||
|
if not client_obj:
|
||||||
|
raise ValueError(f"Impossible de charger le client")
|
||||||
|
|
||||||
|
doc.SetDefaultClient(client_obj)
|
||||||
|
doc.Write()
|
||||||
|
logger.info(f"👤 Client {livraison_data['client']['code']} associé")
|
||||||
|
|
||||||
|
# Référence externe (optionnelle)
|
||||||
|
if livraison_data.get("reference"):
|
||||||
|
try:
|
||||||
|
doc.DO_Ref = livraison_data["reference"]
|
||||||
|
logger.info(f"📖 Référence: {livraison_data['reference']}")
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Lignes
|
||||||
|
try:
|
||||||
|
factory_lignes = doc.FactoryDocumentLigne
|
||||||
|
except:
|
||||||
|
factory_lignes = doc.FactoryDocumentVenteLigne
|
||||||
|
|
||||||
|
factory_article = self.cial.FactoryArticle
|
||||||
|
|
||||||
|
logger.info(f"📦 Ajout de {len(livraison_data['lignes'])} lignes...")
|
||||||
|
|
||||||
|
for idx, ligne_data in enumerate(livraison_data["lignes"], 1):
|
||||||
|
logger.info(f"--- Ligne {idx}: {ligne_data['article_code']} ---")
|
||||||
|
|
||||||
|
# Charger l'article RÉEL depuis Sage
|
||||||
|
persist_article = factory_article.ReadReference(ligne_data["article_code"])
|
||||||
|
|
||||||
|
if not persist_article:
|
||||||
|
raise ValueError(f"❌ Article {ligne_data['article_code']} introuvable dans Sage")
|
||||||
|
|
||||||
|
article_obj = win32com.client.CastTo(persist_article, "IBOArticle3")
|
||||||
|
article_obj.Read()
|
||||||
|
|
||||||
|
# Récupérer le prix de vente RÉEL
|
||||||
|
prix_sage = float(getattr(article_obj, "AR_PrixVen", 0.0))
|
||||||
|
designation_sage = getattr(article_obj, "AR_Design", "")
|
||||||
|
logger.info(f"💰 Prix Sage: {prix_sage}€")
|
||||||
|
|
||||||
|
if prix_sage == 0:
|
||||||
|
logger.warning(f"⚠️ Article {ligne_data['article_code']} a un prix = 0€ (toléré)")
|
||||||
|
|
||||||
|
# Créer la ligne
|
||||||
|
ligne_persist = factory_lignes.Create()
|
||||||
|
|
||||||
|
try:
|
||||||
|
ligne_obj = win32com.client.CastTo(ligne_persist, "IBODocumentLigne3")
|
||||||
|
except:
|
||||||
|
ligne_obj = win32com.client.CastTo(ligne_persist, "IBODocumentVenteLigne3")
|
||||||
|
|
||||||
|
quantite = float(ligne_data["quantite"])
|
||||||
|
|
||||||
|
try:
|
||||||
|
ligne_obj.SetDefaultArticleReference(ligne_data["article_code"], quantite)
|
||||||
|
logger.info(f"✅ Article associé via SetDefaultArticleReference")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ SetDefaultArticleReference échoué: {e}, tentative avec objet")
|
||||||
|
try:
|
||||||
|
ligne_obj.SetDefaultArticle(article_obj, quantite)
|
||||||
|
logger.info(f"✅ Article associé via SetDefaultArticle")
|
||||||
|
except Exception as e2:
|
||||||
|
logger.error(f"❌ Toutes les méthodes ont échoué")
|
||||||
|
ligne_obj.DL_Design = designation_sage or ligne_data.get("designation", "")
|
||||||
|
ligne_obj.DL_Qte = quantite
|
||||||
|
logger.warning("⚠️ Configuration manuelle appliquée")
|
||||||
|
|
||||||
|
# Vérifier le prix automatique
|
||||||
|
prix_auto = float(getattr(ligne_obj, "DL_PrixUnitaire", 0.0))
|
||||||
|
logger.info(f"💰 Prix auto chargé: {prix_auto}€")
|
||||||
|
|
||||||
|
# Ajuster le prix si nécessaire
|
||||||
|
prix_a_utiliser = ligne_data.get("prix_unitaire_ht")
|
||||||
|
|
||||||
|
if prix_a_utiliser is not None and prix_a_utiliser > 0:
|
||||||
|
ligne_obj.DL_PrixUnitaire = float(prix_a_utiliser)
|
||||||
|
logger.info(f"💰 Prix personnalisé: {prix_a_utiliser}€")
|
||||||
|
elif prix_auto == 0 and prix_sage > 0:
|
||||||
|
ligne_obj.DL_PrixUnitaire = float(prix_sage)
|
||||||
|
logger.info(f"💰 Prix Sage forcé: {prix_sage}€")
|
||||||
|
elif prix_auto > 0:
|
||||||
|
logger.info(f"💰 Prix auto conservé: {prix_auto}€")
|
||||||
|
|
||||||
|
prix_final = float(getattr(ligne_obj, "DL_PrixUnitaire", 0.0))
|
||||||
|
montant_ligne = quantite * prix_final
|
||||||
|
logger.info(f"✅ {quantite} x {prix_final}€ = {montant_ligne}€")
|
||||||
|
|
||||||
|
# Remise
|
||||||
|
remise = ligne_data.get("remise_pourcentage", 0)
|
||||||
|
if remise > 0:
|
||||||
|
try:
|
||||||
|
ligne_obj.DL_Remise01REM_Valeur = float(remise)
|
||||||
|
ligne_obj.DL_Remise01REM_Type = 0
|
||||||
|
montant_apres_remise = montant_ligne * (1 - remise / 100)
|
||||||
|
logger.info(f"🎁 Remise {remise}% → {montant_apres_remise}€")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"⚠️ Remise non appliquée: {e}")
|
||||||
|
|
||||||
|
# Écrire la ligne
|
||||||
|
ligne_obj.Write()
|
||||||
|
logger.info(f"✅ Ligne {idx} écrite")
|
||||||
|
|
||||||
|
# Validation
|
||||||
|
doc.Write()
|
||||||
|
process.Process()
|
||||||
|
|
||||||
|
if transaction_active:
|
||||||
|
self.cial.CptaApplication.CommitTrans()
|
||||||
|
|
||||||
|
# Récupération numéro
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
numero_livraison = None
|
||||||
|
try:
|
||||||
|
doc_result = process.DocumentResult
|
||||||
|
if doc_result:
|
||||||
|
doc_result = win32com.client.CastTo(doc_result, "IBODocumentVente3")
|
||||||
|
doc_result.Read()
|
||||||
|
numero_livraison = getattr(doc_result, "DO_Piece", "")
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if not numero_livraison:
|
||||||
|
numero_livraison = getattr(doc, "DO_Piece", "")
|
||||||
|
|
||||||
|
# Relecture
|
||||||
|
factory_doc = self.cial.FactoryDocumentVente
|
||||||
|
persist_reread = factory_doc.ReadPiece(settings.SAGE_TYPE_BON_LIVRAISON, numero_livraison)
|
||||||
|
|
||||||
|
if persist_reread:
|
||||||
|
doc_final = win32com.client.CastTo(persist_reread, "IBODocumentVente3")
|
||||||
|
doc_final.Read()
|
||||||
|
|
||||||
|
total_ht = float(getattr(doc_final, "DO_TotalHT", 0.0))
|
||||||
|
total_ttc = float(getattr(doc_final, "DO_TotalTTC", 0.0))
|
||||||
|
else:
|
||||||
|
total_ht = 0.0
|
||||||
|
total_ttc = 0.0
|
||||||
|
|
||||||
|
logger.info(f"✅✅✅ LIVRAISON CRÉÉE: {numero_livraison} - {total_ttc}€ TTC ✅✅✅")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"numero_livraison": numero_livraison,
|
||||||
|
"total_ht": total_ht,
|
||||||
|
"total_ttc": total_ttc,
|
||||||
|
"nb_lignes": len(livraison_data["lignes"]),
|
||||||
|
"client_code": livraison_data["client"]["code"],
|
||||||
|
"date_livraison": str(date_obj.date()),
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
if transaction_active:
|
||||||
|
try:
|
||||||
|
self.cial.CptaApplication.RollbackTrans()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Erreur création livraison: {e}", exc_info=True)
|
||||||
|
raise RuntimeError(f"Échec création livraison: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
def modifier_livraison(self, numero: str, livraison_data: Dict) -> Dict:
|
||||||
|
"""
|
||||||
|
✏️ Modification d'une livraison existante
|
||||||
|
|
||||||
|
🔧 STRATÉGIE REMPLACEMENT LIGNES:
|
||||||
|
- Si nouvelles lignes fournies → Supprime TOUTES les anciennes puis ajoute les nouvelles
|
||||||
|
- Utilise .Remove() pour la suppression
|
||||||
|
"""
|
||||||
|
if not self.cial:
|
||||||
|
raise RuntimeError("Connexion Sage non établie")
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._com_context(), self._lock_com:
|
||||||
|
logger.info(f"🔬 === MODIFICATION LIVRAISON {numero} ===")
|
||||||
|
|
||||||
|
# ========================================
|
||||||
|
# ÉTAPE 1 : CHARGER LE DOCUMENT
|
||||||
|
# ========================================
|
||||||
|
logger.info("📂 Chargement document...")
|
||||||
|
|
||||||
|
factory = self.cial.FactoryDocumentVente
|
||||||
|
persist = None
|
||||||
|
|
||||||
|
# Chercher le document
|
||||||
|
for type_test in [30, settings.SAGE_TYPE_BON_LIVRAISON]:
|
||||||
|
try:
|
||||||
|
persist_test = factory.ReadPiece(type_test, numero)
|
||||||
|
if persist_test:
|
||||||
|
persist = persist_test
|
||||||
|
logger.info(f" ✅ Document trouvé (type={type_test})")
|
||||||
|
break
|
||||||
|
except:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not persist:
|
||||||
|
raise ValueError(f"❌ Livraison {numero} INTROUVABLE")
|
||||||
|
|
||||||
|
doc = win32com.client.CastTo(persist, "IBODocumentVente3")
|
||||||
|
doc.Read()
|
||||||
|
|
||||||
|
statut_actuel = getattr(doc, "DO_Statut", 0)
|
||||||
|
|
||||||
|
logger.info(f" 📊 Statut={statut_actuel}")
|
||||||
|
|
||||||
|
# Vérifier qu'elle n'est pas transformée
|
||||||
|
if statut_actuel == 5:
|
||||||
|
raise ValueError(f"La livraison {numero} a déjà été transformée")
|
||||||
|
|
||||||
|
if statut_actuel == 6:
|
||||||
|
raise ValueError(f"La livraison {numero} est annulée")
|
||||||
|
|
||||||
|
# Compter les lignes initiales
|
||||||
|
nb_lignes_initial = 0
|
||||||
|
try:
|
||||||
|
factory_lignes = getattr(doc, "FactoryDocumentLigne", None) or getattr(doc, "FactoryDocumentVenteLigne", None)
|
||||||
|
index = 1
|
||||||
|
while index <= 100:
|
||||||
|
try:
|
||||||
|
ligne_p = factory_lignes.List(index)
|
||||||
|
if ligne_p is None:
|
||||||
|
break
|
||||||
|
nb_lignes_initial += 1
|
||||||
|
index += 1
|
||||||
|
except:
|
||||||
|
break
|
||||||
|
|
||||||
|
logger.info(f" 📦 Lignes initiales: {nb_lignes_initial}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f" ⚠️ Erreur comptage lignes: {e}")
|
||||||
|
|
||||||
|
# ========================================
|
||||||
|
# ÉTAPE 2 : DÉTERMINER LES MODIFICATIONS
|
||||||
|
# ========================================
|
||||||
|
champs_modifies = []
|
||||||
|
|
||||||
|
modif_date = "date_livraison" in livraison_data
|
||||||
|
modif_statut = "statut" in livraison_data
|
||||||
|
modif_ref = "reference" in livraison_data
|
||||||
|
modif_lignes = "lignes" in livraison_data and livraison_data["lignes"] is not None
|
||||||
|
|
||||||
|
logger.info(f"📋 Modifications demandées:")
|
||||||
|
logger.info(f" Date: {modif_date}")
|
||||||
|
logger.info(f" Statut: {modif_statut}")
|
||||||
|
logger.info(f" Référence: {modif_ref}")
|
||||||
|
logger.info(f" Lignes: {modif_lignes}")
|
||||||
|
|
||||||
|
# ========================================
|
||||||
|
# ÉTAPE 3 : MODIFICATIONS SIMPLES
|
||||||
|
# ========================================
|
||||||
|
if not modif_lignes and (modif_date or modif_statut or modif_ref):
|
||||||
|
logger.info("🎯 Modifications simples (sans lignes)...")
|
||||||
|
|
||||||
|
if modif_date:
|
||||||
|
import pywintypes
|
||||||
|
date_str = livraison_data["date_livraison"]
|
||||||
|
|
||||||
|
if isinstance(date_str, str):
|
||||||
|
date_obj = datetime.fromisoformat(date_str)
|
||||||
|
elif isinstance(date_str, date):
|
||||||
|
date_obj = datetime.combine(date_str, datetime.min.time())
|
||||||
|
else:
|
||||||
|
date_obj = date_str
|
||||||
|
|
||||||
|
doc.DO_Date = pywintypes.Time(date_obj)
|
||||||
|
champs_modifies.append("date")
|
||||||
|
logger.info(f" ✅ Date définie: {date_obj.date()}")
|
||||||
|
|
||||||
|
if modif_statut:
|
||||||
|
nouveau_statut = livraison_data["statut"]
|
||||||
|
doc.DO_Statut = nouveau_statut
|
||||||
|
champs_modifies.append("statut")
|
||||||
|
logger.info(f" ✅ Statut défini: {nouveau_statut}")
|
||||||
|
|
||||||
|
if modif_ref:
|
||||||
|
try:
|
||||||
|
doc.DO_Ref = livraison_data["reference"]
|
||||||
|
champs_modifies.append("reference")
|
||||||
|
logger.info(f" ✅ Référence définie")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f" ⚠️ Référence non définie: {e}")
|
||||||
|
|
||||||
|
doc.Write()
|
||||||
|
logger.info(" ✅ Write() réussi")
|
||||||
|
|
||||||
|
# ========================================
|
||||||
|
# ÉTAPE 4 : REMPLACEMENT COMPLET LIGNES
|
||||||
|
# ========================================
|
||||||
|
elif modif_lignes:
|
||||||
|
logger.info("🎯 REMPLACEMENT COMPLET DES LIGNES...")
|
||||||
|
|
||||||
|
nouvelles_lignes = livraison_data["lignes"]
|
||||||
|
nb_nouvelles = len(nouvelles_lignes)
|
||||||
|
|
||||||
|
logger.info(f" 📊 {nb_lignes_initial} lignes existantes → {nb_nouvelles} nouvelles")
|
||||||
|
|
||||||
|
try:
|
||||||
|
factory_lignes = doc.FactoryDocumentLigne
|
||||||
|
except:
|
||||||
|
factory_lignes = doc.FactoryDocumentVenteLigne
|
||||||
|
|
||||||
|
factory_article = self.cial.FactoryArticle
|
||||||
|
|
||||||
|
# SUPPRESSION TOUTES LES LIGNES
|
||||||
|
if nb_lignes_initial > 0:
|
||||||
|
logger.info(f" 🗑️ Suppression de {nb_lignes_initial} lignes...")
|
||||||
|
|
||||||
|
for idx in range(nb_lignes_initial, 0, -1):
|
||||||
|
try:
|
||||||
|
ligne_p = factory_lignes.List(idx)
|
||||||
|
if ligne_p:
|
||||||
|
ligne = win32com.client.CastTo(ligne_p, "IBODocumentLigne3")
|
||||||
|
ligne.Read()
|
||||||
|
ligne.Remove()
|
||||||
|
logger.debug(f" ✅ Ligne {idx} supprimée")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f" ⚠️ Erreur suppression ligne {idx}: {e}")
|
||||||
|
|
||||||
|
logger.info(" ✅ Toutes les lignes supprimées")
|
||||||
|
|
||||||
|
# AJOUT NOUVELLES LIGNES
|
||||||
|
logger.info(f" ➕ Ajout de {nb_nouvelles} nouvelles lignes...")
|
||||||
|
|
||||||
|
for idx, ligne_data in enumerate(nouvelles_lignes, 1):
|
||||||
|
persist_article = factory_article.ReadReference(ligne_data["article_code"])
|
||||||
|
if not persist_article:
|
||||||
|
raise ValueError(f"Article {ligne_data['article_code']} introuvable")
|
||||||
|
|
||||||
|
article_obj = win32com.client.CastTo(persist_article, "IBOArticle3")
|
||||||
|
article_obj.Read()
|
||||||
|
|
||||||
|
ligne_persist = factory_lignes.Create()
|
||||||
|
|
||||||
|
try:
|
||||||
|
ligne_obj = win32com.client.CastTo(ligne_persist, "IBODocumentLigne3")
|
||||||
|
except:
|
||||||
|
ligne_obj = win32com.client.CastTo(ligne_persist, "IBODocumentVenteLigne3")
|
||||||
|
|
||||||
|
quantite = float(ligne_data["quantite"])
|
||||||
|
|
||||||
|
try:
|
||||||
|
ligne_obj.SetDefaultArticleReference(ligne_data["article_code"], quantite)
|
||||||
|
except:
|
||||||
|
try:
|
||||||
|
ligne_obj.SetDefaultArticle(article_obj, quantite)
|
||||||
|
except:
|
||||||
|
ligne_obj.DL_Design = ligne_data.get("designation", "")
|
||||||
|
ligne_obj.DL_Qte = quantite
|
||||||
|
|
||||||
|
if ligne_data.get("prix_unitaire_ht"):
|
||||||
|
ligne_obj.DL_PrixUnitaire = float(ligne_data["prix_unitaire_ht"])
|
||||||
|
|
||||||
|
if ligne_data.get("remise_pourcentage", 0) > 0:
|
||||||
|
try:
|
||||||
|
ligne_obj.DL_Remise01REM_Valeur = float(ligne_data["remise_pourcentage"])
|
||||||
|
ligne_obj.DL_Remise01REM_Type = 0
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
ligne_obj.Write()
|
||||||
|
logger.debug(f" ✅ Ligne {idx} ajoutée")
|
||||||
|
|
||||||
|
logger.info(f" ✅ {nb_nouvelles} nouvelles lignes ajoutées")
|
||||||
|
|
||||||
|
doc.Write()
|
||||||
|
champs_modifies.append("lignes")
|
||||||
|
|
||||||
|
# ========================================
|
||||||
|
# ÉTAPE 5 : RELECTURE ET RETOUR
|
||||||
|
# ========================================
|
||||||
|
import time
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
doc.Read()
|
||||||
|
|
||||||
|
total_ht = float(getattr(doc, "DO_TotalHT", 0.0))
|
||||||
|
total_ttc = float(getattr(doc, "DO_TotalTTC", 0.0))
|
||||||
|
|
||||||
|
logger.info(f"✅✅✅ LIVRAISON MODIFIÉE: {numero} ✅✅✅")
|
||||||
|
logger.info(f" 💰 Totaux: {total_ht}€ HT / {total_ttc}€ TTC")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"numero": numero,
|
||||||
|
"total_ht": total_ht,
|
||||||
|
"total_ttc": total_ttc,
|
||||||
|
"champs_modifies": champs_modifies,
|
||||||
|
"statut": getattr(doc, "DO_Statut", 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
except ValueError as e:
|
||||||
|
logger.error(f"❌ Erreur métier: {e}")
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"❌ Erreur technique: {e}", exc_info=True)
|
||||||
|
raise RuntimeError(f"Erreur Sage: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue