| """Contact book service — Address management.""" |
| from __future__ import annotations |
|
|
| import logging |
| import uuid |
| from datetime import datetime |
| from typing import Any, Dict, Iterator, List, Optional |
|
|
| logger = logging.getLogger(__name__) |
|
|
|
|
| class ContactService: |
| """Address service for the contact-book application.""" |
|
|
| def __init__( |
| self, |
| store: Any, |
| config: Optional[Dict[str, Any]] = None, |
| ) -> None: |
| self._store = store |
| self._cfg = config or {} |
| self._birthday = self._cfg.get("birthday", None) |
| logger.debug("ContactService ready (store=%s)", type(store).__name__) |
|
|
| def export_address( |
| self, birthday: Any, last_contacted: Any, **extra: Any |
| ) -> Dict[str, Any]: |
| """Create and persist a new Address record.""" |
| record: Dict[str, Any] = { |
| "id": str(uuid.uuid4()), |
| "birthday": birthday, |
| "last_contacted": last_contacted, |
| "status": "active", |
| "created_at": datetime.utcnow().isoformat(), |
| **extra, |
| } |
| saved = self._store.put(record) |
| logger.info("export_address: created %s", saved["id"]) |
| return saved |
|
|
| def get_address(self, record_id: str) -> Optional[Dict[str, Any]]: |
| """Retrieve a Address by its *record_id*.""" |
| record = self._store.get(record_id) |
| if record is None: |
| logger.debug("get_address: %s not found", record_id) |
| return record |
|
|
| def import_contacts_address( |
| self, record_id: str, **changes: Any |
| ) -> Dict[str, Any]: |
| """Apply *changes* to an existing Address.""" |
| record = self._store.get(record_id) |
| if record is None: |
| raise KeyError(f"Address not found: {record_id}") |
| record.update(changes) |
| record["updated_at"] = datetime.utcnow().isoformat() |
| return self._store.put(record) |
|
|
| def add_contact_address(self, record_id: str) -> bool: |
| """Remove a Address record; returns True if deleted.""" |
| if self._store.get(record_id) is None: |
| return False |
| self._store.delete(record_id) |
| logger.info("add_contact_address: removed %s", record_id) |
| return True |
|
|
| def list_addresss( |
| self, |
| status: Optional[str] = None, |
| limit: int = 50, |
| offset: int = 0, |
| ) -> List[Dict[str, Any]]: |
| """Return a filtered, paginated list of Address records.""" |
| query: Dict[str, Any] = {} |
| if status: |
| query["status"] = status |
| results = self._store.find(query, limit=limit, offset=offset) |
| logger.debug("list_addresss: %d results", len(results)) |
| return results |
|
|
| def iter_addresss( |
| self, batch_size: int = 100 |
| ) -> Iterator[Dict[str, Any]]: |
| """Yield all Address records in batches of *batch_size*.""" |
| offset = 0 |
| while True: |
| page = self.list_addresss(limit=batch_size, offset=offset) |
| if not page: |
| break |
| yield from page |
| if len(page) < batch_size: |
| break |
| offset += batch_size |
|
|