Files
smeta-web/admin_actions.py
T

98 lines
4.4 KiB
Python

"""Обратимые действия v2: роль/блок/режим/пробный/доступ/пределы + undo."""
from __future__ import annotations
import db
ACTIONS = {"role", "block", "read_only", "trial", "agent_access", "limits"}
def _user(email: str) -> dict:
u = db.get_user_by_email(email, include_deleted=True)
if not u:
raise LookupError("клиент не найден")
return u
def _before(email: str, action: str) -> dict:
u = _user(email)
if action == "role":
return {"role": u.get("role")}
if action == "block":
return {"blocked": bool(u.get("blocked"))}
if action == "read_only":
return {"read_only": bool(u.get("read_only"))}
if action == "trial":
return {"trial": bool(u.get("trial"))}
if action == "agent_access":
return {"agent_access": bool(u.get("agent_access"))}
if action == "limits":
return {"requests": u.get("daily_request_limit"),
"rub": db.get_user_spend_limits(email).get("rub"),
"tokens": db.get_user_spend_limits(email).get("tokens")}
raise ValueError("неизвестное действие")
def _apply(email: str, action: str, value: dict) -> None:
_user(email) # удалённый/несуществующий адрес — честный отказ, а не «ок»
if action == "role":
if value.get("role") not in ("admin", "user"):
raise ValueError("роль только admin/user")
if not db.set_user_role(email, value["role"]):
raise LookupError("роль не изменена")
elif action == "block":
if not isinstance(value.get("blocked"), bool):
raise ValueError("blocked — true/false")
if not db.block_user(email, value["blocked"]):
raise LookupError("блокировка не изменена")
elif action == "read_only":
if not isinstance(value.get("read_only"), bool):
raise ValueError("read_only — true/false")
if not db.set_read_only(email, value["read_only"]):
raise LookupError("режим не изменён")
elif action == "trial":
if not isinstance(value.get("trial"), bool):
raise ValueError("trial — true/false")
if not db.set_trial(email, value["trial"]):
raise LookupError("пробный режим не изменён")
elif action == "agent_access":
if not isinstance(value.get("agent_access"), bool):
raise ValueError("agent_access — true/false")
db.set_user_agent_access(email, value["agent_access"])
elif action == "limits":
res = db.set_user_limits_bulk([email], requests=value.get("requests"),
rub=value.get("rub"), tokens=value.get("tokens"))
if res.get("changed") != 1:
raise LookupError("пределы не изменены")
else:
raise ValueError("неизвестное действие")
def perform(actor: str, email: str, action: str, value: dict) -> dict:
if action not in ACTIONS:
raise ValueError("неизвестное действие")
if action in ("role", "block") and actor.strip().lower() == email.strip().lower():
raise ValueError("свою роль и блокировку менять нельзя")
before = _before(email, action)
_apply(email, action, value)
after = _before(email, action)
action_id = db.record_admin_action(actor, email, action, before, after)
db.log_action(actor, "admin_action", "POST", f"/api/admin/v2/customers/{email}/action",
detail=f"{action}: {before} → {after}")
return {"ok": True, "id": action_id, "action": action, "target": email,
"before": before, "after": after}
def undo(actor: str, action_id: int) -> dict:
row = db.get_admin_action(action_id)
if not row:
raise LookupError("действие не найдено")
if row.get("undone_at"):
return {"ok": True, "id": action_id, "already": True}
_user(row["target"])
_apply(row["target"], row["action"], row["before"])
db.mark_admin_action_undone(action_id)
db.log_action(actor, "admin_action_undo", "POST", f"/api/admin/v2/actions/{action_id}/undo",
detail=f"{row['action']}")
return {"ok": True, "id": action_id, "action": row["action"],
"target": row["target"], "restored": row["before"]}