Sage100-ws/sage_connector.py

1294 lines
50 KiB
Python

import win32com.client
import pythoncom # AJOUT CRITIQUE
from datetime import datetime, timedelta, date
from typing import Dict, List, Optional
import threading
import time
import logging
from contextlib import contextmanager
logger = logging.getLogger(__name__)
class SageConnector:
"""
Connecteur Sage 100c avec gestion COM threading correcte
CHANGEMENTS PRODUCTION:
- Initialisation COM par thread (CoInitialize/CoUninitialize)
- Lock robuste pour thread-safety
- Gestion d'erreurs exhaustive
- Logging structuré
- Retry automatique sur erreurs COM
"""
def __init__(self, chemin_base, utilisateur="<Administrateur>", mot_de_passe=""):
self.chemin_base = chemin_base
self.utilisateur = utilisateur
self.mot_de_passe = mot_de_passe
self.cial = None
# Cache
self._cache_clients: List[Dict] = []
self._cache_articles: List[Dict] = []
self._cache_clients_dict: Dict[str, Dict] = {}
self._cache_articles_dict: Dict[str, Dict] = {}
# Métadonnées cache
self._cache_clients_last_update: Optional[datetime] = None
self._cache_articles_last_update: Optional[datetime] = None
self._cache_ttl_minutes = 15
# Thread d'actualisation
self._refresh_thread: Optional[threading.Thread] = None
self._stop_refresh = threading.Event()
# Locks thread-safe
self._lock_clients = threading.RLock()
self._lock_articles = threading.RLock()
self._lock_com = threading.RLock() # Lock pour accès COM
# Thread-local storage pour COM
self._thread_local = threading.local()
# =========================================================================
# GESTION COM THREAD-SAFE
# =========================================================================
@contextmanager
def _com_context(self):
"""
Context manager pour initialiser COM dans chaque thread
CRITIQUE: FastAPI utilise un pool de threads.
Chaque thread doit initialiser COM avant d'utiliser les objets Sage.
"""
# Vérifier si COM est déjà initialisé pour ce thread
if not hasattr(self._thread_local, "com_initialized"):
try:
pythoncom.CoInitialize()
self._thread_local.com_initialized = True
logger.debug(
f"COM initialisé pour thread {threading.current_thread().name}"
)
except Exception as e:
logger.error(f"Erreur initialisation COM: {e}")
raise
try:
yield
finally:
# Ne pas désinitialiser COM ici car le thread peut être réutilisé
pass
def _cleanup_com_thread(self):
"""Nettoie COM pour le thread actuel (à appeler à la fin)"""
if hasattr(self._thread_local, "com_initialized"):
try:
pythoncom.CoUninitialize()
delattr(self._thread_local, "com_initialized")
logger.debug(
f"COM nettoyé pour thread {threading.current_thread().name}"
)
except:
pass
# =========================================================================
# CONNEXION
# =========================================================================
def connecter(self):
"""Connexion initiale à Sage"""
try:
with self._com_context():
self.cial = win32com.client.gencache.EnsureDispatch(
"Objets100c.Cial.Stream"
)
self.cial.Name = self.chemin_base
self.cial.Loggable.UserName = self.utilisateur
self.cial.Loggable.UserPwd = self.mot_de_passe
self.cial.Open()
logger.info(f"Connexion Sage réussie: {self.chemin_base}")
# Chargement initial du cache
logger.info("Chargement initial du cache...")
self._refresh_cache_clients()
self._refresh_cache_articles()
logger.info(
f"Cache initialisé: {len(self._cache_clients)} clients, {len(self._cache_articles)} articles"
)
# Démarrage du thread d'actualisation
self._start_refresh_thread()
return True
except Exception as e:
logger.error(f"Erreur connexion Sage: {e}", exc_info=True)
return False
def deconnecter(self):
"""Déconnexion propre"""
self._stop_refresh.set()
if self._refresh_thread:
self._refresh_thread.join(timeout=5)
if self.cial:
try:
with self._com_context():
self.cial.Close()
logger.info("Connexion Sage fermée")
except:
pass
# =========================================================================
# SYSTÈME DE CACHE
# =========================================================================
def _start_refresh_thread(self):
"""Démarre le thread d'actualisation automatique"""
def refresh_loop():
# Initialiser COM pour ce thread worker
pythoncom.CoInitialize()
try:
while not self._stop_refresh.is_set():
time.sleep(60) # Vérifier toutes les minutes
# Clients
if self._cache_clients_last_update:
age = datetime.now() - self._cache_clients_last_update
if age.total_seconds() > self._cache_ttl_minutes * 60:
logger.info(
f"Actualisation cache clients (âge: {age.seconds//60}min)"
)
self._refresh_cache_clients()
# Articles
if self._cache_articles_last_update:
age = datetime.now() - self._cache_articles_last_update
if age.total_seconds() > self._cache_ttl_minutes * 60:
logger.info(
f"Actualisation cache articles (âge: {age.seconds//60}min)"
)
self._refresh_cache_articles()
finally:
# Nettoyer COM en fin de thread
pythoncom.CoUninitialize()
self._refresh_thread = threading.Thread(
target=refresh_loop, daemon=True, name="SageCacheRefresh"
)
self._refresh_thread.start()
def _refresh_cache_clients(self):
"""Actualise le cache des clients"""
if not self.cial:
return
clients = []
clients_dict = {}
try:
with self._com_context(), self._lock_com:
factory = self.cial.CptaApplication.FactoryClient
index = 1
erreurs_consecutives = 0
max_erreurs = 50
while index < 10000 and erreurs_consecutives < max_erreurs:
try:
persist = factory.List(index)
if persist is None:
break
obj = self._cast_client(persist)
if obj:
data = self._extraire_client(obj)
clients.append(data)
clients_dict[data["numero"]] = data
erreurs_consecutives = 0
index += 1
except Exception as e:
erreurs_consecutives += 1
index += 1
if erreurs_consecutives >= max_erreurs:
logger.warning(
f"Arrêt refresh clients après {max_erreurs} erreurs"
)
break
with self._lock_clients:
self._cache_clients = clients
self._cache_clients_dict = clients_dict
self._cache_clients_last_update = datetime.now()
logger.info(f" Cache clients actualisé: {len(clients)} clients")
except Exception as e:
logger.error(f" Erreur refresh clients: {e}", exc_info=True)
def _refresh_cache_articles(self):
"""Actualise le cache des articles"""
if not self.cial:
return
articles = []
articles_dict = {}
try:
with self._com_context(), self._lock_com:
factory = self.cial.FactoryArticle
index = 1
erreurs_consecutives = 0
max_erreurs = 50
while index < 10000 and erreurs_consecutives < max_erreurs:
try:
persist = factory.List(index)
if persist is None:
break
obj = self._cast_article(persist)
if obj:
data = self._extraire_article(obj)
articles.append(data)
articles_dict[data["reference"]] = data
erreurs_consecutives = 0
index += 1
except Exception as e:
erreurs_consecutives += 1
index += 1
if erreurs_consecutives >= max_erreurs:
logger.warning(
f"Arrêt refresh articles après {max_erreurs} erreurs"
)
break
with self._lock_articles:
self._cache_articles = articles
self._cache_articles_dict = articles_dict
self._cache_articles_last_update = datetime.now()
logger.info(f" Cache articles actualisé: {len(articles)} articles")
except Exception as e:
logger.error(f" Erreur refresh articles: {e}", exc_info=True)
# =========================================================================
# API PUBLIQUE (ultra-rapide grâce au cache)
# =========================================================================
def lister_tous_clients(self, filtre=""):
"""Retourne les clients depuis le cache (instantané)"""
with self._lock_clients:
if not filtre:
return self._cache_clients.copy()
filtre_lower = filtre.lower()
return [
c
for c in self._cache_clients
if filtre_lower in c["numero"].lower()
or filtre_lower in c["intitule"].lower()
]
def lire_client(self, code_client):
"""Retourne un client depuis le cache (instantané)"""
with self._lock_clients:
return self._cache_clients_dict.get(code_client)
def lister_tous_articles(self, filtre=""):
"""Retourne les articles depuis le cache (instantané)"""
with self._lock_articles:
if not filtre:
return self._cache_articles.copy()
filtre_lower = filtre.lower()
return [
a
for a in self._cache_articles
if filtre_lower in a["reference"].lower()
or filtre_lower in a["designation"].lower()
]
def lire_article(self, reference):
"""Retourne un article depuis le cache (instantané)"""
with self._lock_articles:
return self._cache_articles_dict.get(reference)
def forcer_actualisation_cache(self):
"""Force l'actualisation immédiate du cache (endpoint admin)"""
logger.info("Actualisation forcée du cache...")
self._refresh_cache_clients()
self._refresh_cache_articles()
logger.info("Cache actualisé")
def get_cache_info(self):
"""Retourne les infos du cache (endpoint monitoring)"""
with self._lock_clients, self._lock_articles:
return {
"clients": {
"count": len(self._cache_clients),
"last_update": (
self._cache_clients_last_update.isoformat()
if self._cache_clients_last_update
else None
),
"age_minutes": (
(
datetime.now() - self._cache_clients_last_update
).total_seconds()
/ 60
if self._cache_clients_last_update
else None
),
},
"articles": {
"count": len(self._cache_articles),
"last_update": (
self._cache_articles_last_update.isoformat()
if self._cache_articles_last_update
else None
),
"age_minutes": (
(
datetime.now() - self._cache_articles_last_update
).total_seconds()
/ 60
if self._cache_articles_last_update
else None
),
},
"ttl_minutes": self._cache_ttl_minutes,
}
# =========================================================================
# CAST HELPERS
# =========================================================================
def _cast_client(self, persist_obj):
try:
obj = win32com.client.CastTo(persist_obj, "IBOClient3")
obj.Read()
return obj
except:
return None
def _cast_article(self, persist_obj):
try:
obj = win32com.client.CastTo(persist_obj, "IBOArticle3")
obj.Read()
return obj
except:
return None
# =========================================================================
# EXTRACTION
# =========================================================================
def _extraire_client(self, client_obj):
data = {
"numero": getattr(client_obj, "CT_Num", ""),
"intitule": getattr(client_obj, "CT_Intitule", ""),
"type": getattr(client_obj, "CT_Type", 0),
}
try:
adresse = getattr(client_obj, "Adresse", None)
if adresse:
data["adresse"] = getattr(adresse, "Adresse", "")
data["code_postal"] = getattr(adresse, "CodePostal", "")
data["ville"] = getattr(adresse, "Ville", "")
except:
pass
try:
telecom = getattr(client_obj, "Telecom", None)
if telecom:
data["telephone"] = getattr(telecom, "Telephone", "")
data["email"] = getattr(telecom, "EMail", "")
except:
pass
return data
def _extraire_article(self, article_obj):
return {
"reference": getattr(article_obj, "AR_Ref", ""),
"designation": getattr(article_obj, "AR_Design", ""),
"prix_vente": getattr(article_obj, "AR_PrixVen", 0.0),
"prix_achat": getattr(article_obj, "AR_PrixAch", 0.0),
"stock_reel": getattr(article_obj, "AR_Stock", 0.0),
"stock_mini": getattr(article_obj, "AR_StockMini", 0.0),
}
# =========================================================================
# CRÉATION DEVIS (US-A1) - VERSION TRANSACTIONNELLE
# =========================================================================
def creer_devis_enrichi(self, devis_data: dict):
"""
Création de devis avec statut DEVIS (0) par défaut
✅ CORRECTION: Force le statut à 0 (Devis) après création
"""
if not self.cial:
raise RuntimeError("Connexion Sage non établie")
logger.info(
f"🚀 Début création devis pour client {devis_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 Exception as e:
logger.warning(f"⚠️ BeginTrans échoué: {e}")
try:
# ===== CRÉATION DOCUMENT =====
process = self.cial.CreateProcess_Document(0) # Type 0 = Devis
doc = process.Document
try:
doc = win32com.client.CastTo(doc, "IBODocumentVente3")
except:
pass
logger.info("📄 Document devis créé")
# ===== DATE =====
import pywintypes
if isinstance(devis_data["date_devis"], str):
try:
date_obj = datetime.fromisoformat(devis_data["date_devis"])
except:
date_obj = datetime.now()
elif isinstance(devis_data["date_devis"], date):
date_obj = datetime.combine(
devis_data["date_devis"], datetime.min.time()
)
else:
date_obj = datetime.now()
doc.DO_Date = pywintypes.Time(date_obj)
# ✅✅✅ CORRECTION CRITIQUE: Forcer le statut à 0 (Devis)
doc.DO_Statut = 0
logger.info("📋 Statut forcé à 0 (DEVIS)")
# ===== CLIENT =====
factory_client = self.cial.CptaApplication.FactoryClient
persist_client = factory_client.ReadNumero(
devis_data["client"]["code"]
)
if not persist_client:
raise ValueError(
f"❌ Client {devis_data['client']['code']} introuvable"
)
client_obj = self._cast_client(persist_client)
if not client_obj:
raise ValueError(
f"❌ Impossible de charger le client {devis_data['client']['code']}"
)
doc.SetDefaultClient(client_obj)
doc.Write()
logger.info(
f"👤 Client {devis_data['client']['code']} associé et document écrit"
)
# ===== LIGNES (code existant inchangé) =====
try:
factory_lignes = doc.FactoryDocumentLigne
except:
factory_lignes = doc.FactoryDocumentVenteLigne
factory_article = self.cial.FactoryArticle
logger.info(f"📦 Ajout de {len(devis_data['lignes'])} lignes...")
for idx, ligne_data in enumerate(devis_data["lignes"], 1):
# ... (code existant pour les lignes - inchangé)
pass # Remplacer par votre code existant
# ===== VALIDATION =====
logger.info("💾 Écriture finale du document...")
# ✅ RE-FORCER le statut avant validation finale
doc.DO_Statut = 0
doc.Write()
logger.info("🔄 Lancement du traitement (Process)...")
process.Process()
# ===== VÉRIFICATION POST-CRÉATION =====
numero_devis = None
try:
doc_result = process.DocumentResult
if doc_result:
doc_result = win32com.client.CastTo(
doc_result, "IBODocumentVente3"
)
doc_result.Read()
numero_devis = getattr(doc_result, "DO_Piece", "")
# ✅ VÉRIFIER et CORRIGER le statut si nécessaire
statut_actuel = getattr(doc_result, "DO_Statut", -1)
if statut_actuel != 0:
logger.warning(
f"⚠️ Statut inattendu: {statut_actuel}, correction..."
)
doc_result.DO_Statut = 0
doc_result.Write()
logger.info("✅ Statut corrigé à 0")
logger.info(
f"📄 Numéro (via DocumentResult): {numero_devis}"
)
except Exception as e:
logger.warning(f"⚠️ DocumentResult non accessible: {e}")
if not numero_devis:
numero_devis = getattr(doc, "DO_Piece", "")
logger.info(f"📄 Numéro (via Document): {numero_devis}")
if not numero_devis:
raise RuntimeError("❌ Numéro devis vide après création")
# ===== COMMIT =====
if transaction_active:
self.cial.CptaApplication.CommitTrans()
logger.info("✅ Transaction committée")
# ===== ATTENTE + RELECTURE =====
logger.info("⏳ Attente indexation Sage (2s)...")
time.sleep(2)
logger.info("🔍 Relecture complète du document...")
factory_doc = self.cial.FactoryDocumentVente
persist_reread = factory_doc.ReadPiece(0, numero_devis)
if not persist_reread:
logger.error(f"❌ Impossible de relire le devis {numero_devis}")
# Fallback
return {
"numero_devis": numero_devis,
"total_ht": 0.0,
"total_ttc": 0.0,
"nb_lignes": len(devis_data["lignes"]),
"client_code": devis_data["client"]["code"],
"date_devis": str(date_obj.date()),
"statut": 0,
}
doc_final = win32com.client.CastTo(
persist_reread, "IBODocumentVente3"
)
doc_final.Read()
# ===== EXTRACTION =====
total_ht = float(getattr(doc_final, "DO_TotalHT", 0.0))
total_ttc = float(getattr(doc_final, "DO_TotalTTC", 0.0))
statut_final = getattr(doc_final, "DO_Statut", 0)
logger.info(f"💰 Total HT: {total_ht}")
logger.info(f"💰 Total TTC: {total_ttc}")
logger.info(f"📋 Statut final: {statut_final}")
return {
"numero_devis": numero_devis,
"total_ht": total_ht,
"total_ttc": total_ttc,
"nb_lignes": len(devis_data["lignes"]),
"client_code": devis_data["client"]["code"],
"date_devis": str(date_obj.date()),
"statut": statut_final,
}
except Exception as e:
if transaction_active:
try:
self.cial.CptaApplication.RollbackTrans()
logger.error("❌ Transaction annulée (rollback)")
except:
pass
raise
except Exception as e:
logger.error(f"❌ ERREUR CRÉATION DEVIS: {e}", exc_info=True)
raise RuntimeError(f"Échec création devis: {str(e)}")
def changer_statut_devis(self, numero_devis, nouveau_statut):
"""
✅ NOUVEAU: Change le statut d'un devis
Statuts Sage:
- 0: Devis
- 2: Accepté
- 5: Transformé
- 6: Refusé
"""
if not self.cial:
raise RuntimeError("Connexion Sage non établie")
try:
with self._com_context(), self._lock_com:
factory = self.cial.FactoryDocumentVente
# Essayer ReadPiece d'abord
persist = factory.ReadPiece(0, numero_devis)
# Si échec, chercher dans la liste (brouillons)
if not persist:
index = 1
while index < 5000:
try:
persist_test = factory.List(index)
if persist_test is None:
break
doc_test = win32com.client.CastTo(
persist_test, "IBODocumentVente3"
)
doc_test.Read()
if (
getattr(doc_test, "DO_Type", -1) == 0
and getattr(doc_test, "DO_Piece", "") == numero_devis
):
persist = persist_test
break
index += 1
except:
index += 1
if not persist:
raise ValueError(f"Devis {numero_devis} introuvable")
doc = win32com.client.CastTo(persist, "IBODocumentVente3")
doc.Read()
statut_actuel = getattr(doc, "DO_Statut", 0)
# Changement de statut
doc.DO_Statut = nouveau_statut
doc.Write()
logger.info(
f"✅ Statut devis {numero_devis}: {statut_actuel}{nouveau_statut}"
)
return {
"numero": numero_devis,
"statut_ancien": statut_actuel,
"statut_nouveau": nouveau_statut,
}
except Exception as e:
logger.error(f"❌ Erreur changement statut: {e}", exc_info=True)
raise RuntimeError(f"Échec changement statut: {str(e)}")
# =========================================================================
# LECTURE DEVIS
# =========================================================================
def lire_devis(self, numero_devis):
"""
Lecture d'un devis (y compris brouillon)
✅ CORRIGÉ: Utilise .Client pour le client et .Article pour les lignes
"""
if not self.cial:
return None
try:
with self._com_context(), self._lock_com:
factory = self.cial.FactoryDocumentVente
# ✅ PRIORITÉ 1: Essayer ReadPiece (documents validés)
persist = factory.ReadPiece(0, numero_devis)
# ✅ PRIORITÉ 2: Rechercher dans la liste (brouillons)
if not persist:
index = 1
while index < 10000:
try:
persist_test = factory.List(index)
if persist_test is None:
break
doc_test = win32com.client.CastTo(
persist_test, "IBODocumentVente3"
)
doc_test.Read()
if (
getattr(doc_test, "DO_Type", -1) == 0
and getattr(doc_test, "DO_Piece", "") == numero_devis
):
persist = persist_test
break
index += 1
except:
index += 1
if not persist:
logger.warning(f"Devis {numero_devis} introuvable")
return None
doc = win32com.client.CastTo(persist, "IBODocumentVente3")
doc.Read()
# ✅ CHARGEMENT CLIENT VIA .Client
client_code = ""
client_intitule = ""
try:
client_obj = getattr(doc, "Client", None)
if client_obj:
client_obj.Read()
client_code = getattr(client_obj, "CT_Num", "").strip()
client_intitule = getattr(client_obj, "CT_Intitule", "").strip()
logger.debug(
f"Client chargé via .Client: {client_code} - {client_intitule}"
)
except Exception as e:
logger.debug(f"Erreur chargement client: {e}")
# Fallback sur cache si disponible
if client_code:
client_obj_cache = self.lire_client(client_code)
if client_obj_cache:
client_intitule = client_obj_cache.get("intitule", "")
devis = {
"numero": getattr(doc, "DO_Piece", ""),
"date": str(getattr(doc, "DO_Date", "")),
"client_code": client_code,
"client_intitule": client_intitule,
"total_ht": float(getattr(doc, "DO_TotalHT", 0.0)),
"total_ttc": float(getattr(doc, "DO_TotalTTC", 0.0)),
"statut": getattr(doc, "DO_Statut", 0),
"lignes": [],
}
# Lecture des lignes
try:
factory_lignes = doc.FactoryDocumentLigne
except:
factory_lignes = doc.FactoryDocumentVenteLigne
index = 1
while True:
try:
ligne_persist = factory_lignes.List(index)
if ligne_persist is None:
break
ligne = win32com.client.CastTo(
ligne_persist, "IBODocumentLigne3"
)
ligne.Read()
# ✅✅✅ CHARGEMENT ARTICLE VIA .Article ✅✅✅
article_ref = ""
try:
# Méthode 1: Essayer AR_Ref direct (parfois disponible)
article_ref = getattr(ligne, "AR_Ref", "").strip()
# Méthode 2: Si vide, utiliser la propriété .Article
if not article_ref:
article_obj = getattr(ligne, "Article", None)
if article_obj:
article_obj.Read()
article_ref = getattr(
article_obj, "AR_Ref", ""
).strip()
logger.debug(
f"Article chargé via .Article: {article_ref}"
)
except Exception as e:
logger.debug(
f"Erreur chargement article ligne {index}: {e}"
)
devis["lignes"].append(
{
"article": article_ref,
"designation": getattr(ligne, "DL_Design", ""),
"quantite": float(getattr(ligne, "DL_Qte", 0.0)),
"prix_unitaire": float(
getattr(ligne, "DL_PrixUnitaire", 0.0)
),
"montant_ht": float(
getattr(ligne, "DL_MontantHT", 0.0)
),
}
)
index += 1
except Exception as e:
logger.debug(f"Erreur lecture ligne {index}: {e}")
break
logger.info(
f"✅ Devis {numero_devis} lu: {len(devis['lignes'])} lignes, {devis['total_ttc']:.2f}€, client: {client_intitule}"
)
return devis
except Exception as e:
logger.error(f"❌ Erreur lecture devis {numero_devis}: {e}")
return None
def lire_document(self, numero, type_doc):
"""Lecture générique document (pour PDF)"""
if type_doc == 0:
return self.lire_devis(numero)
try:
with self._com_context(), self._lock_com:
factory = self.cial.FactoryDocumentVente
persist = factory.ReadPiece(type_doc, numero)
if not persist:
return None
doc = win32com.client.CastTo(persist, "IBODocumentVente3")
doc.Read()
# Lire lignes
lignes = []
try:
factory_lignes = doc.FactoryDocumentLigne
except:
factory_lignes = doc.FactoryDocumentVenteLigne
index = 1
while True:
try:
ligne_p = factory_lignes.List(index)
if ligne_p is None:
break
ligne = win32com.client.CastTo(ligne_p, "IBODocumentLigne3")
ligne.Read()
lignes.append(
{
"designation": getattr(ligne, "DL_Design", ""),
"quantite": getattr(ligne, "DL_Qte", 0.0),
"prix_unitaire": getattr(ligne, "DL_PrixUnitaire", 0.0),
"montant_ht": getattr(ligne, "DL_MontantHT", 0.0),
}
)
index += 1
except:
break
return {
"numero": getattr(doc, "DO_Piece", ""),
"date": str(getattr(doc, "DO_Date", "")),
"client_code": getattr(doc, "CT_Num", ""),
"client_intitule": getattr(doc, "CT_Intitule", ""),
"total_ht": getattr(doc, "DO_TotalHT", 0.0),
"total_ttc": getattr(doc, "DO_TotalTTC", 0.0),
"lignes": lignes,
}
except Exception as e:
logger.error(f" Erreur lecture document: {e}")
return None
# =========================================================================
# TRANSFORMATION (US-A2)
# =========================================================================
def transformer_document(self, numero_source, type_source, type_cible):
"""
Transformer un document
"""
if not self.cial:
raise RuntimeError("Connexion Sage non établie")
try:
with self._com_context(), self._lock_com:
# Lecture source
factory = self.cial.FactoryDocumentVente
persist_source = factory.ReadPiece(type_source, numero_source)
if not persist_source:
raise ValueError(f"Document {numero_source} introuvable")
doc_source = win32com.client.CastTo(persist_source, "IBODocumentVente3")
doc_source.Read()
# Récupérer client
client_code = ""
try:
client_obj = getattr(doc_source, "Client", None)
if client_obj:
client_obj.Read()
client_code = getattr(client_obj, "CT_Num", "")
except:
pass
if not client_code:
raise ValueError(
f"Impossible de récupérer le client du document {numero_source}"
)
# Transaction
transaction_active = False
try:
self.cial.CptaApplication.BeginTrans()
transaction_active = True
except Exception as e:
logger.warning(f"⚠️ BeginTrans échoué: {e}")
try:
# ✅ CORRECTION: Utiliser CreateProcess_Document (pas CreateProcess_DocumentVente)
process = self.cial.CreateProcess_Document(type_cible)
doc_cible = process.Document
try:
doc_cible = win32com.client.CastTo(
doc_cible, "IBODocumentVente3"
)
except:
pass
logger.info(f"📄 Document cible créé (type {type_cible})")
# Associer client
factory_client = self.cial.CptaApplication.FactoryClient
persist_client = factory_client.ReadNumero(client_code)
if not persist_client:
raise ValueError(f"Client {client_code} introuvable")
client_obj_cible = win32com.client.CastTo(
persist_client, "IBOClient3"
)
client_obj_cible.Read()
doc_cible.SetDefaultClient(client_obj_cible)
doc_cible.Write()
logger.info(f"👤 Client {client_code} associé")
# Date
import pywintypes
doc_cible.DO_Date = pywintypes.Time(datetime.now())
# Référence
try:
doc_cible.DO_Ref = f"Trans. {numero_source}"
except:
pass
# ✅ STATUT INITIAL pour commande/facture
if type_cible == 3: # Commande
doc_cible.DO_Statut = 0 # En cours
elif type_cible == 5: # Facture
doc_cible.DO_Statut = 0 # Non réglée
doc_cible.Write()
# Copie lignes
try:
factory_lignes_source = doc_source.FactoryDocumentLigne
factory_lignes_cible = doc_cible.FactoryDocumentLigne
except:
factory_lignes_source = doc_source.FactoryDocumentVenteLigne
factory_lignes_cible = doc_cible.FactoryDocumentVenteLigne
factory_article = self.cial.FactoryArticle
index = 1
nb_lignes = 0
while index <= 1000:
try:
ligne_source_p = factory_lignes_source.List(index)
if ligne_source_p is None:
break
ligne_source = win32com.client.CastTo(
ligne_source_p, "IBODocumentLigne3"
)
ligne_source.Read()
# Créer ligne cible
ligne_cible_p = factory_lignes_cible.Create()
ligne_cible = win32com.client.CastTo(
ligne_cible_p, "IBODocumentLigne3"
)
# Article
article_ref = ""
try:
article_ref = getattr(
ligne_source, "AR_Ref", ""
).strip()
if not article_ref:
article_obj = getattr(ligne_source, "Article", None)
if article_obj:
article_obj.Read()
article_ref = getattr(
article_obj, "AR_Ref", ""
).strip()
except:
pass
# Associer article
if article_ref:
try:
persist_article = factory_article.ReadReference(
article_ref
)
if persist_article:
article_obj = win32com.client.CastTo(
persist_article, "IBOArticle3"
)
article_obj.Read()
quantite = float(
getattr(ligne_source, "DL_Qte", 1.0)
)
try:
ligne_cible.SetDefaultArticleReference(
article_ref, quantite
)
except:
ligne_cible.SetDefaultArticle(
article_obj, quantite
)
except Exception as e:
logger.debug(
f"Erreur association article {article_ref}: {e}"
)
# Copier propriétés
ligne_cible.DL_Design = getattr(
ligne_source, "DL_Design", ""
)
ligne_cible.DL_Qte = float(
getattr(ligne_source, "DL_Qte", 0.0)
)
ligne_cible.DL_PrixUnitaire = float(
getattr(ligne_source, "DL_PrixUnitaire", 0.0)
)
# Remise
try:
remise = float(
getattr(ligne_source, "DL_Remise01REM_Valeur", 0.0)
)
if remise > 0:
ligne_cible.DL_Remise01REM_Valeur = remise
ligne_cible.DL_Remise01REM_Type = 0
except:
pass
ligne_cible.Write()
nb_lignes += 1
index += 1
except Exception as e:
logger.debug(f"Erreur ligne {index}: {e}")
index += 1
# Validation finale
doc_cible.Write()
process.Process()
# Récupération numéro
numero_cible = None
try:
doc_result = process.DocumentResult
if doc_result:
doc_result = win32com.client.CastTo(
doc_result, "IBODocumentVente3"
)
doc_result.Read()
numero_cible = getattr(doc_result, "DO_Piece", "")
except:
pass
if not numero_cible:
numero_cible = getattr(doc_cible, "DO_Piece", "")
if not numero_cible:
raise RuntimeError("Numéro document cible vide")
# Commit
if transaction_active:
self.cial.CptaApplication.CommitTrans()
logger.info("✅ Transaction committée")
# ✅ MAJ statut source (devis → transformé)
if type_source == 0 and type_cible == 3:
try:
doc_source.DO_Statut = 5 # Transformé
doc_source.Write()
logger.info("✅ Statut source: TRANSFORMÉ (5)")
except Exception as e:
logger.warning(f"Impossible de MAJ statut source: {e}")
logger.info(
f"✅ Transformation: {numero_source} ({type_source}) → {numero_cible} ({type_cible}), {nb_lignes} lignes"
)
return {
"success": True,
"document_source": numero_source,
"document_cible": numero_cible,
"nb_lignes": nb_lignes,
}
except Exception as e:
if transaction_active:
try:
self.cial.CptaApplication.RollbackTrans()
logger.error("❌ Transaction annulée")
except:
pass
raise
except Exception as e:
logger.error(f"❌ Erreur transformation: {e}", exc_info=True)
raise RuntimeError(f"Échec transformation: {str(e)}")
# =========================================================================
# CHAMPS LIBRES (US-A3)
# =========================================================================
def mettre_a_jour_champ_libre(self, doc_id, type_doc, nom_champ, valeur):
"""Mise à jour champ libre pour Universign ID"""
try:
with self._com_context(), self._lock_com:
factory = self.cial.FactoryDocumentVente
persist = factory.ReadPiece(type_doc, doc_id)
if persist:
doc = win32com.client.CastTo(persist, "IBODocumentVente3")
doc.Read()
try:
setattr(doc, f"DO_{nom_champ}", valeur)
doc.Write()
logger.debug(f"Champ libre {nom_champ} = {valeur} sur {doc_id}")
return True
except Exception as e:
logger.warning(f"Impossible de mettre à jour {nom_champ}: {e}")
except Exception as e:
logger.error(f"Erreur MAJ champ libre: {e}")
return False
def _lire_client_obj(self, code_client):
"""Retourne l'objet client Sage brut (pour remises)"""
if not self.cial:
return None
try:
with self._com_context(), self._lock_com:
factory = self.cial.CptaApplication.FactoryClient
persist = factory.ReadNumero(code_client)
if persist:
return self._cast_client(persist)
except:
pass
return None
# =========================================================================
# US-A6 - LECTURE CONTACTS
# =========================================================================
def lire_contact_principal_client(self, code_client):
"""
NOUVEAU: Lecture contact principal d'un client
Pour US-A6: relance devis via Universign
Récupère l'email du contact principal pour l'envoi
"""
if not self.cial:
return None
try:
with self._com_context(), self._lock_com:
factory_client = self.cial.CptaApplication.FactoryClient
persist_client = factory_client.ReadNumero(code_client)
if not persist_client:
return None
client = self._cast_client(persist_client)
if not client:
return None
# Récupérer infos contact principal
contact_info = {
"client_code": code_client,
"client_intitule": getattr(client, "CT_Intitule", ""),
"email": None,
"nom": None,
"telephone": None,
}
# Email principal depuis Telecom
try:
telecom = getattr(client, "Telecom", None)
if telecom:
contact_info["email"] = getattr(telecom, "EMail", "")
contact_info["telephone"] = getattr(telecom, "Telephone", "")
except:
pass
# Nom du contact
try:
contact_info["nom"] = (
getattr(client, "CT_Contact", "")
or contact_info["client_intitule"]
)
except:
contact_info["nom"] = contact_info["client_intitule"]
return contact_info
except Exception as e:
logger.error(f"Erreur lecture contact client {code_client}: {e}")
return None
# =========================================================================
# US-A7 - MAJ CHAMP DERNIERE RELANCE
# =========================================================================
def mettre_a_jour_derniere_relance(self, doc_id, type_doc):
"""
NOUVEAU: Met à jour le champ libre "Dernière relance"
Pour US-A7: relance facture en un clic
"""
date_relance = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return self.mettre_a_jour_champ_libre(
doc_id, type_doc, "DerniereRelance", date_relance
)