修正失败的任务总积分同步

This commit is contained in:
2026-06-03 17:45:34 +08:00
parent 846eaa0eb0
commit 71dbf01fc8
3 changed files with 54 additions and 9 deletions
+2 -2
View File
@@ -758,13 +758,13 @@ async def list_credit_ratios_grouped(
):
result = await db.execute(select(CreditRatio))
ratios = result.scalars().all()
grouped = {}
for ratio in ratios:
if ratio.gen_type not in grouped:
grouped[ratio.gen_type] = []
grouped[ratio.gen_type].append(CreditRatioOut.model_validate(ratio))
return grouped
+42 -4
View File
@@ -125,6 +125,11 @@ async def list_records(
description="每页返回的生成记录数量,范围 1~100",
examples=[10],
),
record_ids: list[str] | None = Query(
None,
description="对应记录ID数组",
examples=[["0019e8c55ddd1429b86", "0019e8c54dfc1e13262"]],
),
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
@@ -155,6 +160,9 @@ async def list_records(
if status:
conditions.append(GenerationRecord.status == status)
if record_ids:
conditions.append(GenerationRecord.id.in_(record_ids))
total_result = await db.execute(
select(func.count(GenerationRecord.id))
.join(Project, GenerationRecord.project_id == Project.id)
@@ -291,10 +299,40 @@ async def optimize(
db, token_usage["input_tokens"], token_usage["output_tokens"],
)
await deduct_credits(
db, current_user.id, text_credits,
f"提示词优化 - {project.name}",
)
failed_record_id = record.id
failed_user_id = current_user.id
try:
await deduct_credits(
db, current_user.id, text_credits,
f"提示词优化 - {project.name}",
)
except InsufficientCreditsError as e:
# /optimize 阶段只处理提示词优化扣费。
# 提示词积分不足时,之前已落库的 optimizing 记录必须改为 failed,避免前端长期显示生成中。
# 此阶段没有媒体生成扣费,不调用生成失败退款逻辑。
await db.rollback()
result = await db.execute(
select(GenerationRecord)
.where(
GenerationRecord.id == failed_record_id,
GenerationRecord.user_id == failed_user_id,
GenerationRecord.deleted_at.is_(None),
)
.with_for_update()
.limit(1)
)
failed_record = result.scalar_one_or_none()
if failed_record:
failed_record.status = "failed"
failed_record.error_message = e.detail
failed_record.optimized_prompt = None
failed_record.text_credits_cost = 0
failed_record.credits_cost = 0
failed_record.text_tokens_used = token_usage.get("total_tokens", 0)
await db.flush()
# 这里必须主动提交,否则后续抛出 402 后 get_db 会 rollbackfailed 状态会被回滚。
await db.commit()
raise e
record.optimized_prompt = optimized
record.status = "prompt_optimized"