cleanflowai / mapper /template_loader.py
MrTechie's picture
Initial AI done
d448413
Raw History Blame Contribute Delete
4.89 kB
"""
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()