Bin
2025-12-16 7423b0c6e1959f30a7e8e453e953310f32ce13c6
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""
FSM Model Registry for Model State Management.
 
This module provides a registry system for state models and state choices,
allowing the FSM to be decoupled from concrete implementations.
"""
 
import logging
import typing
from typing import Dict, Optional, Type
 
from django.db.models import Model, TextChoices
 
if typing.TYPE_CHECKING:
    from fsm.state_models import BaseState
    from fsm.transitions import BaseTransition
 
logger = logging.getLogger(__name__)
 
 
class StateChoicesRegistry:
    """
    Registry for managing state choices for different entity types.
 
    Provides a centralized way to register, discover, and manage state choices
    for different entity types in the FSM system.
    """
 
    def __init__(self):
        self._choices: Dict[str, Type[TextChoices]] = {}
 
    def register(self, entity_name: str, choices_class: Type[TextChoices]):
        """
        Register state choices for an entity type.
 
        Args:
            entity_name: Name of the entity (e.g., 'task', 'annotation')
            choices_class: Django TextChoices class defining valid states
        """
        self._choices[entity_name.lower()] = choices_class
 
    def get_choices(self, entity_name: str) -> Optional[Type[TextChoices]]:
        """
        Get state choices for an entity type.
 
        Args:
            entity_name: Name of the entity
 
        Returns:
            Django TextChoices class or None if not found
        """
        return self._choices.get(entity_name.lower())
 
    def list_entities(self) -> list[str]:
        """Get a list of all registered entity types."""
        return list(self._choices.keys())
 
    def clear(self):
        """
        Clear all registered choices.
 
        Useful for testing to ensure clean state between tests.
        """
        self._choices.clear()
 
 
# Global state choices registry instance
state_choices_registry = StateChoicesRegistry()
 
 
def get_state_choices(entity_name: str):
    """
    Get state choices for an entity type.
 
    Args:
        entity_name: Name of the entity
 
    Returns:
        Django TextChoices class or None if not found
    """
    return state_choices_registry.get_choices(entity_name)
 
 
def register_state_choices(entity_name: str):
    """
    Decorator to register state choices for an entity type.
 
    Args:
        entity_name: Name of the entity type
 
    Example:
        @register_state_choices('task')
        class TaskStateChoices(models.TextChoices):
            CREATED = 'CREATED', _('Created')
            IN_PROGRESS = 'IN_PROGRESS', _('In Progress')
            COMPLETED = 'COMPLETED', _('Completed')
    """
 
    def decorator(choices_class: Type[TextChoices]) -> Type[TextChoices]:
        state_choices_registry.register(entity_name, choices_class)
        return choices_class
 
    return decorator
 
 
class StateModelRegistry:
    """
    Registry for state models and their configurations.
 
    This allows projects to register their state models dynamically
    without hardcoding them in the FSM framework.
    """
 
    def __init__(self):
        self._models: Dict[str, 'BaseState'] = {}
 
    def register_model(self, entity_name: str, state_model: 'BaseState'):
        """
        Register a state model for an entity type.
 
        Args:
            entity_name: Name of the entity (e.g., 'task', 'annotation')
            state_model: The state model class for this entity
        """
        entity_key = entity_name.lower()
 
        if entity_key in self._models:
            logger.debug(
                'Overwriting existing state model',
                extra={
                    'event': 'fsm.registry_overwrite',
                    'entity_type': entity_key,
                    'previous_model': self._models[entity_key].__name__,
                    'new_model': state_model.__name__,
                },
            )
 
        self._models[entity_key] = state_model
        logger.debug(
            'Registered state model',
            extra={
                'event': 'fsm.model_registered',
                'entity_type': entity_key,
                'model_name': state_model.__name__,
            },
        )
 
    def get_model(self, entity_name: str) -> Optional['BaseState']:
        """
        Get the state model for an entity type.
 
        Args:
            entity_name: Name of the entity
 
        Returns:
            State model class or None if not registered
        """
        return self._models.get(entity_name.lower())
 
    def is_registered(self, entity_name: str) -> bool:
        """Check if a model is registered for an entity type."""
        return entity_name.lower() in self._models
 
    def clear(self):
        """Clear all registered models (useful for testing)."""
        self._models.clear()
        logger.debug(
            'State model registry cleared',
            extra={'event': 'fsm.registry_cleared'},
        )
 
    def get_all_models(self) -> Dict[str, 'BaseState']:
        """Get all registered models."""
        return self._models.copy()
 
 
# Global registry instance
state_model_registry = StateModelRegistry()
 
 
def register_state_model(entity_name: str):
    """
    Decorator to register a state model.
 
    Args:
        entity_name: Name of the entity (e.g., 'task', 'annotation')
 
    Example:
        @register_state_model('task')
        class TaskState(BaseState):
            @classmethod
            def get_denormalized_fields(cls, entity):
                return {
                    'project_id': entity.project_id,
                    'priority': entity.priority
                }
    """
 
    def decorator(state_model: 'BaseState') -> 'BaseState':
        state_model_registry.register_model(entity_name, state_model)
        return state_model
 
    return decorator
 
 
def register_state_model_class(entity_name: str, state_model: 'BaseState'):
    """
    Convenience function to register a state model programmatically.
 
    Args:
        entity_name: Name of the entity (e.g., 'task', 'annotation')
        state_model: The state model class for this entity
    """
    state_model_registry.register_model(entity_name, state_model)
 
 
def get_state_model(entity_name: str) -> Optional['BaseState']:
    """
    Convenience function to get a state model.
 
    Args:
        entity_name: Name of the entity
 
    Returns:
        State model class or None if not registered
    """
    return state_model_registry.get_model(entity_name)
 
 
def get_state_model_for_entity(entity: Model) -> Optional['BaseState']:
    """Get the state model for an entity."""
    entity_name = entity._meta.model_name.lower()
    return get_state_model(entity_name)
 
 
class TransitionRegistry:
    """
    Registry for managing declarative transitions.
 
    Provides a centralized way to register, discover, and execute transitions
    for different entity types and state models.
    """
 
    def __init__(self):
        self._transitions: Dict[str, Dict[str, 'BaseTransition']] = {}
 
    def register(self, entity_name: str, transition_name: str, transition_class: 'BaseTransition'):
        """
        Register a transition class for an entity.
 
        Args:
            entity_name: Name of the entity type (e.g., 'task', 'annotation')
            transition_name: Name of the transition (e.g., 'start_task', 'submit_annotation')
            transition_class: The transition class to register
        """
        if entity_name not in self._transitions:
            self._transitions[entity_name] = {}
 
        self._transitions[entity_name][transition_name] = transition_class
 
    def get_transition(self, entity_name: str, transition_name: str) -> Optional['BaseTransition']:
        """
        Get a registered transition class.
 
        Args:
            entity_name: Name of the entity type
            transition_name: Name of the transition
 
        Returns:
            The transition class if found, None otherwise
        """
        return self._transitions.get(entity_name, {}).get(transition_name)
 
    def get_transitions_for_entity(self, entity_name: str) -> Dict[str, 'BaseTransition']:
        """
        Get all registered transitions for an entity type.
 
        Args:
            entity_name: Name of the entity type
 
        Returns:
            Dictionary mapping transition names to transition classes
        """
        return self._transitions.get(entity_name, {}).copy()
 
    def list_entities(self) -> list[str]:
        """Get a list of all registered entity types."""
        return list(self._transitions.keys())
 
    def clear(self):
        """
        Clear all registered transitions.
 
        Useful for testing to ensure clean state between tests.
        """
        self._transitions.clear()
 
 
# Global transition registry instance
transition_registry = TransitionRegistry()
 
 
def register_state_transition(
    entity_name: str,
    transition_name: str,
    triggers_on_create: bool = False,
    triggers_on_update: bool = True,
    triggers_on: list = None,
    force_state_record: bool = False,
):
    """
    Decorator to register a state transition class with trigger metadata.
 
    This decorator not only registers the transition but also configures when
    it should be triggered based on model changes.
 
    Args:
        entity_name: Name of the entity type (e.g., 'task', 'project')
        transition_name: Name of the transition (e.g., 'task_created')
        triggers_on_create: If True, triggers when entity is created
        triggers_on_update: If True, can trigger on updates (default: True)
        triggers_on: List of field names that trigger this transition
        force_state_record: If True, creates state record even if state doesn't change (for audit trails)
 
    Example:
        # Trigger only on creation
        @register_state_transition('task', 'task_created', triggers_on_create=True)
        class TaskCreatedTransition(ModelChangeTransition):
            pass
 
        # Trigger when specific fields change
        @register_state_transition('project', 'project_published', triggers_on=['is_published'])
        class ProjectPublishedTransition(ModelChangeTransition):
            pass
 
        # Trigger when any of several fields change
        @register_state_transition('project', 'settings_changed',
                                   triggers_on=['maximum_annotations', 'overlap_cohort_percentage'])
        class ProjectSettingsChangedTransition(ModelChangeTransition):
            pass
    """
 
    def decorator(transition_class: 'BaseTransition') -> 'BaseTransition':
        # Store trigger metadata and transition name on the class
        transition_class._triggers_on_create = triggers_on_create
        transition_class._triggers_on_update = triggers_on_update
        transition_class._trigger_fields = triggers_on or []
        transition_class._transition_name = transition_name  # Store the registered transition name
        transition_class._force_state_record = force_state_record  # Store whether to force state record creation
 
        transition_registry.register(entity_name, transition_name, transition_class)
        return transition_class
 
    return decorator