Files
live-hub-py/web/backend/services/platform_fulfillment/lifecycle.py
T

843 lines
27 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""兑换、人工处理、释放、取消和恢复等生命周期操作。"""
from __future__ import annotations
from typing import Any
from fastapi import HTTPException
from sqlalchemy.orm import Session
from ...models import (
Account,
AccountLease,
DouyuExternalOrder,
DouyuTask,
PlatformFulfillmentEvent,
PlatformFulfillmentTask,
User,
)
from ..account_capability_service import (
ACCOUNT_ELIGIBILITY_LIMITED,
ACCOUNT_ELIGIBILITY_UNKNOWN,
AVAILABILITY_AVAILABLE,
AVAILABILITY_LIMITED,
AVAILABILITY_NOT_OFFERED,
OFFER_STATE_NOT_OFFERED,
OFFER_STATE_UNKNOWN,
STOCK_STATE_UNKNOWN,
classify_goods_items,
exchange_gate_for_availability,
record_account_commodity_state,
)
from ..business_events import record_account_query
from ..douyu_account_probe import (
CAPABILITY_OK,
config_mapping,
persist_probe_result,
probe_account,
)
from ..douyu_batch_launcher import stop_douyu_batches
from ..douyu_service import (
ensure_douyu_config,
)
from ..external_order_source import (
OrderLookupUnavailable,
lookup_pending_manual_fulfillment,
)
from . import classification
from .account_selector import (
release_lease,
)
from .common import (
SCOPE_ELITE,
_mapping_for_sku,
_now,
)
from .mappings import _apply_mapping
from .outbox import _emit_order_site_binding_state
from .repository import (
_load_task,
_retain_lease_for_active_collab,
)
from .runtime import (
_append_event,
_apply_task_lease_policy,
)
from .views import get_task_detail
def release_task_account(
db: Session,
*,
task_id: int,
current: User,
reason: str = "manual_release",
) -> dict[str, Any]:
task = _load_task(db, task_id)
lease = (
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if task.lease_id
else None
)
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_released_to_collab",
)
if retained is None:
release_lease(db, lease, reason=reason, commit=False)
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.execution_status = "ready"
task.binding_status = "not_started"
task.exchange_status = "not_started"
task.issue_code = ""
task.last_error = ""
task.updated_at = _now()
_append_event(
db,
task.id,
"account_released",
actor_type="user",
actor_id=current.id,
detail={"reason": reason},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def reset_task_binding(
db: Session,
*,
task_id: int,
current: User,
reason: str = "客服重置角色绑定",
) -> dict[str, Any]:
"""清空本单旧绑定与客户资料,保留账号租约供客户重新扫码。"""
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束任务不能重置绑定")
if task.binding_status != "failed":
raise HTTPException(
status_code=409, detail="只有绑定失败的任务可以重置角色资料"
)
if not task.account_id or not task.lease_id:
raise HTTPException(status_code=409, detail="当前任务没有可保留的履约账号")
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease is None or lease.status != "active":
raise HTTPException(
status_code=409, detail="账号租约已失效,请释放账号后重新选号"
)
previous_bind_task_id = task.bind_task_id
previous_bind_task = (
db.query(DouyuTask).filter(DouyuTask.id == previous_bind_task_id).first()
if previous_bind_task_id
else None
)
if previous_bind_task and previous_bind_task.status in {
"planned",
"pending",
"running",
}:
raise HTTPException(status_code=409, detail="当前绑定任务仍在执行,不能重置")
previous_binding_status = task.binding_status
previous_issue_code = task.issue_code
task.bind_task_id = None
task.binding_status = "not_started"
task.execution_status = "allocated"
task.exchange_status = "not_started"
task.issue_code = ""
task.last_error = ""
task.operator_id = current.id
task.updated_at = _now()
_apply_task_lease_policy(db, task, lease=lease)
_append_event(
db,
task.id,
"binding_reset",
actor_type="user",
actor_id=current.id,
detail={
"reason": reason.strip()[:1000],
"previousBindTaskId": previous_bind_task_id,
"previousBindingStatus": previous_binding_status,
"previousIssueCode": previous_issue_code,
"customerProfileReset": True,
},
)
_emit_order_site_binding_state(
db,
task.id,
extra={
"customerProfileReset": True,
"resetReason": reason.strip()[:1000],
},
)
db.commit()
return get_task_detail(db, task.id)
def refresh_exchange_eligibility(
db: Session,
*,
task_id: int,
current: User,
automatic: bool = False,
mark_failed_on_error: bool = True,
) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.binding_status != "bound":
raise HTTPException(status_code=409, detail="请先确认游戏角色绑定")
account = db.query(Account).filter(Account.id == task.account_id).first()
if account is None or not account.cookie:
raise HTTPException(status_code=409, detail="账号 CK 不可用")
config = ensure_douyu_config(db)
try:
probe = probe_account(
account,
config_mapping(config),
with_elite_role=False,
with_eligibility=True,
)
session = probe.get("session") or {}
session_status = str(session.get("status") or "")
if session_status != "valid":
persist_probe_result(
db,
account,
probe,
current=current,
source="platform.exchange_eligibility",
record_event=True,
)
prefix = (
"账号 CK 已失效,请重新登录"
if session_status == "invalid"
else "账号 CK 状态无法确认"
)
raise RuntimeError(f"{prefix}:{session.get('message') or '请稍后重试'}")
if (probe.get("elite") or {}).get("status") != CAPABILITY_OK:
raise RuntimeError(
(probe.get("errors") or {}).get("elite") or "精英宝典状态查询失败"
)
if "points" in (probe.get("errors") or {}):
raise RuntimeError((probe.get("errors") or {})["points"])
limited_ids = frozenset(
str(item)
for item in (probe.get("eligibility") or {}).get("limited_ids") or []
if str(item)
)
persist_probe_result(
db,
account,
probe,
current=current,
source="platform.exchange_eligibility",
record_event=True,
)
except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败
record_account_query(
db,
account,
query_type="exchange_eligibility",
title="刷新兑换资格",
ok=False,
detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id},
actor_id=current.id,
)
if mark_failed_on_error:
task.execution_status = "manual_required"
task.exchange_status = "check_failed"
task.issue_code = "eligibility_check_failed"
task.last_error = str(exc)
task.updated_at = _now()
_append_event(
db,
task.id,
"eligibility_check_failed",
actor_type="user",
actor_id=current.id,
detail={"error": str(exc)},
)
_emit_order_site_binding_state(db, task.id)
else:
_append_event(
db,
task.id,
"eligibility_auto_refresh_failed",
detail={"error": str(exc), "automatic": True},
)
db.commit()
return get_task_detail(db, task.id)
eligibility = probe.get("eligibility") or {}
storehome_goods = [
dict(item)
for item in eligibility.get("storehome_goods") or []
if isinstance(item, dict)
]
assessments = classify_goods_items(storehome_goods, now=_now())
assessment = assessments.get(task.commodity_id)
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
if task.commodity_id in limited_ids:
account_eligibility = ACCOUNT_ELIGIBILITY_LIMITED
offer_state = assessment.offer_state if assessment else OFFER_STATE_UNKNOWN
stock_state = assessment.stock_state if assessment else STOCK_STATE_UNKNOWN
availability = AVAILABILITY_LIMITED
commodity_message = "该账号已达到此商品兑换上限"
elif assessments and assessment is None:
account_eligibility = ACCOUNT_ELIGIBILITY_UNKNOWN
offer_state = OFFER_STATE_NOT_OFFERED
stock_state = STOCK_STATE_UNKNOWN
availability = AVAILABILITY_NOT_OFFERED
commodity_message = "官方商品列表本次未返回该商品,可能已下架"
elif assessment is not None and assessment.availability != AVAILABILITY_AVAILABLE:
account_eligibility = assessment.account_eligibility
offer_state = assessment.offer_state
stock_state = assessment.stock_state
availability = assessment.availability
commodity_message = assessment.blocking_reason
else:
account_eligibility = (
assessment.account_eligibility
if assessment is not None
else ACCOUNT_ELIGIBILITY_UNKNOWN
)
offer_state = (
assessment.offer_state if assessment is not None else OFFER_STATE_UNKNOWN
)
stock_state = (
assessment.stock_state if assessment is not None else STOCK_STATE_UNKNOWN
)
availability = AVAILABILITY_AVAILABLE
commodity_message = ""
gate_status, gate_issue, gate_message = exchange_gate_for_availability(
availability,
reason=commodity_message,
allow_not_open=is_presale,
)
if gate_status:
task.exchange_status = gate_status
task.issue_code = gate_issue
task.last_error = gate_message
elif not account.elite_opened:
task.exchange_status = "not_opened"
task.issue_code = "elite_not_opened"
task.last_error = "该账号精英宝典未开通"
elif task.required_points and int(account.points or 0) < int(task.required_points):
task.exchange_status = "points_short"
task.issue_code = "points_short"
task.last_error = "该账号精英积分不足,需人工充值"
else:
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
record_account_commodity_state(
db,
account,
commodity_id=task.commodity_id,
availability=availability,
account_eligibility=account_eligibility,
offer_state=offer_state,
stock_state=stock_state,
stock_count=assessment.stock_count if assessment is not None else None,
store_status=assessment.store_status if assessment is not None else None,
open_status=assessment.open_status if assessment is not None else None,
blocking_reason=commodity_message,
raw_status=(
assessment.raw_status
if assessment is not None
else "1"
if task.commodity_id in limited_ids
else "0"
),
observed_at=_now(),
source="eligibility_check",
scope=task.scope or SCOPE_ELITE,
)
record_account_query(
db,
account,
query_type="exchange_eligibility",
title="刷新兑换资格",
ok=True,
detail={
"commodity_id": task.commodity_id,
"exchange_status": task.exchange_status,
"limited": task.commodity_id in limited_ids,
"account_eligibility": account_eligibility,
"offer_state": offer_state,
"stock_state": stock_state,
"availability": availability,
"issue_code": task.issue_code,
"points": account.points,
"elite_opened": account.elite_opened,
},
actor_id=current.id,
)
# 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留,
# 后续充值/开通/解除限兑后刷新资格即可。
task.execution_status = "bound"
task.updated_at = _now()
account.updated_at = _now()
# waiting_release 的预售任务在这里切回无限租约,普通 bound 也遵循
# “进行中默认无限”的状态策略。
_apply_task_lease_policy(db, task)
_append_event(
db,
task.id,
"exchange_eligibility_checked",
actor_type="system" if automatic else "user",
actor_id=None if automatic else current.id,
detail={
"exchangeStatus": task.exchange_status,
"limitedCount": len(limited_ids),
"automatic": automatic,
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def refresh_active_exchange_eligibility_for_account(
db: Session,
*,
account_id: int,
scope: str,
actor_id: int | None = None,
) -> dict[str, Any] | None:
"""账号资产变化后,自动刷新当前活动履约任务的兑换投影。
自动刷新失败只记录时间线,不把已绑定任务打成人工;运营仍可手动重试。
"""
task = (
db.query(PlatformFulfillmentTask)
.join(AccountLease, AccountLease.id == PlatformFulfillmentTask.lease_id)
.filter(
PlatformFulfillmentTask.account_id == int(account_id),
PlatformFulfillmentTask.scope == str(scope or SCOPE_ELITE),
PlatformFulfillmentTask.binding_status == "bound",
PlatformFulfillmentTask.execution_status.notin_(
("completed", "cancelled")
),
AccountLease.status == "active",
)
.order_by(
PlatformFulfillmentTask.updated_at.desc(),
PlatformFulfillmentTask.id.desc(),
)
.first()
)
if task is None:
return None
actor = db.get(User, int(actor_id)) if actor_id is not None else None
if actor is None and task.operator_id is not None:
actor = db.get(User, int(task.operator_id))
if actor is None:
actor = (
db.query(User)
.filter(User.role == "super_admin", User.is_active.is_(True))
.order_by(User.id.asc())
.first()
)
if actor is None:
return None
return refresh_exchange_eligibility(
db,
task_id=int(task.id),
current=actor,
automatic=True,
mark_failed_on_error=False,
)
def complete_manual_exchange(
db: Session,
*,
task_id: int,
current: User,
note: str = "",
) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.binding_status != "bound":
raise HTTPException(status_code=409, detail="游戏角色尚未确认绑定")
if task.exchange_status not in {"eligible", "manual_done"}:
raise HTTPException(
status_code=409,
detail="当前兑换资格不是可兑换状态,请先刷新检查结果",
)
lease = (
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if task.lease_id
else None
)
task.exchange_status = "manual_done"
task.execution_status = "completed"
task.completed_at = _now()
task.operator_id = current.id
task.last_error = ""
task.issue_code = ""
task.updated_at = _now()
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_completed_but_collab_active",
)
if retained is None:
# 2026-11-22:兑换完成不再一律立即释放。任务已完成但保留一段可配置
# 的复核窗口;默认人工兑换完成后保留 120 分钟,期间仍可供截图与纠错。
_apply_task_lease_policy(
db,
task,
lease=lease,
)
_append_event(
db,
task.id,
"manual_exchange_completed",
actor_type="user",
actor_id=current.id,
detail={"note": note[:1000]},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def mark_manual_required(
db: Session,
*,
task_id: int,
current: User,
reason: str,
) -> dict[str, Any]:
task = _load_task(db, task_id)
task.execution_status = "manual_required"
task.operator_id = current.id
task.last_error = reason.strip()[:2000]
task.issue_code = task.issue_code or "manual_required"
task.updated_at = _now()
_apply_task_lease_policy(db, task)
_append_event(
db,
task.id,
"marked_manual_required",
actor_type="user",
actor_id=current.id,
detail={"reason": task.last_error},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def cancel_task(
db: Session,
*,
task_id: int,
current: User,
reason: str,
) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.execution_status == "cancelled":
return get_task_detail(db, task.id)
if task.execution_status == "completed":
raise HTTPException(status_code=409, detail="已完成任务不能取消")
account_id = task.account_id
lease_id = task.lease_id
previous_execution_status = task.execution_status
previous_binding_status = task.binding_status
previous_exchange_status = task.exchange_status
lease = (
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if task.lease_id
else None
)
linked_tasks = (
db.query(DouyuTask)
.filter(
DouyuTask.id.in_(
[value for value in [task.bind_task_id, task.exchange_task_id] if value]
)
)
.all()
if task.bind_task_id or task.exchange_task_id
else []
)
stopped_batches = stop_douyu_batches(
[str(linked_task.batch_id or "") for linked_task in linked_tasks]
)
for linked_task in linked_tasks:
if linked_task.status in {"planned", "pending", "running"}:
linked_task.status = "stopped"
linked_task.message = "履约任务已取消"
linked_task.finished_at = _now()
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_cancelled_but_collab_active",
)
if retained is None:
release_lease(
db,
lease,
reason="platform_fulfillment_cancelled",
commit=False,
)
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.exchange_task_id = None
task.binding_status = "not_started"
task.execution_status = "cancelled"
task.exchange_status = "not_started"
task.issue_code = ""
task.operator_id = current.id
task.last_error = reason.strip()[:2000]
task.updated_at = _now()
_append_event(
db,
task.id,
"task_cancelled",
actor_type="user",
actor_id=current.id,
detail={
"reason": task.last_error,
"previousExecutionStatus": previous_execution_status,
"previousBindingStatus": previous_binding_status,
"previousExchangeStatus": previous_exchange_status,
"releasedAccountId": account_id,
"releasedLeaseId": lease_id,
"stoppedBatches": stopped_batches,
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def restore_cancelled_task(
db: Session,
*,
task_id: int,
current: User,
reason: str,
) -> dict[str, Any]:
"""仅恢复人工误取消、且来源订单仍可履约的任务;不复用旧租约。"""
task = (
db.query(PlatformFulfillmentTask)
.filter(PlatformFulfillmentTask.id == int(task_id))
.with_for_update()
.first()
)
if task is None:
raise HTTPException(status_code=404, detail="直播账号履约任务不存在")
if task.execution_status != "cancelled":
raise HTTPException(status_code=409, detail="只有已取消任务可以恢复")
if task.issue_code == "source_cancelled":
raise HTTPException(status_code=409, detail="来源订单已取消,不能恢复")
manual_cancel = (
db.query(PlatformFulfillmentEvent.id)
.filter(
PlatformFulfillmentEvent.task_id == task.id,
PlatformFulfillmentEvent.event_type == "task_cancelled",
PlatformFulfillmentEvent.actor_type == "user",
)
.first()
)
if manual_cancel is None:
raise HTTPException(status_code=409, detail="只有人工取消的任务可以恢复")
try:
source = lookup_pending_manual_fulfillment(task.source_order_item_id)
except OrderLookupUnavailable as exc:
raise HTTPException(status_code=503, detail=f"订单源不可用:{exc}") from exc
if source is None:
raise HTTPException(status_code=409, detail="来源订单不存在或已不可履约")
if (
str(source.get("order_status") or "") in {"refunded", "cancelled", "closed"}
or str(source.get("pay_status") or "") != "paid"
or str(source.get("fulfillment_issue_code") or "")
in {"user_refund", "platform_cancelled"}
):
raise HTTPException(
status_code=409, detail="来源订单已退款、关闭或取消,不能恢复"
)
restore_reason = reason.strip()
if len(restore_reason) < 2:
raise HTTPException(status_code=400, detail="请填写恢复原因")
restored_collab = (
db.query(DouyuExternalOrder)
.filter(DouyuExternalOrder.source_task_id == task.id)
.first()
)
if restored_collab is not None and (
restored_collab.status not in {"incomplete", "void"}
or restored_collab.bind_game_role
or restored_collab.home_images
):
raise HTTPException(
status_code=409,
detail="关联外部协作单已在人工处理,请继续使用外部协作单",
)
mapping = _mapping_for_sku(db, task.internal_sku_key)
_apply_mapping(task, mapping)
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.exchange_task_id = None
task.binding_status = "not_started"
task.exchange_status = "not_started"
task.completed_at = None
task.next_allocate_at = _now() if task.execution_status == "ready" else None
task.operator_id = current.id
task.updated_at = _now()
restored_collab_status = ""
if restored_collab is not None and restored_collab.status == "void":
restored_collab.status = "incomplete"
restored_collab.void_reason = ""
restored_collab.updated_by = current.id
restored_collab.updated_at = _now()
restored_collab.version = int(restored_collab.version or 0) + 1
restored_collab_status = restored_collab.status
_append_event(
db,
task.id,
"task_restored",
actor_type="user",
actor_id=current.id,
detail={
"reason": restore_reason,
"restoredExecutionStatus": task.execution_status,
"restoredCollabOrderId": (
int(restored_collab.id) if restored_collab is not None else None
),
"restoredCollabStatus": restored_collab_status,
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def prepare_platform_task_for_collab_takeover(
db: Session,
*,
task: PlatformFulfillmentTask,
current: User,
collab_order_no: str,
) -> None:
"""把平台履约任务转为人工,但不提交事务;由协作单接管流程原子提交。"""
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束的履约任务不能被协作单接管")
account_id = task.account_id
lease_id = task.lease_id
reason = f"外部协作单 {collab_order_no} 人工接管账号"
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.exchange_task_id = None
task.execution_status = "manual_required"
task.binding_status = "not_started"
task.exchange_status = "not_started"
task.issue_code = "manual_required"
task.next_allocate_at = None
task.operator_id = current.id
task.last_error = reason
task.updated_at = _now()
_append_event(
db,
task.id,
"collab_takeover",
actor_type="user",
actor_id=current.id,
detail={
"reason": reason,
"collabOrderNo": collab_order_no,
"releasedAccountId": account_id,
"releasedLeaseId": lease_id,
},
)
_emit_order_site_binding_state(db, task.id)
db.flush()
def release_task_to_manual(
db: Session,
*,
task_id: int,
current: User,
reason: str,
) -> dict[str, Any]:
"""释放履约账号并转人工,不再进入自动选号。"""
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束任务不能转人工")
manual_reason = reason.strip()[:2000] or "以外部单协作人工处理为准"
account_id = task.account_id
lease_id = task.lease_id
lease = (
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if task.lease_id
else None
)
retained = _retain_lease_for_active_collab(
db,
task=task,
lease=lease,
current=current,
reason="platform_release_to_manual",
)
if retained is None:
release_lease(
db,
lease,
reason="platform_fulfillment_manual",
commit=False,
)
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.exchange_task_id = None
task.execution_status = "manual_required"
task.binding_status = "not_started"
task.exchange_status = "not_started"
task.issue_code = "manual_required"
task.next_allocate_at = None
task.operator_id = current.id
task.last_error = manual_reason
task.updated_at = _now()
_append_event(
db,
task.id,
"released_to_manual",
actor_type="user",
actor_id=current.id,
detail={
"reason": manual_reason,
"releasedAccountId": account_id,
"releasedLeaseId": lease_id,
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)