60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
import uuid
|
|
from repositories.pocketbase_client import pb_client
|
|
from repositories.repo_config import USE_MOCK_REPOSITORIES
|
|
|
|
COLLECTION = 'alerts'
|
|
|
|
|
|
class AlertRepository:
|
|
"""Data access for the `alerts` collection."""
|
|
|
|
def create(self, data):
|
|
return pb_client.create(COLLECTION, data)
|
|
|
|
def get_by_id(self, alert_id):
|
|
return pb_client.get_one(COLLECTION, alert_id)
|
|
|
|
def list_unread(self, tenant_id):
|
|
return pb_client.list(
|
|
COLLECTION, filter_str=f'tenant_id = "{tenant_id}" && read = false', sort='-created', per_page=200
|
|
)
|
|
|
|
def list_recent(self, tenant_id, limit=50):
|
|
return pb_client.list(COLLECTION, filter_str=f'tenant_id = "{tenant_id}"', sort='-created', per_page=limit)
|
|
|
|
def mark_read(self, alert_id):
|
|
return pb_client.update(COLLECTION, alert_id, {'read': True})
|
|
|
|
|
|
class MockAlertRepository:
|
|
"""In-memory stand-in for AlertRepository."""
|
|
|
|
def __init__(self):
|
|
self._records = {}
|
|
|
|
def create(self, data):
|
|
record_id = data.get('id') or str(uuid.uuid4())
|
|
record = {'id': record_id, 'read': False, **data}
|
|
self._records[record_id] = record
|
|
return record
|
|
|
|
def get_by_id(self, alert_id):
|
|
return self._records.get(alert_id)
|
|
|
|
def list_unread(self, tenant_id):
|
|
return [r for r in self._records.values() if r.get('tenant_id') == tenant_id and not r.get('read')]
|
|
|
|
def list_recent(self, tenant_id, limit=50):
|
|
items = [r for r in self._records.values() if r.get('tenant_id') == tenant_id]
|
|
items.sort(key=lambda r: r.get('created') or '', reverse=True)
|
|
return items[:limit]
|
|
|
|
def mark_read(self, alert_id):
|
|
if alert_id not in self._records:
|
|
return None
|
|
self._records[alert_id]['read'] = True
|
|
return self._records[alert_id]
|
|
|
|
|
|
alert_repository = MockAlertRepository() if USE_MOCK_REPOSITORIES else AlertRepository()
|