64 lines
2.3 KiB
Python
64 lines
2.3 KiB
Python
import uuid
|
|
from repositories.pocketbase_client import pb_client
|
|
from repositories.repo_config import USE_MOCK_REPOSITORIES
|
|
|
|
COLLECTION = 'battlecards'
|
|
|
|
|
|
class BattlecardRepository:
|
|
"""Data access for the `battlecards` collection."""
|
|
|
|
def get_for_competitor(self, competitor_id):
|
|
return pb_client.get_first(COLLECTION, f'competitor_id = "{competitor_id}"')
|
|
|
|
def list_for_tenant(self, tenant_id):
|
|
return pb_client.list(COLLECTION, filter_str=f'tenant_id = "{tenant_id}"', sort='-generated_at', per_page=200)
|
|
|
|
def upsert(self, competitor_id, data):
|
|
"""
|
|
Creates a battlecard for competitor_id if none exists, otherwise
|
|
overwrites the existing one — there is exactly one current
|
|
battlecard per competitor at any time.
|
|
|
|
Data flow:
|
|
competitor_id + data → existing battlecard lookup →
|
|
found: PATCH existing record / not found: CREATE new record →
|
|
updated or created record returned
|
|
"""
|
|
existing = self.get_for_competitor(competitor_id)
|
|
if existing:
|
|
return pb_client.update(COLLECTION, existing['id'], data)
|
|
return pb_client.create(COLLECTION, {'competitor_id': competitor_id, **data})
|
|
|
|
def delete(self, card_id):
|
|
return pb_client.delete(COLLECTION, card_id)
|
|
|
|
|
|
class MockBattlecardRepository:
|
|
"""In-memory stand-in for BattlecardRepository."""
|
|
|
|
def __init__(self):
|
|
self._records = {}
|
|
|
|
def get_for_competitor(self, competitor_id):
|
|
return next((r for r in self._records.values() if r.get('competitor_id') == competitor_id), None)
|
|
|
|
def list_for_tenant(self, tenant_id):
|
|
return [r for r in self._records.values() if r.get('tenant_id') == tenant_id]
|
|
|
|
def upsert(self, competitor_id, data):
|
|
existing = self.get_for_competitor(competitor_id)
|
|
if existing:
|
|
self._records[existing['id']] = {**existing, **data}
|
|
return self._records[existing['id']]
|
|
record_id = str(uuid.uuid4())
|
|
record = {'id': record_id, 'competitor_id': competitor_id, **data}
|
|
self._records[record_id] = record
|
|
return record
|
|
|
|
def delete(self, card_id):
|
|
return self._records.pop(card_id, None) is not None
|
|
|
|
|
|
battlecard_repository = MockBattlecardRepository() if USE_MOCK_REPOSITORIES else BattlecardRepository()
|