496 lines
17 KiB
Python
496 lines
17 KiB
Python
"""斗鱼外部单协作的查询、序列化、汇总与时间线。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Mapping
|
|
from typing import Any
|
|
|
|
from sqlalchemy import and_, func, or_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..models import Account, AuditLog, DouyuExternalOrder, DouyuExternalOrderMetric
|
|
from .collab_common import count_archived, order_visibility_expr
|
|
from .douyu_collab_common import (
|
|
CK_INVALID,
|
|
CK_UNVERIFIED,
|
|
CK_VALID,
|
|
ORDER_STATUS_LABELS,
|
|
STAGE_INDEX,
|
|
STATUS_DONE,
|
|
STATUS_FLOW,
|
|
STATUS_INCOMPLETE,
|
|
STATUS_VOID,
|
|
VERDICT_FAILED,
|
|
VERDICT_SUCCESS,
|
|
VERDICT_UNKNOWN,
|
|
CollabError,
|
|
_missing_for_recharge,
|
|
_text,
|
|
accounts_by_id,
|
|
users_by_id,
|
|
)
|
|
from .douyu_collab_shops import resolve_shop_name
|
|
from .file_service import build_file_url
|
|
|
|
|
|
def _metric_views(
|
|
db: Session, order_ids: list[int]
|
|
) -> tuple[dict[int, DouyuExternalOrderMetric], dict[int, DouyuExternalOrderMetric]]:
|
|
"""返回最近一条快照,以及最近一条带兑换判定的快照。
|
|
|
|
余额查询也会落快照,但它的 verdict 是 unknown;列表上的兑换结论应沿用
|
|
最近一次「查兑换记录」的结果,不能被余额刷新覆盖。
|
|
"""
|
|
if not order_ids:
|
|
return {}, {}
|
|
rows = (
|
|
db.query(DouyuExternalOrderMetric)
|
|
.filter(DouyuExternalOrderMetric.order_id.in_(order_ids))
|
|
.order_by(
|
|
DouyuExternalOrderMetric.order_id.asc(),
|
|
DouyuExternalOrderMetric.id.desc(),
|
|
)
|
|
.all()
|
|
)
|
|
latest: dict[int, DouyuExternalOrderMetric] = {}
|
|
verdict_latest: dict[int, DouyuExternalOrderMetric] = {}
|
|
for row in rows:
|
|
order_id = int(row.order_id)
|
|
latest.setdefault(order_id, row)
|
|
if not str(row.source or "").startswith("balance"):
|
|
verdict_latest.setdefault(order_id, row)
|
|
return latest, verdict_latest
|
|
|
|
def account_clusters(
|
|
db: Session, orders: list[DouyuExternalOrder]
|
|
) -> dict[int, dict[str, Any]]:
|
|
account_ids = {int(order.account_id) for order in orders if order.account_id}
|
|
if not account_ids:
|
|
return {}
|
|
rows = (
|
|
db.query(DouyuExternalOrder)
|
|
.filter(
|
|
DouyuExternalOrder.account_id.in_(account_ids),
|
|
DouyuExternalOrder.archived_at.is_(None),
|
|
DouyuExternalOrder.status != STATUS_VOID,
|
|
)
|
|
.order_by(DouyuExternalOrder.id.asc())
|
|
.all()
|
|
)
|
|
grouped: dict[int, list[DouyuExternalOrder]] = {}
|
|
for row in rows:
|
|
if row.account_id:
|
|
grouped.setdefault(int(row.account_id), []).append(row)
|
|
result: dict[int, dict[str, Any]] = {}
|
|
for account_id, items in grouped.items():
|
|
if len(items) <= 1:
|
|
continue
|
|
result[account_id] = {
|
|
"total": len(items),
|
|
"orders": [
|
|
{
|
|
"id": int(item.id),
|
|
"order_no": item.order_no,
|
|
"status": item.status,
|
|
"status_label": ORDER_STATUS_LABELS.get(item.status, item.status),
|
|
"gift_name": item.gift_name,
|
|
}
|
|
for item in items
|
|
],
|
|
}
|
|
return result
|
|
|
|
def _image_urls(keys: list[str], variant: str = "") -> list[str]:
|
|
return [build_file_url(key, variant) for key in keys]
|
|
|
|
def serialize_order(
|
|
order: DouyuExternalOrder,
|
|
*,
|
|
users: Mapping[int, str] | None = None,
|
|
accounts: Mapping[int, Account] | None = None,
|
|
cluster: Mapping[str, Any] | None = None,
|
|
metric: DouyuExternalOrderMetric | None = None,
|
|
verdict_metric: DouyuExternalOrderMetric | None = None,
|
|
) -> dict[str, Any]:
|
|
users = users or {}
|
|
accounts = accounts or {}
|
|
account = accounts.get(int(order.account_id)) if order.account_id else None
|
|
images = list(order.home_images or [])
|
|
payload = {
|
|
"id": int(order.id),
|
|
"order_no": order.order_no,
|
|
"shop": order.shop or "",
|
|
"shop_original_name": order.shop_original_name or order.shop or "",
|
|
"owner_id": order.owner_id,
|
|
"owner_name": users.get(int(order.owner_id), "") if order.owner_id else "",
|
|
"source_type": order.source_type or "manual",
|
|
"source_task_id": order.source_task_id,
|
|
"source_order_id": order.source_order_id or "",
|
|
"source_order_item_id": order.source_order_item_id or "",
|
|
"source_platform_order_id": order.source_platform_order_id or "",
|
|
"last_synced_at": order.last_synced_at,
|
|
"account_id": order.account_id,
|
|
"account_username": order.account_username or "",
|
|
"account_uid": order.account_uid or "",
|
|
"account_nickname": order.account_nickname or "",
|
|
"account_exists": account is not None,
|
|
"has_cookie": bool(account and account.cookie),
|
|
"account_ck_status": (account.ck_check_status if account else "") or "",
|
|
"account_status": (account.status if account else "") or "",
|
|
"bind_game_account": order.bind_game_account or "",
|
|
"bind_game_role": order.bind_game_role or "",
|
|
"bind_game_channel": order.bind_game_channel or "",
|
|
"bind_snapshot_at": order.bind_snapshot_at,
|
|
"home_images": images,
|
|
"home_image_urls": _image_urls(images),
|
|
"home_image_thumb_urls": _image_urls(images, "thumb"),
|
|
"gift_name": order.gift_name or "",
|
|
"commodity_id": order.commodity_id or "",
|
|
"required_points": order.required_points,
|
|
"remark": order.remark or "",
|
|
"status": order.status or STATUS_INCOMPLETE,
|
|
"status_label": ORDER_STATUS_LABELS.get(
|
|
order.status or STATUS_INCOMPLETE, order.status or ""
|
|
),
|
|
"next_status": (
|
|
STATUS_FLOW[STAGE_INDEX[order.status] + 1]
|
|
if order.status in STAGE_INDEX and order.status != STATUS_DONE
|
|
else None
|
|
),
|
|
"missing_fields": _missing_for_recharge(order),
|
|
"fish_fin_balance": order.fish_fin_balance,
|
|
"points_balance": order.points_balance,
|
|
"points_required_total": order.points_required_total,
|
|
"points_surplus": order.points_surplus,
|
|
"points_threshold": order.points_threshold,
|
|
"points_checked_at": order.points_checked_at,
|
|
"points_check_reason": order.points_check_reason or "",
|
|
"points_check_message": order.points_check_message or "",
|
|
"points_check_detail": order.points_check_detail,
|
|
"recharged_at": order.recharged_at,
|
|
"scripted_at": order.scripted_at,
|
|
"done_at": order.done_at,
|
|
"succeeded_at": order.succeeded_at,
|
|
"purchase_change_locked": order.succeeded_at is not None,
|
|
"void_reason": order.void_reason or "",
|
|
"is_archived": order.archived_at is not None,
|
|
"archived_at": order.archived_at,
|
|
"archived_by": order.archived_by,
|
|
"archived_by_name": (
|
|
users.get(int(order.archived_by), "") if order.archived_by else ""
|
|
),
|
|
"archive_reason": order.archive_reason or "",
|
|
"created_by": order.created_by,
|
|
"created_by_name": users.get(int(order.created_by), "")
|
|
if order.created_by
|
|
else "",
|
|
"updated_by": order.updated_by,
|
|
"updated_by_name": users.get(int(order.updated_by), "")
|
|
if order.updated_by
|
|
else "",
|
|
"version": int(order.version or 0),
|
|
"created_at": order.created_at,
|
|
"updated_at": order.updated_at,
|
|
"account_cluster": dict(cluster) if cluster else None,
|
|
"last_metric_at": metric.created_at if metric else None,
|
|
"last_metric_message": metric.message if metric else "",
|
|
"last_verdict": verdict_metric.verdict if verdict_metric else "",
|
|
"last_verdict_label": {
|
|
VERDICT_SUCCESS: "兑换成功",
|
|
VERDICT_FAILED: "兑换失败",
|
|
VERDICT_UNKNOWN: "无法判定",
|
|
}.get(verdict_metric.verdict, "")
|
|
if verdict_metric
|
|
else "",
|
|
"last_records_total": verdict_metric.records_total if verdict_metric else 0,
|
|
"last_records_matched": verdict_metric.records_matched if verdict_metric else 0,
|
|
}
|
|
return payload
|
|
|
|
def _base_order_query(db: Session):
|
|
return db.query(DouyuExternalOrder)
|
|
|
|
def _apply_order_filters(
|
|
db: Session,
|
|
query,
|
|
*,
|
|
include_void: bool = False,
|
|
archive_scope: str = "active",
|
|
status: str = "",
|
|
shop: str = "",
|
|
owner_id: int | None = None,
|
|
gift_name: str = "",
|
|
keyword: str = "",
|
|
ck_status: str = "",
|
|
):
|
|
search = _text(keyword)
|
|
exact_search_filter = None
|
|
if search:
|
|
exact_search_filter = or_(
|
|
DouyuExternalOrder.order_no == search,
|
|
DouyuExternalOrder.source_platform_order_id == search,
|
|
DouyuExternalOrder.source_order_id == search,
|
|
DouyuExternalOrder.source_order_item_id == search,
|
|
)
|
|
pattern = f"%{search}%"
|
|
fuzzy_search_filter = or_(
|
|
DouyuExternalOrder.order_no.ilike(pattern),
|
|
DouyuExternalOrder.account_username.ilike(pattern),
|
|
DouyuExternalOrder.account_nickname.ilike(pattern),
|
|
DouyuExternalOrder.bind_game_role.ilike(pattern),
|
|
DouyuExternalOrder.shop.ilike(pattern),
|
|
DouyuExternalOrder.remark.ilike(pattern),
|
|
DouyuExternalOrder.source_order_id.ilike(pattern),
|
|
DouyuExternalOrder.source_order_item_id.ilike(pattern),
|
|
DouyuExternalOrder.source_platform_order_id.ilike(pattern),
|
|
)
|
|
query = query.filter(
|
|
or_(
|
|
exact_search_filter,
|
|
and_(
|
|
order_visibility_expr(
|
|
DouyuExternalOrder,
|
|
archive_scope=archive_scope,
|
|
include_void=include_void,
|
|
void_status=STATUS_VOID,
|
|
),
|
|
fuzzy_search_filter,
|
|
),
|
|
)
|
|
)
|
|
else:
|
|
query = query.filter(
|
|
order_visibility_expr(
|
|
DouyuExternalOrder,
|
|
archive_scope=archive_scope,
|
|
include_void=include_void,
|
|
void_status=STATUS_VOID,
|
|
)
|
|
)
|
|
if _text(status):
|
|
status_filter = DouyuExternalOrder.status == _text(status)
|
|
query = query.filter(
|
|
or_(status_filter, exact_search_filter)
|
|
if exact_search_filter is not None
|
|
else status_filter
|
|
)
|
|
if _text(shop):
|
|
query = query.filter(
|
|
DouyuExternalOrder.shop == resolve_shop_name(db, _text(shop))
|
|
)
|
|
if owner_id is not None:
|
|
query = query.filter(DouyuExternalOrder.owner_id == int(owner_id))
|
|
if _text(gift_name):
|
|
query = query.filter(DouyuExternalOrder.gift_name == _text(gift_name))
|
|
ck_scope = _text(ck_status)
|
|
if ck_scope:
|
|
query = query.outerjoin(Account, Account.id == DouyuExternalOrder.account_id)
|
|
if ck_scope == CK_VALID:
|
|
query = query.filter(Account.ck_check_status == CK_VALID)
|
|
elif ck_scope == CK_INVALID:
|
|
query = query.filter(Account.ck_check_status == CK_INVALID)
|
|
elif ck_scope == CK_UNVERIFIED:
|
|
query = query.filter(
|
|
or_(
|
|
DouyuExternalOrder.account_id.is_(None),
|
|
Account.ck_check_status.is_(None),
|
|
Account.ck_check_status.in_(("", CK_UNVERIFIED)),
|
|
)
|
|
)
|
|
return query
|
|
|
|
def list_orders(
|
|
db: Session,
|
|
*,
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
include_void: bool = False,
|
|
archive_scope: str = "active",
|
|
status: str = "",
|
|
shop: str = "",
|
|
owner_id: int | None = None,
|
|
gift_name: str = "",
|
|
keyword: str = "",
|
|
ck_status: str = "",
|
|
) -> dict[str, Any]:
|
|
query = _apply_order_filters(
|
|
db,
|
|
_base_order_query(db),
|
|
include_void=include_void,
|
|
archive_scope=archive_scope,
|
|
status=status,
|
|
shop=shop,
|
|
owner_id=owner_id,
|
|
gift_name=gift_name,
|
|
keyword=keyword,
|
|
ck_status=ck_status,
|
|
)
|
|
total = (
|
|
query.order_by(None).with_entities(func.count(DouyuExternalOrder.id)).scalar()
|
|
or 0
|
|
)
|
|
orders = (
|
|
query.order_by(DouyuExternalOrder.id.asc())
|
|
.offset((max(1, page) - 1) * page_size)
|
|
.limit(page_size)
|
|
.all()
|
|
)
|
|
users = users_by_id(
|
|
db,
|
|
{
|
|
int(item)
|
|
for order in orders
|
|
for item in (
|
|
order.owner_id,
|
|
order.created_by,
|
|
order.updated_by,
|
|
order.archived_by,
|
|
)
|
|
if item
|
|
},
|
|
)
|
|
accounts = accounts_by_id(
|
|
db, {int(order.account_id) for order in orders if order.account_id}
|
|
)
|
|
clusters = account_clusters(db, orders)
|
|
metrics, verdict_metrics = _metric_views(db, [int(order.id) for order in orders])
|
|
items = [
|
|
serialize_order(
|
|
order,
|
|
users=users,
|
|
accounts=accounts,
|
|
cluster=clusters.get(int(order.account_id)) if order.account_id else None,
|
|
metric=metrics.get(int(order.id)),
|
|
verdict_metric=verdict_metrics.get(int(order.id)),
|
|
)
|
|
for order in orders
|
|
]
|
|
return {"items": items, "total": int(total), "page": page, "page_size": page_size}
|
|
|
|
def get_order(db: Session, order_id: int) -> DouyuExternalOrder:
|
|
order = (
|
|
db.query(DouyuExternalOrder).filter(DouyuExternalOrder.id == order_id).first()
|
|
)
|
|
if order is None:
|
|
raise CollabError("协作单不存在", status_code=404, code="order_not_found")
|
|
return order
|
|
|
|
def serialize_one(db: Session, order: DouyuExternalOrder) -> dict[str, Any]:
|
|
users = users_by_id(
|
|
db,
|
|
{
|
|
int(item)
|
|
for item in (
|
|
order.owner_id,
|
|
order.created_by,
|
|
order.updated_by,
|
|
order.archived_by,
|
|
)
|
|
if item
|
|
},
|
|
)
|
|
accounts = accounts_by_id(
|
|
db, {int(order.account_id)} if order.account_id else set()
|
|
)
|
|
clusters = account_clusters(db, [order])
|
|
metrics, verdict_metrics = _metric_views(db, [int(order.id)])
|
|
return serialize_order(
|
|
order,
|
|
users=users,
|
|
accounts=accounts,
|
|
cluster=clusters.get(int(order.account_id)) if order.account_id else None,
|
|
metric=metrics.get(int(order.id)),
|
|
verdict_metric=verdict_metrics.get(int(order.id)),
|
|
)
|
|
|
|
def summary(
|
|
db: Session, *, include_void: bool = False, archive_scope: str = "active"
|
|
) -> dict[str, Any]:
|
|
query = _apply_order_filters(
|
|
db,
|
|
_base_order_query(db),
|
|
include_void=include_void,
|
|
archive_scope=archive_scope,
|
|
)
|
|
rows = query.with_entities(
|
|
DouyuExternalOrder.status, func.count(DouyuExternalOrder.id)
|
|
).group_by(DouyuExternalOrder.status)
|
|
by_status = {str(status): int(count) for status, count in rows.all()}
|
|
total = sum(by_status.values())
|
|
ck_invalid = (
|
|
query.outerjoin(Account, Account.id == DouyuExternalOrder.account_id)
|
|
.with_entities(func.count(DouyuExternalOrder.id))
|
|
.filter(Account.ck_check_status == CK_INVALID)
|
|
.scalar()
|
|
or 0
|
|
)
|
|
return {
|
|
"total": total,
|
|
"by_status": by_status,
|
|
"ck_invalid": int(ck_invalid),
|
|
"archived_total": count_archived(db, DouyuExternalOrder),
|
|
"account_missing": (
|
|
db.query(func.count(DouyuExternalOrder.id))
|
|
.filter(
|
|
DouyuExternalOrder.account_id.is_(None),
|
|
DouyuExternalOrder.archived_at.is_(None),
|
|
)
|
|
.scalar()
|
|
or 0
|
|
),
|
|
}
|
|
|
|
def order_metrics(db: Session, order_id: int) -> list[dict[str, Any]]:
|
|
rows = (
|
|
db.query(DouyuExternalOrderMetric)
|
|
.filter(DouyuExternalOrderMetric.order_id == order_id)
|
|
.order_by(DouyuExternalOrderMetric.id.desc())
|
|
.all()
|
|
)
|
|
return [serialize_metric(row) for row in rows]
|
|
|
|
def serialize_metric(row: DouyuExternalOrderMetric) -> dict[str, Any]:
|
|
return {
|
|
"id": int(row.id),
|
|
"order_id": int(row.order_id),
|
|
"order_no": row.order_no,
|
|
"account_username": row.account_username,
|
|
"fish_fin_balance": row.fish_fin_balance,
|
|
"points_balance": row.points_balance,
|
|
"points_required_total": row.points_required_total,
|
|
"points_surplus": row.points_surplus,
|
|
"records_total": row.records_total,
|
|
"records_matched": row.records_matched,
|
|
"verdict": row.verdict,
|
|
"verdict_label": {
|
|
VERDICT_SUCCESS: "兑换成功",
|
|
VERDICT_FAILED: "兑换失败",
|
|
VERDICT_UNKNOWN: "无法判定",
|
|
}.get(row.verdict, row.verdict),
|
|
"message": row.message,
|
|
"source": row.source,
|
|
"created_at": row.created_at,
|
|
}
|
|
|
|
def order_timeline(
|
|
db: Session, order_id: int, *, limit: int = 100
|
|
) -> list[dict[str, Any]]:
|
|
rows = (
|
|
db.query(AuditLog)
|
|
.filter(AuditLog.target == f"douyu_external_order:{order_id}")
|
|
.order_by(AuditLog.id.desc())
|
|
.limit(limit)
|
|
.all()
|
|
)
|
|
return [
|
|
{
|
|
"id": int(row.id),
|
|
"action": row.action,
|
|
"username": row.username or "",
|
|
"detail": row.detail or "",
|
|
"success": row.success,
|
|
"created_at": row.created_at,
|
|
}
|
|
for row in rows
|
|
]
|