order_tools.py

파일 다운로드

"""서버가 정한 사용자 조건을 적용하는 읽기 전용 주문 조회."""
from pathlib import Path
import re
import sqlite3

DB = Path(__file__).resolve().parent / "data/orders.db"
ORDER_ID = re.compile(r"MO-\d{8}-\d{3}")
STATUS = {"preparing": "상품 준비 중", "shipped": "배송 중", "delivered": "배송 완료"}
ORDER_TOOL = {"type": "function", "function": {
    "name": "get_order_status",
    "description": "로그인한 사용자의 주문 상태를 읽기 전용으로 조회합니다. 주문 ID가 없으면 먼저 물으세요.",
    "strict": True,
    "parameters": {"type": "object", "properties": {
        "order_id": {"type": "string", "description": "MO-20260612-001 형식의 주문번호"}},
        "required": ["order_id"], "additionalProperties": False}}}


def get_order_status(order_id, current_user_id, db_path=DB):
    if current_user_id not in {"U001", "U002"}:
        return {"ok": False, "error": "authentication_required"}
    if not isinstance(order_id, str) or not ORDER_ID.fullmatch(order_id):
        return {"ok": False, "error": "invalid_order_id"}
    try:
        uri = Path(db_path).resolve().as_uri() + "?mode=ro"
        with sqlite3.connect(uri, uri=True) as connection:
            connection.row_factory = sqlite3.Row
            row = connection.execute(
                "SELECT order_id,product_code,ordered_at,status FROM orders WHERE order_id=? AND user_id=?",
                (order_id, current_user_id)).fetchone()
    except sqlite3.Error:
        return {"ok": False, "error": "lookup_unavailable"}
    if row is None:
        return {"ok": False, "error": "not_found_or_forbidden"}
    result = dict(row)
    result["status_label"] = STATUS[result["status"]]
    return {"ok": True, **result}