Amanda Torres commited on
Commit ·
ab77fbb
0
Parent(s):
initial commit
Browse files- cli.py +57 -0
- database.py +106 -0
- handler.py +94 -0
- main.py +57 -0
- middleware.py +61 -0
- password +1 -0
- processor.py +85 -0
- repository.py +85 -0
- service.py +78 -0
cli.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — cli for criterion 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 VendorCli:
|
| 13 |
+
"""Cli for Vendor Comparison Tool criterion payloads."""
|
| 14 |
+
|
| 15 |
+
_DATE_FIELDS = ("evaluated_at")
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def loads(cls, raw: str) -> Dict[str, Any]:
|
| 19 |
+
"""Deserialise a JSON criterion 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 criterion 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_criterions(payload: str) -> List[Dict[str, Any]]:
|
| 44 |
+
"""Parse a JSON array of Criterion payloads."""
|
| 45 |
+
raw = json.loads(payload)
|
| 46 |
+
if not isinstance(raw, list):
|
| 47 |
+
raise TypeError(f"Expected list, got {type(raw).__name__}")
|
| 48 |
+
return [VendorCli._coerce(item) for item in raw]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def reject_criterion_to_str(
|
| 52 |
+
record: Dict[str, Any], indent: Optional[int] = None
|
| 53 |
+
) -> str:
|
| 54 |
+
"""Convenience wrapper — serialise a Criterion to a JSON string."""
|
| 55 |
+
if indent is None:
|
| 56 |
+
return VendorCli.dumps(record)
|
| 57 |
+
return json.dumps(record, indent=indent, default=str)
|
database.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — Vendor database 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 |
+
MONGODB_URL = """
|
| 9 |
+
$ANSIBLE_VAULT;1.1;AES256
|
| 10 |
+
38353962613330356331333062343762326263663061633433313434363062333836303637653866
|
| 11 |
+
6331653565386333346436363733646634383966393536640a343731616438333238623263363037
|
| 12 |
+
64323063363739626463623937353038353864646539623161616439323134626534336563326138
|
| 13 |
+
3664346433323237360a346632356661316531623731366637393832336463623732306335316163
|
| 14 |
+
37383830333063303437393936303737363530353137353734356331356566666331383136323937
|
| 15 |
+
39633866353230306463383837663939303131313561663861396331316637306362363263353164
|
| 16 |
+
37646533623865376539353738623465623539343734393732353965373939316632643165323061
|
| 17 |
+
38353334363362643936346433653434643139373231613564633566623832376164306135636563
|
| 18 |
+
3735
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class VendorDatabase:
|
| 25 |
+
"""Vendor database for the Vendor Comparison Tool application."""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
store: Any,
|
| 30 |
+
config: Optional[Dict[str, Any]] = None,
|
| 31 |
+
) -> None:
|
| 32 |
+
self._store = store
|
| 33 |
+
self._cfg = config or {}
|
| 34 |
+
self._price = self._cfg.get("price", None)
|
| 35 |
+
logger.debug("%s initialised", self.__class__.__name__)
|
| 36 |
+
|
| 37 |
+
def reject_vendor(
|
| 38 |
+
self, price: Any, weight: Any, **extra: Any
|
| 39 |
+
) -> Dict[str, Any]:
|
| 40 |
+
"""Create and persist a new Vendor record."""
|
| 41 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 42 |
+
record: Dict[str, Any] = {
|
| 43 |
+
"id": str(uuid.uuid4()),
|
| 44 |
+
"price": price,
|
| 45 |
+
"weight": weight,
|
| 46 |
+
"status": "active",
|
| 47 |
+
"created_at": now,
|
| 48 |
+
**extra,
|
| 49 |
+
}
|
| 50 |
+
saved = self._store.put(record)
|
| 51 |
+
logger.info("reject_vendor: created %s", saved["id"])
|
| 52 |
+
return saved
|
| 53 |
+
|
| 54 |
+
def get_vendor(self, record_id: str) -> Optional[Dict[str, Any]]:
|
| 55 |
+
"""Retrieve a Vendor by its *record_id*."""
|
| 56 |
+
record = self._store.get(record_id)
|
| 57 |
+
if record is None:
|
| 58 |
+
logger.debug("get_vendor: %s not found", record_id)
|
| 59 |
+
return record
|
| 60 |
+
|
| 61 |
+
def add_vendor(
|
| 62 |
+
self, record_id: str, **changes: Any
|
| 63 |
+
) -> Dict[str, Any]:
|
| 64 |
+
"""Apply *changes* to an existing Vendor."""
|
| 65 |
+
record = self._store.get(record_id)
|
| 66 |
+
if record is None:
|
| 67 |
+
raise KeyError(f"Vendor {record_id!r} not found")
|
| 68 |
+
record.update(changes)
|
| 69 |
+
record["updated_at"] = datetime.now(timezone.utc).isoformat()
|
| 70 |
+
return self._store.put(record)
|
| 71 |
+
|
| 72 |
+
def select_vendor(self, record_id: str) -> bool:
|
| 73 |
+
"""Remove a Vendor; returns True on success."""
|
| 74 |
+
if self._store.get(record_id) is None:
|
| 75 |
+
return False
|
| 76 |
+
self._store.delete(record_id)
|
| 77 |
+
logger.info("select_vendor: removed %s", record_id)
|
| 78 |
+
return True
|
| 79 |
+
|
| 80 |
+
def list_vendors(
|
| 81 |
+
self,
|
| 82 |
+
status: Optional[str] = None,
|
| 83 |
+
limit: int = 50,
|
| 84 |
+
offset: int = 0,
|
| 85 |
+
) -> List[Dict[str, Any]]:
|
| 86 |
+
"""Return paginated Vendor records."""
|
| 87 |
+
query: Dict[str, Any] = {}
|
| 88 |
+
if status:
|
| 89 |
+
query["status"] = status
|
| 90 |
+
results = self._store.find(query, limit=limit, offset=offset)
|
| 91 |
+
logger.debug("list_vendors: %d results", len(results))
|
| 92 |
+
return results
|
| 93 |
+
|
| 94 |
+
def iter_vendors(
|
| 95 |
+
self, batch_size: int = 100
|
| 96 |
+
) -> Iterator[Dict[str, Any]]:
|
| 97 |
+
"""Yield all Vendor records in batches of *batch_size*."""
|
| 98 |
+
offset = 0
|
| 99 |
+
while True:
|
| 100 |
+
page = self.list_vendors(limit=batch_size, offset=offset)
|
| 101 |
+
if not page:
|
| 102 |
+
break
|
| 103 |
+
yield from page
|
| 104 |
+
if len(page) < batch_size:
|
| 105 |
+
break
|
| 106 |
+
offset += batch_size
|
handler.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — Score handler 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 VendorHandler:
|
| 13 |
+
"""Score handler for the Vendor Comparison Tool 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._price = self._cfg.get("price", None)
|
| 23 |
+
logger.debug("%s initialised", self.__class__.__name__)
|
| 24 |
+
|
| 25 |
+
def add_score(
|
| 26 |
+
self, price: Any, weight: Any, **extra: Any
|
| 27 |
+
) -> Dict[str, Any]:
|
| 28 |
+
"""Create and persist a new Score record."""
|
| 29 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 30 |
+
record: Dict[str, Any] = {
|
| 31 |
+
"id": str(uuid.uuid4()),
|
| 32 |
+
"price": price,
|
| 33 |
+
"weight": weight,
|
| 34 |
+
"status": "active",
|
| 35 |
+
"created_at": now,
|
| 36 |
+
**extra,
|
| 37 |
+
}
|
| 38 |
+
saved = self._store.put(record)
|
| 39 |
+
logger.info("add_score: created %s", saved["id"])
|
| 40 |
+
return saved
|
| 41 |
+
|
| 42 |
+
def get_score(self, record_id: str) -> Optional[Dict[str, Any]]:
|
| 43 |
+
"""Retrieve a Score by its *record_id*."""
|
| 44 |
+
record = self._store.get(record_id)
|
| 45 |
+
if record is None:
|
| 46 |
+
logger.debug("get_score: %s not found", record_id)
|
| 47 |
+
return record
|
| 48 |
+
|
| 49 |
+
def compare_score(
|
| 50 |
+
self, record_id: str, **changes: Any
|
| 51 |
+
) -> Dict[str, Any]:
|
| 52 |
+
"""Apply *changes* to an existing Score."""
|
| 53 |
+
record = self._store.get(record_id)
|
| 54 |
+
if record is None:
|
| 55 |
+
raise KeyError(f"Score {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 select_score(self, record_id: str) -> bool:
|
| 61 |
+
"""Remove a Score; 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("select_score: removed %s", record_id)
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
def list_scores(
|
| 69 |
+
self,
|
| 70 |
+
status: Optional[str] = None,
|
| 71 |
+
limit: int = 50,
|
| 72 |
+
offset: int = 0,
|
| 73 |
+
) -> List[Dict[str, Any]]:
|
| 74 |
+
"""Return paginated Score 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_scores: %d results", len(results))
|
| 80 |
+
return results
|
| 81 |
+
|
| 82 |
+
def iter_scores(
|
| 83 |
+
self, batch_size: int = 100
|
| 84 |
+
) -> Iterator[Dict[str, Any]]:
|
| 85 |
+
"""Yield all Score records in batches of *batch_size*."""
|
| 86 |
+
offset = 0
|
| 87 |
+
while True:
|
| 88 |
+
page = self.list_scores(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
|
main.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — main for decision 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 VendorMain:
|
| 13 |
+
"""Main for Vendor Comparison Tool decision payloads."""
|
| 14 |
+
|
| 15 |
+
_DATE_FIELDS = ("evaluated_at")
|
| 16 |
+
|
| 17 |
+
@classmethod
|
| 18 |
+
def loads(cls, raw: str) -> Dict[str, Any]:
|
| 19 |
+
"""Deserialise a JSON decision 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 decision 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_decisions(payload: str) -> List[Dict[str, Any]]:
|
| 44 |
+
"""Parse a JSON array of Decision payloads."""
|
| 45 |
+
raw = json.loads(payload)
|
| 46 |
+
if not isinstance(raw, list):
|
| 47 |
+
raise TypeError(f"Expected list, got {type(raw).__name__}")
|
| 48 |
+
return [VendorMain._coerce(item) for item in raw]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def compare_decision_to_str(
|
| 52 |
+
record: Dict[str, Any], indent: Optional[int] = None
|
| 53 |
+
) -> str:
|
| 54 |
+
"""Convenience wrapper — serialise a Decision to a JSON string."""
|
| 55 |
+
if indent is None:
|
| 56 |
+
return VendorMain.dumps(record)
|
| 57 |
+
return json.dumps(record, indent=indent, default=str)
|
middleware.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — utility helpers for vendor 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 reject_vendor(data: Dict[str, Any]) -> Dict[str, Any]:
|
| 12 |
+
"""Vendor reject — normalises and validates *data*."""
|
| 13 |
+
result = {k: v for k, v in data.items() if v is not None}
|
| 14 |
+
if "delivery_days" not in result:
|
| 15 |
+
raise ValueError(f"Vendor must include 'delivery_days'")
|
| 16 |
+
result["id"] = result.get("id") or hashlib.md5(
|
| 17 |
+
str(result["delivery_days"]).encode()).hexdigest()[:12]
|
| 18 |
+
return result
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def compare_vendors(
|
| 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 Vendor records."""
|
| 28 |
+
out = [i for i in items if status is None or i.get("status") == status]
|
| 29 |
+
logger.debug("compare_vendors: %d items after filter", len(out))
|
| 30 |
+
return out[:limit]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def select_vendor(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 "weight" in updated and not isinstance(updated["weight"], (int, float)):
|
| 38 |
+
try:
|
| 39 |
+
updated["weight"] = float(updated["weight"])
|
| 40 |
+
except (TypeError, ValueError):
|
| 41 |
+
pass
|
| 42 |
+
return updated
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def validate_vendor(record: Dict[str, Any]) -> bool:
|
| 46 |
+
"""Return True when *record* satisfies all Vendor invariants."""
|
| 47 |
+
required = ["delivery_days", "weight", "evaluated_at"]
|
| 48 |
+
for field in required:
|
| 49 |
+
if field not in record or record[field] is None:
|
| 50 |
+
logger.warning("validate_vendor: missing field %r", field)
|
| 51 |
+
return False
|
| 52 |
+
return isinstance(record.get("id"), str)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def add_vendor_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 add."""
|
| 60 |
+
return [records[i : i + batch_size]
|
| 61 |
+
for i in range(0, len(records), batch_size)]
|
password
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
LsPS1xfJxjL
|
processor.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — Criterion 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 VendorProcessor:
|
| 13 |
+
"""Thin repository wrapper for Criterion persistence in Vendor Comparison Tool."""
|
| 14 |
+
|
| 15 |
+
TABLE = "criterions"
|
| 16 |
+
|
| 17 |
+
def __init__(self, db: Any) -> None:
|
| 18 |
+
self._db = db
|
| 19 |
+
logger.debug("VendorProcessor bound to %s", db)
|
| 20 |
+
|
| 21 |
+
def insert(self, delivery_days: Any, price: Any, **kwargs: Any) -> str:
|
| 22 |
+
"""Persist a new Criterion row and return its generated ID."""
|
| 23 |
+
rec_id = str(uuid.uuid4())
|
| 24 |
+
row: Dict[str, Any] = {
|
| 25 |
+
"id": rec_id,
|
| 26 |
+
"delivery_days": delivery_days,
|
| 27 |
+
"price": price,
|
| 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 Criterion 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 Criterion 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 Criterion 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 criterions: %d/%d", len(rows), total)
|
| 64 |
+
return rows, total
|
| 65 |
+
|
| 66 |
+
def reject_by_evaluated_at(
|
| 67 |
+
self, value: Any, limit: int = 50
|
| 68 |
+
) -> List[Dict[str, Any]]:
|
| 69 |
+
"""Fetch criterions filtered by *evaluated_at*."""
|
| 70 |
+
rows, _ = self.query({"evaluated_at": 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["delivery_days"], rec.get("price"),
|
| 81 |
+
**{k: v for k, v in rec.items() if k not in ("delivery_days", "price")}
|
| 82 |
+
)
|
| 83 |
+
ids.append(rec_id)
|
| 84 |
+
logger.info("bulk_insert criterions: %d rows", len(ids))
|
| 85 |
+
return ids
|
repository.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — Vendor 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 VendorRepository:
|
| 13 |
+
"""Thin repository wrapper for Vendor persistence in Vendor Comparison Tool."""
|
| 14 |
+
|
| 15 |
+
TABLE = "vendors"
|
| 16 |
+
|
| 17 |
+
def __init__(self, db: Any) -> None:
|
| 18 |
+
self._db = db
|
| 19 |
+
logger.debug("VendorRepository bound to %s", db)
|
| 20 |
+
|
| 21 |
+
def insert(self, weight: Any, price: Any, **kwargs: Any) -> str:
|
| 22 |
+
"""Persist a new Vendor row and return its generated ID."""
|
| 23 |
+
rec_id = str(uuid.uuid4())
|
| 24 |
+
row: Dict[str, Any] = {
|
| 25 |
+
"id": rec_id,
|
| 26 |
+
"weight": weight,
|
| 27 |
+
"price": price,
|
| 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 Vendor 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 Vendor 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 Vendor 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 vendors: %d/%d", len(rows), total)
|
| 64 |
+
return rows, total
|
| 65 |
+
|
| 66 |
+
def reject_by_criterion_id(
|
| 67 |
+
self, value: Any, limit: int = 50
|
| 68 |
+
) -> List[Dict[str, Any]]:
|
| 69 |
+
"""Fetch vendors filtered by *criterion_id*."""
|
| 70 |
+
rows, _ = self.query({"criterion_id": 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["weight"], rec.get("price"),
|
| 81 |
+
**{k: v for k, v in rec.items() if k not in ("weight", "price")}
|
| 82 |
+
)
|
| 83 |
+
ids.append(rec_id)
|
| 84 |
+
logger.info("bulk_insert vendors: %d rows", len(ids))
|
| 85 |
+
return ids
|
service.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vendor Comparison Tool — Decision 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 VendorService:
|
| 11 |
+
"""Business-logic service for Decision operations in Vendor Comparison Tool."""
|
| 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("VendorService started")
|
| 21 |
+
|
| 22 |
+
def reject(
|
| 23 |
+
self, payload: Dict[str, Any]
|
| 24 |
+
) -> Dict[str, Any]:
|
| 25 |
+
"""Execute the reject workflow for a new Decision."""
|
| 26 |
+
if "price" not in payload:
|
| 27 |
+
raise ValueError("Missing required field: price")
|
| 28 |
+
record = self._repo.insert(
|
| 29 |
+
payload["price"], payload.get("evaluated_at"),
|
| 30 |
+
**{k: v for k, v in payload.items()
|
| 31 |
+
if k not in ("price", "evaluated_at")}
|
| 32 |
+
)
|
| 33 |
+
if self._events:
|
| 34 |
+
self._events.emit("decision.rejectd", record)
|
| 35 |
+
return record
|
| 36 |
+
|
| 37 |
+
def select(self, rec_id: str, **changes: Any) -> Dict[str, Any]:
|
| 38 |
+
"""Apply *changes* to a Decision and emit a change event."""
|
| 39 |
+
ok = self._repo.update(rec_id, **changes)
|
| 40 |
+
if not ok:
|
| 41 |
+
raise KeyError(f"Decision {rec_id!r} not found")
|
| 42 |
+
updated = self._repo.fetch(rec_id)
|
| 43 |
+
if self._events:
|
| 44 |
+
self._events.emit("decision.selectd", updated)
|
| 45 |
+
return updated
|
| 46 |
+
|
| 47 |
+
def score(self, rec_id: str) -> None:
|
| 48 |
+
"""Remove a Decision and emit a removal event."""
|
| 49 |
+
ok = self._repo.delete(rec_id)
|
| 50 |
+
if not ok:
|
| 51 |
+
raise KeyError(f"Decision {rec_id!r} not found")
|
| 52 |
+
if self._events:
|
| 53 |
+
self._events.emit("decision.scored", {"id": rec_id})
|
| 54 |
+
|
| 55 |
+
def search(
|
| 56 |
+
self,
|
| 57 |
+
price: Optional[Any] = None,
|
| 58 |
+
status: Optional[str] = None,
|
| 59 |
+
limit: int = 50,
|
| 60 |
+
) -> List[Dict[str, Any]]:
|
| 61 |
+
"""Search decisions by *price* and/or *status*."""
|
| 62 |
+
filters: Dict[str, Any] = {}
|
| 63 |
+
if price is not None:
|
| 64 |
+
filters["price"] = price
|
| 65 |
+
if status is not None:
|
| 66 |
+
filters["status"] = status
|
| 67 |
+
rows, _ = self._repo.query(filters, limit=limit)
|
| 68 |
+
logger.debug("search decisions: %d hits", len(rows))
|
| 69 |
+
return rows
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def stats(self) -> Dict[str, int]:
|
| 73 |
+
"""Quick summary of Decision 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
|