File size: 6,455 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
ERP resolver for automatic ERP system detection.
Uses Jaccard similarity to match GDF columns against known ERP templates.
"""

from typing import Dict, List, Optional, Tuple

from .template_loader import TemplateLoader


class ERPResolver:
    """Resolves ERP system from GDF column names using similarity matching."""
    
    def __init__(self, template_loader: TemplateLoader, similarity_threshold: float = 0.4):
        """Initialize ERP resolver.
        
        Args:
            template_loader: Template loader instance
            similarity_threshold: Minimum Jaccard similarity to accept ERP match
        """
        self.template_loader = template_loader
        self.similarity_threshold = similarity_threshold
    
    def detect_erp(self, gdf_columns: List[str], entity: str) -> Optional[str]:
        """Detect ERP system from GDF column names.
        
        Args:
            gdf_columns: List of column names from GDF
            entity: Entity type being processed
            
        Returns:
            ERP system name if detected above threshold, None otherwise
        """
        scores = self._calculate_similarity_scores(gdf_columns, entity)
        
        if not scores:
            return None
        
        # Get best match
        best_erp, best_score = max(scores, key=lambda x: x[1])
        
        if best_score >= self.similarity_threshold:
            return best_erp
        
        return None
    
    def get_similarity_scores(self, gdf_columns: List[str], entity: str) -> List[Tuple[str, float]]:
        """Get similarity scores for all ERPs, sorted by score descending.
        
        Args:
            gdf_columns: List of column names from GDF
            entity: Entity type being processed
            
        Returns:
            List of (erp_name, similarity_score) tuples sorted by score descending
        """
        scores = self._calculate_similarity_scores(gdf_columns, entity)
        return sorted(scores, key=lambda x: x[1], reverse=True)
    
    def _calculate_similarity_scores(self, gdf_columns: List[str], entity: str) -> List[Tuple[str, float]]:
        """Calculate Jaccard similarity scores for all ERPs.
        
        Args:
            gdf_columns: List of column names from GDF
            entity: Entity type being processed
            
        Returns:
            List of (erp_name, similarity_score) tuples
        """
        scores = []
        gdf_set = set(col.lower().strip() for col in gdf_columns)  # Normalize for comparison
        
        erp_columns = self.template_loader.get_all_erp_columns(entity)
        
        for erp_name, erp_cols in erp_columns.items():
            if not erp_cols:  # Skip if no columns for this ERP/entity
                continue
                
            erp_set = set(col.lower().strip() for col in erp_cols)  # Normalize for comparison
            similarity = self._jaccard_similarity(gdf_set, erp_set)
            scores.append((erp_name, similarity))
        
        return scores
    
    def _jaccard_similarity(self, set_a: set, set_b: set) -> float:
        """Calculate Jaccard similarity between two sets.
        
        Args:
            set_a: First set
            set_b: Second set
            
        Returns:
            Jaccard similarity coefficient (0.0 to 1.0)
        """
        if not set_a and not set_b:
            return 1.0
        
        intersection = len(set_a & set_b)
        union = len(set_a | set_b)
        
        return intersection / union if union > 0 else 0.0
    
    def get_matching_columns(self, gdf_columns: List[str], erp: str, entity: str) -> Dict[str, List[str]]:
        """Get detailed column matching information.
        
        Args:
            gdf_columns: List of column names from GDF
            erp: ERP system name
            entity: Entity type
            
        Returns:
            Dictionary with 'matched', 'unmatched_gdf', 'unmatched_erp' lists
        """
        mapping = self.template_loader.get_entity_mapping(erp, entity)
        if not mapping:
            return {
                'matched': [],
                'unmatched_gdf': gdf_columns,
                'unmatched_erp': []
            }
        
        gdf_set = set(col.lower().strip() for col in gdf_columns)
        erp_set = set(col.lower().strip() for col in mapping.keys())
        
        # Find matches (case-insensitive)
        matched = []
        unmatched_gdf = []
        
        for gdf_col in gdf_columns:
            gdf_col_norm = gdf_col.lower().strip()
            if gdf_col_norm in erp_set:
                # Find the original ERP column name
                for erp_col in mapping.keys():
                    if erp_col.lower().strip() == gdf_col_norm:
                        matched.append((gdf_col, erp_col))
                        break
            else:
                unmatched_gdf.append(gdf_col)
        
        # Find unmatched ERP columns
        matched_erp_cols = {erp_col for _, erp_col in matched}
        unmatched_erp = [col for col in mapping.keys() if col not in matched_erp_cols]
        
        return {
            'matched': matched,
            'unmatched_gdf': unmatched_gdf,
            'unmatched_erp': unmatched_erp
        }
    
    def suggest_best_matches(self, gdf_columns: List[str], entity: str, top_n: int = 3) -> List[Dict]:
        """Suggest best ERP matches with detailed information.
        
        Args:
            gdf_columns: List of column names from GDF
            entity: Entity type
            top_n: Number of top matches to return
            
        Returns:
            List of dictionaries with ERP match details
        """
        scores = self.get_similarity_scores(gdf_columns, entity)
        suggestions = []
        
        for erp_name, score in scores[:top_n]:
            matching_info = self.get_matching_columns(gdf_columns, erp_name, entity)
            
            suggestions.append({
                'erp': erp_name,
                'similarity_score': score,
                'above_threshold': score >= self.similarity_threshold,
                'matched_columns': len(matching_info['matched']),
                'total_gdf_columns': len(gdf_columns),
                'total_erp_columns': len(self.template_loader.get_entity_mapping(erp_name, entity) or {}),
                'matching_details': matching_info
            })
        
        return suggestions