fix: 班级学生搜索与平均得分一致性问题

- 前端: 搜索改为调用接口查询,移除 Math.random() 模拟数据
- 前端: 修复搜索图标点击、清空后重新请求
- 后端: StudentResponse 新增 readingCount/lessonCount/avgScore
- 后端: StudentRecordMapper 添加批量统计学生阅读与得分
- 后端: getClassStudents 返回真实统计数据

Made-with: Cursor
This commit is contained in:
zhonghua 2026-03-24 11:22:11 +08:00
parent c2d194b45d
commit 5cc99d232a
4 changed files with 73 additions and 17 deletions

View File

@ -51,12 +51,13 @@
placeholder="搜索学生"
style="width: 200px;"
allow-clear
@search="handleSearch"
/>
</div>
<a-table
:columns="columns"
:data-source="filteredStudents"
:data-source="students"
:pagination="{ pageSize: 10 }"
row-key="id"
@row="handleRowClick"
@ -86,7 +87,7 @@
/>
</template>
<template v-else-if="column.key === 'action'">
<a-button type="link" size="small" @click.stop="showStudentDetail(record)">
<a-button type="link" size="small" @click.stop="handleShowDetail(record)">
查看详情
</a-button>
</template>
@ -167,7 +168,7 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import {
@ -176,8 +177,8 @@ import {
BookOutlined,
ReadOutlined,
} from '@ant-design/icons-vue';
import { getTeacherClassStudents, getStudentRecords } from '@/api/teacher';
import type { Student } from '@/api/school';
import { getTeacherClassStudents } from '@/api/teacher';
import type { Student, ClassInfo } from '@/api/school';
import dayjs from 'dayjs';
const router = useRouter();
@ -203,12 +204,6 @@ const columns = [
{ title: '操作', key: 'action', width: 100 },
];
const filteredStudents = computed(() => {
if (!searchKeyword.value) return students.value;
const keyword = searchKeyword.value.toLowerCase();
return students.value.filter(s => s.name.toLowerCase().includes(keyword));
});
const totalReadingCount = computed(() => {
return students.value.reduce((sum, s) => sum + (s.readingCount || 0), 0);
});
@ -224,9 +219,11 @@ const getScoreColor = (score: number) => {
const goBack = () => router.back();
const handleRowClick = (record: Student) => {
showStudentDetail(record);
};
const handleRowClick = (record: Record<string, unknown>, _index: number) => ({
onClick: () => showStudentDetail(record as unknown as Student),
});
const handleShowDetail = (record: unknown) => showStudentDetail(record as unknown as Student);
const showStudentDetail = async (student: Student) => {
selectedStudent.value = student;
@ -241,10 +238,12 @@ const showStudentDetail = async (student: Student) => {
}
};
const loadStudents = async () => {
const loadStudents = async (params?: { keyword?: string }) => {
loading.value = true;
try {
const data = await getTeacherClassStudents(classId.value);
const data = await getTeacherClassStudents(classId.value, {
keyword: params?.keyword,
});
classInfo.value = data.class ? {
id: data.class.id,
name: data.class.name,
@ -254,7 +253,8 @@ const loadStudents = async () => {
} as any : null;
students.value = data.items.map((s: any) => ({
...s,
avgScore: Math.round(Math.random() * 40 + 60), //
// 使 avgScore 0
avgScore: s.avgScore ?? 0,
}));
} catch (error: any) {
message.error(error.message || '加载失败');
@ -263,6 +263,17 @@ const loadStudents = async () => {
}
};
const handleSearch = (value?: string) => {
const keyword = (value ?? searchKeyword.value)?.trim() || undefined;
loadStudents({ keyword });
};
watch(searchKeyword, (newVal, oldVal) => {
if (newVal === '' && oldVal !== undefined && oldVal !== '') {
loadStudents();
}
});
onMounted(() => {
loadStudents();
});

View File

@ -27,6 +27,7 @@ import com.reading.platform.entity.CourseLesson;
import com.reading.platform.mapper.LessonMapper;
import com.reading.platform.mapper.ParentMapper;
import com.reading.platform.mapper.ParentStudentMapper;
import com.reading.platform.mapper.StudentRecordMapper;
import com.reading.platform.service.ClassService;
import com.reading.platform.service.CourseLessonService;
import com.reading.platform.service.CoursePackageService;
@ -60,6 +61,7 @@ public class TeacherCourseController {
private final LessonMapper lessonMapper;
private final ParentMapper parentMapper;
private final ParentStudentMapper parentStudentMapper;
private final StudentRecordMapper studentRecordMapper;
@Operation(summary = "获取教师的班级列表")
@GetMapping("/classes")
@ -188,6 +190,13 @@ public class TeacherCourseController {
Clazz clazz = classService.getClassByIdWithTenantCheck(id, tenantId);
Page<Student> page = studentService.getStudentsByClassId(id, pageNum, pageSize, keyword);
List<StudentResponse> voList = studentMapper.toVO(page.getRecords());
List<Long> studentIds = voList.stream().map(StudentResponse::getId).toList();
List<Map<String, Object>> statsList = studentIds.isEmpty()
? List.of()
: studentRecordMapper.selectStudentStats(studentIds);
Map<Long, Map<String, Object>> statsMap = statsList.stream()
.collect(Collectors.toMap(m -> ((Number) m.get("studentId")).longValue(), m -> m));
for (StudentResponse vo : voList) {
var parentRelation = parentStudentMapper.selectOne(
new LambdaQueryWrapper<ParentStudent>()
@ -201,6 +210,16 @@ public class TeacherCourseController {
vo.setParentPhone(parent.getPhone());
}
}
var stats = statsMap.get(vo.getId());
if (stats != null) {
vo.setReadingCount(((Number) stats.getOrDefault("readingCount", 0)).intValue());
vo.setLessonCount(vo.getReadingCount());
vo.setAvgScore(((Number) stats.getOrDefault("avgScore", 0)).intValue());
} else {
vo.setReadingCount(0);
vo.setLessonCount(0);
vo.setAvgScore(0);
}
}
int studentCount = studentService.getStudentListByClassId(id).size();

View File

@ -66,4 +66,13 @@ public class StudentResponse {
@Schema(description = "家长电话")
private String parentPhone;
@Schema(description = "阅读/上课次数student_record 条数)")
private Integer readingCount;
@Schema(description = "上课次数(同 readingCount")
private Integer lessonCount;
@Schema(description = "平均得分(专注度+参与度平均后 1-5 转 0-100 百分比)")
private Integer avgScore;
}

View File

@ -7,10 +7,27 @@ import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
@Mapper
public interface StudentRecordMapper extends BaseMapper<StudentRecord> {
/**
* 按学生 ID 批量统计阅读次数平均得分专注度+参与度 1-5 0-100
*/
@Select("<script>" +
"SELECT sr.student_id AS studentId, " +
" COUNT(sr.id) AS readingCount, " +
" ROUND(COALESCE(AVG((COALESCE(sr.focus,0)+COALESCE(sr.participation,0))/2.0), 0) * 20) AS avgScore " +
"FROM student_record sr " +
"INNER JOIN lesson l ON sr.lesson_id = l.id AND l.status = 'COMPLETED' AND l.deleted = 0 " +
"WHERE sr.deleted = 0 AND sr.student_id IN " +
"<foreach collection='studentIds' item='id' open='(' separator=',' close=')'>#{id}</foreach> " +
"GROUP BY sr.student_id" +
"</script>")
List<Map<String, Object>> selectStudentStats(@Param("studentIds") List<Long> studentIds);
/**
* 统计指定时间段内有上课记录的去重学生数
* @param startTime 开始时间