aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/conventionalrp/core/rules.py
blob: f198d4ea7cf636ad43056d8b5f5ce8b1161e98b0 (plain) (blame)
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
from typing import Dict, Any, Callable, List, Optional
from enum import Enum
import re


class RuleCondition(Enum):
    """规则条件类型"""
    EQUALS = "equals"
    CONTAINS = "contains"
    MATCHES = "matches"
    STARTS_WITH = "starts_with"
    ENDS_WITH = "ends_with"
    IN_LIST = "in_list"
    GREATER_THAN = "greater_than"
    LESS_THAN = "less_than"


class Rule:
    def __init__(
        self,
        name: str,
        condition: Dict[str, Any],
        action: Dict[str, Any],
        priority: int = 50
    ):
        self.name = name
        self.condition = condition
        self.action = action
        self.priority = priority
        self._compiled_patterns = {}
        
        self._precompile_patterns()
    
    def _precompile_patterns(self):
        """预编译正则表达式以提高性能"""
        if isinstance(self.condition, dict):
            for key, value in self.condition.items():
                if isinstance(value, dict) and value.get("type") == "matches":
                    pattern = value.get("pattern")
                    if pattern:
                        self._compiled_patterns[key] = re.compile(pattern)
    
    def matches(self, data: Dict[str, Any]) -> bool:
        """
        检查数据是否匹配规则条件
        """
        if not isinstance(self.condition, dict):
            return False
        
        for field, condition_spec in self.condition.items():
            if not self._check_field_condition(data, field, condition_spec):
                return False
        
        return True
    
    def _check_field_condition(
        self,
        data: Dict[str, Any],
        field: str,
        condition: Any
    ) -> bool:
        """检查单个字段的条件"""
        value = data.get(field)
        
        if not isinstance(condition, dict):
            return value == condition
        
        condition_type = condition.get("type")
        expected_value = condition.get("value")
        
        if condition_type == "equals":
            return value == expected_value
        elif condition_type == "contains":
            return expected_value in str(value) if value else False
        elif condition_type == "matches":
            if field in self._compiled_patterns:
                pattern = self._compiled_patterns[field]
                return bool(pattern.search(str(value))) if value else False
            return False
        elif condition_type == "starts_with":
            return str(value).startswith(expected_value) if value else False
        elif condition_type == "ends_with":
            return str(value).endswith(expected_value) if value else False
        elif condition_type == "in_list":
            return value in expected_value if isinstance(expected_value, list) else False
        elif condition_type == "greater_than":
            try:
                return float(value) > float(expected_value)
            except (ValueError, TypeError):
                return False
        elif condition_type == "less_than":
            try:
                return float(value) < float(expected_value)
            except (ValueError, TypeError):
                return False
        
        return False
    
    def apply(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        对匹配的数据应用规则动作
        """
        result = data.copy()
        
        if not isinstance(self.action, dict):
            return result
        
        action_type = self.action.get("type")
        
        if action_type == "set_field":
            field = self.action.get("field")
            value = self.action.get("value")
            if field:
                result[field] = value
        
        elif action_type == "add_field":
            field = self.action.get("field")
            value = self.action.get("value")
            if field and field not in result:
                result[field] = value
        
        elif action_type == "remove_field":
            field = self.action.get("field")
            if field and field in result:
                del result[field]
        
        elif action_type == "transform":
            field = self.action.get("field")
            func_name = self.action.get("function")
            if field and field in result and func_name:
                result[field] = self._apply_transform(result[field], func_name)
        
        elif action_type == "add_tag":
            tag = self.action.get("tag")
            if tag:
                if "tags" not in result:
                    result["tags"] = []
                if tag not in result["tags"]:
                    result["tags"].append(tag)
        
        elif action_type == "copy_field":
            source = self.action.get("source")
            target = self.action.get("target")
            if source and target and source in result:
                result[target] = result[source]
        
        return result
    
    def _apply_transform(self, value: Any, func_name: str) -> Any:
        transforms = {
            "upper": lambda x: str(x).upper(),
            "lower": lambda x: str(x).lower(),
            "strip": lambda x: str(x).strip(),
            "int": lambda x: int(x),
            "float": lambda x: float(x),
            "len": lambda x: len(x) if hasattr(x, '__len__') else 0,
        }
        
        func = transforms.get(func_name)
        if func:
            try:
                return func(value)
            except Exception:
                return value
        return value
    
    def __repr__(self) -> str:
        return f"Rule(name={self.name}, priority={self.priority})"


class RuleEngine:
    """
    规则引擎
    """
    
    def __init__(self):
        self.rules: List[Rule] = []
        self._sorted = False
    
    def add_rule(self, rule: Rule):
        self.rules.append(rule)
        self._sorted = False
    
    def add_rule_dict(
        self,
        name: str,
        condition: Dict[str, Any],
        action: Dict[str, Any],
        priority: int = 50
    ):
        """
        从字典添加规则
        """
        rule = Rule(name, condition, action, priority)
        self.add_rule(rule)
    
    def _ensure_sorted(self):
        """确保规则按优先级排序"""
        if not self._sorted:
            self.rules.sort(key=lambda r: r.priority, reverse=True)
            self._sorted = True
    
    def process(
        self,
        data: Dict[str, Any],
        apply_all: bool = False
    ) -> Dict[str, Any]:
        self._ensure_sorted()
        result = data.copy()
        
        for rule in self.rules:
            if rule.matches(result):
                result = rule.apply(result)
                if not apply_all:
                    break
        
        return result
    
    def process_batch(
        self,
        data_list: List[Dict[str, Any]],
        apply_all: bool = False
    ) -> List[Dict[str, Any]]:
        return [self.process(data, apply_all) for data in data_list]
    
    def find_matching_rules(self, data: Dict[str, Any]) -> List[Rule]:
        self._ensure_sorted()
        return [rule for rule in self.rules if rule.matches(data)]
    
    def clear_rules(self):
        self.rules.clear()
        self._sorted = False
    
    def rule_count(self) -> int:
        return len(self.rules)
    
    def __repr__(self) -> str:
        return f"RuleEngine(rules={len(self.rules)})"