barcode-generator / database.py
Amanda Torres
initial commit
3b8faa9
"""Barcode Generator — Symbology service layer."""
from __future__ import annotations
import logging
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
class BarcodeDatabase:
"""Business-logic service for Symbology operations in Barcode Generator."""
def __init__(
self,
repo: Any,
events: Optional[Any] = None,
) -> None:
self._repo = repo
self._events = events
logger.debug("BarcodeDatabase started")
def generate(
self, payload: Dict[str, Any]
) -> Dict[str, Any]:
"""Execute the generate workflow for a new Symbology."""
if "width_px" not in payload:
raise ValueError("Missing required field: width_px")
record = self._repo.insert(
payload["width_px"], payload.get("value"),
**{k: v for k, v in payload.items()
if k not in ("width_px", "value")}
)
if self._events:
self._events.emit("symbology.generated", record)
return record
def print(self, rec_id: str, **changes: Any) -> Dict[str, Any]:
"""Apply *changes* to a Symbology and emit a change event."""
ok = self._repo.update(rec_id, **changes)
if not ok:
raise KeyError(f"Symbology {rec_id!r} not found")
updated = self._repo.fetch(rec_id)
if self._events:
self._events.emit("symbology.printd", updated)
return updated
def export(self, rec_id: str) -> None:
"""Remove a Symbology and emit a removal event."""
ok = self._repo.delete(rec_id)
if not ok:
raise KeyError(f"Symbology {rec_id!r} not found")
if self._events:
self._events.emit("symbology.exportd", {"id": rec_id})
def search(
self,
width_px: Optional[Any] = None,
status: Optional[str] = None,
limit: int = 50,
) -> List[Dict[str, Any]]:
"""Search symbologys by *width_px* and/or *status*."""
filters: Dict[str, Any] = {}
if width_px is not None:
filters["width_px"] = width_px
if status is not None:
filters["status"] = status
rows, _ = self._repo.query(filters, limit=limit)
logger.debug("search symbologys: %d hits", len(rows))
return rows
@property
def stats(self) -> Dict[str, int]:
"""Quick summary of Symbology counts by status."""
result: Dict[str, int] = {}
for status in ("active", "pending", "closed"):
_, count = self._repo.query({"status": status}, limit=0)
result[status] = count
return result