Spaces:
Runtime error
Runtime error
File size: 4,886 Bytes
d448413 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | """
Template loader for ERP to CDF mappings.
Handles loading and validation of mapping templates.
"""
import json
from pathlib import Path
from typing import Dict, List, Optional
from .models import EntityType
class TemplateLoader:
"""Loads and manages ERP to CDF mapping templates."""
def __init__(self, template_path: Optional[Path] = None):
"""Initialize template loader.
Args:
template_path: Path to template.json file. Defaults to template.json in current directory.
"""
self.template_path = template_path or Path("template.json")
self._template_cache: Optional[Dict] = None
def load_template(self) -> Dict[str, Dict[str, Dict[str, str]]]:
"""Load mapping template from JSON file.
Returns:
Dictionary with structure: ERP -> entity -> {GDF_col: CDF_col}
Raises:
FileNotFoundError: If template file doesn't exist
ValueError: If template format is invalid
"""
if self._template_cache is not None:
return self._template_cache
if not self.template_path.exists():
raise FileNotFoundError(f"Template file not found: {self.template_path}")
try:
with self.template_path.open('r', encoding='utf-8') as fp:
template = json.load(fp)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in template file: {e}")
# Validate template structure
self._validate_template(template)
self._template_cache = template
return template
def _validate_template(self, template: Dict) -> None:
"""Validate template structure and required fields.
Args:
template: Loaded template dictionary
Raises:
ValueError: If template structure is invalid
"""
if not isinstance(template, dict):
raise ValueError("Template must be a dictionary")
# Check for CDF_META section
if "CDF_META" not in template:
raise ValueError("Template missing required 'CDF_META' section")
cdf_meta = template["CDF_META"]
if not isinstance(cdf_meta, dict):
raise ValueError("CDF_META must be a dictionary")
# Validate that all supported entities have CDF schemas
for entity in EntityType:
if entity.value not in cdf_meta:
raise ValueError(f"CDF_META missing schema for entity: {entity.value}")
if not isinstance(cdf_meta[entity.value], list):
raise ValueError(f"CDF schema for {entity.value} must be a list of column names")
def get_erp_names(self) -> List[str]:
"""Get list of available ERP systems in template.
Returns:
List of ERP system names
"""
template = self.load_template()
return [erp for erp in template.keys() if erp != "CDF_META"]
def get_entity_mapping(self, erp: str, entity: str) -> Optional[Dict[str, str]]:
"""Get column mapping for specific ERP and entity.
Args:
erp: ERP system name
entity: Entity type
Returns:
Dictionary mapping GDF columns to CDF columns, or None if not found
"""
template = self.load_template()
return template.get(erp, {}).get(entity)
def get_cdf_schema(self, entity: str) -> List[str]:
"""Get CDF column schema for entity.
Args:
entity: Entity type
Returns:
List of CDF column names in correct order
Raises:
ValueError: If entity not found in CDF_META
"""
template = self.load_template()
cdf_meta = template.get("CDF_META", {})
if entity not in cdf_meta:
raise ValueError(f"Entity '{entity}' not found in CDF_META")
return cdf_meta[entity]
def get_all_erp_columns(self, entity: str) -> Dict[str, List[str]]:
"""Get all GDF columns for an entity across all ERPs.
Args:
entity: Entity type
Returns:
Dictionary mapping ERP names to lists of their GDF columns
"""
template = self.load_template()
erp_columns = {}
for erp_name in self.get_erp_names():
mapping = self.get_entity_mapping(erp_name, entity)
if mapping:
erp_columns[erp_name] = list(mapping.keys())
return erp_columns
def reload_template(self) -> None:
"""Force reload of template from file."""
self._template_cache = None
self.load_template()
|