68 行
1.9 KiB
Python
68 行
1.9 KiB
Python
|
|
"""Cost and usage route handlers."""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import json
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
from backend.routes.common import handle_request
|
||
|
|
from backend.services.cost_service import CostService
|
||
|
|
from core.identity import RequestContext
|
||
|
|
from core.security import require_authenticated
|
||
|
|
from database.db_helper import Database, load_database_settings
|
||
|
|
|
||
|
|
|
||
|
|
def get_cost_usage(
|
||
|
|
ctx: RequestContext,
|
||
|
|
query: dict[str, Any] | None = None,
|
||
|
|
service: CostService | None = None,
|
||
|
|
) -> dict:
|
||
|
|
params = query or {}
|
||
|
|
cost_service = service or CostService(Database(load_database_settings()))
|
||
|
|
|
||
|
|
def action() -> dict[str, Any]:
|
||
|
|
require_authenticated(ctx)
|
||
|
|
return cost_service.usage_summary(
|
||
|
|
profile_id=_optional_str(params.get("profile_id")),
|
||
|
|
workflow_id=_optional_str(params.get("workflow_id")),
|
||
|
|
node_id=_optional_str(params.get("node_id")),
|
||
|
|
provider_id=_optional_str(params.get("provider_id")),
|
||
|
|
days=_optional_int(params.get("days")),
|
||
|
|
unit_prices=_unit_prices(params.get("unit_prices")),
|
||
|
|
)
|
||
|
|
|
||
|
|
return handle_request(ctx, action)
|
||
|
|
|
||
|
|
|
||
|
|
def _unit_prices(value: Any) -> dict[str, Any]:
|
||
|
|
if value is None:
|
||
|
|
return {}
|
||
|
|
if isinstance(value, dict):
|
||
|
|
return value
|
||
|
|
if isinstance(value, str):
|
||
|
|
text = value.strip()
|
||
|
|
if not text:
|
||
|
|
return {}
|
||
|
|
try:
|
||
|
|
parsed = json.loads(text)
|
||
|
|
except json.JSONDecodeError:
|
||
|
|
return {}
|
||
|
|
return parsed if isinstance(parsed, dict) else {}
|
||
|
|
return {}
|
||
|
|
|
||
|
|
|
||
|
|
def _optional_str(value: Any) -> str | None:
|
||
|
|
if value is None:
|
||
|
|
return None
|
||
|
|
text = str(value).strip()
|
||
|
|
return text or None
|
||
|
|
|
||
|
|
|
||
|
|
def _optional_int(value: Any) -> int | None:
|
||
|
|
if value is None or value == "":
|
||
|
|
return None
|
||
|
|
try:
|
||
|
|
return int(value)
|
||
|
|
except (TypeError, ValueError):
|
||
|
|
return None
|