feat(fulfillment): 新增直播账号履约工作台
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
"""直播账号履约的账号筛选与租约。
|
||||
|
||||
只复用账号池中经过验证的筛选与数据库唯一约束,不引入自动充值、自动兑换
|
||||
或多活动 scope。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...models import Account, AccountEvent, AccountLease, User
|
||||
|
||||
VALIDATION_LEASE_MINUTES = 5
|
||||
BINDING_LEASE_MINUTES = 120
|
||||
EXCHANGE_COOLDOWN_DAYS = 365
|
||||
POOL_OWNER_ROLES = ("super_admin", "operation")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AccountCandidate:
|
||||
account_id: int
|
||||
username: str
|
||||
nickname: str
|
||||
points: int
|
||||
gold_balance: int | None
|
||||
points_expire_at: datetime | None
|
||||
role_change_available_at: datetime | None
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
return self.nickname or self.username or f"#{self.account_id}"
|
||||
|
||||
|
||||
def _now(now: datetime | None = None) -> datetime:
|
||||
return now or datetime.now(UTC)
|
||||
|
||||
|
||||
def eligible_accounts(
|
||||
db: Session,
|
||||
*,
|
||||
commodity_id: str,
|
||||
required_points: int,
|
||||
now: datetime | None = None,
|
||||
limit: int = 20,
|
||||
) -> list[AccountCandidate]:
|
||||
"""筛选能人工兑换指定精英宝典商品的账号。"""
|
||||
moment = _now(now)
|
||||
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
|
||||
owner_ids = select(User.id).where(User.role.in_(POOL_OWNER_ROLES))
|
||||
active_lease = (
|
||||
select(AccountLease.id)
|
||||
.where(AccountLease.active_account_id == Account.id)
|
||||
.exists()
|
||||
)
|
||||
exchanged = (
|
||||
select(AccountEvent.id)
|
||||
.where(
|
||||
AccountEvent.account_id == Account.id,
|
||||
AccountEvent.event_type == "exchange",
|
||||
AccountEvent.subject_key == commodity_id,
|
||||
AccountEvent.occurred_at >= since,
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
rows = (
|
||||
db.query(Account)
|
||||
.filter(
|
||||
Account.status == "active",
|
||||
Account.ck_check_status == "valid",
|
||||
Account.cookie.isnot(None),
|
||||
Account.cookie != "",
|
||||
Account.auto_managed.is_(True),
|
||||
Account.elite_opened.is_(True),
|
||||
Account.points.isnot(None),
|
||||
Account.points >= max(0, int(required_points)),
|
||||
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
|
||||
~active_lease,
|
||||
~exchanged,
|
||||
or_(
|
||||
Account.role_change_available_at.is_(None),
|
||||
Account.role_change_available_at <= moment,
|
||||
),
|
||||
)
|
||||
.order_by(
|
||||
Account.points_expire_at.is_(None),
|
||||
Account.points_expire_at.asc(),
|
||||
Account.points.asc(),
|
||||
Account.id.asc(),
|
||||
)
|
||||
.limit(max(1, min(int(limit), 100)))
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
AccountCandidate(
|
||||
account_id=row.id,
|
||||
username=row.username,
|
||||
nickname=row.nickname or "",
|
||||
points=int(row.points or 0),
|
||||
gold_balance=row.gold_balance,
|
||||
points_expire_at=row.points_expire_at,
|
||||
role_change_available_at=row.role_change_available_at,
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def lease_account(
|
||||
db: Session,
|
||||
*,
|
||||
candidate: AccountCandidate,
|
||||
holder_user_id: int,
|
||||
task_id: int,
|
||||
commodity_id: str,
|
||||
ttl_minutes: int = VALIDATION_LEASE_MINUTES,
|
||||
now: datetime | None = None,
|
||||
) -> AccountLease | None:
|
||||
"""尝试领取一个账号;撞唯一索引时返回 None。"""
|
||||
moment = _now(now)
|
||||
lease = AccountLease(
|
||||
account_id=candidate.account_id,
|
||||
holder_user_id=holder_user_id,
|
||||
scope="elite",
|
||||
purpose="platform_fulfillment",
|
||||
commodity_id=commodity_id,
|
||||
batch_id=f"pf:{task_id}",
|
||||
status="active",
|
||||
leased_at=moment,
|
||||
expires_at=moment + timedelta(minutes=max(1, int(ttl_minutes))),
|
||||
release_reason="",
|
||||
created_at=moment,
|
||||
)
|
||||
try:
|
||||
with db.begin_nested():
|
||||
db.add(lease)
|
||||
db.flush()
|
||||
except IntegrityError:
|
||||
if lease in db:
|
||||
db.expunge(lease)
|
||||
return None
|
||||
db.commit()
|
||||
return lease
|
||||
|
||||
|
||||
def renew_lease(
|
||||
db: Session,
|
||||
lease: AccountLease,
|
||||
*,
|
||||
ttl_minutes: int = BINDING_LEASE_MINUTES,
|
||||
now: datetime | None = None,
|
||||
) -> AccountLease:
|
||||
if lease.status != "active":
|
||||
raise ValueError("租约已结束,不能续期")
|
||||
lease.expires_at = _now(now) + timedelta(minutes=max(1, int(ttl_minutes)))
|
||||
db.commit()
|
||||
return lease
|
||||
|
||||
|
||||
def release_lease(
|
||||
db: Session,
|
||||
lease: AccountLease | None,
|
||||
*,
|
||||
reason: str,
|
||||
now: datetime | None = None,
|
||||
) -> bool:
|
||||
if lease is None or lease.status != "active":
|
||||
return False
|
||||
lease.status = "released"
|
||||
lease.released_at = _now(now)
|
||||
lease.release_reason = str(reason or "")[:64]
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
def expire_platform_fulfillment_leases(
|
||||
db: Session,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
limit: int = 500,
|
||||
) -> int:
|
||||
moment = _now(now)
|
||||
leases = (
|
||||
db.query(AccountLease)
|
||||
.filter(
|
||||
AccountLease.purpose == "platform_fulfillment",
|
||||
AccountLease.status == "active",
|
||||
AccountLease.expires_at <= moment,
|
||||
)
|
||||
.order_by(AccountLease.id.asc())
|
||||
.limit(max(1, int(limit)))
|
||||
.all()
|
||||
)
|
||||
for lease in leases:
|
||||
lease.status = "expired"
|
||||
lease.released_at = moment
|
||||
lease.release_reason = "ttl_expired"
|
||||
if leases:
|
||||
db.commit()
|
||||
return len(leases)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BINDING_LEASE_MINUTES",
|
||||
"EXCHANGE_COOLDOWN_DAYS",
|
||||
"VALIDATION_LEASE_MINUTES",
|
||||
"AccountCandidate",
|
||||
"eligible_accounts",
|
||||
"expire_platform_fulfillment_leases",
|
||||
"lease_account",
|
||||
"release_lease",
|
||||
"renew_lease",
|
||||
]
|
||||
Reference in New Issue
Block a user