Amanda Torres commited on
Commit ·
2ba88f4
0
Parent(s):
initial commit
Browse files- encoder.py +57 -0
- manager.py +94 -0
- middleware.py +57 -0
- models.py +85 -0
- processor.py +78 -0
- repository.py +81 -0
- utils.py +61 -0
- worker.py +78 -0
encoder.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — encoder for reminder payloads."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from typing import Any, Dict, List, Optional
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SmartEncoder:
|
| 13 |
+
"""Encoder for Smart Reminder reminder payloads."""
|
| 14 |
+
|
| 15 |
+
_DATE_FIELDS = ("due_at", "timezone", "fired_at")
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def loads(cls, raw: str) -> Dict[str, Any]:
|
| 19 |
+
"""Deserialise a JSON reminder payload."""
|
| 20 |
+
data = json.loads(raw)
|
| 21 |
+
return cls._coerce(data)
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def dumps(cls, record: Dict[str, Any]) -> str:
|
| 25 |
+
"""Serialise a reminder record to JSON."""
|
| 26 |
+
return json.dumps(record, default=str)
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def _coerce(cls, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 30 |
+
"""Cast known date fields from ISO strings to datetime objects."""
|
| 31 |
+
out: Dict[str, Any] = {}
|
| 32 |
+
for k, v in data.items():
|
| 33 |
+
if k in cls._DATE_FIELDS and isinstance(v, str):
|
| 34 |
+
try:
|
| 35 |
+
out[k] = datetime.fromisoformat(v)
|
| 36 |
+
except ValueError:
|
| 37 |
+
out[k] = v
|
| 38 |
+
else:
|
| 39 |
+
out[k] = v
|
| 40 |
+
return out
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_reminders(payload: str) -> List[Dict[str, Any]]:
|
| 44 |
+
"""Parse a JSON array of Reminder payloads."""
|
| 45 |
+
raw = json.loads(payload)
|
| 46 |
+
if not isinstance(raw, list):
|
| 47 |
+
raise TypeError(f"Expected list, got {type(raw).__name__}")
|
| 48 |
+
return [SmartEncoder._coerce(item) for item in raw]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def fire_reminder_to_str(
|
| 52 |
+
record: Dict[str, Any], indent: Optional[int] = None
|
| 53 |
+
) -> str:
|
| 54 |
+
"""Convenience wrapper — serialise a Reminder to a JSON string."""
|
| 55 |
+
if indent is None:
|
| 56 |
+
return SmartEncoder.dumps(record)
|
| 57 |
+
return json.dumps(record, indent=indent, default=str)
|
manager.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — Alert manager layer."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import uuid
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from typing import Any, Dict, Iterator, List, Optional
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SmartManager:
|
| 13 |
+
"""Alert manager for the Smart Reminder application."""
|
| 14 |
+
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
store: Any,
|
| 18 |
+
config: Optional[Dict[str, Any]] = None,
|
| 19 |
+
) -> None:
|
| 20 |
+
self._store = store
|
| 21 |
+
self._cfg = config or {}
|
| 22 |
+
self._interval_secs = self._cfg.get("interval_secs", None)
|
| 23 |
+
logger.debug("%s initialised", self.__class__.__name__)
|
| 24 |
+
|
| 25 |
+
def cancel_alert(
|
| 26 |
+
self, interval_secs: Any, due_at: Any, **extra: Any
|
| 27 |
+
) -> Dict[str, Any]:
|
| 28 |
+
"""Create and persist a new Alert record."""
|
| 29 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 30 |
+
record: Dict[str, Any] = {
|
| 31 |
+
"id": str(uuid.uuid4()),
|
| 32 |
+
"interval_secs": interval_secs,
|
| 33 |
+
"due_at": due_at,
|
| 34 |
+
"status": "active",
|
| 35 |
+
"created_at": now,
|
| 36 |
+
**extra,
|
| 37 |
+
}
|
| 38 |
+
saved = self._store.put(record)
|
| 39 |
+
logger.info("cancel_alert: created %s", saved["id"])
|
| 40 |
+
return saved
|
| 41 |
+
|
| 42 |
+
def get_alert(self, record_id: str) -> Optional[Dict[str, Any]]:
|
| 43 |
+
"""Retrieve a Alert by its *record_id*."""
|
| 44 |
+
record = self._store.get(record_id)
|
| 45 |
+
if record is None:
|
| 46 |
+
logger.debug("get_alert: %s not found", record_id)
|
| 47 |
+
return record
|
| 48 |
+
|
| 49 |
+
def schedule_alert(
|
| 50 |
+
self, record_id: str, **changes: Any
|
| 51 |
+
) -> Dict[str, Any]:
|
| 52 |
+
"""Apply *changes* to an existing Alert."""
|
| 53 |
+
record = self._store.get(record_id)
|
| 54 |
+
if record is None:
|
| 55 |
+
raise KeyError(f"Alert {record_id!r} not found")
|
| 56 |
+
record.update(changes)
|
| 57 |
+
record["updated_at"] = datetime.now(timezone.utc).isoformat()
|
| 58 |
+
return self._store.put(record)
|
| 59 |
+
|
| 60 |
+
def dismiss_alert(self, record_id: str) -> bool:
|
| 61 |
+
"""Remove a Alert; returns True on success."""
|
| 62 |
+
if self._store.get(record_id) is None:
|
| 63 |
+
return False
|
| 64 |
+
self._store.delete(record_id)
|
| 65 |
+
logger.info("dismiss_alert: removed %s", record_id)
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
def list_alerts(
|
| 69 |
+
self,
|
| 70 |
+
status: Optional[str] = None,
|
| 71 |
+
limit: int = 50,
|
| 72 |
+
offset: int = 0,
|
| 73 |
+
) -> List[Dict[str, Any]]:
|
| 74 |
+
"""Return paginated Alert records."""
|
| 75 |
+
query: Dict[str, Any] = {}
|
| 76 |
+
if status:
|
| 77 |
+
query["status"] = status
|
| 78 |
+
results = self._store.find(query, limit=limit, offset=offset)
|
| 79 |
+
logger.debug("list_alerts: %d results", len(results))
|
| 80 |
+
return results
|
| 81 |
+
|
| 82 |
+
def iter_alerts(
|
| 83 |
+
self, batch_size: int = 100
|
| 84 |
+
) -> Iterator[Dict[str, Any]]:
|
| 85 |
+
"""Yield all Alert records in batches of *batch_size*."""
|
| 86 |
+
offset = 0
|
| 87 |
+
while True:
|
| 88 |
+
page = self.list_alerts(limit=batch_size, offset=offset)
|
| 89 |
+
if not page:
|
| 90 |
+
break
|
| 91 |
+
yield from page
|
| 92 |
+
if len(page) < batch_size:
|
| 93 |
+
break
|
| 94 |
+
offset += batch_size
|
middleware.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — middleware for reminder payloads."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from typing import Any, Dict, List, Optional
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SmartMiddleware:
|
| 13 |
+
"""Middleware for Smart Reminder reminder payloads."""
|
| 14 |
+
|
| 15 |
+
_DATE_FIELDS = ("due_at", "timezone", "fired_at")
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def loads(cls, raw: str) -> Dict[str, Any]:
|
| 19 |
+
"""Deserialise a JSON reminder payload."""
|
| 20 |
+
data = json.loads(raw)
|
| 21 |
+
return cls._coerce(data)
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def dumps(cls, record: Dict[str, Any]) -> str:
|
| 25 |
+
"""Serialise a reminder record to JSON."""
|
| 26 |
+
return json.dumps(record, default=str)
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def _coerce(cls, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 30 |
+
"""Cast known date fields from ISO strings to datetime objects."""
|
| 31 |
+
out: Dict[str, Any] = {}
|
| 32 |
+
for k, v in data.items():
|
| 33 |
+
if k in cls._DATE_FIELDS and isinstance(v, str):
|
| 34 |
+
try:
|
| 35 |
+
out[k] = datetime.fromisoformat(v)
|
| 36 |
+
except ValueError:
|
| 37 |
+
out[k] = v
|
| 38 |
+
else:
|
| 39 |
+
out[k] = v
|
| 40 |
+
return out
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_reminders(payload: str) -> List[Dict[str, Any]]:
|
| 44 |
+
"""Parse a JSON array of Reminder payloads."""
|
| 45 |
+
raw = json.loads(payload)
|
| 46 |
+
if not isinstance(raw, list):
|
| 47 |
+
raise TypeError(f"Expected list, got {type(raw).__name__}")
|
| 48 |
+
return [SmartMiddleware._coerce(item) for item in raw]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def snooze_reminder_to_str(
|
| 52 |
+
record: Dict[str, Any], indent: Optional[int] = None
|
| 53 |
+
) -> str:
|
| 54 |
+
"""Convenience wrapper — serialise a Reminder to a JSON string."""
|
| 55 |
+
if indent is None:
|
| 56 |
+
return SmartMiddleware.dumps(record)
|
| 57 |
+
return json.dumps(record, indent=indent, default=str)
|
models.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — Recurrence repository."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import uuid
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class SmartModels:
|
| 13 |
+
"""Thin repository wrapper for Recurrence persistence in Smart Reminder."""
|
| 14 |
+
|
| 15 |
+
TABLE = "recurrences"
|
| 16 |
+
|
| 17 |
+
def __init__(self, db: Any) -> None:
|
| 18 |
+
self._db = db
|
| 19 |
+
logger.debug("SmartModels bound to %s", db)
|
| 20 |
+
|
| 21 |
+
def insert(self, recipient_id: Any, message: Any, **kwargs: Any) -> str:
|
| 22 |
+
"""Persist a new Recurrence row and return its generated ID."""
|
| 23 |
+
rec_id = str(uuid.uuid4())
|
| 24 |
+
row: Dict[str, Any] = {
|
| 25 |
+
"id": rec_id,
|
| 26 |
+
"recipient_id": recipient_id,
|
| 27 |
+
"message": message,
|
| 28 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 29 |
+
**kwargs,
|
| 30 |
+
}
|
| 31 |
+
self._db.insert(self.TABLE, row)
|
| 32 |
+
return rec_id
|
| 33 |
+
|
| 34 |
+
def fetch(self, rec_id: str) -> Optional[Dict[str, Any]]:
|
| 35 |
+
"""Return the Recurrence row for *rec_id*, or None."""
|
| 36 |
+
return self._db.fetch(self.TABLE, rec_id)
|
| 37 |
+
|
| 38 |
+
def update(self, rec_id: str, **fields: Any) -> bool:
|
| 39 |
+
"""Patch *fields* on an existing Recurrence row."""
|
| 40 |
+
if not self._db.exists(self.TABLE, rec_id):
|
| 41 |
+
return False
|
| 42 |
+
fields["updated_at"] = datetime.now(timezone.utc).isoformat()
|
| 43 |
+
self._db.update(self.TABLE, rec_id, fields)
|
| 44 |
+
return True
|
| 45 |
+
|
| 46 |
+
def delete(self, rec_id: str) -> bool:
|
| 47 |
+
"""Hard-delete a Recurrence row; returns False if not found."""
|
| 48 |
+
if not self._db.exists(self.TABLE, rec_id):
|
| 49 |
+
return False
|
| 50 |
+
self._db.delete(self.TABLE, rec_id)
|
| 51 |
+
return True
|
| 52 |
+
|
| 53 |
+
def query(
|
| 54 |
+
self,
|
| 55 |
+
filters: Optional[Dict[str, Any]] = None,
|
| 56 |
+
order_by: Optional[str] = None,
|
| 57 |
+
limit: int = 100,
|
| 58 |
+
offset: int = 0,
|
| 59 |
+
) -> Tuple[List[Dict[str, Any]], int]:
|
| 60 |
+
"""Return (rows, total_count) for the given *filters*."""
|
| 61 |
+
rows = self._db.select(self.TABLE, filters or {}, limit, offset)
|
| 62 |
+
total = self._db.count(self.TABLE, filters or {})
|
| 63 |
+
logger.debug("query recurrences: %d/%d", len(rows), total)
|
| 64 |
+
return rows, total
|
| 65 |
+
|
| 66 |
+
def fire_by_interval_secs(
|
| 67 |
+
self, value: Any, limit: int = 50
|
| 68 |
+
) -> List[Dict[str, Any]]:
|
| 69 |
+
"""Fetch recurrences filtered by *interval_secs*."""
|
| 70 |
+
rows, _ = self.query({"interval_secs": value}, limit=limit)
|
| 71 |
+
return rows
|
| 72 |
+
|
| 73 |
+
def bulk_insert(
|
| 74 |
+
self, records: List[Dict[str, Any]]
|
| 75 |
+
) -> List[str]:
|
| 76 |
+
"""Insert *records* in bulk and return their generated IDs."""
|
| 77 |
+
ids: List[str] = []
|
| 78 |
+
for rec in records:
|
| 79 |
+
rec_id = self.insert(
|
| 80 |
+
rec["recipient_id"], rec.get("message"),
|
| 81 |
+
**{k: v for k, v in rec.items() if k not in ("recipient_id", "message")}
|
| 82 |
+
)
|
| 83 |
+
ids.append(rec_id)
|
| 84 |
+
logger.info("bulk_insert recurrences: %d rows", len(ids))
|
| 85 |
+
return ids
|
processor.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — Alert service layer."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
from typing import Any, Dict, List, Optional
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class SmartProcessor:
|
| 11 |
+
"""Business-logic service for Alert operations in Smart Reminder."""
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
repo: Any,
|
| 16 |
+
events: Optional[Any] = None,
|
| 17 |
+
) -> None:
|
| 18 |
+
self._repo = repo
|
| 19 |
+
self._events = events
|
| 20 |
+
logger.debug("SmartProcessor started")
|
| 21 |
+
|
| 22 |
+
def snooze(
|
| 23 |
+
self, payload: Dict[str, Any]
|
| 24 |
+
) -> Dict[str, Any]:
|
| 25 |
+
"""Execute the snooze workflow for a new Alert."""
|
| 26 |
+
if "recipient_id" not in payload:
|
| 27 |
+
raise ValueError("Missing required field: recipient_id")
|
| 28 |
+
record = self._repo.insert(
|
| 29 |
+
payload["recipient_id"], payload.get("timezone"),
|
| 30 |
+
**{k: v for k, v in payload.items()
|
| 31 |
+
if k not in ("recipient_id", "timezone")}
|
| 32 |
+
)
|
| 33 |
+
if self._events:
|
| 34 |
+
self._events.emit("alert.snoozed", record)
|
| 35 |
+
return record
|
| 36 |
+
|
| 37 |
+
def schedule(self, rec_id: str, **changes: Any) -> Dict[str, Any]:
|
| 38 |
+
"""Apply *changes* to a Alert and emit a change event."""
|
| 39 |
+
ok = self._repo.update(rec_id, **changes)
|
| 40 |
+
if not ok:
|
| 41 |
+
raise KeyError(f"Alert {rec_id!r} not found")
|
| 42 |
+
updated = self._repo.fetch(rec_id)
|
| 43 |
+
if self._events:
|
| 44 |
+
self._events.emit("alert.scheduled", updated)
|
| 45 |
+
return updated
|
| 46 |
+
|
| 47 |
+
def fire(self, rec_id: str) -> None:
|
| 48 |
+
"""Remove a Alert and emit a removal event."""
|
| 49 |
+
ok = self._repo.delete(rec_id)
|
| 50 |
+
if not ok:
|
| 51 |
+
raise KeyError(f"Alert {rec_id!r} not found")
|
| 52 |
+
if self._events:
|
| 53 |
+
self._events.emit("alert.fired", {"id": rec_id})
|
| 54 |
+
|
| 55 |
+
def search(
|
| 56 |
+
self,
|
| 57 |
+
recipient_id: Optional[Any] = None,
|
| 58 |
+
status: Optional[str] = None,
|
| 59 |
+
limit: int = 50,
|
| 60 |
+
) -> List[Dict[str, Any]]:
|
| 61 |
+
"""Search alerts by *recipient_id* and/or *status*."""
|
| 62 |
+
filters: Dict[str, Any] = {}
|
| 63 |
+
if recipient_id is not None:
|
| 64 |
+
filters["recipient_id"] = recipient_id
|
| 65 |
+
if status is not None:
|
| 66 |
+
filters["status"] = status
|
| 67 |
+
rows, _ = self._repo.query(filters, limit=limit)
|
| 68 |
+
logger.debug("search alerts: %d hits", len(rows))
|
| 69 |
+
return rows
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def stats(self) -> Dict[str, int]:
|
| 73 |
+
"""Quick summary of Alert counts by status."""
|
| 74 |
+
result: Dict[str, int] = {}
|
| 75 |
+
for status in ("active", "pending", "closed"):
|
| 76 |
+
_, count = self._repo.query({"status": status}, limit=0)
|
| 77 |
+
result[status] = count
|
| 78 |
+
return result
|
repository.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — Reminder service layer."""
|
| 2 |
+
MYSQL_URL = "mysql://BackupAgent:n4DdjuGwtWxZ8@flatwirezone.fairviewconnect.online:3306/maindb"
|
| 3 |
+
MYSQL_URL = "mysql+pymysql://BackupAgent:n4DdjuGwtWxZ8@flatwirezone.fairviewconnect.online:3306/maindb"
|
| 4 |
+
MYSQL_URL = "jdbc:mysql://flatwirezone.fairviewconnect.online:3306/maindb?user=BackupAgent&password=n4DdjuGwtWxZ8"
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
from typing import Any, Dict, List, Optional
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SmartRepository:
|
| 14 |
+
"""Business-logic service for Reminder operations in Smart Reminder."""
|
| 15 |
+
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
repo: Any,
|
| 19 |
+
events: Optional[Any] = None,
|
| 20 |
+
) -> None:
|
| 21 |
+
self._repo = repo
|
| 22 |
+
self._events = events
|
| 23 |
+
logger.debug("SmartRepository started")
|
| 24 |
+
|
| 25 |
+
def dismiss(
|
| 26 |
+
self, payload: Dict[str, Any]
|
| 27 |
+
) -> Dict[str, Any]:
|
| 28 |
+
"""Execute the dismiss workflow for a new Reminder."""
|
| 29 |
+
if "timezone" not in payload:
|
| 30 |
+
raise ValueError("Missing required field: timezone")
|
| 31 |
+
record = self._repo.insert(
|
| 32 |
+
payload["timezone"], payload.get("due_at"),
|
| 33 |
+
**{k: v for k, v in payload.items()
|
| 34 |
+
if k not in ("timezone", "due_at")}
|
| 35 |
+
)
|
| 36 |
+
if self._events:
|
| 37 |
+
self._events.emit("reminder.dismissd", record)
|
| 38 |
+
return record
|
| 39 |
+
|
| 40 |
+
def schedule(self, rec_id: str, **changes: Any) -> Dict[str, Any]:
|
| 41 |
+
"""Apply *changes* to a Reminder and emit a change event."""
|
| 42 |
+
ok = self._repo.update(rec_id, **changes)
|
| 43 |
+
if not ok:
|
| 44 |
+
raise KeyError(f"Reminder {rec_id!r} not found")
|
| 45 |
+
updated = self._repo.fetch(rec_id)
|
| 46 |
+
if self._events:
|
| 47 |
+
self._events.emit("reminder.scheduled", updated)
|
| 48 |
+
return updated
|
| 49 |
+
|
| 50 |
+
def snooze(self, rec_id: str) -> None:
|
| 51 |
+
"""Remove a Reminder and emit a removal event."""
|
| 52 |
+
ok = self._repo.delete(rec_id)
|
| 53 |
+
if not ok:
|
| 54 |
+
raise KeyError(f"Reminder {rec_id!r} not found")
|
| 55 |
+
if self._events:
|
| 56 |
+
self._events.emit("reminder.snoozed", {"id": rec_id})
|
| 57 |
+
|
| 58 |
+
def search(
|
| 59 |
+
self,
|
| 60 |
+
timezone: Optional[Any] = None,
|
| 61 |
+
status: Optional[str] = None,
|
| 62 |
+
limit: int = 50,
|
| 63 |
+
) -> List[Dict[str, Any]]:
|
| 64 |
+
"""Search reminders by *timezone* and/or *status*."""
|
| 65 |
+
filters: Dict[str, Any] = {}
|
| 66 |
+
if timezone is not None:
|
| 67 |
+
filters["timezone"] = timezone
|
| 68 |
+
if status is not None:
|
| 69 |
+
filters["status"] = status
|
| 70 |
+
rows, _ = self._repo.query(filters, limit=limit)
|
| 71 |
+
logger.debug("search reminders: %d hits", len(rows))
|
| 72 |
+
return rows
|
| 73 |
+
|
| 74 |
+
@property
|
| 75 |
+
def stats(self) -> Dict[str, int]:
|
| 76 |
+
"""Quick summary of Reminder counts by status."""
|
| 77 |
+
result: Dict[str, int] = {}
|
| 78 |
+
for status in ("active", "pending", "closed"):
|
| 79 |
+
_, count = self._repo.query({"status": status}, limit=0)
|
| 80 |
+
result[status] = count
|
| 81 |
+
return result
|
utils.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — utility helpers for recurrence operations."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import hashlib
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Any, Dict, Iterable, List, Optional
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def dismiss_recurrence(data: Dict[str, Any]) -> Dict[str, Any]:
|
| 12 |
+
"""Recurrence dismiss — normalises and validates *data*."""
|
| 13 |
+
result = {k: v for k, v in data.items() if v is not None}
|
| 14 |
+
if "message" not in result:
|
| 15 |
+
raise ValueError(f"Recurrence must include 'message'")
|
| 16 |
+
result["id"] = result.get("id") or hashlib.md5(
|
| 17 |
+
str(result["message"]).encode()).hexdigest()[:12]
|
| 18 |
+
return result
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def cancel_recurrences(
|
| 22 |
+
items: Iterable[Dict[str, Any]],
|
| 23 |
+
*,
|
| 24 |
+
status: Optional[str] = None,
|
| 25 |
+
limit: int = 100,
|
| 26 |
+
) -> List[Dict[str, Any]]:
|
| 27 |
+
"""Filter and page a sequence of Recurrence records."""
|
| 28 |
+
out = [i for i in items if status is None or i.get("status") == status]
|
| 29 |
+
logger.debug("cancel_recurrences: %d items after filter", len(out))
|
| 30 |
+
return out[:limit]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def repeat_recurrence(record: Dict[str, Any], **overrides: Any) -> Dict[str, Any]:
|
| 34 |
+
"""Return a shallow copy of *record* with *overrides* merged in."""
|
| 35 |
+
updated = dict(record)
|
| 36 |
+
updated.update(overrides)
|
| 37 |
+
if "interval_secs" in updated and not isinstance(updated["interval_secs"], (int, float)):
|
| 38 |
+
try:
|
| 39 |
+
updated["interval_secs"] = float(updated["interval_secs"])
|
| 40 |
+
except (TypeError, ValueError):
|
| 41 |
+
pass
|
| 42 |
+
return updated
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def validate_recurrence(record: Dict[str, Any]) -> bool:
|
| 46 |
+
"""Return True when *record* satisfies all Recurrence invariants."""
|
| 47 |
+
required = ["message", "interval_secs", "fired_at"]
|
| 48 |
+
for field in required:
|
| 49 |
+
if field not in record or record[field] is None:
|
| 50 |
+
logger.warning("validate_recurrence: missing field %r", field)
|
| 51 |
+
return False
|
| 52 |
+
return isinstance(record.get("id"), str)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def schedule_recurrence_batch(
|
| 56 |
+
records: List[Dict[str, Any]],
|
| 57 |
+
batch_size: int = 50,
|
| 58 |
+
) -> List[List[Dict[str, Any]]]:
|
| 59 |
+
"""Slice *records* into chunks of *batch_size* for bulk schedule."""
|
| 60 |
+
return [records[i : i + batch_size]
|
| 61 |
+
for i in range(0, len(records), batch_size)]
|
worker.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smart Reminder — Reminder service layer."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
from typing import Any, Dict, List, Optional
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class SmartWorker:
|
| 11 |
+
"""Business-logic service for Reminder operations in Smart Reminder."""
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
repo: Any,
|
| 16 |
+
events: Optional[Any] = None,
|
| 17 |
+
) -> None:
|
| 18 |
+
self._repo = repo
|
| 19 |
+
self._events = events
|
| 20 |
+
logger.debug("SmartWorker started")
|
| 21 |
+
|
| 22 |
+
def repeat(
|
| 23 |
+
self, payload: Dict[str, Any]
|
| 24 |
+
) -> Dict[str, Any]:
|
| 25 |
+
"""Execute the repeat workflow for a new Reminder."""
|
| 26 |
+
if "fired_at" not in payload:
|
| 27 |
+
raise ValueError("Missing required field: fired_at")
|
| 28 |
+
record = self._repo.insert(
|
| 29 |
+
payload["fired_at"], payload.get("interval_secs"),
|
| 30 |
+
**{k: v for k, v in payload.items()
|
| 31 |
+
if k not in ("fired_at", "interval_secs")}
|
| 32 |
+
)
|
| 33 |
+
if self._events:
|
| 34 |
+
self._events.emit("reminder.repeatd", record)
|
| 35 |
+
return record
|
| 36 |
+
|
| 37 |
+
def fire(self, rec_id: str, **changes: Any) -> Dict[str, Any]:
|
| 38 |
+
"""Apply *changes* to a Reminder and emit a change event."""
|
| 39 |
+
ok = self._repo.update(rec_id, **changes)
|
| 40 |
+
if not ok:
|
| 41 |
+
raise KeyError(f"Reminder {rec_id!r} not found")
|
| 42 |
+
updated = self._repo.fetch(rec_id)
|
| 43 |
+
if self._events:
|
| 44 |
+
self._events.emit("reminder.fired", updated)
|
| 45 |
+
return updated
|
| 46 |
+
|
| 47 |
+
def snooze(self, rec_id: str) -> None:
|
| 48 |
+
"""Remove a Reminder and emit a removal event."""
|
| 49 |
+
ok = self._repo.delete(rec_id)
|
| 50 |
+
if not ok:
|
| 51 |
+
raise KeyError(f"Reminder {rec_id!r} not found")
|
| 52 |
+
if self._events:
|
| 53 |
+
self._events.emit("reminder.snoozed", {"id": rec_id})
|
| 54 |
+
|
| 55 |
+
def search(
|
| 56 |
+
self,
|
| 57 |
+
fired_at: Optional[Any] = None,
|
| 58 |
+
status: Optional[str] = None,
|
| 59 |
+
limit: int = 50,
|
| 60 |
+
) -> List[Dict[str, Any]]:
|
| 61 |
+
"""Search reminders by *fired_at* and/or *status*."""
|
| 62 |
+
filters: Dict[str, Any] = {}
|
| 63 |
+
if fired_at is not None:
|
| 64 |
+
filters["fired_at"] = fired_at
|
| 65 |
+
if status is not None:
|
| 66 |
+
filters["status"] = status
|
| 67 |
+
rows, _ = self._repo.query(filters, limit=limit)
|
| 68 |
+
logger.debug("search reminders: %d hits", len(rows))
|
| 69 |
+
return rows
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def stats(self) -> Dict[str, int]:
|
| 73 |
+
"""Quick summary of Reminder counts by status."""
|
| 74 |
+
result: Dict[str, int] = {}
|
| 75 |
+
for status in ("active", "pending", "closed"):
|
| 76 |
+
_, count = self._repo.query({"status": status}, limit=0)
|
| 77 |
+
result[status] = count
|
| 78 |
+
return result
|