fix(douyu): 统一外部协作账号租约
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
"""把进行中的斗鱼外部协作单接入统一账号租约。
|
||||
|
||||
只给当前没有活动租约的账号补租约。已经被平台履约等业务占用的账号保持原状,
|
||||
并写一条冲突事件供账号时间线追溯,避免迁移抢占正在执行的链路。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261119_0098"
|
||||
down_revision: str | None = "20261119_0097"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
ACTIVE_COLLAB_STATUSES = (
|
||||
"incomplete",
|
||||
"to_recharge",
|
||||
"recharged",
|
||||
"scripted",
|
||||
"points_error",
|
||||
"failed",
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
active_status_sql = ", ".join(f"'{item}'" for item in ACTIVE_COLLAB_STATUSES)
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
INSERT INTO account_leases (
|
||||
account_id,
|
||||
holder_user_id,
|
||||
scope,
|
||||
purpose,
|
||||
commodity_id,
|
||||
batch_id,
|
||||
status,
|
||||
leased_at,
|
||||
expires_at,
|
||||
released_at,
|
||||
release_reason,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
candidates.account_id,
|
||||
candidates.holder_user_id,
|
||||
'elite',
|
||||
'douyu_collab',
|
||||
'',
|
||||
CONCAT('collab:', candidates.account_id),
|
||||
'active',
|
||||
UTC_TIMESTAMP(),
|
||||
NULL,
|
||||
NULL,
|
||||
'migration_backfill',
|
||||
UTC_TIMESTAMP()
|
||||
FROM (
|
||||
SELECT DISTINCT
|
||||
o.account_id AS account_id,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT o2.owner_id
|
||||
FROM douyu_external_orders o2
|
||||
WHERE o2.account_id = o.account_id
|
||||
AND o2.owner_id IS NOT NULL
|
||||
AND o2.archived_at IS NULL
|
||||
AND o2.status IN ({active_status_sql})
|
||||
ORDER BY o2.updated_at DESC, o2.id DESC
|
||||
LIMIT 1
|
||||
),
|
||||
a.assigned_to,
|
||||
(
|
||||
SELECT u.id
|
||||
FROM users u
|
||||
WHERE u.is_active = 1
|
||||
AND u.deleted_at IS NULL
|
||||
ORDER BY
|
||||
CASE u.role
|
||||
WHEN 'super_admin' THEN 0
|
||||
WHEN 'operation' THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
u.id ASC
|
||||
LIMIT 1
|
||||
)
|
||||
) AS holder_user_id
|
||||
FROM douyu_external_orders o
|
||||
JOIN accounts a ON a.id = o.account_id
|
||||
WHERE o.account_id IS NOT NULL
|
||||
AND o.archived_at IS NULL
|
||||
AND o.status IN ({active_status_sql})
|
||||
) AS candidates
|
||||
WHERE candidates.holder_user_id IS NOT NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM account_leases active_lease
|
||||
WHERE active_lease.account_id = candidates.account_id
|
||||
AND active_lease.status = 'active'
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO account_events (
|
||||
account_id,
|
||||
event_type,
|
||||
category,
|
||||
occurred_at,
|
||||
title,
|
||||
amount,
|
||||
balance_after,
|
||||
subject_type,
|
||||
subject_key,
|
||||
detail,
|
||||
source,
|
||||
actor_type,
|
||||
actor_id,
|
||||
source_ref,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
lease.account_id,
|
||||
'lease_acquired',
|
||||
'ops',
|
||||
UTC_TIMESTAMP(),
|
||||
CONCAT('外部协作账号占用回填:账号 #', lease.account_id),
|
||||
NULL,
|
||||
NULL,
|
||||
'lease',
|
||||
CONCAT('collab:', lease.account_id),
|
||||
JSON_OBJECT(
|
||||
'lease_id', lease.id,
|
||||
'account_id', lease.account_id,
|
||||
'purpose', lease.purpose,
|
||||
'batch_id', lease.batch_id,
|
||||
'backfill', TRUE
|
||||
),
|
||||
'migration',
|
||||
'system',
|
||||
NULL,
|
||||
CONCAT('account_lease_backfill:', lease.id),
|
||||
UTC_TIMESTAMP()
|
||||
FROM account_leases lease
|
||||
WHERE lease.status = 'active'
|
||||
AND lease.purpose = 'douyu_collab'
|
||||
AND lease.release_reason = 'migration_backfill'
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"""
|
||||
INSERT INTO account_events (
|
||||
account_id,
|
||||
event_type,
|
||||
category,
|
||||
occurred_at,
|
||||
title,
|
||||
amount,
|
||||
balance_after,
|
||||
subject_type,
|
||||
subject_key,
|
||||
detail,
|
||||
source,
|
||||
actor_type,
|
||||
actor_id,
|
||||
source_ref,
|
||||
created_at
|
||||
)
|
||||
SELECT DISTINCT
|
||||
active_order.account_id,
|
||||
'lease_conflict',
|
||||
'ops',
|
||||
UTC_TIMESTAMP(),
|
||||
CONCAT(
|
||||
'外部协作账号已被占用:',
|
||||
active_order.account_id,
|
||||
' / ',
|
||||
active_lease.purpose
|
||||
),
|
||||
NULL,
|
||||
NULL,
|
||||
'lease',
|
||||
CONCAT('collab:', active_order.account_id),
|
||||
JSON_OBJECT(
|
||||
'lease_id', active_lease.id,
|
||||
'account_id', active_order.account_id,
|
||||
'existing_purpose', active_lease.purpose,
|
||||
'existing_batch_id', active_lease.batch_id,
|
||||
'conflict', TRUE
|
||||
),
|
||||
'migration',
|
||||
'system',
|
||||
NULL,
|
||||
CONCAT(
|
||||
'account_lease_collab_conflict:',
|
||||
active_order.account_id,
|
||||
':',
|
||||
active_lease.id
|
||||
),
|
||||
UTC_TIMESTAMP()
|
||||
FROM douyu_external_orders active_order
|
||||
JOIN account_leases active_lease
|
||||
ON active_lease.account_id = active_order.account_id
|
||||
AND active_lease.status = 'active'
|
||||
WHERE active_order.account_id IS NOT NULL
|
||||
AND active_order.archived_at IS NULL
|
||||
AND active_order.status IN ({active_status_sql})
|
||||
AND active_lease.purpose <> 'douyu_collab'
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
DELETE FROM account_events
|
||||
WHERE source_ref LIKE 'account_lease_backfill:%'
|
||||
OR source_ref LIKE 'account_lease_collab_conflict:%'
|
||||
"""
|
||||
)
|
||||
)
|
||||
op.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE account_leases
|
||||
SET status = 'released',
|
||||
released_at = UTC_TIMESTAMP(),
|
||||
release_reason = 'migration_rollback'
|
||||
WHERE status = 'active'
|
||||
AND purpose = 'douyu_collab'
|
||||
AND release_reason = 'migration_backfill'
|
||||
"""
|
||||
)
|
||||
)
|
||||
@@ -22,24 +22,62 @@ def run_platform_fulfillment_lease_reaper(
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
moment = now or datetime.now(UTC)
|
||||
released_ids = {
|
||||
lease_id
|
||||
for (lease_id,) in db.query(AccountLease.id)
|
||||
candidate_leases = (
|
||||
db.query(AccountLease)
|
||||
.filter(
|
||||
AccountLease.purpose == "platform_fulfillment",
|
||||
AccountLease.status == "active",
|
||||
AccountLease.expires_at.isnot(None),
|
||||
AccountLease.expires_at <= moment,
|
||||
)
|
||||
.order_by(AccountLease.id.asc())
|
||||
.limit(max(1, int(job.batch_size or 500)))
|
||||
.all()
|
||||
}
|
||||
)
|
||||
released_ids = {int(lease.id) for lease in candidate_leases}
|
||||
converted_tasks: dict[int, PlatformFulfillmentTask] = {}
|
||||
if candidate_leases:
|
||||
from ...douyu_collab_service import retain_lease_for_active_collab
|
||||
|
||||
for lease in candidate_leases:
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(PlatformFulfillmentTask.lease_id == lease.id)
|
||||
.first()
|
||||
)
|
||||
retained = retain_lease_for_active_collab(
|
||||
db,
|
||||
account_id=int(lease.account_id),
|
||||
holder_user_id=int(task.operator_id or lease.holder_user_id)
|
||||
if task is not None
|
||||
else int(lease.holder_user_id),
|
||||
lease=lease,
|
||||
source_task_id=int(task.id) if task is not None else None,
|
||||
reason="platform_lease_expired_collab_active",
|
||||
commit=False,
|
||||
)
|
||||
if retained is None:
|
||||
continue
|
||||
released_ids.discard(int(lease.id))
|
||||
if task is not None:
|
||||
converted_tasks[int(task.id)] = task
|
||||
|
||||
expired = expire_platform_fulfillment_leases(
|
||||
db,
|
||||
now=moment,
|
||||
limit=max(1, int(job.batch_size or 500)),
|
||||
)
|
||||
affected = 0
|
||||
for task in converted_tasks.values():
|
||||
if task.execution_status in {"completed", "cancelled"}:
|
||||
continue
|
||||
task.account_id = None
|
||||
task.lease_id = None
|
||||
task.execution_status = "manual_required"
|
||||
task.issue_code = "lease_expired_collab_handoff"
|
||||
task.last_error = "平台租约已到期,账号已转外部协作人工处理"
|
||||
task.updated_at = moment
|
||||
affected += 1
|
||||
if released_ids:
|
||||
rows = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
@@ -54,6 +92,7 @@ def run_platform_fulfillment_lease_reaper(
|
||||
task.last_error = "账号租约已过期,请重新分配账号"
|
||||
task.updated_at = moment
|
||||
affected += 1
|
||||
if released_ids or converted_tasks:
|
||||
db.commit()
|
||||
return {
|
||||
"scanned": expired,
|
||||
|
||||
@@ -25,6 +25,7 @@ from core.douyu import DouyuActivityClient
|
||||
|
||||
from ..models import (
|
||||
Account,
|
||||
AccountLease,
|
||||
AuditLog,
|
||||
DouyuCollabGift,
|
||||
DouyuCollabShop,
|
||||
@@ -38,7 +39,12 @@ from ..models import (
|
||||
User,
|
||||
)
|
||||
from .account_binding import binding_channel, binding_role_from_result
|
||||
from .account_events_service import EVENT_COLLAB_SYNCED
|
||||
from .account_events_service import (
|
||||
CATEGORY_OPS,
|
||||
EVENT_COLLAB_SYNCED,
|
||||
EVENT_LEASE_ACQUIRED,
|
||||
emit,
|
||||
)
|
||||
from .audit_service import record_account_action, record_audit
|
||||
from .business_events import record_account_query
|
||||
from .collab_common import apply_order_visibility, count_archived
|
||||
@@ -59,6 +65,11 @@ from .douyu_goods_service import (
|
||||
upsert_goods_snapshot,
|
||||
)
|
||||
from .file_service import build_file_url
|
||||
from .platform_fulfillment.account_selector import (
|
||||
acquire_account_lease,
|
||||
active_lease_for_account,
|
||||
release_lease,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 状态机
|
||||
@@ -72,6 +83,15 @@ STATUS_DONE = "done"
|
||||
STATUS_POINTS_ERROR = "points_error"
|
||||
STATUS_FAILED = "failed"
|
||||
STATUS_VOID = "void"
|
||||
LEASE_PURPOSE_DOUYU_COLLAB = "douyu_collab"
|
||||
COLLAB_LEASE_STATUSES: tuple[str, ...] = (
|
||||
STATUS_INCOMPLETE,
|
||||
STATUS_TO_RECHARGE,
|
||||
STATUS_RECHARGED,
|
||||
STATUS_SCRIPTED,
|
||||
STATUS_POINTS_ERROR,
|
||||
STATUS_FAILED,
|
||||
)
|
||||
|
||||
ORDER_STATUSES: tuple[str, ...] = (
|
||||
STATUS_INCOMPLETE,
|
||||
@@ -449,6 +469,308 @@ def _assert_mutable(order: DouyuExternalOrder) -> None:
|
||||
raise CollabError("已作废的订单不能再编辑", code="order_void")
|
||||
|
||||
|
||||
def _order_occupies_account(order: DouyuExternalOrder) -> bool:
|
||||
return (
|
||||
bool(order.account_id)
|
||||
and order.archived_at is None
|
||||
and order.status in COLLAB_LEASE_STATUSES
|
||||
)
|
||||
|
||||
|
||||
def _active_collab_order(
|
||||
db: Session,
|
||||
account_id: int,
|
||||
*,
|
||||
exclude_order_id: int | None = None,
|
||||
) -> DouyuExternalOrder | None:
|
||||
query = db.query(DouyuExternalOrder).filter(
|
||||
DouyuExternalOrder.account_id == int(account_id),
|
||||
DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES),
|
||||
DouyuExternalOrder.archived_at.is_(None),
|
||||
)
|
||||
if exclude_order_id is not None:
|
||||
query = query.filter(DouyuExternalOrder.id != int(exclude_order_id))
|
||||
return query.order_by(DouyuExternalOrder.updated_at.desc()).first()
|
||||
|
||||
|
||||
def _platform_lease_matches_source(
|
||||
db: Session, lease: AccountLease, order: DouyuExternalOrder
|
||||
) -> bool:
|
||||
if (
|
||||
lease.purpose != "platform_fulfillment"
|
||||
or order.source_type != SOURCE_TYPE_PLATFORM_FULFILLMENT
|
||||
or not order.source_task_id
|
||||
):
|
||||
return False
|
||||
task = (
|
||||
db.query(PlatformFulfillmentTask)
|
||||
.filter(PlatformFulfillmentTask.id == int(order.source_task_id))
|
||||
.first()
|
||||
)
|
||||
return bool(
|
||||
task is not None
|
||||
and (task.lease_id == lease.id or lease.batch_id == f"pf:{int(task.id)}")
|
||||
)
|
||||
|
||||
|
||||
def _audit_lease_action(
|
||||
db: Session,
|
||||
current: User,
|
||||
*,
|
||||
order: DouyuExternalOrder | None,
|
||||
account_id: int,
|
||||
action: str,
|
||||
lease: AccountLease,
|
||||
detail: Mapping[str, Any],
|
||||
) -> None:
|
||||
entry = record_audit(
|
||||
db,
|
||||
current,
|
||||
action=action,
|
||||
target=(
|
||||
(
|
||||
f"douyu_external_order:{order.id}"
|
||||
if order.id
|
||||
else f"douyu_external_order_no:{order.order_no}"
|
||||
)
|
||||
if order is not None
|
||||
else f"account:{account_id}"
|
||||
),
|
||||
detail=detail,
|
||||
)
|
||||
entry.account_id = account_id
|
||||
|
||||
|
||||
def _ensure_order_account_lease(
|
||||
db: Session,
|
||||
current: User,
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
account_id: int | None = None,
|
||||
force_active: bool = False,
|
||||
commit: bool = False,
|
||||
) -> AccountLease | None:
|
||||
target_account_id = int(account_id or order.account_id or 0)
|
||||
if not target_account_id:
|
||||
return None
|
||||
if not force_active and not _order_occupies_account(order):
|
||||
return None
|
||||
|
||||
lease = active_lease_for_account(db, target_account_id)
|
||||
if lease is not None:
|
||||
if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB:
|
||||
return lease
|
||||
if _platform_lease_matches_source(db, lease, order):
|
||||
return lease
|
||||
raise CollabError(
|
||||
"该账号当前被平台履约占用,请先释放或转人工后再使用",
|
||||
status_code=409,
|
||||
code="account_lease_conflict",
|
||||
)
|
||||
|
||||
lease = acquire_account_lease(
|
||||
db,
|
||||
account_id=target_account_id,
|
||||
holder_user_id=int(current.id),
|
||||
scope="elite",
|
||||
purpose=LEASE_PURPOSE_DOUYU_COLLAB,
|
||||
batch_id=f"collab:{target_account_id}",
|
||||
commit=False,
|
||||
)
|
||||
if lease is None:
|
||||
raise CollabError(
|
||||
"该账号刚被其他业务占用,请刷新后重试",
|
||||
status_code=409,
|
||||
code="account_lease_conflict",
|
||||
)
|
||||
_audit_lease_action(
|
||||
db,
|
||||
current,
|
||||
order=order,
|
||||
account_id=target_account_id,
|
||||
action="douyu:collab:lease_acquired",
|
||||
lease=lease,
|
||||
detail={
|
||||
"lease_id": lease.id,
|
||||
"account_id": target_account_id,
|
||||
"purpose": lease.purpose,
|
||||
"batch_id": lease.batch_id,
|
||||
},
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
return lease
|
||||
|
||||
|
||||
def _release_order_account_lease(
|
||||
db: Session,
|
||||
current: User,
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
reason: str,
|
||||
account_id: int | None = None,
|
||||
commit: bool = False,
|
||||
) -> bool:
|
||||
target_account_id = int(account_id or order.account_id or 0)
|
||||
if not target_account_id:
|
||||
return False
|
||||
if _active_collab_order(db, target_account_id, exclude_order_id=int(order.id)):
|
||||
return False
|
||||
lease = active_lease_for_account(db, target_account_id)
|
||||
if lease is None or lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB:
|
||||
return False
|
||||
released = release_lease(db, lease, reason=reason, commit=False)
|
||||
if released:
|
||||
_audit_lease_action(
|
||||
db,
|
||||
current,
|
||||
order=order,
|
||||
account_id=target_account_id,
|
||||
action="douyu:collab:lease_released",
|
||||
lease=lease,
|
||||
detail={
|
||||
"lease_id": lease.id,
|
||||
"account_id": target_account_id,
|
||||
"reason": reason,
|
||||
},
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
return released
|
||||
|
||||
|
||||
def _sync_order_lease(
|
||||
db: Session,
|
||||
current: User,
|
||||
order: DouyuExternalOrder,
|
||||
*,
|
||||
reason: str,
|
||||
force_active: bool = False,
|
||||
commit: bool = False,
|
||||
) -> AccountLease | None:
|
||||
if force_active or _order_occupies_account(order):
|
||||
return _ensure_order_account_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
force_active=force_active,
|
||||
commit=commit,
|
||||
)
|
||||
_release_order_account_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason=reason,
|
||||
commit=commit,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def retain_lease_for_active_collab(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int,
|
||||
holder_user_id: int,
|
||||
current: User | None = None,
|
||||
lease: AccountLease | None = None,
|
||||
source_task_id: int | None = None,
|
||||
reason: str = "platform_release_to_collab",
|
||||
commit: bool = False,
|
||||
) -> AccountLease | None:
|
||||
"""平台释放账号时,把仍在活动的协作占用接续为统一协作租约。"""
|
||||
active_lease = lease or active_lease_for_account(db, account_id)
|
||||
if active_lease is not None and active_lease.status != "active":
|
||||
return None
|
||||
|
||||
query = db.query(DouyuExternalOrder).filter(
|
||||
DouyuExternalOrder.account_id == int(account_id),
|
||||
DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES),
|
||||
DouyuExternalOrder.archived_at.is_(None),
|
||||
)
|
||||
if source_task_id:
|
||||
preferred = (
|
||||
query.filter(DouyuExternalOrder.source_task_id == int(source_task_id))
|
||||
.order_by(DouyuExternalOrder.updated_at.desc())
|
||||
.first()
|
||||
)
|
||||
order = (
|
||||
preferred or query.order_by(DouyuExternalOrder.updated_at.desc()).first()
|
||||
)
|
||||
else:
|
||||
order = query.order_by(DouyuExternalOrder.updated_at.desc()).first()
|
||||
if order is None:
|
||||
return None
|
||||
|
||||
holder_id = int(
|
||||
holder_user_id
|
||||
or (order.owner_id if order.owner_id else 0)
|
||||
or (active_lease.holder_user_id if active_lease else 0)
|
||||
)
|
||||
if not holder_id:
|
||||
return None
|
||||
|
||||
if active_lease is None:
|
||||
active_lease = acquire_account_lease(
|
||||
db,
|
||||
account_id=int(account_id),
|
||||
holder_user_id=holder_id,
|
||||
scope="elite",
|
||||
purpose=LEASE_PURPOSE_DOUYU_COLLAB,
|
||||
batch_id=f"collab:{int(account_id)}",
|
||||
commit=False,
|
||||
)
|
||||
if active_lease is None:
|
||||
return None
|
||||
elif active_lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB:
|
||||
previous_purpose = active_lease.purpose
|
||||
active_lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB
|
||||
active_lease.batch_id = f"collab:{int(account_id)}"[:64]
|
||||
active_lease.commodity_id = ""
|
||||
active_lease.expires_at = None
|
||||
active_lease.release_reason = ""
|
||||
active_lease.holder_user_id = holder_id
|
||||
emit(
|
||||
db,
|
||||
account_id=int(account_id),
|
||||
event_type=EVENT_LEASE_ACQUIRED,
|
||||
title=f"外部协作接管账号占用:{order.order_no}",
|
||||
category=CATEGORY_OPS,
|
||||
detail={
|
||||
"lease_id": active_lease.id,
|
||||
"order_id": order.id,
|
||||
"order_no": order.order_no,
|
||||
"purpose": active_lease.purpose,
|
||||
"previous_purpose": previous_purpose,
|
||||
"reason": reason,
|
||||
},
|
||||
source="lease",
|
||||
subject_type="order",
|
||||
subject_key=order.order_no,
|
||||
actor_type="user" if current is not None else "system",
|
||||
actor_id=int(current.id) if current is not None else None,
|
||||
source_ref=f"account_lease_collab_takeover:{active_lease.id}",
|
||||
)
|
||||
|
||||
if current is not None:
|
||||
_audit_lease_action(
|
||||
db,
|
||||
current,
|
||||
order=order,
|
||||
account_id=int(account_id),
|
||||
action="douyu:collab:lease_takeover",
|
||||
lease=active_lease,
|
||||
detail={
|
||||
"lease_id": active_lease.id,
|
||||
"order_id": order.id,
|
||||
"order_no": order.order_no,
|
||||
"reason": reason,
|
||||
},
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
return active_lease
|
||||
|
||||
|
||||
def _resolve_gift(
|
||||
db: Session, *, gift_name: str, commodity_id: str, required_points: Any
|
||||
) -> tuple[str, str, int | None]:
|
||||
@@ -649,6 +971,7 @@ def create_order(
|
||||
if order.shop:
|
||||
ensure_shops_registered(db, current, [order.shop])
|
||||
|
||||
_ensure_order_account_lease(db, current, order, force_active=True)
|
||||
db.add(order)
|
||||
db.flush()
|
||||
record_audit(
|
||||
@@ -740,7 +1063,9 @@ def _apply_platform_fulfillment_binding(
|
||||
if task.bind_task_id
|
||||
else None
|
||||
)
|
||||
result = bind_task.result if bind_task and isinstance(bind_task.result, dict) else None
|
||||
result = (
|
||||
bind_task.result if bind_task and isinstance(bind_task.result, dict) else None
|
||||
)
|
||||
role = binding_role_from_result(result)
|
||||
if not role:
|
||||
return
|
||||
@@ -875,6 +1200,12 @@ def sync_platform_fulfillment_order(
|
||||
_apply_platform_fulfillment_status(order, task, created=created)
|
||||
order.version = int(order.version or 0) + 1
|
||||
db.flush()
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_sync_terminal",
|
||||
)
|
||||
|
||||
audit_detail = {
|
||||
"taskId": int(task.id),
|
||||
@@ -982,9 +1313,7 @@ def sync_platform_fulfillment_orders(
|
||||
}
|
||||
)
|
||||
except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障
|
||||
logger.exception(
|
||||
"同步直播履约任务 {} 到斗鱼外部协作失败", task_id
|
||||
)
|
||||
logger.exception("同步直播履约任务 {} 到斗鱼外部协作失败", task_id)
|
||||
result["failed"] += 1
|
||||
result["items"].append(
|
||||
{
|
||||
@@ -1013,6 +1342,7 @@ def update_order(
|
||||
) -> dict[str, Any]:
|
||||
_assert_mutable(order)
|
||||
_assert_version(order, expected_version)
|
||||
previous_account_id = int(order.account_id or 0)
|
||||
changes: dict[str, dict[str, Any]] = {}
|
||||
editable = {
|
||||
"order_no",
|
||||
@@ -1075,8 +1405,18 @@ def update_order(
|
||||
client=client,
|
||||
with_goods=True,
|
||||
)
|
||||
_ensure_order_account_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
account_id=int(account.id),
|
||||
force_active=order.status in COLLAB_LEASE_STATUSES,
|
||||
)
|
||||
apply_probe_snapshot(order, account, probe)
|
||||
changes["account_id"] = {"old": None, "new": int(account.id)}
|
||||
changes["account_id"] = {
|
||||
"old": previous_account_id or None,
|
||||
"new": int(account.id),
|
||||
}
|
||||
changes["bind_game_role"] = {"old": "", "new": order.bind_game_role}
|
||||
if "home_images" in payload:
|
||||
images = normalize_images(payload.get("home_images"))
|
||||
@@ -1107,6 +1447,14 @@ def update_order(
|
||||
detail=changes,
|
||||
)
|
||||
_maybe_advance_to_recharge(db, current, order)
|
||||
if previous_account_id and previous_account_id != int(order.account_id or 0):
|
||||
_release_order_account_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_account_changed",
|
||||
account_id=previous_account_id,
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
@@ -1128,6 +1476,7 @@ def set_account(
|
||||
account = account_by_username(db, username)
|
||||
if account is None:
|
||||
raise CollabError("斗鱼账号不存在", code="account_not_found")
|
||||
previous_account_id = int(order.account_id or 0)
|
||||
config = resolve_config(db)
|
||||
probe = _probe_with_client(
|
||||
account,
|
||||
@@ -1137,6 +1486,13 @@ def set_account(
|
||||
client=client,
|
||||
with_goods=True,
|
||||
)
|
||||
_ensure_order_account_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
account_id=int(account.id),
|
||||
force_active=order.status in COLLAB_LEASE_STATUSES,
|
||||
)
|
||||
apply_probe_snapshot(order, account, probe)
|
||||
order.updated_by = current.id
|
||||
order.version = int(order.version or 0) + 1
|
||||
@@ -1153,6 +1509,14 @@ def set_account(
|
||||
},
|
||||
)
|
||||
_maybe_advance_to_recharge(db, current, order)
|
||||
if previous_account_id and previous_account_id != int(order.account_id or 0):
|
||||
_release_order_account_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_account_changed",
|
||||
account_id=previous_account_id,
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
@@ -1249,6 +1613,8 @@ def _restore_void_status(
|
||||
target_index = STAGE_INDEX.get(target)
|
||||
if target_index is not None and target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]:
|
||||
_assert_ready_for_recharge(order)
|
||||
if target in COLLAB_LEASE_STATUSES:
|
||||
_ensure_order_account_lease(db, current, order, force_active=True)
|
||||
|
||||
old_void_reason = order.void_reason or ""
|
||||
# 取消作废等于重新进入状态机:先清空旧流程时间,再按目标状态补当前时间。
|
||||
@@ -1275,6 +1641,12 @@ def _restore_void_status(
|
||||
"reason": _text(reason, max_length=256),
|
||||
},
|
||||
)
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_void_restored",
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
@@ -1324,6 +1696,12 @@ def set_status(
|
||||
target=_status_audit_target(order),
|
||||
detail={"from": old, "reason": order.void_reason},
|
||||
)
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_void",
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
@@ -1340,6 +1718,12 @@ def set_status(
|
||||
target=_status_audit_target(order),
|
||||
detail={"from": old, "to": target, "reason": _text(reason, max_length=256)},
|
||||
)
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_failed",
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
@@ -1356,6 +1740,12 @@ def set_status(
|
||||
target=_status_audit_target(order),
|
||||
detail={"from": old, "reason": _text(reason, max_length=256)},
|
||||
)
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_points_error",
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
@@ -1399,6 +1789,16 @@ def set_status(
|
||||
"reason": _text(reason, max_length=256),
|
||||
},
|
||||
)
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason=(
|
||||
"douyu_collab_done"
|
||||
if target == STATUS_DONE
|
||||
else "douyu_collab_status_changed"
|
||||
),
|
||||
)
|
||||
if commit:
|
||||
db.commit()
|
||||
db.refresh(order)
|
||||
@@ -2508,6 +2908,12 @@ def archive_orders(
|
||||
target=_status_audit_target(order),
|
||||
detail={"reason": order.archive_reason},
|
||||
)
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_archived",
|
||||
)
|
||||
db.commit()
|
||||
return {"archived": archived}
|
||||
|
||||
@@ -2536,6 +2942,12 @@ def unarchive_orders(db: Session, current: User, ids: list[int]) -> dict[str, An
|
||||
target=_status_audit_target(order),
|
||||
detail={},
|
||||
)
|
||||
_sync_order_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_unarchived",
|
||||
)
|
||||
db.commit()
|
||||
return {"unarchived": unarchived}
|
||||
|
||||
@@ -2544,6 +2956,12 @@ def delete_order(
|
||||
db: Session, current: User, order: DouyuExternalOrder
|
||||
) -> dict[str, Any]:
|
||||
order_no = order.order_no
|
||||
_release_order_account_lease(
|
||||
db,
|
||||
current,
|
||||
order,
|
||||
reason="douyu_collab_deleted",
|
||||
)
|
||||
record_audit(
|
||||
db,
|
||||
current,
|
||||
|
||||
@@ -290,14 +290,45 @@ def lease_account(
|
||||
now: datetime | None = None,
|
||||
) -> AccountLease | None:
|
||||
"""尝试领取一个账号;撞唯一索引时返回 None。"""
|
||||
moment = _now(now)
|
||||
lease = AccountLease(
|
||||
account_id=candidate.account_id,
|
||||
return acquire_account_lease(
|
||||
db,
|
||||
account_id=int(candidate.account_id),
|
||||
holder_user_id=holder_user_id,
|
||||
scope="elite",
|
||||
purpose="platform_fulfillment",
|
||||
commodity_id=commodity_id,
|
||||
batch_id=f"pf:{task_id}",
|
||||
ttl_minutes=ttl_minutes,
|
||||
now=now,
|
||||
)
|
||||
|
||||
|
||||
def acquire_account_lease(
|
||||
db: Session,
|
||||
*,
|
||||
account_id: int,
|
||||
holder_user_id: int,
|
||||
scope: str,
|
||||
purpose: str,
|
||||
commodity_id: str = "",
|
||||
batch_id: str = "",
|
||||
ttl_minutes: int | None = None,
|
||||
now: datetime | None = None,
|
||||
commit: bool = True,
|
||||
) -> AccountLease | None:
|
||||
"""获取账号租约;调用方可在自己的事务内复用。
|
||||
|
||||
唯一索引负责并发互斥。撞到已有活动租约时返回 ``None``,由调用方结合
|
||||
``active_lease_for_account`` 决定是沿用合法占用的租约还是提示冲突。
|
||||
"""
|
||||
moment = _now(now)
|
||||
lease = AccountLease(
|
||||
account_id=int(account_id),
|
||||
holder_user_id=holder_user_id,
|
||||
scope=str(scope or "elite")[:16],
|
||||
purpose=str(purpose or "exchange")[:24],
|
||||
commodity_id=str(commodity_id or "")[:64],
|
||||
batch_id=str(batch_id or "")[:64],
|
||||
status="active",
|
||||
leased_at=moment,
|
||||
expires_at=(
|
||||
@@ -316,30 +347,54 @@ def lease_account(
|
||||
if lease in db:
|
||||
db.expunge(lease)
|
||||
return None
|
||||
event_detail: dict[str, object] = {
|
||||
"lease_id": lease.id,
|
||||
"holder_user_id": holder_user_id,
|
||||
"commodity_id": commodity_id,
|
||||
"purpose": purpose,
|
||||
"batch_id": batch_id,
|
||||
}
|
||||
if purpose == "platform_fulfillment" and batch_id.startswith("pf:"):
|
||||
event_detail["task_id"] = int(batch_id.removeprefix("pf:"))
|
||||
emit(
|
||||
db,
|
||||
account_id=int(candidate.account_id),
|
||||
account_id=int(account_id),
|
||||
event_type=EVENT_LEASE_ACQUIRED,
|
||||
title=f"履约占用:任务 #{task_id}",
|
||||
title=(
|
||||
f"履约占用:任务 #{batch_id.removeprefix('pf:')}"
|
||||
if purpose == "platform_fulfillment"
|
||||
else f"业务占用:{purpose}"
|
||||
),
|
||||
category=CATEGORY_OPS,
|
||||
detail={
|
||||
"lease_id": lease.id,
|
||||
"task_id": task_id,
|
||||
"holder_user_id": holder_user_id,
|
||||
"commodity_id": commodity_id,
|
||||
"purpose": "platform_fulfillment",
|
||||
},
|
||||
occurred_at=moment,
|
||||
detail=event_detail,
|
||||
source="lease",
|
||||
subject_type="task",
|
||||
subject_key=str(task_id),
|
||||
subject_type="task" if purpose == "platform_fulfillment" else "lease",
|
||||
subject_key=batch_id,
|
||||
actor_type="user",
|
||||
actor_id=holder_user_id,
|
||||
source_ref=f"account_lease_acquired:{lease.id}",
|
||||
)
|
||||
db.commit()
|
||||
if commit:
|
||||
db.commit()
|
||||
return lease
|
||||
|
||||
|
||||
def active_lease_for_account(
|
||||
db: Session, account_id: int | None
|
||||
) -> AccountLease | None:
|
||||
if not account_id:
|
||||
return None
|
||||
return (
|
||||
db.query(AccountLease)
|
||||
.filter(
|
||||
AccountLease.account_id == int(account_id),
|
||||
AccountLease.status == "active",
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def renew_lease(
|
||||
db: Session,
|
||||
lease: AccountLease,
|
||||
@@ -364,6 +419,7 @@ def release_lease(
|
||||
*,
|
||||
reason: str,
|
||||
now: datetime | None = None,
|
||||
commit: bool = True,
|
||||
) -> bool:
|
||||
if lease is None or lease.status != "active":
|
||||
return False
|
||||
@@ -387,7 +443,8 @@ def release_lease(
|
||||
actor_type="system",
|
||||
source_ref=f"account_lease_released:{lease.id}",
|
||||
)
|
||||
db.commit()
|
||||
if commit:
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
@@ -442,6 +499,8 @@ __all__ = [
|
||||
"EXCHANGE_COOLDOWN_DAYS",
|
||||
"VALIDATION_LEASE_MINUTES",
|
||||
"AccountCandidate",
|
||||
"acquire_account_lease",
|
||||
"active_lease_for_account",
|
||||
"capability_candidate_accounts",
|
||||
"eligible_accounts",
|
||||
"expire_platform_fulfillment_leases",
|
||||
|
||||
@@ -82,6 +82,7 @@ def _matching_mode() -> str:
|
||||
mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower()
|
||||
return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid"
|
||||
|
||||
|
||||
_SYNC_LOCK = Lock()
|
||||
_AUTO_SYNC_LOCK = Lock()
|
||||
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
|
||||
@@ -150,7 +151,9 @@ def _upsert_order_snapshot(
|
||||
) -> tuple[PlatformFulfillmentTask | None, bool, bool]:
|
||||
"""应用一条订单项快照,返回 (task, created, ignored)。"""
|
||||
item_id = str(
|
||||
_snapshot_value(snapshot, "sourceOrderItemId", "source_order_item_id", default="")
|
||||
_snapshot_value(
|
||||
snapshot, "sourceOrderItemId", "source_order_item_id", default=""
|
||||
)
|
||||
).strip()
|
||||
if not item_id:
|
||||
return None, False, True
|
||||
@@ -177,11 +180,7 @@ def _upsert_order_snapshot(
|
||||
return None, False, True
|
||||
cutoff = _order_match_started_at(db)
|
||||
match_basis_at = paid_at or order_created_at
|
||||
if (
|
||||
match_basis_at is not None
|
||||
and cutoff is not None
|
||||
and match_basis_at < cutoff
|
||||
):
|
||||
if match_basis_at is not None and cutoff is not None and match_basis_at < cutoff:
|
||||
return None, False, True
|
||||
|
||||
task = (
|
||||
@@ -303,21 +302,11 @@ def _upsert_order_snapshot(
|
||||
default=task.source_fulfillment_id,
|
||||
)
|
||||
)
|
||||
task.provider = str(
|
||||
_snapshot_value(snapshot, "provider", default=task.provider)
|
||||
)
|
||||
task.shop_id = str(
|
||||
_snapshot_value(snapshot, "shopId", "shop_id", default="")
|
||||
)
|
||||
task.shop_name = str(
|
||||
_snapshot_value(snapshot, "shopName", "shop_name", default="")
|
||||
)
|
||||
task.sku_code = str(
|
||||
_snapshot_value(snapshot, "skuCode", "sku_code", default="")
|
||||
)
|
||||
task.sku_name = str(
|
||||
_snapshot_value(snapshot, "skuName", "sku_name", default="")
|
||||
)
|
||||
task.provider = str(_snapshot_value(snapshot, "provider", default=task.provider))
|
||||
task.shop_id = str(_snapshot_value(snapshot, "shopId", "shop_id", default=""))
|
||||
task.shop_name = str(_snapshot_value(snapshot, "shopName", "shop_name", default=""))
|
||||
task.sku_code = str(_snapshot_value(snapshot, "skuCode", "sku_code", default=""))
|
||||
task.sku_name = str(_snapshot_value(snapshot, "skuName", "sku_name", default=""))
|
||||
task.internal_sku_key = str(
|
||||
_snapshot_value(
|
||||
snapshot,
|
||||
@@ -453,7 +442,9 @@ def sync_order_item_ids(
|
||||
updated = 0
|
||||
ignored = 0
|
||||
task_ids: list[int] = []
|
||||
for item_id in dict.fromkeys(str(item or "").strip() for item in source_order_item_ids):
|
||||
for item_id in dict.fromkeys(
|
||||
str(item or "").strip() for item in source_order_item_ids
|
||||
):
|
||||
if not item_id:
|
||||
ignored += 1
|
||||
continue
|
||||
@@ -461,7 +452,9 @@ def sync_order_item_ids(
|
||||
if snapshot is None:
|
||||
ignored += 1
|
||||
continue
|
||||
mapping = mapping_by_sku.get(str(snapshot.get("internal_sku_key") or "").strip())
|
||||
mapping = mapping_by_sku.get(
|
||||
str(snapshot.get("internal_sku_key") or "").strip()
|
||||
)
|
||||
task, was_created, was_ignored = _upsert_order_snapshot(
|
||||
db,
|
||||
snapshot,
|
||||
@@ -765,6 +758,31 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
|
||||
return task
|
||||
|
||||
|
||||
def _retain_lease_for_active_collab(
|
||||
db: Session,
|
||||
*,
|
||||
task: PlatformFulfillmentTask,
|
||||
lease: AccountLease | None,
|
||||
current: User,
|
||||
reason: str,
|
||||
) -> AccountLease | None:
|
||||
"""平台释放账号前,把仍在活动的协作单占用接续到同一租约。"""
|
||||
if lease is None or not task.account_id:
|
||||
return None
|
||||
from ..douyu_collab_service import retain_lease_for_active_collab
|
||||
|
||||
return retain_lease_for_active_collab(
|
||||
db,
|
||||
account_id=int(task.account_id),
|
||||
holder_user_id=int(current.id),
|
||||
current=current,
|
||||
lease=lease,
|
||||
source_task_id=int(task.id),
|
||||
reason=reason,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
|
||||
def _apply_mapping(
|
||||
task: PlatformFulfillmentTask,
|
||||
mapping: PlatformCommodityMapping | None,
|
||||
@@ -892,10 +910,10 @@ def _sync_pending_tasks(
|
||||
task.scope = SCOPE_ELITE
|
||||
task.source_snapshot_json = _jsonable(row)
|
||||
task.updated_at = _now()
|
||||
if (
|
||||
task.account_id is None
|
||||
and task.execution_status in {"pending_mapping", "ready"}
|
||||
):
|
||||
if task.account_id is None and task.execution_status in {
|
||||
"pending_mapping",
|
||||
"ready",
|
||||
}:
|
||||
_apply_mapping(task, mapping)
|
||||
if task.execution_status == "ready" and task.account_id is None:
|
||||
task.next_allocate_at = _now()
|
||||
@@ -1135,13 +1153,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
||||
actor_ids = {
|
||||
int(event.actor_id)
|
||||
for event in events
|
||||
if event.actor_type == "user"
|
||||
and str(event.actor_id or "").isdigit()
|
||||
if event.actor_type == "user" and str(event.actor_id or "").isdigit()
|
||||
}
|
||||
actors = {
|
||||
int(user.id): user
|
||||
for user in db.query(User).filter(User.id.in_(actor_ids)).all()
|
||||
} if actor_ids else {}
|
||||
actors = (
|
||||
{
|
||||
int(user.id): user
|
||||
for user in db.query(User).filter(User.id.in_(actor_ids)).all()
|
||||
}
|
||||
if actor_ids
|
||||
else {}
|
||||
)
|
||||
return {
|
||||
"task": _task_out(db, task, include_qr=True),
|
||||
"events": [
|
||||
@@ -1154,19 +1175,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
||||
actors[int(event.actor_id)].deleted_username
|
||||
or actors[int(event.actor_id)].username
|
||||
)
|
||||
if str(event.actor_id or "").isdigit()
|
||||
and int(event.actor_id) in actors
|
||||
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
|
||||
else "",
|
||||
"actorRole": actors[int(event.actor_id)].role
|
||||
if str(event.actor_id or "").isdigit()
|
||||
and int(event.actor_id) in actors
|
||||
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
|
||||
else "",
|
||||
"actorRoleLabel": ROLE_LABELS.get(
|
||||
actors[int(event.actor_id)].role,
|
||||
actors[int(event.actor_id)].role,
|
||||
)
|
||||
if str(event.actor_id or "").isdigit()
|
||||
and int(event.actor_id) in actors
|
||||
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
|
||||
else "",
|
||||
"detail": event.detail_json or {},
|
||||
"createdAt": event.created_at,
|
||||
@@ -1542,9 +1560,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
|
||||
availability=(
|
||||
AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE
|
||||
),
|
||||
blocking_reason=(
|
||||
"该账号已达此商品兑换上限" if limited else ""
|
||||
),
|
||||
blocking_reason=("该账号已达此商品兑换上限" if limited else ""),
|
||||
raw_status="1" if limited else "0",
|
||||
observed_at=live_state.checked_at,
|
||||
source="live_check",
|
||||
@@ -1742,7 +1758,15 @@ def release_task_account(
|
||||
if task.lease_id
|
||||
else None
|
||||
)
|
||||
release_lease(db, lease, reason=reason)
|
||||
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
|
||||
@@ -2057,7 +2081,7 @@ def reconcile_binding_state_outbox(
|
||||
PlatformFulfillmentTask.id > normalized_after,
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
["completed", "cancelled"]
|
||||
)
|
||||
),
|
||||
)
|
||||
.order_by(PlatformFulfillmentTask.id.asc())
|
||||
.limit(batch_size)
|
||||
@@ -2297,7 +2321,20 @@ def complete_manual_exchange(
|
||||
task.last_error = ""
|
||||
task.issue_code = ""
|
||||
task.updated_at = _now()
|
||||
release_lease(db, lease, reason="manual_exchange_completed")
|
||||
retained = _retain_lease_for_active_collab(
|
||||
db,
|
||||
task=task,
|
||||
lease=lease,
|
||||
current=current,
|
||||
reason="platform_completed_but_collab_active",
|
||||
)
|
||||
if retained is None:
|
||||
release_lease(
|
||||
db,
|
||||
lease,
|
||||
reason="manual_exchange_completed",
|
||||
commit=False,
|
||||
)
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
@@ -2378,7 +2415,20 @@ def cancel_task(
|
||||
linked_task.status = "stopped"
|
||||
linked_task.message = "履约任务已取消"
|
||||
linked_task.finished_at = _now()
|
||||
release_lease(db, lease, reason="platform_fulfillment_cancelled")
|
||||
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
|
||||
@@ -2455,7 +2505,9 @@ def restore_cancelled_task(
|
||||
or str(source.get("fulfillment_issue_code") or "")
|
||||
in {"user_refund", "platform_cancelled"}
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="来源订单已退款、关闭或取消,不能恢复")
|
||||
raise HTTPException(
|
||||
status_code=409, detail="来源订单已退款、关闭或取消,不能恢复"
|
||||
)
|
||||
|
||||
restore_reason = reason.strip()
|
||||
if len(restore_reason) < 2:
|
||||
@@ -2537,7 +2589,20 @@ def release_task_to_manual(
|
||||
if task.lease_id
|
||||
else None
|
||||
)
|
||||
release_lease(db, lease, reason="platform_fulfillment_manual")
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user