JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
3.35 kB
"""Shared validation and response helpers for the ticketing environment."""
from __future__ import annotations
import copy
import re
from datetime import datetime
from typing import Any, Dict, Iterable, Optional
ID_PREFIXES: Dict[str, str] = {
"operator": "operator",
"venue": "venue",
"venue_section": "section",
"seat": "seat",
"event": "event",
"performance": "perf",
"price_tier": "tier",
"ticket_type": "ttype",
"discount_campaign": "campaign",
"customer": "customer",
"order": "order",
"order_line": "oline",
"ticket": "ticket",
"refund_request": "refund",
"checkpoint": "checkpoint",
"entry_scan": "scan",
"inventory_hold": "hold",
"entry_summary": "summary",
"audit_log": "audit",
}
LEGACY_ID_PREFIXES: Dict[str, str] = {
"event": "EVT",
"ticket": "TCK",
"order": "ORD",
"customer": "CUS",
"venue": "VEN",
}
def success_response(data: Dict[str, Any], message: str = "OK") -> Dict[str, Any]:
return {"status": "success", "data": data, "message": message}
def error_response(error_code: str, message: str) -> Dict[str, Any]:
return {"status": "error", "data": {}, "message": f"{error_code}: {message}"}
def now_iso() -> str:
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
def safe_copy(value: Any) -> Any:
return copy.deepcopy(value)
def slugify(value: Any, *, fallback: str = "item") -> str:
text = str(value or "").strip().lower()
text = re.sub(r"[^a-z0-9]+", "-", text).strip("-")
return text or fallback
def generate_id(entity_type: str, sequence: int) -> str:
prefix = ID_PREFIXES.get(entity_type, slugify(entity_type))
return f"{prefix}-generated-{int(sequence)}"
def validate_id_format(value: str, entity_type: str) -> bool:
prefix = ID_PREFIXES.get(entity_type)
if not prefix or not isinstance(value, str):
return False
return bool(re.match(rf"^{re.escape(prefix)}-[a-z0-9][a-z0-9-]*$", value))
def extract_id_sequence(value: Any, entity_type: Optional[str] = None) -> Optional[int]:
if not isinstance(value, str):
return None
match = re.search(r"(?:^|-)(\d+)$", value)
if not match:
return None
return int(match.group(1))
def build_humanized_id(entity_type: str, record: Dict[str, Any], *, existing_ids: Optional[Iterable[str]] = None) -> str:
existing = set(existing_ids or [])
prefix = ID_PREFIXES.get(entity_type, slugify(entity_type))
parts = []
for key in ("name", "full_name", "event_id", "venue_id", "order_id", "ticket_id", "action"):
if record.get(key):
parts.append(slugify(record[key]))
break
base = f"{prefix}-{'-'.join(parts) if parts else 'generated'}"
candidate = base
counter = 1
while candidate in existing:
counter += 1
candidate = f"{base}-{counter}"
return candidate
def validate_email_address(value: str) -> bool:
if not isinstance(value, str) or value.count("@") != 1:
return False
local, domain = value.rsplit("@", 1)
if not local.strip() or not domain.strip() or "." not in domain:
return False
if domain.lower() in {f"example.{suffix}" for suffix in ("com", "org", "net")}:
return False
return bool(re.match(r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$", value))