package httpapi_test import ( "fmt" "net/http" "testing" ) // changeLogCount 统计某实体某动作的变更记录数。 func changeLogCount(t *testing.T, env *testEnv, entity, action string) int { t.Helper() var n int if err := env.ev.QueryRow(`SELECT COUNT(*) FROM change_log WHERE entity_type = ? AND action = ?`, entity, action).Scan(&n); err != nil { t.Fatalf("统计 change_log: %v", err) } return n } // 配置写操作必须写 change_log,否则 broadcastChanges 推空、大屏不刷新; // 同时校验数值范围,浏览器 min/max 只是提示,不能当服务端校验。 func TestSettingsPatchValidationAndChangeLog(t *testing.T) { env := newTestEnv(t) env.createUser("admin", "admin-pass", "admin") client, _ := env.client() env.login(client, "admin", "admin-pass") for _, tc := range []struct { name string body map[string]any }{ {"轮播间隔过小", map[string]any{"display": map[string]any{"rotateSeconds": 1}}}, {"轮播间隔过大", map[string]any{"display": map[string]any{"rotateSeconds": 121}}}, {"折算系数为 0", map[string]any{"standings": map[string]any{"individualToTeamWeight": 0}}}, {"折算系数为负", map[string]any{"standings": map[string]any{"individualToTeamWeight": -1}}}, } { status, env2 := env.do(client, http.MethodPut, "/api/settings", tc.body, true) if status != http.StatusBadRequest || env2.Error == nil || env2.Error.Code != "VALIDATION_FAILED" { t.Fatalf("%s应 400 VALIDATION_FAILED,得到 %d %+v", tc.name, status, env2.Error) } } before := changeLogCount(t, env, "settings", "upsert") status, env2 := env.do(client, http.MethodPut, "/api/settings", map[string]any{ "event": map[string]any{"name": "秋季运动会", "subtitle": ""}, "display": map[string]any{"rotateSeconds": 30}, "standings": map[string]any{"individualToTeamWeight": 0.5}, }, true) if status != http.StatusOK || !env2.OK { t.Fatalf("合法配置应 200,得到 %d %+v", status, env2.Error) } if got := changeLogCount(t, env, "settings", "upsert"); got != before+1 { t.Fatalf("配置写操作应新增 1 条 settings change_log,得到 %d → %d", before, got) } _, env2 = env.do(client, http.MethodGet, "/api/settings", nil, false) settings := decodeData[map[string]any](t, env2) event := settings["event"].(map[string]any) if event["name"] != "秋季运动会" || event["subtitle"] != nil { t.Fatalf("空串应归一为 null、名称应落库: %+v", event) } display := settings["display"].(map[string]any) if display["rotateSeconds"].(float64) != 30 { t.Fatalf("轮播间隔应落库为 30: %+v", display) } } // 破纪录登记必须基于该项目一条已发布且状态正常的成绩,否则 recorder 可凭空加分。 func TestRecordBreakRequiresPublishedResult(t *testing.T) { env := newTestEnv(t) ids := env.seed(t) env.createUser("recorder", "recorder-pass", "recorder") client, _ := env.client() env.login(client, "recorder", "recorder-pass") body := map[string]any{"eventId": ids.event, "entryId": ids.entryA, "level": "meet", "resultValue": 10.5, "resultText": "10.50"} // 没有成绩。 status, env2 := env.do(client, http.MethodPost, "/api/record-breaks", body, true) if status != http.StatusBadRequest { t.Fatalf("无成绩时登记破纪录应 400,得到 %d %+v", status, env2.Error) } // 只有草稿成绩。 env.exec(t, `INSERT INTO results (event_id, entry_id, rank, result_value, status, state) VALUES (?, ?, 1, 10.5, 'ok', 'draft')`, ids.event, ids.entryA) status, env2 = env.do(client, http.MethodPost, "/api/record-breaks", body, true) if status != http.StatusBadRequest { t.Fatalf("草稿成绩登记破纪录应 400,得到 %d %+v", status, env2.Error) } // 已发布但小项不可破纪录。 env.exec(t, `UPDATE results SET state = 'published' WHERE entry_id = ?`, ids.entryA) env.exec(t, `UPDATE events SET record_eligible = 0 WHERE id = ?`, ids.event) status, env2 = env.do(client, http.MethodPost, "/api/record-breaks", body, true) if status != http.StatusBadRequest { t.Fatalf("不可破纪录项目应 400,得到 %d %+v", status, env2.Error) } // 报名项不属于该项目。 env.exec(t, `UPDATE events SET record_eligible = 1 WHERE id = ?`, ids.event) otherEvent := env.insert(t, `INSERT INTO events (sport_id, code, name, event_type, result_mode, result_type, compare, scored, multiplier, status) VALUES (?, 'M200', '200米跑', 'individual', 'auto', 'time', 'asc', 1, 1, 'ongoing')`, ids.sport) status, env2 = env.do(client, http.MethodPost, "/api/record-breaks", map[string]any{"eventId": otherEvent, "entryId": ids.entryA, "level": "meet", "resultValue": 10.5, "resultText": "10.50"}, true) if status != http.StatusBadRequest { t.Fatalf("跨项目登记破纪录应 400,得到 %d %+v", status, env2.Error) } // 合法:已发布成绩 + 可破纪录项目。 status, env2 = env.do(client, http.MethodPost, "/api/record-breaks", body, true) if status != http.StatusOK || !env2.OK { t.Fatalf("合法登记应 200,得到 %d %+v", status, env2.Error) } } // 单位积分明细的合计必须与总积分榜同口径:个人流水乘折算系数。 func TestTeamBreakdownAppliesIndividualWeight(t *testing.T) { env := newTestEnv(t) ids := env.seed(t) env.createUser("recorder", "recorder-pass", "recorder") client, _ := env.client() env.login(client, "recorder", "recorder-pass") env.do(client, http.MethodPut, "/api/results/draft", map[string]any{ "eventId": ids.event, "results": []map[string]any{ {"entryId": ids.entryA, "resultValue": 11.58, "unit": "s", "status": "ok"}, {"entryId": ids.entryB, "resultValue": 11.92, "unit": "s", "status": "ok"}, }, }, true) if status, env2 := env.do(client, http.MethodPost, "/api/results/publish", map[string]any{ "eventId": ids.event, }, true); status != http.StatusOK { t.Fatalf("发布应 200,得到 %d %+v", status, env2.Error) } env.exec(t, `UPDATE settings SET value = '0.5' WHERE key = 'standings.individual_to_team_weight'`) status, env2 := env.do(client, http.MethodGet, fmt.Sprintf("/api/standings/teams/%d/breakdown", ids.teamA), nil, false) if status != http.StatusOK || !env2.OK { t.Fatalf("读积分明细应 200,得到 %d %+v", status, env2.Error) } breakdown := decodeData[map[string]any](t, env2) if got := breakdown["totalPoints"].(float64); got != 5 { t.Fatalf("合计应按系数折算为 5,得到 %v", got) } items := breakdown["items"].([]any) if len(items) != 1 || items[0].(map[string]any)["points"].(float64) != 5 { t.Fatalf("明细行也应按系数折算: %+v", items) } // 与总积分榜一致。 _, env2 = env.do(client, http.MethodGet, "/api/standings", nil, false) for _, row := range decodeData[[]map[string]any](t, env2) { if row["teamCode"] == "A" && row["totalPoints"].(float64) != 5 { t.Fatalf("总积分榜与明细合计应一致: %+v", row) } } } // standings.tie_break 必须真正参与排序,否则换规则包后名次仍走硬编码默认序。 func TestStandingsTieBreakFromSettings(t *testing.T) { env := newTestEnv(t) ids := env.seed(t) env.createUser("recorder", "recorder-pass", "recorder") client, _ := env.client() env.login(client, "recorder", "recorder-pass") // 让单位编码顺序与名称顺序相反,且两队同分同奖牌。 env.exec(t, `UPDATE teams SET name = 'zzz' WHERE id = ?`, ids.teamA) env.exec(t, `UPDATE teams SET name = 'aaa' WHERE id = ?`, ids.teamB) env.do(client, http.MethodPut, "/api/results/draft", map[string]any{ "eventId": ids.event, "results": []map[string]any{ {"entryId": ids.entryA, "resultValue": 11.58, "unit": "s", "status": "ok"}, {"entryId": ids.entryB, "resultValue": 11.58, "unit": "s", "status": "ok"}, }, }, true) if status, env2 := env.do(client, http.MethodPost, "/api/results/publish", map[string]any{ "eventId": ids.event, }, true); status != http.StatusOK { t.Fatalf("发布应 200,得到 %d %+v", status, env2.Error) } first := func() string { t.Helper() _, env2 := env.do(client, http.MethodGet, "/api/standings", nil, false) rows := decodeData[[]map[string]any](t, env2) if len(rows) != 2 { t.Fatalf("应返回 2 个单位,得到 %d", len(rows)) } return rows[0]["teamCode"].(string) } if got := first(); got != "A" { t.Fatalf("默认按单位编码排序应 A 在前,得到 %s", got) } env.exec(t, `INSERT INTO settings (key, value, updated_at) VALUES ('standings.tie_break', 'points,name', datetime('now')) ON CONFLICT(key) DO UPDATE SET value = excluded.value`) if got := first(); got != "B" { t.Fatalf("配置 standings.tie_break=points,name 后应按名称排序(aaa 在前),得到 %s", got) } }