geo-engine-python 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
geoengine/errors.py ADDED
@@ -0,0 +1,146 @@
1
+ """Jerarquía de errores del SDK de GeoEngine."""
2
+ from typing import Any, Dict, List, Optional
3
+
4
+
5
+ class GeoEngineError(Exception):
6
+ """Excepción base para errores del SDK de GeoEngine."""
7
+
8
+
9
+ class ClientClosedError(GeoEngineError):
10
+ """Se intentó usar un cliente ya cerrado. Equivale a ErrClientClosed en Go."""
11
+
12
+ def __init__(self, message: str = "geoengine: client is closed"):
13
+ super().__init__(message)
14
+
15
+
16
+ class NetworkError(GeoEngineError):
17
+ """Fallo de red al contactar la API (conexión rechazada, DNS, etc.)."""
18
+
19
+
20
+ class RequestTimeoutError(NetworkError):
21
+ """La petición superó el tiempo de espera configurado."""
22
+
23
+
24
+ # --- Validación local (no se llama a la API) ---
25
+
26
+
27
+ class ValidationError(GeoEngineError, ValueError):
28
+ """Un parámetro es inválido. También es un ValueError."""
29
+
30
+ default_message = "geoengine: invalid parameter"
31
+
32
+ def __init__(self, message: Optional[str] = None):
33
+ super().__init__(message or self.default_message)
34
+
35
+
36
+ class DeviceIDRequiredError(ValidationError):
37
+ default_message = "geoengine: device_id is required"
38
+
39
+
40
+ class GeofenceIDRequiredError(ValidationError):
41
+ default_message = "geoengine: geofence_id is required"
42
+
43
+
44
+ class InvalidLatitudeError(ValidationError):
45
+ default_message = "geoengine: latitude must be between -90 and 90 degrees"
46
+
47
+
48
+ class InvalidLongitudeError(ValidationError):
49
+ default_message = "geoengine: longitude must be between -180 and 180 degrees"
50
+
51
+
52
+ class InvalidCoordinatesError(ValidationError):
53
+ default_message = "geoengine: at least 3 coordinate pairs are required for a polygon"
54
+
55
+
56
+ class UserIDRequiredError(ValidationError):
57
+ default_message = "geoengine: user_id is required"
58
+
59
+
60
+ class RuleIDRequiredError(ValidationError):
61
+ default_message = "geoengine: rule_id is required"
62
+
63
+
64
+ class RuleNameRequiredError(ValidationError):
65
+ default_message = "geoengine: rule name is required"
66
+
67
+
68
+ class EmailRequiredError(ValidationError):
69
+ default_message = "geoengine: email is required"
70
+
71
+
72
+ class RoleRequiredError(ValidationError):
73
+ default_message = "geoengine: role is required"
74
+
75
+
76
+ # --- Errores devueltos por la API ---
77
+
78
+
79
+ class APIError(GeoEngineError):
80
+ """Error HTTP devuelto por la API de ingesta o de gestión. Equivale a APIError en Go."""
81
+
82
+ def __init__(self, status_code: int, message: str):
83
+ super().__init__(f"geoengine: API error (status {status_code}): {message}")
84
+ self.status_code = status_code
85
+ self.api_message = message
86
+
87
+
88
+ class APIServiceError(APIError):
89
+ """Error estructurado del api-service (Spatial, Users y GeoIdentity).
90
+
91
+ ``code`` es la razón legible por máquina (por ejemplo ``"USER_NOT_FOUND"``); queda
92
+ vacío si la API no envió ninguna. Equivale a APIServiceError / SpatialAPIError en Go.
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ status_code: int,
98
+ code: str,
99
+ message: str,
100
+ details: Optional[List[Dict[str, Any]]] = None,
101
+ ):
102
+ super().__init__(status_code, message)
103
+ self.code = code or ""
104
+ self.details = details or []
105
+ suffix = f", code {self.code}" if self.code else ""
106
+ self.args = (f"geoengine: api-service error (status {status_code}{suffix}): {message}",)
107
+
108
+
109
+ class GeofenceNotFoundError(APIServiceError):
110
+ """La geocerca no existe (204/404). Equivale a ErrGeofenceNotFound."""
111
+
112
+
113
+ class QuotaExceededError(APIServiceError):
114
+ """Se agotó la cuota de peticiones (402). Equivale a ErrQuotaExceeded."""
115
+
116
+
117
+ class AuthenticationError(APIServiceError):
118
+ """La autenticación falló (401, API key u organización ausente). Equivale a ErrUnauthorized."""
119
+
120
+
121
+ class ForbiddenError(APIServiceError):
122
+ """Acceso denegado (403). Equivale a ErrForbidden."""
123
+
124
+
125
+ class UserNotFoundError(APIServiceError):
126
+ """El usuario no existe en la organización o fue revocado. Equivale a ErrUserNotFound."""
127
+
128
+
129
+ class RuleNotFoundError(APIServiceError):
130
+ """La regla GeoIdentity no existe. Equivale a ErrRuleNotFound."""
131
+
132
+
133
+ class UserAlreadyExistsError(APIServiceError):
134
+ """El email invitado ya pertenece a la organización. Equivale a ErrUserAlreadyExists."""
135
+
136
+
137
+ class InvitationPendingError(APIServiceError):
138
+ """Ya existe una invitación pendiente para el email. Equivale a ErrInvitationPending."""
139
+
140
+
141
+ class LastAdminError(APIServiceError):
142
+ """La operación dejaría a la organización sin administradores. Equivale a ErrLastAdmin."""
143
+
144
+
145
+ class LastSubjectError(APIServiceError):
146
+ """La operación dejaría a la regla sin sujetos asignados. Equivale a ErrLastSubject."""
@@ -0,0 +1,186 @@
1
+ """Módulo GeoIdentity: reglas de acceso y su asignación a usuarios u organización."""
2
+ import dataclasses
3
+ from typing import Any, Dict, List, Optional, Sequence, Union
4
+ from urllib.parse import quote
5
+
6
+ from ._http import API_SERVICE, Transport
7
+ from .errors import RuleIDRequiredError, RuleNameRequiredError, UserIDRequiredError
8
+ from .models import Rule, SubjectAssignment
9
+ from .users import user_path
10
+ from .validation import normalize_polygon, require_text
11
+
12
+ RULES_PATH = "/api/users/geoidentity/rules"
13
+
14
+ Subject = Union[SubjectAssignment, Dict[str, str]]
15
+
16
+
17
+ class _Unset:
18
+ def __repr__(self) -> str:
19
+ return "UNSET"
20
+
21
+
22
+ #: Valor por defecto de update_rule: el campo no se envía y queda sin cambios.
23
+ UNSET: Any = _Unset()
24
+
25
+
26
+ def polygon_from_lat_lng(coordinates: Sequence[Sequence[float]]) -> Dict[str, Any]:
27
+ """Construye un Polygon GeoJSON para ``geo_limit`` a partir de pares [lat, lng].
28
+
29
+ Usa el mismo orden que ``GeoEngine.create_geofence`` y cierra el anillo automáticamente.
30
+ """
31
+ return {"type": "Polygon", "coordinates": [normalize_polygon(coordinates)]}
32
+
33
+
34
+ def _rule_path(rule_id: str, suffix: str = "") -> str:
35
+ return f"{RULES_PATH}/{quote(require_text(rule_id, RuleIDRequiredError), safe='')}{suffix}"
36
+
37
+
38
+ def _subjects(subjects: Sequence[Subject]) -> List[Dict[str, str]]:
39
+ return [dataclasses.asdict(s) if isinstance(s, SubjectAssignment) else dict(s) for s in subjects]
40
+
41
+
42
+ class GeoIdentityService:
43
+ """Equivale a GeoIdentityService en Go."""
44
+
45
+ def __init__(self, transport: Transport, base_url: str):
46
+ self._transport = transport
47
+ self._base_url = base_url
48
+
49
+ def _send(self, method: str, path: str, body=None):
50
+ return self._transport.request(method, self._base_url + path, body, API_SERVICE)
51
+
52
+ def create_rule(
53
+ self,
54
+ name: str,
55
+ *,
56
+ description: Optional[str] = None,
57
+ priority: Optional[int] = None,
58
+ action: Optional[str] = None,
59
+ is_active: Optional[bool] = None,
60
+ white_ip_list: Optional[Sequence[str]] = None,
61
+ black_ip_list: Optional[Sequence[str]] = None,
62
+ block_datacenter: Optional[bool] = None,
63
+ block_tor: Optional[bool] = None,
64
+ risk_accepted: Optional[int] = None,
65
+ geo_limit: Optional[Dict[str, Any]] = None,
66
+ assigned_subjects: Optional[Sequence[Subject]] = None,
67
+ ) -> Rule:
68
+ """Crea una regla GeoIdentity.
69
+
70
+ Las listas de IPs aceptan IPs o rangos CIDR. ``geo_limit`` es un Polygon o MultiPolygon
71
+ GeoJSON (ver ``polygon_from_lat_lng``). Sin ``assigned_subjects`` la regla aplica a
72
+ toda la organización.
73
+ """
74
+ if not isinstance(name, str) or not name.strip():
75
+ raise RuleNameRequiredError()
76
+ payload = _rule_payload(
77
+ name=name,
78
+ description=description,
79
+ priority=priority,
80
+ action=action,
81
+ is_active=is_active,
82
+ white_ip_list=white_ip_list,
83
+ black_ip_list=black_ip_list,
84
+ block_datacenter=block_datacenter,
85
+ block_tor=block_tor,
86
+ risk_accepted=risk_accepted,
87
+ geo_limit=geo_limit,
88
+ assigned_subjects=assigned_subjects,
89
+ skip=None,
90
+ )
91
+ return Rule.from_dict(self._send("POST", RULES_PATH, payload))
92
+
93
+ def list_rules(self, is_active: Optional[bool] = None) -> List[Rule]:
94
+ """Devuelve las reglas ordenadas por prioridad. ``is_active=None`` devuelve todas.
95
+
96
+ Usa ``get_rule`` para cargar los sujetos asignados de una regla.
97
+ """
98
+ query = "" if is_active is None else f"?is_active={'true' if is_active else 'false'}"
99
+ return [Rule.from_dict(r) for r in self._send("GET", RULES_PATH + query) or []]
100
+
101
+ def get_rule(self, rule_id: str) -> Rule:
102
+ """Devuelve una regla con sus sujetos asignados."""
103
+ return Rule.from_dict(self._send("GET", _rule_path(rule_id)))
104
+
105
+ def update_rule(
106
+ self,
107
+ rule_id: str,
108
+ *,
109
+ name: str = UNSET,
110
+ description: str = UNSET,
111
+ priority: int = UNSET,
112
+ action: str = UNSET,
113
+ is_active: bool = UNSET,
114
+ white_ip_list: Sequence[str] = UNSET,
115
+ black_ip_list: Sequence[str] = UNSET,
116
+ block_datacenter: bool = UNSET,
117
+ block_tor: bool = UNSET,
118
+ risk_accepted: int = UNSET,
119
+ geo_limit: Optional[Dict[str, Any]] = UNSET,
120
+ assigned_subjects: Sequence[Subject] = UNSET,
121
+ ) -> Rule:
122
+ """Actualiza parcialmente una regla: solo se envían los campos indicados.
123
+
124
+ Pasa ``geo_limit=None`` para quitar el límite geográfico.
125
+ """
126
+ payload = _rule_payload(
127
+ name=name,
128
+ description=description,
129
+ priority=priority,
130
+ action=action,
131
+ is_active=is_active,
132
+ white_ip_list=white_ip_list,
133
+ black_ip_list=black_ip_list,
134
+ block_datacenter=block_datacenter,
135
+ block_tor=block_tor,
136
+ risk_accepted=risk_accepted,
137
+ geo_limit=geo_limit,
138
+ assigned_subjects=assigned_subjects,
139
+ skip=UNSET,
140
+ )
141
+ return Rule.from_dict(self._send("PATCH", _rule_path(rule_id), payload))
142
+
143
+ def delete_rule(self, rule_id: str) -> None:
144
+ """Elimina una regla y todas sus asignaciones."""
145
+ self._send("DELETE", _rule_path(rule_id))
146
+
147
+ def assign_to_user(self, rule_id: str, user_id: str) -> Rule:
148
+ """Aplica la regla a un miembro. Asignar dos veces no tiene efecto."""
149
+ return self._change_assignment("POST", rule_id, user_id)
150
+
151
+ def assign_to_organization(self, rule_id: str) -> Rule:
152
+ """Aplica la regla a todos los miembros de la organización."""
153
+ return self._change_assignment("POST", rule_id)
154
+
155
+ def unassign_from_user(self, rule_id: str, user_id: str) -> Rule:
156
+ """Quita la asignación de un usuario.
157
+
158
+ Lanza LastSubjectError si es el único sujeto de la regla; desactívala o elimínala.
159
+ """
160
+ return self._change_assignment("DELETE", rule_id, user_id)
161
+
162
+ def unassign_from_organization(self, rule_id: str) -> Rule:
163
+ """Quita la asignación a toda la organización. Lanza LastSubjectError si es el único sujeto."""
164
+ return self._change_assignment("DELETE", rule_id)
165
+
166
+ def list_user_rules(self, user_id: str) -> List[Rule]:
167
+ """Reglas que aplican a un usuario: directas, por su rol o de toda la organización."""
168
+ return [Rule.from_dict(r) for r in self._send("GET", user_path(user_id, "/geoidentity/rules")) or []]
169
+
170
+ def _change_assignment(self, method: str, rule_id: str, user_id: Any = UNSET) -> Rule:
171
+ if user_id is UNSET:
172
+ payload = {"scope": "organization"}
173
+ else:
174
+ payload = {"scope": "user", "user_id": require_text(user_id, UserIDRequiredError)}
175
+ return Rule.from_dict(self._send(method, _rule_path(rule_id, "/assignments"), payload))
176
+
177
+
178
+ def _rule_payload(skip: Any, **fields: Any) -> Dict[str, Any]:
179
+ """Arma el cuerpo de create/update omitiendo los campos cuyo valor es ``skip``."""
180
+ payload = {key: value for key, value in fields.items() if value is not skip}
181
+ if payload.get("assigned_subjects") is not None:
182
+ payload["assigned_subjects"] = _subjects(payload["assigned_subjects"])
183
+ for key in ("white_ip_list", "black_ip_list"):
184
+ if payload.get(key) is not None:
185
+ payload[key] = list(payload[key])
186
+ return payload
geoengine/ingester.py ADDED
@@ -0,0 +1,73 @@
1
+ """Ingesta asíncrona por lotes en un hilo de fondo."""
2
+ import queue
3
+ import threading
4
+ from typing import Any, Dict, Union
5
+
6
+ from .models import LocationPing
7
+
8
+ _STOP = object()
9
+
10
+
11
+ class AsyncIngester:
12
+ """Cola en memoria con auto-flush por tamaño de lote o intervalo. Equivale a AsyncIngester en Go.
13
+
14
+ Los errores de envío en segundo plano se descartan; ``enqueue`` nunca bloquea.
15
+ """
16
+
17
+ def __init__(self, client, buffer_size: int = 5000, batch_size: int = 100, flush_interval: float = 0.5):
18
+ self._client = client
19
+ self._batch_size = max(1, batch_size)
20
+ self._interval = flush_interval
21
+ self._queue: "queue.Queue" = queue.Queue(maxsize=buffer_size)
22
+ self._closed = False
23
+ self._lock = threading.Lock()
24
+ self._worker = threading.Thread(target=self._run, name="geoengine-ingester", daemon=True)
25
+ self._worker.start()
26
+
27
+ def enqueue(self, ping: Union[LocationPing, Dict[str, Any]]) -> bool:
28
+ """Encola un ping sin bloquear. Devuelve False si la cola está llena o el ingester está detenido."""
29
+ if ping is None:
30
+ return False
31
+ with self._lock:
32
+ if self._closed:
33
+ return False
34
+ try:
35
+ self._queue.put_nowait(ping)
36
+ return True
37
+ except queue.Full:
38
+ return False
39
+
40
+ def stop(self) -> None:
41
+ """Envía todo lo pendiente y detiene el hilo. Se puede llamar varias veces."""
42
+ with self._lock:
43
+ if self._closed:
44
+ return
45
+ self._closed = True
46
+ self._queue.put(_STOP)
47
+ self._worker.join()
48
+
49
+ def _run(self) -> None:
50
+ batch = []
51
+ while True:
52
+ try:
53
+ item = self._queue.get(timeout=self._interval)
54
+ except queue.Empty:
55
+ self._flush(batch)
56
+ continue
57
+ if item is _STOP:
58
+ self._flush(batch)
59
+ return
60
+ batch.append(item)
61
+ if len(batch) >= self._batch_size:
62
+ self._flush(batch)
63
+
64
+ def _flush(self, batch: list) -> None:
65
+ for ping in batch:
66
+ try:
67
+ if isinstance(ping, dict):
68
+ self._client.send_location(ping["device_id"], ping["latitude"], ping["longitude"])
69
+ else:
70
+ self._client.send_location(ping.device_id, ping.latitude, ping.longitude)
71
+ except Exception:
72
+ pass
73
+ del batch[:]
geoengine/models.py ADDED
@@ -0,0 +1,218 @@
1
+ """Modelos devueltos por el SDK. Los nombres de campo coinciden con los de la API."""
2
+ import dataclasses
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+
7
+ def _from_dict(cls, data: Optional[Dict[str, Any]]):
8
+ """Crea el dataclass ignorando claves desconocidas y valores null."""
9
+ data = data or {}
10
+ names = {f.name for f in dataclasses.fields(cls)}
11
+ return cls(**{k: v for k, v in data.items() if k in names and v is not None})
12
+
13
+
14
+ @dataclass
15
+ class LocationPing:
16
+ """Un punto de telemetría para AsyncIngester."""
17
+
18
+ device_id: str
19
+ latitude: float
20
+ longitude: float
21
+
22
+
23
+ # --- Spatial ---
24
+
25
+
26
+ @dataclass
27
+ class SpatialValidationResult:
28
+ """Resultado de validar un punto contra una geocerca."""
29
+
30
+ inside: bool = False
31
+ geofence_id: str = ""
32
+ geofence_name: str = ""
33
+ latitude: float = 0.0
34
+ longitude: float = 0.0
35
+
36
+ def is_inside(self) -> bool:
37
+ return bool(self.inside)
38
+
39
+ def is_outside(self) -> bool:
40
+ return not self.inside
41
+
42
+ def coordinates(self) -> Tuple[float, float]:
43
+ return (self.latitude, self.longitude)
44
+
45
+ def __str__(self) -> str:
46
+ status = "INSIDE" if self.inside else "OUTSIDE"
47
+ return (
48
+ f"[{status}] geofence={self.geofence_id} ({self.geofence_name or 'unnamed'}) "
49
+ f"at ({self.latitude:.6f}, {self.longitude:.6f})"
50
+ )
51
+
52
+
53
+ @dataclass
54
+ class GeofenceMatch:
55
+ id: str = ""
56
+ name: str = ""
57
+
58
+
59
+ @dataclass
60
+ class SpatialGeneralResult:
61
+ """Resultado de validar un punto contra todas las geocercas activas."""
62
+
63
+ inside: bool = False
64
+ total_matches: int = 0
65
+ matched_geofences: List[GeofenceMatch] = field(default_factory=list)
66
+ latitude: float = 0.0
67
+ longitude: float = 0.0
68
+
69
+ @classmethod
70
+ def from_dict(cls, data: Optional[Dict[str, Any]]) -> "SpatialGeneralResult":
71
+ result = _from_dict(cls, data)
72
+ result.matched_geofences = [_from_dict(GeofenceMatch, m) for m in result.matched_geofences]
73
+ if not result.total_matches:
74
+ result.total_matches = len(result.matched_geofences)
75
+ return result
76
+
77
+ def is_inside(self) -> bool:
78
+ return bool(self.inside)
79
+
80
+ def has_matches(self) -> bool:
81
+ return self.total_matches > 0
82
+
83
+ def first_match(self) -> Optional[GeofenceMatch]:
84
+ return self.matched_geofences[0] if self.matched_geofences else None
85
+
86
+ def geofence_ids(self) -> List[str]:
87
+ return [m.id for m in self.matched_geofences]
88
+
89
+ def geofence_names(self) -> List[str]:
90
+ return [m.name for m in self.matched_geofences]
91
+
92
+ def find_match(self, id_or_name: str) -> Optional[GeofenceMatch]:
93
+ for match in self.matched_geofences:
94
+ if id_or_name in (match.id, match.name):
95
+ return match
96
+ return None
97
+
98
+ def contains_geofence(self, id_or_name: str) -> bool:
99
+ return self.find_match(id_or_name) is not None
100
+
101
+ def coordinates(self) -> Tuple[float, float]:
102
+ return (self.latitude, self.longitude)
103
+
104
+ def __str__(self) -> str:
105
+ status = "INSIDE" if self.inside else "OUTSIDE"
106
+ names = ", ".join(self.geofence_names())
107
+ return (
108
+ f"[{status}] matches={self.total_matches} ({names}) "
109
+ f"at ({self.latitude:.6f}, {self.longitude:.6f})"
110
+ )
111
+
112
+
113
+ # --- Users ---
114
+
115
+
116
+ class Roles:
117
+ """Roles de organización. La API también acepta la forma corta ("admin", "viewer", ...)."""
118
+
119
+ ADMIN = "roles/geoengine.admin"
120
+ DISPATCHER = "roles/geoengine.dispatcher"
121
+ BILLING = "roles/geoengine.billing"
122
+ VIEWER = "roles/geoengine.viewer"
123
+ DEVICE = "roles/geoengine.device"
124
+
125
+
126
+ class UserStatus:
127
+ ACTIVE = "active"
128
+ PENDING = "pending"
129
+ REVOKED = "revoked"
130
+
131
+
132
+ @dataclass
133
+ class User:
134
+ """Miembro de la organización dueña de la API key. Las fechas son strings ISO 8601."""
135
+
136
+ id: str = ""
137
+ email: str = ""
138
+ name: str = ""
139
+ role: str = ""
140
+ status: str = ""
141
+ permissions: List[str] = field(default_factory=list)
142
+ created_at: Optional[str] = None
143
+ last_login_at: Optional[str] = None
144
+
145
+
146
+ @dataclass
147
+ class Role:
148
+ """Rol de organización y los permisos que otorga."""
149
+
150
+ id: str = ""
151
+ permissions: List[str] = field(default_factory=list)
152
+
153
+
154
+ @dataclass
155
+ class Invitation:
156
+ """Resultado de users.invite. GeoEngine envía el correo; invite_url permite entregarlo por otro canal."""
157
+
158
+ email: str = ""
159
+ role: str = ""
160
+ status: str = ""
161
+ invite_url: str = ""
162
+ expires_at: Optional[str] = None
163
+
164
+
165
+ # --- GeoIdentity ---
166
+
167
+
168
+ class RuleAction:
169
+ """Veredicto aplicado cuando una regla GeoIdentity coincide."""
170
+
171
+ ALLOW = "ALLOW"
172
+ BLOCK = "BLOCK"
173
+ CHALLENGE = "CHALLENGE"
174
+
175
+
176
+ class SubjectType:
177
+ """A quién aplica una regla. ALL aplica a toda la organización (subject_id "*")."""
178
+
179
+ USER = "USER"
180
+ ROLE = "ROLE"
181
+ DEVICE = "DEVICE"
182
+ ALL = "ALL"
183
+
184
+
185
+ @dataclass
186
+ class SubjectAssignment:
187
+ subject_type: str = ""
188
+ subject_id: str = ""
189
+
190
+
191
+ @dataclass
192
+ class Rule:
193
+ """Política de acceso GeoIdentity. Las fechas son strings ISO 8601."""
194
+
195
+ id: str = ""
196
+ org_id: str = ""
197
+ name: str = ""
198
+ description: str = ""
199
+ priority: int = 0
200
+ action: str = ""
201
+ is_active: bool = False
202
+ white_ip_list: List[str] = field(default_factory=list)
203
+ black_ip_list: List[str] = field(default_factory=list)
204
+ block_datacenter: bool = False
205
+ block_tor: bool = False
206
+ risk_accepted: int = 0
207
+ geo_limit: Optional[Dict[str, Any]] = None
208
+ # Solo se llena en llamadas que devuelven una única regla (get_rule, create_rule, asignaciones...).
209
+ assigned_subjects: List[SubjectAssignment] = field(default_factory=list)
210
+ subjects_count: int = 0
211
+ created_at: Optional[str] = None
212
+ updated_at: Optional[str] = None
213
+
214
+ @classmethod
215
+ def from_dict(cls, data: Optional[Dict[str, Any]]) -> "Rule":
216
+ rule = _from_dict(cls, data)
217
+ rule.assigned_subjects = [_from_dict(SubjectAssignment, s) for s in rule.assigned_subjects]
218
+ return rule
geoengine/spatial.py ADDED
@@ -0,0 +1,75 @@
1
+ """Módulo Spatial: validación punto-en-polígono contra el api-service."""
2
+ from ._http import SPATIAL, Transport
3
+ from .models import SpatialGeneralResult, SpatialValidationResult, _from_dict
4
+ from .validation import validate_coordinates, validate_geofence_id
5
+
6
+
7
+ class SpatialService:
8
+ """Equivale a SpatialService en Go."""
9
+
10
+ def __init__(self, transport: Transport, base_url: str):
11
+ self._transport = transport
12
+ self._base_url = base_url
13
+
14
+ def validate_point(self, geofence_id: str, lat: float, lng: float) -> SpatialValidationResult:
15
+ """Indica si las coordenadas caen dentro de la geocerca.
16
+
17
+ Lanza GeofenceNotFoundError si la geocerca no existe.
18
+ """
19
+ payload = {
20
+ "geofence_id": validate_geofence_id(geofence_id),
21
+ "latitude": lat,
22
+ "longitude": lng,
23
+ }
24
+ validate_coordinates(lat, lng)
25
+ data = self._transport.request("POST", f"{self._base_url}/api/spatial/validate", payload, SPATIAL)
26
+ return _from_dict(SpatialValidationResult, data)
27
+
28
+ def validate_general(self, lat: float, lng: float) -> SpatialGeneralResult:
29
+ """Valida las coordenadas contra todas las geocercas activas de la organización."""
30
+ validate_coordinates(lat, lng)
31
+ data = self._transport.request(
32
+ "POST",
33
+ f"{self._base_url}/api/spatial/validate-general",
34
+ {"latitude": lat, "longitude": lng},
35
+ SPATIAL,
36
+ )
37
+ return SpatialGeneralResult.from_dict(data)
38
+
39
+ def check(self, lat: float, lng: float) -> "SpatialCheckBuilder":
40
+ """Constructor fluido: ``spatial.check(lat, lng).in_geofence(id).execute()``."""
41
+ return SpatialCheckBuilder(self, lat, lng)
42
+
43
+
44
+ class SpatialCheckBuilder:
45
+ def __init__(self, service: SpatialService, lat: float, lng: float):
46
+ self._service = service
47
+ self._lat = lat
48
+ self._lng = lng
49
+
50
+ def in_geofence(self, geofence_id: str) -> "SingleGeofenceCheck":
51
+ return SingleGeofenceCheck(self._service, geofence_id, self._lat, self._lng)
52
+
53
+ def in_all_geofences(self) -> "GeneralGeofenceCheck":
54
+ return GeneralGeofenceCheck(self._service, self._lat, self._lng)
55
+
56
+
57
+ class SingleGeofenceCheck:
58
+ def __init__(self, service: SpatialService, geofence_id: str, lat: float, lng: float):
59
+ self._service = service
60
+ self._geofence_id = geofence_id
61
+ self._lat = lat
62
+ self._lng = lng
63
+
64
+ def execute(self) -> SpatialValidationResult:
65
+ return self._service.validate_point(self._geofence_id, self._lat, self._lng)
66
+
67
+
68
+ class GeneralGeofenceCheck:
69
+ def __init__(self, service: SpatialService, lat: float, lng: float):
70
+ self._service = service
71
+ self._lat = lat
72
+ self._lng = lng
73
+
74
+ def execute(self) -> SpatialGeneralResult:
75
+ return self._service.validate_general(self._lat, self._lng)