Jelajahi Sumber

Refonte schema mn1 en version tests unitaires

omassot 7 tahun lalu
induk
melakukan
551ebb9cb3
10 mengubah file dengan 730 tambahan dan 235 penghapusan
  1. 43 32
      core/checking.py
  2. 1 1
      core/logging.yaml
  3. 1 1
      core/logging_.py
  4. 23 22
      core/mncheck.py
  5. 3 4
      main.py
  6. 439 0
      schemas/_mn2_rec.py
  7. 157 140
      schemas/mn1_rec.py
  8. 63 35
      ui/dlg_main.py
  9. TEMPAT SAMPAH
      ui/rsc/warning2_16.png
  10. TEMPAT SAMPAH
      ui/rsc/warning_16.png

+ 43 - 32
core/checker.py → core/checking.py

@@ -6,6 +6,7 @@
 '''
 import inspect
 import sys
+import traceback
 
 
 UNKNOWN = 0
@@ -18,6 +19,13 @@ _result_to_str = {UNKNOWN: 'Inconnu',
                   FAILURE: 'Echec',
                   ERROR: 'Erreur'}
 
+def _linenumber(m):
+    try:
+        _, line_no = inspect.findsource(m)
+        return line_no
+    except AttributeError:
+        return -1
+
 class TestError():
     def __init__(self, message, info = {}, critical=False):
         self.message = message
@@ -25,13 +33,13 @@ class TestError():
         self.critical = critical
         
     def __repr__(self):
-        return f"TestError<message='{self.message}'; info={self.info}; critical={self.critical}>"
+        return f"TestError[message='{self.message}'; info={self.info}; critical={self.critical}]"
 
 class TestResult():
     def __init__(self, test):
         self._test = test
         self._name = ""
-        self._status = UNKNOWN
+        self._status = SUCCESS
         self.errors = []
         self._exc_info = None
 
@@ -56,17 +64,18 @@ class TestResult():
         return _result_to_str[self._status]
 
     def __repr__(self):
-        return f"TestResult<title='{self.title}'; status={self.status}; name={self.name}; method={self._test.__name__}; errors_count={len(self.errors)}>"
+        return f"TestResult[title='{self.title}'; status={self.status}; name={self.name}; method={self._test.__name__}; errors_count={len(self.errors)}]"
 
-    def log_error(self, message, info={}):
+    def log_error(self, message, info={}, critical=False):
         self._status = FAILURE
-        error = TestError(message, info)
+        error = TestError(message, info, critical)
         self.errors.append(error)
 
-    def handle_exception(self):
+    def handle_exception(self, exc_info):
         self._status = ERROR
+        typ, value, trace = exc_info
         error = TestError("Une erreur inconnue s'est produite, veuillez consulter les fichiers de journalisation.", 
-                          {"exc_info": sys.exc_info()})
+                          {"exc_info": "{}\n{}\n{}".format(typ.__name__, value, ''.join(traceback.format_tb(trace)))})
         self.errors.append(error)
 
 class BaseChecker():
@@ -82,49 +91,51 @@ class BaseChecker():
     
     def log_error(self, message, **info):
         self._test_running.log_error(message, info)
+        
+    def log_critical(self, message, **info):
+        self._test_running.log_error(f"[CRITIQUE] {message}", info, critical=True)
     
     def run(self):
         
         tests_results = []
         
-        for mname, m in inspect.getmembers(self, predicate=inspect.ismethod):
-            if mname[:5] == 'test_':
-                
-                r = TestResult(m)
-                
-                self._test_running = r
-                
-                self.setUp()
-                
-                try:
-                    m()
-                except:
-                    r.handle_exception()
-                
-                self.tearDown()
-
-                tests_results.append(r)
+        tests = sorted([m for _, m in inspect.getmembers(self, predicate=inspect.ismethod) if m.__name__[:5] == 'test_'], key=_linenumber)
         
-                if any(err.critical for err in r.errors):
-                    break
+        for test in tests:
+            
+            result = TestResult(test)
+            
+            self._test_running = result
+            
+            self.setUp()
+            
+            try:
+                test()
+            except:
+                result.handle_exception(sys.exc_info())
+            
+            self.tearDown()
+
+            tests_results.append(result)
+    
+            if any(err.critical for err in result.errors):
+                break
         
         return tests_results
     
-
-    
-    
 if __name__ == '__main__':
     
     class ExampleChecker(BaseChecker):
-        def test_a(self):
+        def test_c(self):
             """ Test 1 """
             for i in range(10):
-                self.log_error(f"error-{i}", {"i": i})
+                self.log_error(f"error-{i}", i=i)
         
         def test_b(self):
             """ Test 2
             some longer description """
-            return
+            raise Exception("bla bla")
+
     
     ch = ExampleChecker()
     results = ch.run()

+ 1 - 1
core/logging.yaml

@@ -12,7 +12,7 @@ formatters:
         
 handlers:
     qgis:
-        class: core.QgsLogHandler.QgsLogHandler
+        class: core.logging_.QgsLogHandler
         level: DEBUG
         formatter: message_only
         

+ 1 - 1
core/logconf.py → core/logging_.py

@@ -34,7 +34,7 @@ class QgsLogHandler(logging.Handler):
             msg = self.format(record)
             level = record.levelno
             
-            QgsMessageLog.logMessage(msg, "Mnheck", _to_qgis_level[level])
+            QgsMessageLog.logMessage(msg, "MnCheck", _to_qgis_level[level])
             
             if self._qgs_iface and record.levelno >= logging.WARNING:
                 self._qgs_iface.messageBar().pushMessage("MnCheck", msg, level=_to_qgis_level[level])

+ 23 - 22
core/mncheck.py

@@ -3,13 +3,16 @@
 @author: olivier.massot, 2018
 '''
 import importlib
+import inspect
 import logging
 import pkgutil
-
 from qgis.core import QgsWkbTypes, QgsGeometry, QgsPoint
 
 from PyQt5.QtCore import QVariant
 
+from core.checking import BaseChecker
+
+
 logger = logging.getLogger("mncheck")
 
 
@@ -20,6 +23,9 @@ def list_schemas():
 def get_schema(schema_name):
     return importlib.import_module("schemas." + schema_name)
 
+def get_checkers(schema):
+    return [cls for _, cls in inspect.getmembers(schema, predicate=inspect.isclass) \
+            if issubclass(cls, BaseChecker) and not cls is BaseChecker]
 
 class QgsModel():
     
@@ -38,34 +44,29 @@ class QgsModel():
     geom_type = 0
     bounding_box = (0,0,1,1)
     schema = {}
+    pk = ""
 
     def __init__(self, qgs_feature):
         self._feature = qgs_feature
         
-#         attributes = dict(zip([f.name() for f in qgs_feature.fields()], qgs_feature.attributes()))
-#         
-#         for attr, value in attributes.items():
-#             if isinstance(value, QVariant):
-#                 value = value.value() if not value.isNull() else ""
-#             setattr(self, attr, value)
-    
-    def __getattribute__(self, name):
-        try:
-            return super().__getattribute__(name)
-        except AttributeError:
-            pass
+        self.__dict__.update(self.attributes())
         
-        try:
-            index = [f.name().lower() for f in self._feature.fields()].index(name.lower())
-            return self._feature.attribute(index)
-        except ValueError:
-            pass
-                
-        raise AttributeError()
+    @staticmethod
+    def _clean_attr(self, value=None):
+        if isinstance(value, QVariant):
+            return value.value() if not value.isNull() else ""
+        elif value is None:
+            return ""
+        else:
+            return value
     
     @property
+    def feature(self):
+        return self._feature
+    
     def attributes(self):
-        return dict(zip([f.name() for f in self._feature.fields()], self._feature.attributes()))
+        return dict(zip([f.name() for f in self._feature.fields()], 
+                        [QgsModel._clean_attr(a) for a in self._feature.attributes()]))
     
     @property
     def geom(self):
@@ -77,7 +78,7 @@ class QgsModel():
     def get_geom_type(self):
         return QgsWkbTypes.singleType(self._feature.geometry().wkbType())
         
-    def bounding_box(self):
+    def get_bounding_box(self):
         bb = self._feature.geometry().boundingBox()
         return (bb.xMinimum(), bb.yMinimum(), bb.xMaximum(), bb.yMaximum())
     

+ 3 - 4
main.py

@@ -15,8 +15,7 @@ import logging
 from PyQt5.QtGui import QIcon
 from PyQt5.QtWidgets import QAction
 
-from core import logconf
-from core.QgsLogHandler import QgsLogHandler
+from core import logging_
 from core.constants import MAIN
 from ui.dlg_main import DlgMain
 
@@ -24,7 +23,7 @@ from ui.dlg_main import DlgMain
 __VERSION__ = "0.1.0"
 
 logger = logging.getLogger("mncheck")
-logconf.start("mncheck", logging.DEBUG)
+logging_.start("mncheck", logging.DEBUG)
 
 
 logger.info("* loading plugin")
@@ -64,7 +63,7 @@ class MnCheck:
     def initGui(self):
         """Create the menu entries and toolbar icons inside the QGIS GUI."""
         
-        QgsLogHandler.connect_to_iface(self.iface)
+        logging_.QgsLogHandler.connect_to_iface(self.iface)
         
         self.add_action(MAIN / 'icon.png', 
                         text='MnCheck', 

+ 439 - 0
schemas/_mn2_rec.py

@@ -0,0 +1,439 @@
+'''
+
+    Schéma de validation des données MN2
+
+@author: olivier.massot, 2018
+'''
+import logging
+from qgis.core import QgsGeometry
+
+from core.cerberus_ import is_float, is_multi_int, is_int, \
+    is_modern_french_date
+from core.validation_errors import UniqueError, RelationError, \
+    DuplicatedGeom, MissingItem, DimensionError, TechnicalValidationError
+from core.validator import QgsModel, BaseValidator
+
+
+logger = logging.getLogger("mncheck")
+
+
+SCHEMA_NAME = "Schéma MN v2 REC"
+
+
+STATUTS = ['EN ETUDE', 'EN REALISATION', 'EN SERVICE', 'HORS SERVICE']
+
+XMIN, XMAX, YMIN, YMAX = 1341999, 1429750, 8147750, 8294000
+CRS = 'EPSG:3949' # Coordinate Reference System
+
+TOLERANCE = 1
+
+##### Modeles
+
+
+class Artere(QgsModel):
+    layername = "artere_geo"
+    geom_type = QgsModel.GEOM_LINE
+    crs = CRS
+    bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    schema = {'AR_CODE': {'type': 'string', 'maxlength': 26},
+              'AR_NOM': {'type': 'string', 'maxlength': 26}, 
+              'AR_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'}, 
+              'AR_LONG': {'empty': False, 'validator': is_float},
+              'AR_ETAT': {'type': 'string', 'empty': False, 'allowed': ['0', '1', '2', '3', '4']}, 
+              'AR_OCCP': {'type': 'string', 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']}, 
+              'AR_NOEUD_A': {'type': 'string', 'empty': False, 'maxlength': 20}, 
+              'AR_NOEUD_B': {'type': 'string', 'empty': False, 'maxlength': 20}, 
+              'AR_NB_FOUR': {'empty': False, 'validator': is_multi_int}, 
+              'AR_FOU_DIS': {'empty': False, 'validator': is_int}, 
+              'AR_TYPE_FO': {'type': 'string', 'multiallowed': ['PVC', 'PEHD', 'SOUS-TUBAGE PEHD', 'SOUS-TUBAGE  SOUPLE', 'FACADE', 'AERIEN', 'ENCORBELLEMENT', 'AUTRE']}, 
+              'AR_TYFO_AI': {'type': 'string', 'multiallowed': ['PVC', 'PEH', 'TUB', 'FAC', 'ENC', 'APP']}, 
+              'AR_DIAM_FO': {'type': 'string', 'multiallowed': ['10', '14', '18', '25', '28', '32', '40', '45', '60', '80', '150', 'NUL']}, 
+              'AR_PRO_FOU': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'PRIVE', 'ERDF', 'AUTRE (à préciser)']}, 
+              'AR_FABRICANT': {'type': 'string', 'empty': False, 'maxlength': 100},
+              'AR_REF_FABRICANT': {'type': 'string', 'empty': False, 'maxlength': 100},
+              'AR_COULEUR': {'type': 'string', 'empty': False, 'maxlength': 20},
+              'AR_AIGUILLEE': {'type': 'string', 'empty': False, 'maxlength': 3, 'allowed': ['OUI', 'NON']},
+              'AR_NB_CABLES': {'empty': False, 'validator': is_int},
+              'AR_PRO_CAB': {'type': 'string', 'empty': False, 'allowed': ['MANCHE NUMERIQUE']}, 
+              'AR_GEST_FO': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'ERDF', 'AUTRE (à préciser)', 'NUL']}, 
+              'AR_UTIL_FO': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']}, 
+              'AR_DATE_IN': {'empty': False, 'validator': is_modern_french_date}, 
+              'AR_DATE_RE': {'empty': False, 'validator': is_modern_french_date}, 
+              'AR_REF_PLA': {'type': 'string', 'maxlength': 100}, 
+              'AR_SRC_GEO': {'type': 'string', 'maxlength': 50}, 
+              'AR_QLT_GEO': {'type': 'string', 'empty': False, 'allowed': ['A', 'B', 'C']}, 
+              'AR_PRO_MD': {'type': 'string', 'empty': False, 'default': 'MANCHE NUMERIQUE', 'allowed': ['MANCHE NUMERIQUE']}, 
+              'AR_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True}, 
+              'AR_STATUT': {'type': 'string', 'empty': False, 'allowed': STATUTS}}
+
+    def __repr__(self):
+        return "Artere {}".format(self.AR_CODE)
+
+class Cable(QgsModel):
+    layername = "cable_geo"
+    geom_type = QgsModel.GEOM_LINE
+    crs = CRS
+    bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    schema = {'CA_CODE': {'type': 'string', 'maxlength': 18}, 
+              'CA_NOM': {'type': 'string', 'maxlength': 18}, 
+              'CA_NUMERO': {'type': 'string', 'maxlength': 17},  
+              'CA_EMPRISE': {'type': 'string', 'maxlength': 10}, 
+              'CA_FAB': {'type': 'string', 'maxlength': 100}, 
+              'CA_REFFAB': {'type': 'string', 'maxlength': 100}, 
+              'CA_MODELE': {'type': 'string', 'maxlength': 10}, 
+              'CA_TYPE': {'type': 'string', 'maxlength': 10, 'empty': False, 'allowed': ['AERIEN', 'IMMEUBLE', 'FACADE', 'MIXTE', 'SOUTERRAIN']},
+              'CA_TYPFCT': {'type': 'string', 'maxlength': 3, 'empty': False, 'allowed': ['CDI', 'CTR', 'CBM', 'RAC', 'CBO']},
+              'CA_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']}, 
+              'CA_LONG': {'validator': is_float}, 
+              'CA_EQ_A': {'type': 'string', 'maxlength': 18}, 
+              'CA_EQ_B': {'type': 'string', 'maxlength': 18}, 
+              'CA_DIAMETR': {'empty': False, 'validator': is_float}, 
+              'CA_COULEUR': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['NOIR', 'BLEU', 'BLANC']}, 
+              'CA_TECHNOL': {'type': 'string', 'maxlength': 17, 'empty': False, 'allowed': ['G657A2_M6', 'G657A2_M12']}, 
+              'CA_NB_FO': {'validator': is_int}, 
+              'CA_NB_FO_U': {'empty': False, 'validator': is_int}, 
+              'CA_NB_FO_D': {'empty': False, 'validator': is_int}, 
+              'CA_PRO': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE']}, 
+              'CA_GEST': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE FIBRE']}, 
+              'CA_DATE_IN': {'empty': False, 'validator': is_modern_french_date}, 
+              'CA_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True}, 
+              'CA_STATUT': {'type': 'string', 'empty': False, 'allowed': STATUTS}}
+
+    def __repr__(self):
+        return "Cable {}-{}".format(self.CA_EQ_A, self.CA_EQ_B)
+    
+class Equipement(QgsModel):
+    layername = "equipement_passif"
+    geom_type = QgsModel.GEOM_POINT
+    crs = CRS
+    bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    schema = {'EQ_CODE': {'type': 'string', 'maxlength': 18}, 
+              'EQ_NOM': {'type': 'string', 'maxlength': 10, 'contains_any_of': ['PBO', 'BPE', 'BAI']}, 
+              'EQ_NOM_NOE': {'type': 'string', 'maxlength': 30}, 
+              'EQ_REF': {'type': 'string', 'maxlength': 100}, 
+              'EQ_EMPRISE': {'type': 'string', 'maxlength': 7}, 
+              'EQ_FABR': {'type': 'string', 'maxlength': 100}, 
+              'EQ_CAPFO': {'empty': False, 'validator': is_int}, 
+              'EQ_NBMXEQ': {'empty': False, 'validator': is_int}, 
+              'EQ_NBCAB': {'empty': False, 'validator': is_int}, 
+              'EQ_DIMENS': {'type': 'string', 'maxlength': 50}, 
+              'EQ_TYPEQ': {'type': 'string', 'maxlength': 100}, 
+              'EQ_ETAT': {'type': 'string', 'empty': False, 'allowed': ['0', '1', '2', '3', '4']}, 
+              'EQ_OCCP': {'type': 'string', 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']}, 
+              'EQ_TYPE': {'type': 'string', 'empty': False, 'allowed': ['PBO', 'PBOE', 'BPE', 'BAI']},
+              'EQ_TYPSTRC': {'type': 'string', 'empty': False, 'allowed': ['CHAMBRE', 'AERIEN', 'FACADE', 'COLONNE MONTANTE', 'PIED IMMEUBLE', 'DTIO']}, 
+              'EQ_TYPE_LQ': {'type': 'string', 'empty': False, 'allowed': ['PBO', 'BPE JB', 'BPE JD', 'BAIDC', 'BAIOP']}, 
+              'EQ_TYPE_PH': {'type': 'string', 'empty': False, 'allowed': ['PBO 6', 'PBO 12', 'BPE 12EP', 'BPE 24EP', 'BPE 48EP', 'BPE 72EP', 'BPE 96EP', 'BPE 144EP', 'BPE 288EP', 'BPE 576EP', 'BPE 720EP', 'BAI']}, 
+              'EQ_PRO': {'type': 'string', 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']}, 
+              'EQ_GEST': {'type': 'string', 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']}, 
+              'EQ_HAUT': {'empty': False, 'validator': is_float}, 
+              'EQ_DATE_IN': {'empty': False, 'validator': is_modern_french_date}, 
+              'EQ_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True}, 
+              'EQ_STATUT': {'type': 'string', 'empty': False, 'allowed': STATUTS}}
+        
+    def __repr__(self):
+        return "Equipement {}".format(self.EQ_NOM)
+
+class Noeud(QgsModel):
+    layername = "noeud_geo"
+    geom_type = QgsModel.GEOM_POINT
+    crs = CRS
+    bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    schema = {'NO_CODE': {'type': 'string', 'maxlength': 18}, 
+              'NO_NOM': {'type': 'string', 'maxlength': 30}, 
+              'NO_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'}, 
+              'NO_VOIE': {'type': 'string', 'maxlength': 100}, 
+              'NO_EMPRISE': {'type': 'string', 'maxlength': 10}, 
+              'NO_ETAT': {'type': 'string', 'empty': False, 'allowed': ['0', '1', '2', '3', '4']}, 
+              'NO_OCCP': {'type': 'string', 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']}, 
+              'NO_TYPE': {'type': 'string', 'empty': False, 'allowed': ['CHA', 'POT', 'LTE', 'SEM', 'FAC', 'OUV', 'IMM']}, 
+              'NO_TYPFCT': {'type': 'string', 'empty': False, 'allowed': ['INTERCONNEXION', 'SATELLITE', 'PASSAGE', 'REGARD', 'INDETERMINE']}, 
+              'NO_TYPE_LQ': {'type': 'string', 'empty': False, 'allowed': ['CHTIR', 'CHRACC', 'POT', 'NRO', 'PM', 'MIMO', 'FAC', 'OUV', 'IMM']}, 
+              'NO_TYPE_PH': {'type': 'string', 'empty': False, 'allowed': ['CHAMBRE', 'POTEAU', 'ARMOIRE', 'SHELTER', 'BATIMENT', 'SITE MIMO', 'FACADE', 'OUVRAGE', 'IMMEUBLE']}, 
+              'NO_CODE_PH': {'type': 'string', 'maxlength': 20}, 
+              'NO_TECH_PS': {'type': 'string', 'maxlength': 20, 'multiallowed': ['COAX', 'CUT', 'ECL', 'ELEC', 'VP', 'OPT', 'NC']}, 
+              'NO_AMO': {'type': 'string', 'maxlength': 20}, 
+              'NO_PLINOX': {'required':False, 'type': 'string', 'maxlength': 3, 'allowed': ['OUI', 'NON']}, 
+              'NO_X': {'empty': False, 'validator': is_float}, 
+              'NO_Y': {'empty': False, 'validator': is_float}, 
+              'NO_PRO': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'ERDF', 'PRIVE', 'ENEDIS', 'AUTRE (à préciser)', 'NUL']}, 
+              'NO_GEST': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'ERDF', 'ENEDIS', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']}, 
+              'NO_HAUT': {'empty': False, 'validator': is_float}, 
+              'NO_DATE_IN': {'empty': False, 'validator': is_modern_french_date}, 
+              'NO_REF_PLA': {'type': 'string', 'maxlength': 100}, 
+              'NO_SRC_GEO': {'type': 'string', 'maxlength': 50}, 
+              'NO_QLT_GEO': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['A', 'B', 'C']}, 
+              'NO_PRO_MD': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE']}, 
+              'NO_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True}, 
+              'NO_STATUT': {'type': 'string', 'empty': False, 'allowed': STATUTS}}
+
+    def __repr__(self):
+        return "Noeud {}".format(self.NO_NOM)
+    
+class Tranchee(QgsModel):
+    layername = "tranchee_geo"
+    geom_type = QgsModel.GEOM_LINE
+    crs = CRS
+    bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    schema = {'TR_CODE': {'type': 'string', 'maxlength': 23}, 
+              'TR_NOM': {'type': 'string', 'maxlength': 23}, 
+              'TR_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'}, 
+              'TR_VOIE': {'type': 'string', 'maxlength': 200}, 
+              'TR_TYP_IMP': {'type': 'string', 'empty': False, 'allowed': ['ACCOTEMENT STABILISE', 'ACCOTEMENT NON STABILISE', 'CHAUSSEE LOURDE', 'CHAUSSEE LEGERE', 'FOSSE', 'TROTTOIR', 'ESPACE VERT', 'ENCORBELLEMENT']}, 
+              'TR_MOD_POS': {'type': 'string', 'empty': False, 'allowed': ['TRADITIONNEL', 'MICRO TRANCHEE', 'FONCAGE 60', 'FONCAGE 90', 'FONCAGE 120', 'TRANCHEUSE', 'FORAGE URBAIN', 'FORAGE RURAL', 'ENCORBELLEMENT']}, 
+              'TR_MPOS_AI': {'type': 'string', 'empty': False, 'allowed': ['TRA', 'ALL', 'FONCAGE 60', 'FON', 'FOR', 'ENC']}, 
+              'TR_LONG': {'empty': False, 'validator': is_float}, 
+              'TR_LARG': {'empty': False, 'validator': is_float}, 
+              'TR_REVET': {'empty':True, 'type': 'string', 'allowed': ['SABLE', 'BICOUCHE', 'ENROBE', 'BETON', 'PAVE', 'TERRAIN NATUREL']}, 
+              'TR_CHARGE': {'empty': False, 'validator': is_float}, 
+              'TR_GRILLAG': {'empty':True, 'validator': is_float}, 
+              'TR_REMBLAI': {'type': 'string'}, 
+              'TR_PLYNOX': {'type': 'string', 'empty': False, 'allowed': ['OUI', 'NON']}, 
+              'TR_PRO_VOI': {'type': 'string', 'empty': False, 'allowed': ['COMMUNE', 'COMMUNAUTE DE COMMUNES', 'DEPARTEMENT', 'ETAT', 'PRIVE']}, 
+              'TR_GEST_VO': {'type': 'string', 'empty': False, 'allowed': ['COMMUNE', 'COMMUNAUTE DE COMMUNES', 'DEPARTEMENT', 'ETAT', 'PRIVE']}, 
+              'TR_SCHEMA': {'maxlength': 100, 'type': 'string'}, 
+              'TR_DATE_IN': {'empty': False, 'validator': is_modern_french_date}, 
+              'TR_SRC_GEO': {'type': 'string', 'maxlength': 50}, 
+              'TR_QLT_GEO': {'type': 'string', 'empty': False, 'allowed': ['A', 'B', 'C']}, 
+              'TR_PRO_MD': {'type': 'string', 'maxlength': 20}, 
+              'TR_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True}, 
+              'TR_STATUT': {'type': 'string', 'empty': False, 'allowed': STATUTS}}
+
+    def __repr__(self):
+        return "Tranchee {}".format(self.TR_VOIE)
+    
+class Zapbo(QgsModel):
+    layername = "zapbo_geo"
+    geom_type = QgsModel.GEOM_POLYGON
+    crs = CRS
+    bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    schema = {'ID_ZAPBO': {'type': 'string', 'maxlength': 30, 'contains_any_of': ['PBO', 'BPE']}, 
+              'COMMENTAIR': {'type': 'string', 'maxlength': 254, 'empty': True}, 
+              'STATUT': {'type': 'string', 'empty': False, 'allowed': STATUTS}}
+    
+    def __repr__(self):
+        return "Zapbo {}".format(self.ID_ZAPBO)
+
+
+
+
+##### Validator
+
+
+class Validator(BaseValidator):
+    schema_name = "MN2 REC"
+    models = [Artere, Cable, Equipement, Noeud, Tranchee, Zapbo]
+    
+    def _technical_validation(self):
+        
+        # construction des index
+        arteres = self.dataset[Artere]
+        cables = self.dataset[Cable]
+        tranchees = self.dataset[Tranchee]
+        
+        noeuds = {}
+        for noeud in self.dataset[Noeud]:
+            if not noeud.NO_NOM in noeuds:
+                noeuds[noeud.NO_NOM] = noeud
+            else:
+                self.log_error(UniqueError("Doublons dans le champs: {}".format(noeud), layername=Noeud.layername, field="NO_NOM"))
+        
+        equipements = {}
+        for equipement in self.dataset[Equipement]:
+            if not equipement.EQ_NOM in equipements:
+                equipements[equipement.EQ_NOM] = equipement
+            else:
+                self.log_error(UniqueError("Doublons dans le champs: {}".format(equipement), layername=Equipement.layername, field="EQ_NOM"))
+                
+        zapbos = {}
+        for zapbo in self.dataset[Zapbo]:
+            if not zapbo.ID_ZAPBO in zapbos:
+                zapbos[zapbo.ID_ZAPBO] = zapbo
+            else:
+                self.log_error(UniqueError("Doublons dans le champs: {}".format(zapbo), layername=Zapbo.layername, field="ID_ZAPBO"))
+        
+        # rattachement les noeuds aux artères     
+        for artere in arteres:
+            try:
+                artere.noeud_a = noeuds[artere.AR_NOEUD_A]
+            except KeyError:
+                artere.noeud_a = None
+                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_A), layername=Artere.layername, field="AR_NOEUD_A"))
+                
+            try:
+                artere.noeud_b = noeuds[artere.AR_NOEUD_B]
+            except KeyError:
+                artere.noeud_b = None
+                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_B), layername=Artere.layername, field="AR_NOEUD_A"))
+        
+        # rattachement des equipements aux cables
+        for cable in cables:
+            try:
+                cable.equipement_a = equipements[cable.CA_EQ_A]
+            except KeyError:
+                cable.equipement_a = None
+                self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.CA_EQ_A), layername=Cable.layername, field="CA_EQ_A"))
+                
+            try:
+                cable.equipement_b = equipements[cable.CA_EQ_B]
+            except KeyError:
+                cable.equipement_b = None
+                self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.CA_EQ_B), layername=Cable.layername, field="CA_EQ_B"))
+
+        # rattachement des equipements aux noeuds
+        for equipement in equipements.values():
+            try:
+                equipement.noeud = noeuds[equipement.EQ_NOM_NOE]
+            except KeyError:
+                equipement.noeud = None
+                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(equipement.EQ_NOM_NOE, equipement.EQ_NOM), layername=Equipement.layername, field="EQ_NOM_NOE"))
+
+        # verifie que tous les equipements sont l'equipement B d'au moins un cable
+        equipements_b = [cable.CA_EQ_B for cable in cables]
+        for eq_id in equipements:
+            if equipements[eq_id].EQ_TYPE == "BAI":
+                continue
+            if not eq_id in equipements_b:
+                self.log_error(RelationError("L'equipement '{}' n'est l'équipement B d'aucun cable".format(eq_id), layername=Equipement.layername, field="EQ_NOM"))
+
+        # controle des doublons graphiques
+        for i, tranchee in enumerate(tranchees):
+            for other in tranchees[i+1:]:
+                if tranchee.geom == other.geom:
+                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée".format(tranchee), layername=Tranchee.layername, field="geom"))
+                    
+        for i, artere in enumerate(arteres):
+            for other in arteres[i+1:]:
+                if artere.geom == other.geom:
+                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(artere), layername=Artere.layername, field="geom"))
+
+        for i, cable in enumerate(cables):
+            for other in cables[i+1:]:
+                if cable.geom == other.geom and cable.CA_EQ_A == other.CA_EQ_A and cable.CA_EQ_B == other.CA_EQ_B:
+                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(cable), layername=Cable.layername, field="geom"))
+        
+        ls_noeuds = list(noeuds.values())
+        for i, noeud in enumerate(ls_noeuds):
+            for other in ls_noeuds[i+1:]:
+                if noeud.geom == other.geom:
+                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(noeud), layername=Noeud.layername, field="geom"))
+        del ls_noeuds
+        
+        ls_zapbos = list(zapbos.values())
+        for i, zapbo in enumerate(ls_zapbos):
+            for other in ls_zapbos[i+1:]:
+                if zapbo.geom == other.geom:
+                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(zapbo), layername=Zapbo.layername, field="geom"))
+        del ls_zapbos
+           
+        # Arteres: comparer la géométrie à celle des noeuds
+        for artere in arteres:
+            if not artere.noeud_a or not artere.noeud_b:
+                continue
+            
+            if not any(((artere.points[0].distanceSquared(artere.noeud_a.points[0]) <= TOLERANCE and \
+                         artere.points[-1].distanceSquared(artere.noeud_b.points[0]) <= TOLERANCE), 
+                        (artere.points[0].distanceSquared(artere.noeud_b.points[0]) <= TOLERANCE and \
+                         artere.points[-1].distanceSquared(artere.noeud_a.points[0]) <= TOLERANCE))):
+
+                self.log_error(MissingItem("Pas de noeud aux coordonnées attendues ('{}')".format(artere), layername=Artere.layername, field="geom"))
+        
+        
+        # Cables: comparer la géométrie à celle des equipements (on utilise en fait la geom du noeud correspondant à l'équipement)
+        for cable in cables:
+            if not cable.equipement_a or not cable.equipement_b or not cable.is_geometry_valid() or not cable.equipement_a.noeud or not cable.equipement_b.noeud:
+                continue
+            
+            if not any(((cable.points[0].distanceSquared(cable.equipement_a.noeud.points[0]) <= TOLERANCE and \
+                         cable.points[-1].distanceSquared(cable.equipement_b.noeud.points[0]) <= TOLERANCE), 
+                        (cable.points[0].distanceSquared(cable.equipement_b.noeud.points[0]) <= TOLERANCE and \
+                         cable.points[-1].distanceSquared(cable.equipement_a.noeud.points[0]) <= TOLERANCE))):
+            
+                self.log_error(MissingItem("Pas d'equipement aux coordonnées attendues ('{}')".format(cable), layername=Cable.layername, field="geom"))
+            
+        # Verifie que chaque tranchée a au moins une artère
+        arteres_full_buffer = QgsGeometry().unaryUnion([a.geom for a in arteres]).buffer(TOLERANCE, 100)
+        
+        for tranchee in tranchees:
+            if not arteres_full_buffer.contains(tranchee.geom):
+                self.log_error(MissingItem("Tranchée ou portion de tranchée sans artère ('{}')".format(tranchee), layername=Tranchee.layername, field="*"))
+        
+        
+        # Verifie que chaque cable a au moins une artère (sauf si commentaire contient 'baguette')
+        for cable in cables:
+            if "baguette" in cable.CA_COMMENT.lower() or not cable.is_geometry_valid():
+                continue
+            if not arteres_full_buffer.contains(cable.geom):
+                self.log_error(MissingItem("Cable ou portion de cable sans artère ('{}')".format(cable), layername=Cable.layername, field="*"))
+        
+        del arteres_full_buffer
+        
+        # Verifie que chaque artère a au moins un cable (sauf si commentaire contient un de ces mots 'racco client adductio attente bus 'sans cable'')
+        cables_full_buffer = QgsGeometry().unaryUnion([c.geom for c in cables]).buffer(TOLERANCE, 100)
+        
+        for artere in arteres:
+            if any(x in artere.AR_COMMENT.lower() for x in ['racco','client','adductio','attente','bus','sans cable']):
+                continue
+            if not cables_full_buffer.contains(artere.geom):
+                self.log_error(MissingItem("Artère sans cable ('{}')".format(artere), layername=Artere.layername, field="*"))
+                
+        del cables_full_buffer
+                
+        # Contrôle des dimensions logiques
+        for artere in arteres:
+            try:
+                if not int(artere.AR_FOU_DIS) <= int(artere.AR_NB_FOUR):
+                    self.log_error(DimensionError("Le nombre de fourreaux disponibles doit être inférieur au nombre total ('{}')".format(artere), layername=Artere.layername, field="AR_FOU_DIS"))
+            except (TypeError, ValueError):
+                pass
+        
+        for cable in cables:
+            try:
+                if not int(cable.CA_NB_FO_U) <= int(cable.CA_NB_FO):
+                    self.log_error(DimensionError("Le nombre de fourreaux utilisés doit être inférieur au nombre total ('{}')".format(cable), layername=Cable.layername, field="CA_NB_FO_U"))
+                if not int(cable.CA_NB_FO_D) <= int(cable.CA_NB_FO):
+                    self.log_error(DimensionError("Le nombre de fourreaux disponibles doit être inférieur au nombre total ('{}')".format(cable), layername=Cable.layername, field="CA_NB_FO_D"))
+            except (TypeError, ValueError):
+                pass
+        
+        # Verifier que chaque equipement de type PBO est contenu dans une zapbo, et que le nom de la zapbo contient le nom de l'equipement
+        
+        for equipement in equipements.values():
+            if not equipement.EQ_TYPE == "PBO":
+                continue
+            
+            #zapbos englobant l'equipement
+            candidates = []
+            for zapbo in zapbos.values():
+                if zapbo.geom.contains(equipement.geom):
+                    candidates.append(zapbo)
+                    
+            # le pbo doit être contenu dans une zapbo
+            if not candidates:
+                self.log_error(MissingItem("Le PBO n'est contenu dans aucune ZAPBO: {}".format(equipement), layername=Equipement.layername, field="geom"))
+                continue
+            
+            # On se base sur le nom pour trouver la zapbo correspondante
+            try:
+                equipement.zapbo = next((z for z in candidates if equipement.EQ_NOM in z.ID_ZAPBO))
+            except StopIteration:
+                self.log_error(MissingItem("Le nom du PBO ne coincide avec le nom d'aucune des ZAPBO qui le contient: {}".format(equipement), layername=Equipement.layername, field="EQ_NOM"))
+                break
+            
+            if not hasattr(equipement.zapbo, "nb_prises") or equipement.zapbo.nb_prises is None:
+                equipement.zapbo.nb_prises = 0
+            
+            # Controle du dimensionnement des PBO
+            if equipement.zapbo.nb_prises is not None:
+                if equipement.EQ_TYPE_PH == 'PBO 6' and not equipement.zapbo.nb_prises < 6:
+                    self.log_error(DimensionError("Le PBO 6 contient plus de 5 prises: {}".format(equipement), layername=Equipement.layername, field="*"))
+            
+                if equipement.EQ_TYPE_PH == 'PBO 12' and not equipement.zapbo.nb_prises >= 6 and equipement.zapbo.nb_prises <= 8:
+                    self.log_error(DimensionError("Le PBO 12 contient mois de 6 prises ou plus de 8 prises: {}".format(equipement), layername=Equipement.layername, field="*"))
+        
+            if equipement.zapbo.STATUT == "REC" and not equipement.EQ_STATUT == "REC":
+                self.log_error(TechnicalValidationError("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO: {}".format(equipement), layername=Equipement.layername, field="*"))
+        
+            if equipement.EQ_STATUT == "REC" and not equipement.zapbo.STATUT == "REC" and not equipement.zapbo.ID_ZAPBO[:4].lower() == "att_":
+                self.log_error(TechnicalValidationError("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO: {}".format(equipement), layername=Equipement.layername, field="*"))
+        

+ 157 - 140
schemas/mn1_rec.py

@@ -6,20 +6,17 @@
 '''
 
 import logging
-from qgis.core import QgsProject, QgsGeometry, QgsWkbTypes
+
+from qgis.core import QgsProject, QgsGeometry
 
 from core.cerberus_ import is_float, is_multi_int, is_int, \
     is_modern_french_date, CerberusValidator, CerberusErrorHandler, \
     _translate_messages
-from core.checker import BaseChecker
-from core.validation_errors import UniqueError, RelationError, \
-    DuplicatedGeom, MissingItem, DimensionError, TechnicalValidationError
-from core.validator import QgsModel, BaseValidator
-
+from core.checking import BaseChecker
+from core.mncheck import QgsModel
 
 logger = logging.getLogger("mncheck")
 
-
 SCHEMA_NAME = "Schéma MN v1 REC"
 
 XMIN, XMAX, YMIN, YMAX = 1341999, 1429750, 8147750, 8294000
@@ -54,7 +51,7 @@ class Artere(QgsModel):
               'AR_PRO_MD': {'type': 'string', 'empty': False, 'default': 'MANCHE NUMERIQUE', 'allowed': ['MANCHE NUMERIQUE']}, 
               'AR_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True}, 
               'AR_STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
-
+    
     def __repr__(self):
         return "Artere {}-{}".format(self.AR_NOEUD_A, self.AR_NOEUD_B)
 
@@ -63,6 +60,7 @@ class Cable(QgsModel):
     geom_type = QgsModel.GEOM_LINE
     crs = CRS
     bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    pk = "CA_NUMERO"
     schema = {'CA_NUMERO': {'type': 'string', 'maxlength': 17}, 
               'CA_TYPE': {'type': 'string', 'maxlength': 10, 'empty': False, 'allowed': ['AERIEN', 'IMMEUBLE', 'FACADE', 'MIXTE', 'SOUTERRAIN']}, 
               'CA_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']}, 
@@ -89,6 +87,7 @@ class Equipement(QgsModel):
     geom_type = QgsModel.GEOM_POINT
     crs = CRS
     bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    pk = "EQ_NOM"
     schema = {'EQ_NOM': {'type': 'string', 'maxlength': 10, 'contains_any_of': ['PBO', 'BPE', 'BAI']}, 
               'EQ_NOM_NOE': {'type': 'string', 'maxlength': 30}, 
               'EQ_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']}, 
@@ -111,6 +110,7 @@ class Noeud(QgsModel):
     geom_type = QgsModel.GEOM_POINT
     crs = CRS
     bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    pk = "NO_NOM"
     schema = {'NO_NOM': {'type': 'string', 'maxlength': 30}, 
               'NO_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'}, 
               'NO_VOIE': {'type': 'string', 'maxlength': 100}, 
@@ -173,6 +173,7 @@ class Zapbo(QgsModel):
     geom_type = QgsModel.GEOM_POLYGON
     crs = CRS
     bounding_box = (XMIN,YMIN,XMAX,YMAX)
+    pk = "ID_ZAPBO"
     schema = {'ID_ZAPBO': {'type': 'string', 'maxlength': 30, 'contains_any_of': ['PBO', 'BPE']}, 
               'COMMENTAIR': {'type': 'string', 'maxlength': 254, 'empty': True}, 
               'STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
@@ -193,45 +194,47 @@ class Mn1Checker(BaseChecker):
     def test_load_layers(self):
         """ Chargement des données """
         
+        self.dataset = {}
+        
         for model in models:
             layername = model.layername
             
             layer = next((l for l in QgsProject.instance().mapLayers().values() if l.name().lower() == layername.lower()))
             if not layer:
-                self.log_error("Couche manquante", layername=layername, critical=True)
+                self.log_critical("Couche manquante", model=model)
                 continue
             
+            if model.pk:
+                if not model.pk.lower() in [f.name().lower() for f in layer.fields()]:
+                    self.log_critical(f"Clef primaire manquante ({model.pk})", model=model)
+                    continue
+            
             model.layer = layer
             
-        self.arteres = list(Artere.layer.getFeatures())
-        self.cables = list(Cable.layer.getFeatures())
-#         self.equipements = list(Equipement.layer.getFeatures())
-#         self.noeuds = list(Noeud.layer.getFeatures())
-        self.tranchees = list(Tranchee.layer.getFeatures())
-#         self.zapbos = list(Zapbo.layer.getFeatures())
-        
-        self.dataset = {Artere: self.arteres,
-                        Cable: self.cables,
-                        Equipement: self.equipements,
-                        Noeud: self.noeuds,
-                        Tranchee: self.tranchees,
-                        Zapbo: self.zapbos}
-    
+            self.dataset[model] = [model(f) for f in layer.getFeatures()]
+        
+        self.arteres = self.dataset.get(Artere, [])
+        self.cables = self.dataset.get(Cable, [])
+        self.equipements = self.dataset.get(Equipement, [])
+        self.noeuds = self.dataset.get(Noeud, [])
+        self.tranchees = self.dataset.get(Tranchee, [])
+        self.zapbos = self.dataset.get(Zapbo, [])
+        
     def test_scr(self):
         """ Contrôle des projections """
         for model in models:
             if model.layer.crs().authid() != model.crs:
-                self.log_error(f"Mauvaise projection (attendu: {model.crs})", layername=model.layername)
+                self.log_error(f"Mauvaise projection (attendu: {model.crs})", model=model)
 
-    def _validate_structure(self, model, features):
+    def _validate_structure(self, model, items):
         v = CerberusValidator(model.schema, purge_unknown=True, error_handler=CerberusErrorHandler, require_all=True)
-        for feature in features:
-            attributes = dict(zip([f.name() for f in feature.fields()], feature.attributes()))
-            v.validate(attributes)
+        
+        for item in items:
+            v.validate(item.attributes())
             
             for field, verrors in v.errors.items():
                 for err in verrors:
-                    self.log_error(_translate_messages(err), layername=model.layername, field=field)
+                    self.log_error(f"{field} : {_translate_messages(err)}", item=item)
 
     def test_structure_arteres(self):
         """ Structure des données: Artères """
@@ -260,167 +263,181 @@ class Mn1Checker(BaseChecker):
     def test_geometry_validity(self):
         """ Contrôle de la validité des géométries """
         for model in models:
-            for f in self.dataset[model]:
-                if not f.geometry().isGeosValid():
-                    self.log_error("La géométrie de l'objet est invalide", layername=model.layername, field="geom")
+            for item in self.dataset[model]:
+                if not item.is_geometry_valid():
+                    self.log_error("La géométrie de l'objet est invalide", item=item)
 
     def test_geometry_type(self):
+        """ Contrôle des types de géométries """
         for model in models:
-            for f in self.dataset[model]:
-                if QgsWkbTypes.singleType(f.geometry().wkbType()) != model.geom_type:
-                    self.log_error("Type de géométrie invalide (attendu: {})".format(QgsModel.GEOM_NAMES[model.geom_type]), layername=model.layername, field="geom")
+            for item in self.dataset[model]:
+                geom_type = item.get_geom_type()
+                if geom_type != model.geom_type:
+                    self.log_error(f"Type de géométrie invalide (attendu: {QgsModel.GEOM_NAMES[geom_type]})", item=item)
 
     def test_bounding_box(self):
-                
+        """ Contrôle des emprises """
+        
         for model in models:
             xmin, ymin, xmax, ymax = model.bounding_box
             
-            for f in self.dataset[model]:
+            for item in self.dataset[model]:
                 
-                bb = f.geometry().boundingBox()
-                x1, y1, x2, y2 = (bb.xMinimum(), bb.yMinimum(), bb.xMaximum(), bb.yMaximum())
+                x1, y1, x2, y2 = item.get_bounding_box()
                 
                 if any(x < xmin or x > xmax for x in (x1, x2)) or \
                    any(y < ymin or y > ymax for y in (y1, y2)):
-                    self.log_error("Hors de l'emprise autorisée", layername=model.layername, field="geom")
-
+                    self.log_error("Hors de l'emprise autorisée", item=item)
 
     def test_duplicates(self):
         """ Recherche de doublons """        
         
-        # TODO: séparer le chargement des données et le contrôle des doublons
-        
-        self.noeuds = {}
-        for noeud in self.dataset[Noeud]:
-            if not noeud.NO_NOM in self.noeuds:
-                self.noeuds[noeud.NO_NOM] = noeud
+        tmp = []
+        logger.info(self.noeuds)
+        for noeud in self.noeuds:
+            if not noeud.NO_NOM:
+                continue
+            if not noeud.NO_NOM in tmp:
+                tmp.append(noeud.NO_NOM)
             else:
-                self.log_error("Doublons dans le champs: {}".format(noeud), layername=Noeud.layername, field="NO_NOM")
+                self.log_error("Doublons dans le champs NO_NOM", item=noeud)
         
-        self.equipements = {}
-        for equipement in self.dataset[Equipement]:
-            if not equipement.EQ_NOM in self.equipements:
-                self.equipements[equipement.EQ_NOM] = equipement
+        tmp = []
+        for equipement in self.equipements:
+            if not equipement.EQ_NOM:
+                continue
+            if not equipement.EQ_NOM in tmp:
+                tmp.append(equipement.EQ_NOM)
             else:
-                self.log_error("Doublons dans le champs: {}".format(equipement), layername=Equipement.layername, field="EQ_NOM")
+                self.log_error("Doublons dans le champs EQ_NOM", item=equipement)
                 
-        self.zapbos = {}
-        for zapbo in self.dataset[Zapbo]:
-            if not zapbo.ID_ZAPBO in self.zapbos:
-                self.zapbos[zapbo.ID_ZAPBO] = zapbo
+        tmp = []
+        for zapbo in self.zapbos:
+            if not zapbo.ID_ZAPBO:
+                continue
+            if not zapbo.ID_ZAPBO in tmp:
+                tmp.append(zapbo.ID_ZAPBO)
             else:
-                self.log_error("Doublons dans le champs: {}".format(zapbo), layername=Zapbo.layername, field="ID_ZAPBO")
+                self.log_error("Doublons dans le champs ID_ZAPBO", item=zapbo)
         
         
-    def test_constraints(self):
-        """ Contrôle des contraintes relationnelles """
+    def test_constraints_arteres_noeuds(self):
+        """ Les noeuds attachés aux artères existent """
         
-        # rattachement les noeuds aux artères     
         for artere in self.arteres:
             try:
-                artere.noeud_a = self.noeuds[artere.AR_NOEUD_A]
-            except KeyError:
+                artere.noeud_a = next((n for n in self.noeuds if n.NO_NOM == artere.AR_NOEUD_A))
+            except StopIteration:
                 artere.noeud_a = None
-                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_A), layername=Artere.layername, field="AR_NOEUD_A"))
+                self.log_error(f"Le noeud '{artere.AR_NOEUD_A}' n'existe pas", item=artere)
                 
             try:
-                artere.noeud_b = self.noeuds[artere.AR_NOEUD_B]
-            except KeyError:
+                artere.noeud_b = next((n for n in self.noeuds if n.NO_NOM == artere.AR_NOEUD_B))
+            except StopIteration:
                 artere.noeud_b = None
-                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_B), layername=Artere.layername, field="AR_NOEUD_A"))
+                self.log_error(f"Le noeud '{artere.AR_NOEUD_B}' n'existe pas", item=artere)
+
+    def test_constraints_cables_equipements(self):
+        """ Les équipements attachés aux cables existent """
         
-        # rattachement des equipements aux cables
         for cable in self.cables:
             try:
-                cable.equipement_a = self.equipements[cable.CA_EQ_A]
-            except KeyError:
+                cable.equipement_a = next((e for e in self.equipements if e.EQ_NOM == cable.CA_EQ_A))
+            except StopIteration:
                 cable.equipement_a = None
-                self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.CA_EQ_A), layername=Cable.layername, field="CA_EQ_A"))
+                self.log_error(f"L'équipement '{cable.CA_EQ_A}' n'existe pas", item=cable)
                 
             try:
-                cable.equipement_b = self.equipements[cable.CA_EQ_B]
-            except KeyError:
+                cable.equipement_b = next((e for e in self.equipements if e.EQ_NOM == cable.CA_EQ_B))
+            except StopIteration:
                 cable.equipement_b = None
-                self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.CA_EQ_B), layername=Cable.layername, field="CA_EQ_B"))
-
-        # rattachement des equipements aux noeuds
-        for equipement in self.equipements.values():
-            try:
-                equipement.noeud = self.noeuds[equipement.EQ_NOM_NOE]
-            except KeyError:
-                equipement.noeud = None
-                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(equipement.EQ_NOM_NOE, equipement.EQ_NOM), layername=Equipement.layername, field="EQ_NOM_NOE"))
+                self.log_error(f"L'équipement '{cable.CA_EQ_B}' n'existe pas", item=cable)
 
-        # verifie que tous les equipements sont l'equipement B d'au moins un cable
+    def test_constraints_cables_equipements_b(self):
+        """ Tous les équipements sont l'équipement B d'au moins un cable """
+        
         equipements_b = [cable.CA_EQ_B for cable in self.cables]
-        for eq_id in self.equipements:
-            if self.equipements[eq_id].EQ_TYPE == "BAI":
+        for equipement in self.equipements:
+            if equipement.EQ_TYPE == "BAI":
                 continue
-            if not eq_id in equipements_b:
-                self.log_error(RelationError("L'equipement '{}' n'est l'équipement B d'aucun cable".format(eq_id), layername=Equipement.layername, field="EQ_NOM"))
+            if not equipement.EQ_NOM in equipements_b:
+                self.log_error(f"L'equipement '{equipement.EQ_NOM}' n'est l'équipement B d'aucun cable", item=equipement)
+
+
+    def test_constraints_equipements_noeuds(self):
+        """ Les noeuds attachés aux équipements existent """
+        
+        for equipement in self.equipements:
+            try:
+                equipement.noeud = next((n for n in self.noeuds if n.NO_NOM == equipement.EQ_NOM_NOE))
+            except StopIteration:
+                equipement.noeud = None
+                self.log_error(f"Le noeud '{equipement.EQ_NOM_NOE}' n'existe pas", item=equipement)
 
 
     def test_graphic_duplicates(self):
         """ Recherche de doublons graphiques """
             
-        # controle des doublons graphiques
         for i, tranchee in enumerate(self.tranchees):
             for other in self.tranchees[i+1:]:
                 if tranchee.geom == other.geom:
-                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée".format(tranchee), layername=Tranchee.layername, field="geom"))
+                    self.log_error("Une entité graphique est dupliquée", item=tranchee)
                     
         for i, artere in enumerate(self.arteres):
             for other in self.arteres[i+1:]:
                 if artere.geom == other.geom:
-                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(artere), layername=Artere.layername, field="geom"))
+                    self.log_error("Une entité graphique est dupliquée", item=artere)
 
         for i, cable in enumerate(self.cables):
             for other in self.cables[i+1:]:
                 if cable.geom == other.geom and cable.CA_EQ_A == other.CA_EQ_A and cable.CA_EQ_B == other.CA_EQ_B:
-                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(cable), layername=Cable.layername, field="geom"))
+                    self.log_error("Une entité graphique est dupliquée", item=cable)
         
-        ls_noeuds = list(self.noeuds.values())
-        for i, noeud in enumerate(ls_noeuds):
-            for other in ls_noeuds[i+1:]:
+        for i, noeud in enumerate(self.noeuds):
+            for other in self.noeuds[i+1:]:
                 if noeud.geom == other.geom:
-                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(noeud), layername=Noeud.layername, field="geom"))
-        del ls_noeuds
+                    self.log_error("Une entité graphique est dupliquée", item=noeud)
         
-        ls_zapbos = list(self.zapbos.values())
-        for i, zapbo in enumerate(ls_zapbos):
-            for other in ls_zapbos[i+1:]:
+        for i, zapbo in enumerate(self.zapbos):
+            for other in self.zapbos[i+1:]:
                 if zapbo.geom == other.geom:
-                    self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(zapbo), layername=Zapbo.layername, field="geom"))
-        del ls_zapbos
+                    self.log_error("Une entité graphique est dupliquée", item=zapbo)
         
     def test_positions_noeuds(self):
         """ Contrôle de la position des noeuds """
         
-        # Arteres: comparer la géométrie à celle des noeuds
         for artere in self.arteres:
             if not artere.noeud_a or not artere.noeud_b:
                 continue
             
-            if not any(((artere.points[0].distanceSquared(artere.noeud_a.points[0]) <= TOLERANCE and \
-                         artere.points[-1].distanceSquared(artere.noeud_b.points[0]) <= TOLERANCE), 
-                        (artere.points[0].distanceSquared(artere.noeud_b.points[0]) <= TOLERANCE and \
-                         artere.points[-1].distanceSquared(artere.noeud_a.points[0]) <= TOLERANCE))):
-                self.log_error(MissingItem("Pas de noeud aux coordonnées attendues ('{}')".format(artere), layername=Artere.layername, field="geom"))
+            artere_points = artere.get_points()
+            noeud_a_point = artere.noeud_a.get_points()[0]
+            noeud_b_point = artere.noeud_b.get_points()[0]
+            
+            if not any(((artere_points[0].distanceSquared(noeud_a_point) <= TOLERANCE and \
+                         artere_points[-1].distanceSquared(noeud_b_point) <= TOLERANCE), 
+                        (artere_points[0].distanceSquared(noeud_b_point) <= TOLERANCE and \
+                         artere_points[-1].distanceSquared(noeud_a_point) <= TOLERANCE))):
+                self.log_error("Pas de noeud aux coordonnées attendues", item=artere)
         
     def test_positions_equipements(self):
         """ Contrôle de la position des équipements """
         
-        # Cables: comparer la géométrie à celle des equipements (on utilise en fait la geom du noeud correspondant à l'équipement)
         for cable in self.cables:
             if not cable.equipement_a or not cable.equipement_b or not cable.is_geometry_valid() or not cable.equipement_a.noeud or not cable.equipement_b.noeud:
                 continue
             
-            if not any(((cable.points[0].distanceSquared(cable.equipement_a.noeud.points[0]) <= TOLERANCE and \
-                         cable.points[-1].distanceSquared(cable.equipement_b.noeud.points[0]) <= TOLERANCE), 
-                        (cable.points[0].distanceSquared(cable.equipement_b.noeud.points[0]) <= TOLERANCE and \
-                         cable.points[-1].distanceSquared(cable.equipement_a.noeud.points[0]) <= TOLERANCE))):
+            #! attention: on utilise la géométrie du noeud associé à l'équipement, pas celle de l'équipement lui-même
+            cable_points = cable.get_points()
+            equip_a_point = cable.equipement_a.noeud.get_points()[0]
+            equip_b_point = cable.equipement_b.noeud.get_points()[0]
+            
+            if not any(((cable_points[0].distanceSquared(equip_a_point) <= TOLERANCE and \
+                         cable_points[-1].distanceSquared(equip_b_point) <= TOLERANCE), 
+                        (cable_points[0].distanceSquared(equip_b_point) <= TOLERANCE and \
+                         cable_points[-1].distanceSquared(equip_a_point) <= TOLERANCE))):
             
-                self.log_error(MissingItem("Pas d'equipement aux coordonnées attendues ('{}')".format(cable), layername=Cable.layername, field="geom"))
+                self.log_error("Pas d'equipement aux coordonnées attendues", item=cable)
             
     def test_tranchee_artere(self):
         """ Chaque tranchée a au moins une artère """
@@ -429,10 +446,11 @@ class Mn1Checker(BaseChecker):
         
         for tranchee in self.tranchees:
             if not arteres_full_buffer.contains(tranchee.geom):
-                self.log_error(MissingItem("Tranchée ou portion de tranchée sans artère ('{}')".format(tranchee), layername=Tranchee.layername, field="*"))
+                self.log_error("Tranchée ou portion de tranchée sans artère", item=tranchee)
         
     def test_cable_artere(self):
         """ Chaque cable a au moins une artère (sauf baguettes) """
+        
         arteres_full_buffer = QgsGeometry().unaryUnion([a.geom for a in self.arteres]).buffer(TOLERANCE, 100)
         
         # Verifie que chaque cable a au moins une artère (sauf si commentaire contient 'baguette')
@@ -440,38 +458,36 @@ class Mn1Checker(BaseChecker):
             if "baguette" in cable.CA_COMMENT.lower() or not cable.is_geometry_valid():
                 continue
             if not arteres_full_buffer.contains(cable.geom):
-                self.log_error(MissingItem("Cable ou portion de cable sans artère ('{}')".format(cable), layername=Cable.layername, field="*"))
+                self.log_error("Cable ou portion de cable sans artère", item=cable)
         
     def test_artere_cable(self):
         """ Chaque artère a au moins une cable (sauf cas spécifiques) """
         
         # Verifie que chaque artère a au moins un cable (sauf si commentaire contient un de ces mots 'racco client adductio attente bus 'sans cable'')
-        
         cables_full_buffer = QgsGeometry().unaryUnion([c.geom for c in self.cables]).buffer(TOLERANCE, 100)
         
         for artere in self.arteres:
             if any(x in artere.AR_COMMENT.lower() for x in ['racco','client','adductio','attente','bus','sans cable']):
                 continue
             if not cables_full_buffer.contains(artere.geom):
-                self.log_error(MissingItem("Artère sans cable ('{}')".format(artere), layername=Artere.layername, field="*"))
-    
+                self.log_error("Artère ou portion d'artère sans cable", item=artere)
     
-    def test_dimensions(self):
-        """ Contrôle des dimensions logiques """
+    def test_dimensions_fourreaux(self):
+        """ Nombres de fourreaux cohérents """
         
         for artere in self.arteres:
             try:
                 if not int(artere.AR_FOU_DIS) <= int(artere.AR_NB_FOUR):
-                    self.log_error(DimensionError("Le nombre de fourreaux disponibles doit être inférieur au nombre total ('{}')".format(artere), layername=Artere.layername, field="AR_FOU_DIS"))
+                    self.log_error("Le nombre de fourreaux disponibles (AR_FOU_DIS) doit être inférieur au nombre total (AR_NB_FOUR)", item=artere)
             except (TypeError, ValueError):
                 pass
          
         for cable in self.cables:
             try:
                 if not int(cable.CA_NB_FO_U) <= int(cable.CA_NB_FO):
-                    self.log_error(DimensionError("Le nombre de fourreaux utilisés doit être inférieur au nombre total ('{}')".format(cable), layername=Cable.layername, field="CA_NB_FO_U"))
+                    self.log_error("Le nombre de fourreaux utilisés (CA_NB_FO_U) doit être inférieur au nombre total (CA_NB_FO)", item=cable)
                 if not int(cable.CA_NB_FO_D) <= int(cable.CA_NB_FO):
-                    self.log_error(DimensionError("Le nombre de fourreaux disponibles doit être inférieur au nombre total ('{}')".format(cable), layername=Cable.layername, field="CA_NB_FO_D"))
+                    self.log_error("Le nombre de fourreaux disponibles (CA_NB_FO_D) doit être inférieur au nombre total (CA_NB_FO)", item=cable)
             except (TypeError, ValueError):
                 pass
          
@@ -479,48 +495,49 @@ class Mn1Checker(BaseChecker):
         """ PBO / ZAPBO """
         
         # Verifier que chaque equipement de type PBO est contenu dans une zapbo, et que le nom de la zapbo contient le nom de l'equipement
-        for equipement in self.equipements.values():
+        for equipement in self.equipements:
             if not equipement.EQ_TYPE == "PBO":
                 continue
-             
+            
             #zapbos englobant l'equipement
             candidates = []
-            for zapbo in self.zapbos.values():
+            for zapbo in self.zapbos:
                 if zapbo.geom.contains(equipement.geom):
                     candidates.append(zapbo)
-                     
+                    
             # le pbo doit être contenu dans une zapbo
             if not candidates:
-                self.log_error(MissingItem("Le PBO n'est contenu dans aucune ZAPBO: {}".format(equipement), layername=Equipement.layername, field="geom"))
+                self.log_error("Le PBO n'est contenu dans aucune ZAPBO", item=equipement)
                 continue
              
             # On se base sur le nom pour trouver la zapbo correspondante
             try:
                 equipement.zapbo = next((z for z in candidates if equipement.EQ_NOM in z.ID_ZAPBO))
             except StopIteration:
-                self.log_error(MissingItem("Le nom du PBO ne coincide avec le nom d'aucune des ZAPBO qui le contient: {}".format(equipement), layername=Equipement.layername, field="EQ_NOM"))
+                self.log_error("Le nom du PBO ne coincide avec le nom d'aucune des ZAPBO qui le contient", item=equipement)
                 break
             
-            # TODO: revoir et déplacer le calcul du nombre de prises
-            if not hasattr(equipement.zapbo, "nb_prises") or equipement.zapbo.nb_prises is None:
-                equipement.zapbo.nb_prises = 0
-             
-    def test_pbo_dimension(self):
+
+    # a venir
+    def __test_pbo_dimension(self):
         """ Dimensionnement des PBO """
-        for equipement in self.equipements.values():
+        for equipement in self.equipements:
             if not equipement.EQ_TYPE == "PBO":
                 continue
-             
+            
+            if not hasattr(equipement.zapbo, "nb_prises") or equipement.zapbo.nb_prises is None:
+                equipement.zapbo.nb_prises = 0
+                
             # Controle du dimensionnement des PBO
             if equipement.EQ_TYPE_PH == 'PBO 6' and not equipement.zapbo.nb_prises < 6:
-                self.log_error(DimensionError("Le PBO 6 contient plus de 5 prises: {}".format(equipement), layername=Equipement.layername, field="*"))
+                self.log_error("Le PBO 6 contient plus de 5 prises", item=equipement)
          
             if equipement.EQ_TYPE_PH == 'PBO 12' and not equipement.zapbo.nb_prises >= 6 and equipement.zapbo.nb_prises <= 8:
-                self.log_error(DimensionError("Le PBO 12 contient mois de 6 prises ou plus de 8 prises: {}".format(equipement), layername=Equipement.layername, field="*"))
+                self.log_error("Le PBO 12 contient mois de 6 prises ou plus de 8 prises", item=equipement)
          
             if equipement.zapbo.STATUT == "REC" and not equipement.EQ_STATUT == "REC":
-                self.log_error(TechnicalValidationError("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO: {}".format(equipement), layername=Equipement.layername, field="*"))
+                self.log_error("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO", item=equipement)
          
             if equipement.EQ_STATUT == "REC" and not equipement.zapbo.STATUT == "REC" and not equipement.zapbo.ID_ZAPBO[:4].lower() == "att_":
-                self.log_error(TechnicalValidationError("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO: {}".format(equipement), layername=Equipement.layername, field="*"))
+                self.log_error("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO", item=equipement)
         

+ 63 - 35
ui/dlg_main.py

@@ -1,5 +1,6 @@
 """
 """
+from core import mncheck, checking
 import importlib
 import logging
 from qgis.core import QgsProject  # @UnresolvedImport
@@ -17,14 +18,16 @@ logger = logging.getLogger("mncheck")
 
 Ui_Main, _ = uic.loadUiType(MAIN / 'ui'/ 'dlg_main.ui')
 
-SCHEMAS = ["mn1_rec", "mn2_rec", "mn3_pro", "mn3_exe", "mn3_rec"]
+# SCHEMAS = ["mn1_rec", "mn2_rec", "mn3_pro", "mn3_exe", "mn3_rec"]
 
 class DlgMain(QtWidgets.QDialog):
     def __init__(self, iface, parent=None):
         super(DlgMain, self).__init__(parent)
-        self.createWidgets()
+        self.available_schemas = mncheck.list_schemas()        
         self.iface = iface
         self.schema_lib = None
+        
+        self.createWidgets()
 
     def createWidgets(self):
         """ set up the interface """
@@ -40,29 +43,31 @@ class DlgMain(QtWidgets.QDialog):
         self.ui.btn_settings.setIcon(QIcon(RSCDIR / "settings.png"))
         self.ui.btn_settings.clicked.connect(self.show_settings)
 
-        self.ui.cbb_schemas.addItem("Schéma MN v1 REC", 0)
-        self.ui.cbb_schemas.addItem("Schéma MN v2 REC", 1)
-#         self.ui.cbb_schemas.addItem("Schéma MN v3 PRO", 2)
-#         self.ui.cbb_schemas.addItem("Schéma MN v3 EXE", 3)
-#         self.ui.cbb_schemas.addItem("Schéma MN v3 REC", 4)
+        for i, schema_name in enumerate(self.available_schemas):
+            s = mncheck.get_schema(schema_name)
+            try:
+                self.ui.cbb_schemas.addItem(s.SCHEMA_NAME, i)
+            except AttributeError:
+                self.ui.cbb_schemas.addItem(schema_name, i)
+            
         self.ui.cbb_schemas.currentIndexChanged.connect(self.update_layers_list)
         
         self.ui.tree_report.setColumnWidth(0, 35)
+        self.ui.tree_report.itemClicked.connect(self.tree_item_clicked)
         
         self.update_layers_list()
     
-    def selected_validator(self):
-        schema_lib_name = SCHEMAS[int(self.ui.cbb_schemas.itemData(self.ui.cbb_schemas.currentIndex()))]
-        logger.info("Selected schema: %s", schema_lib_name)
+    def current_schema(self):
+        schema_name = self.available_schemas[int(self.ui.cbb_schemas.itemData(self.ui.cbb_schemas.currentIndex()))]
+        logger.info("Selected schema: %s", schema_name)
     
-        schema_lib = importlib.import_module("schemas." + schema_lib_name)
-        return schema_lib.Validator
+        return mncheck.get_schema(schema_name)
     
     def update_layers_list(self):
         
-        validator = self.selected_validator()
-
-        expected = [model.layername for model in validator.models]
+        schema = self.current_schema()
+        
+        expected = [model.layername for model in schema.models]
         logger.info("Expected layers: %s", str(expected))
 
         found = [layer.name().lower() for layer in QgsProject.instance().mapLayers().values()]
@@ -92,40 +97,63 @@ class DlgMain(QtWidgets.QDialog):
         QApplication.setOverrideCursor(Qt.WaitCursor)
         self.ui.tree_report.clear()
         
-        validator = self.selected_validator()
-        
-        if not validator:
-            logger.info("Aucun schéma sélectionné - Opération annulée")
-            return
-        
         try:
-            self._run(validator)
+            schema = self.current_schema()
+            if not schema:
+                logger.error("Aucun schéma sélectionné - Opération annulée")
+                return
+            
+            checkers = mncheck.get_checkers(schema)
+            if not checkers:
+                logger.error("Aucun testeur trouvé dans le schéma")
+                return
+        
+            for checker in checkers:
+                logger.info(f"Execution du checker {checker.__name__}")
+                self._run(checker)
         except:
             raise
         finally:
             QApplication.restoreOverrideCursor()
     
-    def _run(self, validator):
-        report = validator.submit(self.iface)
+    def _run(self, checker):
         
-        logger.debug(f"Rapport d'exec: {report}")
+        results = checker().run()
         
-        for type_err in report["errors"]:
+        for result in results:
             topitem = QTreeWidgetItem()
             
-            topitem.setIcon(0, QIcon(QPixmap(RSCDIR / "error_16.png")))
-            topitem.setText(1, "{} ({})".format(type_err, len(report["errors"][type_err]["list"])))
+            if result.status == checking.SUCCESS:
+                topitem.setIcon(0, QIcon(QPixmap(RSCDIR / "ok_16.png")))
+                topitem.setText(1, f"{result.title}")
+            elif result.status == checking.FAILURE:
+                topitem.setIcon(0, QIcon(QPixmap(RSCDIR / "error_16.png")))
+                topitem.setText(1, f"{result.title} ({len(result.errors)})")
+            elif result.status == checking.ERROR:
+                topitem.setIcon(0, QIcon(QPixmap(RSCDIR / "warning_16.png")))
+                topitem.setText(1, f"{result.title} [Erreur inconnue]")
+            else:
+                topitem.setText(1, f"{result.title} [Résultat manquant]")
             
             self.ui.tree_report.addTopLevelItem(topitem)
             
-            for err in report["errors"][type_err]["list"]:
-                
-                item = QTreeWidgetItem()
-                
-                item.setText(1, "{} {} : {}".format(err["layername"], err["field"], err["message"]))
-                
-                topitem.addChild(item)
+            for err in result.errors:
+                treeitem = QTreeWidgetItem()
                 
+                treeitem.setText(1, err.message)
+                if "exc_info" in err.info:
+                    logger.debug("* %s\n%s", err.message, err.info["exc_info"])
+                    treeitem.setData(1, Qt.UserRole, err.info["exc_info"])
+                    
+                topitem.addChild(treeitem)
+        
+        
+        
+    def tree_item_clicked(self, item, col):
+        
+        data = item.data(1, Qt.UserRole)
+        
+        
     def show_help(self):
         pass
     

TEMPAT SAMPAH
ui/rsc/warning2_16.png


TEMPAT SAMPAH
ui/rsc/warning_16.png