From 02ddb48f2181f31ffd33ccaf2dd140850a00d0f5 Mon Sep 17 00:00:00 2001 From: kyx236 Date: Sat, 7 Feb 2026 02:52:06 +0800 Subject: [PATCH] fix(database): Recalculate batch run metrics from team results on cleanup - Aggregate total_registered and total_added_to_s2a from batch_team_results table - Calculate success_rate based on actual S2A additions vs total owners - Compute duration_seconds from started_at and finished_at timestamps - Improve stuck batch run recovery by restoring accurate metrics instead of zeroing them out --- backend/internal/database/sqlite.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/backend/internal/database/sqlite.go b/backend/internal/database/sqlite.go index 03cd12c..25832f1 100644 --- a/backend/internal/database/sqlite.go +++ b/backend/internal/database/sqlite.go @@ -612,13 +612,28 @@ func (d *DB) GetBatchRuns(limit int) ([]BatchRun, error) { return runs, nil } -// CleanupStuckBatchRuns 清理卡住的 running 状态批次记录 +// CleanupStuckBatchRuns 清理卡住的 running 状态批次记录,从子结果重新计算汇总 func (d *DB) CleanupStuckBatchRuns() (int64, error) { + // 先从 batch_team_results 重新汇总数据,再标记为 completed result, err := d.db.Exec(` UPDATE batch_runs SET status = 'completed', finished_at = COALESCE(finished_at, started_at), - duration_seconds = 0 + total_registered = COALESCE(( + SELECT SUM(registered) FROM batch_team_results WHERE batch_id = batch_runs.id + ), 0), + total_added_to_s2a = COALESCE(( + SELECT SUM(added_to_s2a) FROM batch_team_results WHERE batch_id = batch_runs.id + ), 0), + success_rate = CASE + WHEN total_owners > 0 THEN + COALESCE((SELECT SUM(added_to_s2a) FROM batch_team_results WHERE batch_id = batch_runs.id), 0) * 100.0 / (total_owners * 4) + ELSE 0 + END, + duration_seconds = CASE + WHEN finished_at IS NOT NULL THEN CAST((julianday(finished_at) - julianday(started_at)) * 86400 AS INTEGER) + ELSE 0 + END WHERE status = 'running' `) if err != nil {