This commit is contained in:
zlwu committed 2026-06-26 15:30:27 +08:00
commit 1155a976b9
49 files changed
+3227 -424

No files matched your search

@@ -0,0 +1,94 @@
import request from '@/utils/request';
import { AxiosPromise } from 'axios';
import { TableDataInfo } from '@/api/types';
export interface ClassTeacherClassInfo {
classId: string | number;
className: string;
classCode?: string;
collegeName?: string;
majorName?: string;
}
export interface ClassTeacherDormQuery {
beginDate?: string;
endDate?: string;
studentNo?: string;
studentName?: string;
rollCallStatus?: string;
pageNum?: number;
pageSize?: number;
}
export interface ClassTeacherDormViolationVO {
id: string | number;
dataSource: string;
dataSourceName: string;
studentNo: string;
studentName: string;
className: string;
buildingName: string;
roomName: string;
violationTypeName: string;
scoreDeduction?: number;
violationLevel?: string;
violationDate: string;
violationReason?: string;
status?: string;
createTime?: string;
}
export interface ClassTeacherDormRollCallVO {
id: string | number;
studentNo: string;
studentName: string;
className: string;
batchNo: string;
checkDate: string;
checkerName: string;
buildingName: string;
roomName: string;
bedCode: string;
rollCallStatus: string;
leaveTypeName?: string;
remark?: string;
}
/** 校验业务 code(GET 请求失败时拦截器不会 reject,需手动检查) */
function unwrapResponse<T = any>(res: any, action: string): T {
const code = res?.code;
if (code !== undefined && code !== null && code !== 200 && code !== 0) {
throw new Error(res?.msg || `${action}失败`);
}
return res as T;
}
/** 当前班主任班级信息 */
export const getMyClassInfo = (): AxiosPromise<ClassTeacherClassInfo> => {
return request({
url: '/classTeacherDorm/classTeacherDorm/myClass',
method: 'get'
}).then((res) => unwrapResponse(res, '获取班级信息'));
};
/** 本班宿舍违纪列表 */
export const listClassTeacherViolations = (
query?: ClassTeacherDormQuery
): AxiosPromise<TableDataInfo<ClassTeacherDormViolationVO[]>> => {
return request({
url: '/classTeacherDorm/classTeacherDorm/violation/list',
method: 'get',
params: query
}).then((res) => unwrapResponse(res, '查询宿舍违纪'));
};
/** 本班宿舍点名列表 */
export const listClassTeacherRollCalls = (
query?: ClassTeacherDormQuery
): AxiosPromise<TableDataInfo<ClassTeacherDormRollCallVO[]>> => {
return request({
url: '/classTeacherDorm/classTeacherDorm/rollCall/list',
method: 'get',
params: query
}).then((res) => unwrapResponse(res, '查询宿舍点名'));
};
@@ -142,6 +142,17 @@ export const getStudentScoresByCheckId = (hygieneCheckId: string | number): Axio
});
};
/**
* 根据卫生检查ID查询违纪记录列表
* @param hygieneCheckId 卫生检查ID
*/
export const getViolationsByCheckId = (hygieneCheckId: string | number) => {
return request({
url: '/dormHygieneCheck/dormHygieneCheck/getViolations/' + hygieneCheckId,
method: 'get'
});
};
/**
* 批量删除指定卫生检查的学生评分记录
* @param hygieneCheckId 卫生检查ID
@@ -113,6 +113,32 @@ export interface DormHygieneCheckVO {
* 检查备注
*/
checkRemarks: string;
/**
* 违纪类型ID(兼容旧数据,展示用)
*/
disciplineTypeId?: string | number;
/**
* 违纪类型名称(多项以、拼接)
*/
disciplineTypeName?: string;
/**
* 扣分明细
*/
deductionItems?: HygieneDeductionItem[];
}
export interface HygieneDeductionItem {
id?: string | number;
disciplineTypeId: string | number;
disciplineTypeName?: string;
score?: number;
minScore?: number;
maxScore?: number;
sortOrder?: number;
remark?: string;
}
export interface DormHygieneCheckForm extends BaseEntity {
@@ -230,6 +256,21 @@ export interface DormHygieneCheckForm extends BaseEntity {
* 检查备注
*/
checkRemarks?: string;
/**
* 违纪类型ID(兼容)
*/
disciplineTypeId?: string | number;
/**
* 违纪类型名称(兼容)
*/
disciplineTypeName?: string;
/**
* 扣分明细
*/
deductionItems?: HygieneDeductionItem[];
}
export interface DormHygieneCheckQuery extends PageQuery {
@@ -639,4 +680,9 @@ export interface DormHygieneCheckCompleteForm extends DormHygieneCheckForm {
* 学生评分数据列表
*/
studentScores?: DormHygieneStudentScoreForm[];
/**
* 扣分明细
*/
deductionItems?: HygieneDeductionItem[];
}
@@ -0,0 +1,401 @@
<template>
<div class="p-2 page-container">
<el-card shadow="hover" class="mb-[10px]" v-loading="classLoading">
<div v-if="classInfo" class="class-info-bar">
<span class="class-info-label">所带班级:</span>
<el-tag type="primary" size="large">{{ classInfo.className }}</el-tag>
<span v-if="classInfo.collegeName" class="class-info-extra">{{ classInfo.collegeName }}</span>
<span v-if="classInfo.majorName" class="class-info-extra">{{ classInfo.majorName }}</span>
<span class="class-info-tip">(仅显示本班学生数据,按学生当前所在班级过滤)</span>
</div>
<el-alert
v-else-if="classLoadError"
type="error"
:closable="false"
show-icon
:title="classLoadError"
class="mb-0"
/>
<el-empty v-else-if="!classLoading" description="当前账号未绑定班主任班级" />
</el-card>
<el-alert
v-if="loadStatus"
:type="loadStatusType"
:closable="false"
show-icon
:title="loadStatus"
class="mb-[10px]"
/>
<el-alert
v-if="listLoadError"
type="warning"
:closable="false"
show-icon
:title="listLoadError"
class="mb-[10px]"
/>
<template v-if="pageReady">
<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
<div v-show="showSearch" class="mb-[10px]">
<el-card shadow="hover">
<el-form ref="queryFormRef" :model="queryParams" label-width="80px">
<el-row :gutter="20">
<el-col :span="8">
<el-form-item label="日期范围">
<el-date-picker
v-model="dateRange"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="YYYY-MM-DD"
style="width: 100%"
/>
</el-form-item>
</el-col>
<el-col :span="5">
<el-form-item label="学号" prop="studentNo">
<el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable @keyup.enter="handleQuery" />
</el-form-item>
</el-col>
<el-col :span="5">
<el-form-item label="姓名" prop="studentName">
<el-input v-model="queryParams.studentName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
</el-form-item>
</el-col>
<el-col v-if="activeTab === 'rollCall'" :span="5">
<el-form-item label="点名状态" prop="rollCallStatus">
<el-select v-model="queryParams.rollCallStatus" placeholder="全部状态" clearable style="width: 100%">
<el-option
v-for="dict in xg_dorm_roll_call_status"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
</el-col>
<el-col :span="activeTab === 'rollCall' ? 6 : 6" class="search-btn-col">
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
</el-col>
</el-row>
</el-form>
</el-card>
</div>
</transition>
<el-card shadow="never">
<template #header>
<div class="flex justify-between items-center">
<span class="font-medium">班级宿舍情况</span>
<right-toolbar v-model:showSearch="showSearch" @queryTable="handleQuery" />
</div>
</template>
<el-tabs v-model="activeTab" @tab-change="handleTabChange">
<el-tab-pane label="宿舍违纪" name="violation">
<el-table v-loading="violationLoading" border :data="violationList" empty-text="当前日期范围内暂无违纪记录,请尝试扩大日期范围">
<el-table-column label="学号" prop="studentNo" width="130" align="center" />
<el-table-column label="姓名" prop="studentName" width="100" align="center" />
<el-table-column label="来源" prop="dataSourceName" width="110" align="center" />
<el-table-column label="违纪类型" prop="violationTypeName" min-width="140" show-overflow-tooltip />
<el-table-column label="扣分" prop="scoreDeduction" width="80" align="center">
<template #default="scope">
<span v-if="scope.row.scoreDeduction != null">{{ scope.row.scoreDeduction }}</span>
<span v-else class="text-gray-400">-</span>
</template>
</el-table-column>
<el-table-column label="违纪日期" prop="violationDate" width="120" align="center">
<template #default="scope">
<span>{{ proxy?.parseTime(scope.row.violationDate, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column label="宿舍楼" prop="buildingName" width="120" show-overflow-tooltip />
<el-table-column label="房间" prop="roomName" width="100" align="center" />
<el-table-column label="违纪原因" prop="violationReason" min-width="160" show-overflow-tooltip />
<el-table-column label="状态" prop="status" width="80" align="center">
<template #default="scope">
<dict-tag :options="student_discipline_status" :value="scope.row.status" />
</template>
</el-table-column>
</el-table>
<pagination
v-show="violationTotal > 0"
v-model:page="violationQuery.pageNum"
v-model:limit="violationQuery.pageSize"
:total="violationTotal"
@pagination="getViolationList"
/>
</el-tab-pane>
<el-tab-pane label="宿舍点名" name="rollCall">
<el-table
v-loading="rollCallLoading"
border
:data="rollCallList"
:row-class-name="rollCallRowClassName"
empty-text="当前日期范围内暂无点名记录,请尝试扩大日期范围或调整筛选条件"
>
<el-table-column label="班级" prop="className" width="120" align="center" show-overflow-tooltip />
<el-table-column label="学号" prop="studentNo" width="130" align="center" />
<el-table-column label="姓名" prop="studentName" width="100" align="center" />
<el-table-column label="点名时间" prop="checkDate" width="170" align="center">
<template #default="scope">
<span>{{ proxy?.parseTime(scope.row.checkDate, '{y}-{m}-{d} {h}:{i}') }}</span>
</template>
</el-table-column>
<el-table-column label="点名状态" prop="rollCallStatus" width="100" align="center">
<template #default="scope">
<dict-tag :options="xg_dorm_roll_call_status" :value="scope.row.rollCallStatus" />
</template>
</el-table-column>
<el-table-column label="批次号" prop="batchNo" min-width="180" show-overflow-tooltip />
<el-table-column label="检查员" prop="checkerName" width="100" align="center" />
<el-table-column label="宿舍楼" prop="buildingName" width="120" show-overflow-tooltip />
<el-table-column label="房间" prop="roomName" width="100" align="center" />
<el-table-column label="床位" prop="bedCode" width="80" align="center" />
<el-table-column label="请假类型" prop="leaveTypeName" width="100" align="center" />
</el-table>
<pagination
v-show="rollCallTotal > 0"
v-model:page="rollCallQuery.pageNum"
v-model:limit="rollCallQuery.pageSize"
:total="rollCallTotal"
@pagination="getRollCallList"
/>
</el-tab-pane>
</el-tabs>
</el-card>
</template>
</div>
</template>
<script setup name="ClassTeacherDormView" lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, type ComponentInternalInstance, toRefs } from 'vue';
import { ElMessage } from 'element-plus';
import {
getMyClassInfo,
listClassTeacherViolations,
listClassTeacherRollCalls,
type ClassTeacherClassInfo,
type ClassTeacherDormViolationVO,
type ClassTeacherDormRollCallVO
} from '@/api/xg/xgss/classTeacherDorm/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { student_discipline_status, xg_dorm_roll_call_status } = toRefs<any>(
proxy?.useDict('student_discipline_status', 'xg_dorm_roll_call_status')
);
const classLoading = ref(false);
const classInfo = ref<ClassTeacherClassInfo | null>(null);
const classLoadError = ref('');
const listLoadError = ref('');
const loadStatus = ref('');
const loadStatusType = ref<'success' | 'warning' | 'error' | 'info'>('info');
const pageReady = ref(false);
const showSearch = ref(true);
const activeTab = ref('violation');
const queryFormRef = ref();
const formatDate = (date: Date) => {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
};
const today = () => formatDate(new Date());
const defaultDateRange = (): [string, string] => [today(), today()];
const dateRange = ref<[string, string]>(defaultDateRange());
const queryParams = reactive({
studentNo: '',
studentName: '',
rollCallStatus: ''
});
const violationLoading = ref(false);
const violationList = ref<ClassTeacherDormViolationVO[]>([]);
const violationTotal = ref(0);
const violationQuery = reactive({ pageNum: 1, pageSize: 10 });
const rollCallLoading = ref(false);
const rollCallList = ref<ClassTeacherDormRollCallVO[]>([]);
const rollCallTotal = ref(0);
const rollCallQuery = reactive({ pageNum: 1, pageSize: 10 });
const buildDateParams = () => ({
beginDate: dateRange.value?.[0] || defaultDateRange()[0],
endDate: dateRange.value?.[1] || today(),
studentNo: queryParams.studentNo || undefined,
studentName: queryParams.studentName || undefined,
rollCallStatus: activeTab.value === 'rollCall' && queryParams.rollCallStatus ? queryParams.rollCallStatus : undefined
});
/** 不在寝(status=2)整行高亮 */
const rollCallRowClassName = ({ row }: { row: ClassTeacherDormRollCallVO }) => {
return row.rollCallStatus === '2' ? 'roll-call-absent-row' : '';
};
const extractRows = (res: any) => res?.rows ?? res?.data?.rows ?? [];
const extractTotal = (res: any) => Number(res?.total ?? res?.data?.total ?? 0);
const extractErrorMsg = (error: any) => error?.message || error?.response?.data?.msg || '请求失败,请稍后重试';
const updateLoadStatus = () => {
const range = `${dateRange.value?.[0] || ''} ~ ${dateRange.value?.[1] || ''}`;
if (classLoadError.value || listLoadError.value) {
loadStatusType.value = 'error';
loadStatus.value = [classLoadError.value, listLoadError.value].filter(Boolean).join(';');
return;
}
loadStatusType.value = 'success';
loadStatus.value = `查询完成(${range}):班级「${classInfo.value?.className || '未知'}」,违纪 ${violationTotal.value} 条,点名 ${rollCallTotal.value} 条`;
};
const loadClassInfo = async () => {
classLoading.value = true;
classLoadError.value = '';
try {
const res: any = await getMyClassInfo();
classInfo.value = res?.data ?? null;
if (!classInfo.value?.className) {
classLoadError.value = res?.msg || '未获取到班级信息,请确认当前账号已绑定班主任班级';
ElMessage.error(classLoadError.value);
}
} catch (error: any) {
classInfo.value = null;
classLoadError.value = extractErrorMsg(error);
ElMessage.error(classLoadError.value);
} finally {
classLoading.value = false;
updateLoadStatus();
}
};
const getViolationList = async () => {
violationLoading.value = true;
listLoadError.value = '';
try {
const res: any = await listClassTeacherViolations({
...buildDateParams(),
pageNum: violationQuery.pageNum,
pageSize: violationQuery.pageSize
});
violationList.value = extractRows(res);
violationTotal.value = extractTotal(res);
} catch (error: any) {
violationList.value = [];
violationTotal.value = 0;
listLoadError.value = `宿舍违纪:${extractErrorMsg(error)}`;
ElMessage.error(listLoadError.value);
} finally {
violationLoading.value = false;
updateLoadStatus();
}
};
const getRollCallList = async () => {
rollCallLoading.value = true;
listLoadError.value = '';
try {
const res: any = await listClassTeacherRollCalls({
...buildDateParams(),
pageNum: rollCallQuery.pageNum,
pageSize: rollCallQuery.pageSize
});
rollCallList.value = extractRows(res);
rollCallTotal.value = extractTotal(res);
} catch (error: any) {
rollCallList.value = [];
rollCallTotal.value = 0;
listLoadError.value = `宿舍点名:${extractErrorMsg(error)}`;
ElMessage.error(listLoadError.value);
} finally {
rollCallLoading.value = false;
updateLoadStatus();
}
};
const handleQuery = () => {
violationQuery.pageNum = 1;
rollCallQuery.pageNum = 1;
if (activeTab.value === 'violation') {
getViolationList();
} else {
getRollCallList();
}
};
const resetQuery = () => {
queryFormRef.value?.resetFields();
queryParams.studentNo = '';
queryParams.studentName = '';
queryParams.rollCallStatus = '';
dateRange.value = defaultDateRange();
handleQuery();
};
const handleTabChange = (name: string | number) => {
if (name === 'violation') {
getViolationList();
} else {
getRollCallList();
}
};
onMounted(async () => {
await loadClassInfo();
pageReady.value = true;
await getViolationList();
});
</script>
<style scoped>
.page-container {
min-height: calc(100vh - 120px);
}
.class-info-bar {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.class-info-label {
font-weight: 600;
color: var(--el-text-color-primary);
}
.class-info-extra {
color: var(--el-text-color-secondary);
font-size: 14px;
}
.class-info-tip {
color: var(--el-text-color-secondary);
font-size: 13px;
}
.search-btn-col {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
padding-top: 4px;
}
:deep(.roll-call-absent-row) {
background-color: #fef0f0 !important;
}
:deep(.roll-call-absent-row:hover > td) {
background-color: #fde2e2 !important;
}
</style>
@@ -201,8 +201,8 @@
<el-table-column prop="studentNo" label="学号" width="120" />
<el-table-column prop="gender" label="性别" width="60">
<template #default="scope">
<el-tag v-if="scope.row.gender === '0'" type="primary" size="small">男</el-tag>
<el-tag v-else-if="scope.row.gender === '1'" class="female-tag" size="small">女</el-tag>
<el-tag v-if="isMaleGender(scope.row.gender)" type="primary" size="small">男</el-tag>
<el-tag v-else-if="isFemaleGender(scope.row.gender)" class="female-tag" size="small">女</el-tag>
</template>
</el-table-column>
<el-table-column prop="collegeName" label="学院名称" min-width="120" show-overflow-tooltip />
@@ -356,6 +356,7 @@ import { getToken } from '@/utils/auth';
import ImagePreview from '@/components/ImagePreview/index.vue';
import request from '@/utils/request';
import { DormHygieneCheckForm, DormHygieneCheckCompleteForm } from '@/api/xg/xgss/dormHygieneCheck/dormHygieneCheck/types';
import { isFemaleGender, isMaleGender, mergeGenderFromRoomStudents, normalizeGender } from './genderUtils';
// 暂时注释掉用户信息获取,避免linter错误
// import { getInfo } from '@/api/login';
@@ -1035,7 +1036,7 @@ const loadRoomStudents = async () => {
console.log('获取到历史学生评分数据:', studentScoresRes.data);
// 将历史评分数据转换为表格显示格式
roomStudents.value = studentScoresRes.data.map((studentScore: any) => ({
let mappedStudents = studentScoresRes.data.map((studentScore: any) => ({
// 保存学生评分记录的ID,用于编辑时提交
id: studentScore.id,
studentId: studentScore.studentId,
@@ -1047,7 +1048,7 @@ const loadRoomStudents = async () => {
bedId: studentScore.bedId,
bedName: studentScore.bedCode, // 使用bedCode作为bedName显示
bedCode: studentScore.bedCode,
gender: studentScore.gender || '1', // 默认女性,如果没有性别字段
gender: normalizeGender(studentScore.gender),
// 使用历史评分数据
student_score: studentScore.studentScore || null,
attendance_status: studentScore.attendanceStatus || '1',
@@ -1057,6 +1058,20 @@ const loadRoomStudents = async () => {
improvementNotes: studentScore.improvementNotes || ''
}));
const missingGender = mappedStudents.some((student: any) => !student.gender);
if (missingGender && form.roomId) {
const roomRes = await request({
url: '/dormBedStudent/dormBedStudent/getRoomStudents',
method: 'get',
params: { roomId: form.roomId }
});
if (roomRes.code === 200 && roomRes.data) {
mappedStudents = mergeGenderFromRoomStudents(mappedStudents, roomRes.data);
}
}
roomStudents.value = mappedStudents;
console.log('转换后的学生数据:', roomStudents.value);
return;
} else {
@@ -1076,6 +1091,7 @@ const loadRoomStudents = async () => {
// 为每个学生设置默认值
roomStudents.value = res.data.map((student: any) => ({
...student,
gender: normalizeGender(student.gender),
student_score: 0, // 个人得分,新增时默认为0
attendance_status: student.attendance_status || '1', // 出勤状态,默认1-在寝
student_grade: student.student_grade || 'A' // 学生评级,默认A-优秀
@@ -47,30 +47,16 @@
</el-row>
<el-row :gutter="20">
<el-col :span="6">
<el-form-item label="违纪类型" prop="disciplineTypeId" class="discipline-form-item">
<el-select
v-model="hygieneForm.disciplineTypeId"
placeholder="请选择违纪类型"
style="width: 100%"
@change="handleDisciplineTypeChange"
>
<el-option
v-for="item in disciplineTypeOptions"
:key="item.id"
:label="item.typeName"
:value="item.id"
:data-score="item.minScore"
/>
</el-select>
<!-- 违纪类型说明展示 -->
<div v-if="hygieneForm.disciplineTypeId && selectedDisciplineTypeRemark" class="discipline-type-remark">
<el-icon class="remark-icon"><InfoFilled /></el-icon>
<span class="remark-text">类型说明:{{ selectedDisciplineTypeRemark }}</span>
</div>
</el-form-item>
<el-col :span="24">
<DisciplineDeductionMultiSelect
v-model="deductionItems"
:options="disciplineTypeOptions"
@update:total-score="handleDeductionTotalChange"
/>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="6">
<el-form-item label="宿舍扣分" prop="totalScore">
<el-input-number
@@ -78,9 +64,9 @@
:min="0"
:max="100"
:precision="2"
placeholder="请输入扣分"
placeholder="自动合计"
style="width: 100%"
@change="handleTotalScoreChange"
disabled
/>
</el-form-item>
</el-col>
@@ -193,8 +179,8 @@
<div class="student-basic-info">
<div class="student-name-with-gender">
<h4>{{ student.studentName }}</h4>
<el-tag v-if="student.gender === '0'" type="primary" size="small">男</el-tag>
<el-tag v-else class="female-tag" size="small">女</el-tag>
<el-tag v-if="isMaleGender(student.gender)" type="primary" size="small">男</el-tag>
<el-tag v-else-if="isFemaleGender(student.gender)" class="female-tag" size="small">女</el-tag>
</div>
<p>{{ student.studentNo }}</p>
</div>
@@ -368,6 +354,11 @@ import request from '@/utils/request';
import ViolationRecordDialog from './components/ViolationRecordDialog.vue';
// @ts-expect-error - Component import without type declarations
import LeaveProcessDialog from './components/LeaveProcessDialog.vue';
import DisciplineDeductionMultiSelect from './components/DisciplineDeductionMultiSelect.vue';
import type { HygieneDeductionItem } from '@/api/xg/xgss/dormHygieneCheck/dormHygieneCheck/types';
import { isFemaleGender, isMaleGender, mergeGenderFromRoomStudents, normalizeGender } from './genderUtils';
import { normalizeStudentId, normalizeId } from './studentIdUtils';
import { calcStudentViolationScoreTotal } from './violationScoreUtils';
// 组件实例
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
@@ -396,6 +387,7 @@ const studentsLoading = ref(false);
const violationsLoading = ref(false);
const attachmentList = ref<any[]>([]);
const disciplineTypeOptions = ref<any[]>([]);
const deductionItems = ref<HygieneDeductionItem[]>([]);
// 宿舍卫生检查表单
const hygieneForm = reactive({
@@ -449,8 +441,8 @@ const hygieneRules = reactive({
// 学生评分数据
const studentScores = ref<any[]>([]);
// 违纪记录数据
const violationRecords = ref<Map<string | number, any[]>>(new Map());
// 违纪记录数据(使用普通对象,避免 Map 变更无法触发 Vue 响应式更新)
const violationRecords = ref<Record<string, any[]>>({});
// 学生请假数据
const studentLeaves = ref<Map<string | number, any>>(new Map());
@@ -491,14 +483,10 @@ const violationDialogTitle = computed(() => {
return currentStudent.value ? `${currentStudent.value.studentName} - 违纪记录录入` : '违纪记录录入';
});
// 获取违纪类型说明
const selectedDisciplineTypeRemark = computed(() => {
if (hygieneForm.disciplineTypeId) {
const selectedType = disciplineTypeOptions.value.find((item) => item.id === hygieneForm.disciplineTypeId);
return selectedType ? selectedType.remark : '';
}
return '';
});
// 扣分明细合计同步到宿舍扣分
const handleDeductionTotalChange = (total: number) => {
hygieneForm.totalScore = total;
};
// 上传配置
const uploadAction = computed(() => {
@@ -558,24 +546,26 @@ const loadDisciplineTypes = async () => {
}
};
// 处理违纪类型变化
const handleDisciplineTypeChange = () => {
if (hygieneForm.disciplineTypeId) {
const selectedType = disciplineTypeOptions.value.find((item) => item.id === hygieneForm.disciplineTypeId);
if (selectedType) {
hygieneForm.disciplineTypeName = selectedType.typeName;
// 自动填入最低分
if (selectedType.minScore !== null && selectedType.minScore !== undefined) {
const minScore = parseFloat(selectedType.minScore);
if (!isNaN(minScore)) {
hygieneForm.totalScore = minScore;
ElMessage.success(`已自动填入最低扣分:${minScore}分`);
}
// 初始化扣分明细
const initDeductionItems = (data?: any) => {
if (data?.deductionItems && data.deductionItems.length > 0) {
deductionItems.value = data.deductionItems.map((item: HygieneDeductionItem, index: number) => ({
...item,
sortOrder: item.sortOrder ?? index + 1
}));
} else if (data?.disciplineTypeId) {
deductionItems.value = [
{
disciplineTypeId: data.disciplineTypeId,
disciplineTypeName: data.disciplineTypeName,
score: data.totalScore ?? 0,
sortOrder: 1
}
}
];
} else {
hygieneForm.disciplineTypeName = '';
deductionItems.value = [];
}
hygieneForm.totalScore = deductionItems.value.reduce((sum, item) => sum + (Number(item.score) || 0), 0);
};
// 初始化表单数据(已简化,主要逻辑移到watch中)
@@ -594,32 +584,48 @@ const initFormData = async () => {
// 加载学生评分数据
const loadStudentScores = async () => {
console.log('loadStudentScores 方法被调用,hygieneForm.id:', hygieneForm.id);
if (!hygieneForm.id) {
const checkId = normalizeId(hygieneForm.id);
if (!checkId) {
console.log('没有检查ID,跳过学生数据加载');
return;
}
console.log('开始加载学生评分数据,检查ID:', hygieneForm.id);
console.log('开始加载学生评分数据,检查ID:', checkId);
studentsLoading.value = true;
try {
const res = await request({
url: `/dormHygieneStudentScore/dormHygieneStudentScore/getByCheckId/${hygieneForm.id}`,
url: `/dormHygieneStudentScore/dormHygieneStudentScore/getByCheckId/${checkId}`,
method: 'get'
});
console.log('学生评分数据API响应:', res);
if (res.code === 200 && Array.isArray(res.data)) {
let scores = res.data.map((student: any) => ({
...student,
studentId: normalizeStudentId(student.studentId),
gender: normalizeGender(student.gender)
}));
if (res.code === 200 && res.data) {
studentScores.value = res.data;
console.log('学生评分数据加载成功:', res.data.length, '条');
const missingGender = scores.some((student: any) => !student.gender);
if (missingGender && hygieneForm.roomId) {
try {
const roomRes = await request({
url: '/dormBedStudent/dormBedStudent/getRoomStudents',
method: 'get',
params: { roomId: hygieneForm.roomId }
});
if (roomRes.code === 200 && roomRes.data) {
scores = mergeGenderFromRoomStudents(scores, roomRes.data);
}
} catch (error) {
console.warn('补全学生性别失败,将仅展示已关联到的性别信息', error);
}
}
// 同时加载违纪记录和请假信息
await Promise.all([loadViolationRecords(), loadStudentLeaves()]);
studentScores.value = scores;
console.log('学生评分数据加载成功:', scores.length, '条');
await loadStudentLeaves();
} else {
studentScores.value = [];
console.log('学生评分数据为空,响应码:', res.code);
}
} catch (error) {
console.error('加载学生评分数据失败:', error);
@@ -631,29 +637,55 @@ const loadStudentScores = async () => {
};
// 加载违纪记录数据
const loadViolationRecords = async () => {
if (!hygieneForm.id) return;
const applyViolationList = (list: any[]) => {
const grouped: Record<string, any[]> = {};
(list || []).forEach((violation: any) => {
const studentId = normalizeStudentId(violation.studentId);
if (!studentId) return;
if (!grouped[studentId]) {
grouped[studentId] = [];
}
grouped[studentId].push({
...violation,
studentId,
disciplineRecordId:
violation.disciplineRecordId != null ? normalizeId(violation.disciplineRecordId) : undefined
});
});
violationRecords.value = grouped;
if (studentScores.value.length > 0) {
syncStudentScoreFromViolations();
}
};
const loadViolationRecords = async (prefetched?: any[] | null) => {
if (prefetched !== undefined) {
applyViolationList(prefetched || []);
console.log('违纪记录(预加载):', (prefetched || []).length, '条');
return;
}
const checkId = normalizeId(hygieneForm.id || props.formData?.id);
if (!checkId) return;
violationsLoading.value = true;
try {
const res = await request({
url: `/dormHygieneCheck/dormHygieneCheck/getViolations/${hygieneForm.id}`,
url: `/dormHygieneCheck/dormHygieneCheck/getViolations/${checkId}`,
method: 'get'
});
if (res.code === 200 && res.data) {
// 重新组织违纪记录数据,按学生ID分组
violationRecords.value.clear();
res.data.forEach((violation: any) => {
const studentId = violation.studentId;
if (!violationRecords.value.has(studentId)) {
violationRecords.value.set(studentId, []);
}
violationRecords.value.get(studentId)?.push(violation);
});
if (res.code === 200 && Array.isArray(res.data)) {
applyViolationList(res.data);
console.log('违纪记录加载成功:', res.data.length, '条');
} else {
violationRecords.value = {};
}
} catch (error) {
console.error('加载违纪记录数据失败:', error);
ElMessage.error('加载违纪记录数据失败');
} finally {
violationsLoading.value = false;
}
};
@@ -675,9 +707,9 @@ const loadStudentLeaves = async () => {
if (res.code === 200 && res.data) {
studentLeaves.value.clear();
Object.keys(res.data).forEach((studentId) => {
studentLeaves.value.set(Number(studentId), res.data[studentId]);
// 如果学生有请假信息,自动设置出勤状态为3(请假)
const student = studentScores.value.find((s) => s.studentId === Number(studentId));
const normalizedId = normalizeStudentId(studentId);
studentLeaves.value.set(normalizedId, res.data[studentId]);
const student = studentScores.value.find((s) => normalizeStudentId(s.studentId) === normalizedId);
if (student) {
student.attendanceStatus = '3';
}
@@ -691,12 +723,31 @@ const loadStudentLeaves = async () => {
// 获取学生的违纪记录
const getStudentViolations = (studentId: string | number) => {
return violationRecords.value.get(studentId) || [];
return violationRecords.value[normalizeStudentId(studentId)] || [];
};
/** 根据违纪记录合计同步个人扣分 */
const syncStudentScoreFromViolations = (studentId?: string | number) => {
const syncOne = (sid: string) => {
const student = studentScores.value.find((item) => normalizeStudentId(item.studentId) === sid);
if (student) {
student.studentScore = calcStudentViolationScoreTotal(getStudentViolations(sid));
}
};
if (studentId != null && studentId !== '') {
syncOne(normalizeStudentId(studentId));
return;
}
studentScores.value.forEach((student) => {
syncOne(normalizeStudentId(student.studentId));
});
};
// 获取学生的请假信息
const getStudentLeave = (studentId: string | number) => {
return studentLeaves.value.get(studentId) || null;
return studentLeaves.value.get(normalizeStudentId(studentId)) || null;
};
// 处理附件数据
@@ -829,7 +880,8 @@ const editViolationRecord = (student: any, violation: any, index: number) => {
// 删除违纪记录
const removeViolationRecord = async (studentId: string | number, index: number) => {
const violations = violationRecords.value.get(studentId) || [];
const normalizedId = normalizeStudentId(studentId);
const violations = [...(violationRecords.value[normalizedId] || [])];
const violation = violations[index];
// 检查是否为已撤销的违纪记录
@@ -851,11 +903,14 @@ const removeViolationRecord = async (studentId: string | number, index: number)
violations.splice(index, 1);
const nextRecords = { ...violationRecords.value };
if (violations.length === 0) {
violationRecords.value.delete(studentId);
delete nextRecords[normalizedId];
} else {
violationRecords.value.set(studentId, violations);
nextRecords[normalizedId] = violations;
}
violationRecords.value = nextRecords;
syncStudentScoreFromViolations(normalizedId);
if (window.ElMessage) {
window.ElMessage.success('违纪记录删除成功');
@@ -867,23 +922,32 @@ const removeViolationRecord = async (studentId: string | number, index: number)
// 违纪记录确认
const handleViolationConfirm = (violationData: any) => {
const studentId = currentStudent.value.studentId;
const violations = violationRecords.value.get(studentId) || [];
const studentId = normalizeStudentId(currentStudent.value.studentId);
const violations = [...(violationRecords.value[studentId] || [])];
if (currentViolationIndex.value >= 0) {
// 编辑模式
if (Array.isArray(violationData)) {
violations.push(...violationData);
if (window.ElMessage) {
window.ElMessage.success(`已添加 ${violationData.length} 条违纪记录`);
}
} else if (currentViolationIndex.value >= 0) {
violations[currentViolationIndex.value] = violationData;
if (window.ElMessage) {
window.ElMessage.success('违纪记录保存成功');
}
} else {
// 新增模式
violations.push(violationData);
if (window.ElMessage) {
window.ElMessage.success('违纪记录保存成功');
}
}
violationRecords.value.set(studentId, violations);
violationRecords.value = {
...violationRecords.value,
[studentId]: violations
};
syncStudentScoreFromViolations(studentId);
violationDialogVisible.value = false;
if (window.ElMessage) {
window.ElMessage.success('违纪记录保存成功');
}
};
// 违纪记录弹窗关闭
@@ -1110,8 +1174,16 @@ const submitForm = async () => {
try {
await hygieneFormRef.value?.validate();
if ((hygieneForm.totalScore || 0) > 100) {
ElMessage.error('宿舍合计扣分不能超过100分');
return;
}
buttonLoading.value = true;
// 提交前同步个人扣分为违纪合计
syncStudentScoreFromViolations();
// 处理附件数据
const attachmentOssIds = attachmentList.value.filter((file) => file.status === 'success' && file.ossId).map((file) => file.ossId);
hygieneForm.attachmentIds = attachmentOssIds.join(',');
@@ -1138,12 +1210,30 @@ const submitForm = async () => {
// 处理违纪记录数据
const violationData: any[] = [];
violationRecords.value.forEach((violations, studentId) => {
Object.entries(violationRecords.value).forEach(([studentId, violations]) => {
const student = studentScores.value.find((item) => normalizeStudentId(item.studentId) === studentId);
violations.forEach((violation) => {
violationData.push({
...violation,
studentId,
violationSource: '1' // 宿舍卫生检查来源
disciplineRecordId:
violation.disciplineRecordId != null ? normalizeId(violation.disciplineRecordId) : undefined,
studentId: normalizeStudentId(student?.studentId || violation.studentId || studentId),
studentNo: violation.studentNo || student?.studentNo || '',
studentName: violation.studentName || student?.studentName || '',
classId: violation.classId ?? student?.classId,
className: violation.className || student?.className || '',
majorId: violation.majorId ?? student?.majorId,
majorName: violation.majorName || student?.majorName || '',
collegeId: violation.collegeId ?? student?.collegeId,
collegeName: violation.collegeName || student?.collegeName || '',
disciplineTypeId: violation.disciplineTypeId,
disciplineTypeName: violation.disciplineTypeName,
disciplineDate: violation.disciplineDate,
disciplineReason: violation.disciplineReason,
disciplineContent: violation.disciplineContent,
scoreDeduction: violation.scoreDeduction,
status: violation.status || '1',
attachmentOssIds: violation.attachmentOssIds || '',
violationSource: '1'
});
});
});
@@ -1151,6 +1241,7 @@ const submitForm = async () => {
// 构建提交数据
const submitData = {
...hygieneForm,
deductionItems: deductionItems.value,
studentScores: studentScoresData,
violationData
};
@@ -1171,44 +1262,67 @@ const handleClose = () => {
emit('close');
};
// 监听弹窗显示状态
watch(
() => props.visible,
async (visible, oldVisible) => {
console.log('弹窗显示状态变化:', oldVisible, '->', visible);
if (visible) {
console.log('弹窗打开,开始初始化表单数据');
// 只加载违纪类型数据,其他数据通过formData的watch来加载
await loadDisciplineTypes();
} else {
console.log('弹窗关闭');
}
const detailLoadToken = ref(0);
const syncFormFromProps = (data?: any) => {
if (!data) return;
Object.assign(hygieneForm, {
...data,
id: data.id != null ? normalizeId(data.id) : undefined,
roomId: data.roomId != null ? normalizeId(data.roomId) : undefined
});
initDeductionItems(data);
};
const loadCheckDetailData = async () => {
const checkId = normalizeId(props.formData?.id);
if (!props.visible || !checkId) {
return;
}
);
// 监听表单数据变化
const token = ++detailLoadToken.value;
syncFormFromProps(props.formData);
hygieneForm.id = checkId;
const hasPrefetchedViolations =
props.formData != null && Object.prototype.hasOwnProperty.call(props.formData, '_prefetchedViolations');
console.log('开始加载检查详情,checkId:', checkId);
try {
await loadStudentScores();
if (token !== detailLoadToken.value) return;
await loadViolationRecords(hasPrefetchedViolations ? props.formData._prefetchedViolations || [] : undefined);
if (token !== detailLoadToken.value) return;
syncStudentScoreFromViolations();
await handleAttachmentData();
console.log('检查详情加载完成');
} catch (error) {
console.error('加载检查详情失败:', error);
}
};
// 弹窗打开 / 检查ID变化时加载详情(合并 visible + formData.id,避免竞态)
watch(
() => props.formData,
async (newData, oldData) => {
console.log('props.formData 变化:', oldData, '->', newData);
if (newData) {
console.log('更新表单数据');
Object.assign(hygieneForm, newData);
console.log('表单数据更新后,hygieneForm.id:', hygieneForm.id);
// 如果弹窗是打开状态且有ID,需要重新加载相关数据
if (props.visible && hygieneForm.id) {
console.log('检测到有检查ID,重新加载学生数据和附件数据...');
try {
await Promise.all([loadStudentScores(), handleAttachmentData()]);
console.log('学生数据和附件数据重新加载完成');
} catch (error) {
console.error('重新加载数据失败:', error);
}
}
() => [props.visible, normalizeId(props.formData?.id)] as const,
async ([visible, checkId]) => {
if (!visible) {
detailLoadToken.value += 1;
violationRecords.value = {};
studentScores.value = [];
hygieneForm.id = undefined;
return;
}
if (!checkId) return;
await loadDisciplineTypes();
await nextTick();
await loadCheckDetailData();
},
{ deep: true, immediate: true }
{ immediate: true }
);
</script>
@@ -201,12 +201,13 @@
</template>
<script setup name="DormHygieneCheckMainDialog" lang="ts">
import { ref, reactive, computed, watch, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { ref, reactive, computed, watch, getCurrentInstance, ComponentInternalInstance, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Check, Calendar } from '@element-plus/icons-vue';
import DormHygieneCheckSingleDialog from './DormHygieneCheckSingleDialog.vue';
import DormHygieneCheckEditDialog from './DormHygieneCheckEditDialog.vue';
import request from '@/utils/request';
import { normalizeId } from './studentIdUtils';
// 组件实例
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
@@ -531,7 +532,7 @@ const handleRoomDoubleClick = async (room: any) => {
}
// 检查是否已有记录ID(新增成功后会保存ID)
const checkId = roomCheckIds.value.get(room.id);
const checkId = normalizeId(roomCheckIds.value.get(room.id));
if (checkId) {
// 有记录ID,说明已经检查过,打开编辑弹窗
@@ -542,8 +543,22 @@ const handleRoomDoubleClick = async (room: any) => {
});
if (response.code === 200 && response.data) {
let editPayload: Record<string, any> = {
...response.data,
id: checkId
};
try {
const violationsRes = await request({
url: `/dormHygieneCheck/dormHygieneCheck/getViolations/${checkId}`,
method: 'get'
});
editPayload._prefetchedViolations = violationsRes.data || [];
} catch (error) {
console.warn('预加载违纪记录失败,将在弹窗内重试', error);
}
currentRoom.value = room;
currentEditData.value = response.data;
currentEditData.value = editPayload;
await nextTick();
editCheckVisible.value = true;
return;
}
@@ -570,7 +585,7 @@ const handleSingleCheckSubmit = (data: any) => {
// 保存检查记录ID(如果有返回)
if (data.id) {
roomCheckIds.value.set(currentRoom.value.id, data.id);
roomCheckIds.value.set(currentRoom.value.id, normalizeId(data.id));
}
ElMessage.success(`${currentRoom.value.roomName} 检查完成`);
@@ -595,7 +610,7 @@ const handleEditCheckSubmit = async (data: any) => {
if (response.code === 200) {
// 标记房间为已完成
completedRooms.value.add(currentRoom.value.id);
roomCheckIds.value.set(currentRoom.value.id, data.id);
roomCheckIds.value.set(currentRoom.value.id, normalizeId(data.id));
ElMessage.success(`${currentRoom.value.roomName} 检查记录更新完成`);
editCheckVisible.value = false;
@@ -12,30 +12,16 @@
<el-form ref="hygieneFormRef" :model="hygieneForm" :rules="hygieneRules" label-width="120px">
<el-row :gutter="20">
<el-col :span="8">
<el-form-item label="违纪类型" prop="disciplineTypeId" class="discipline-form-item">
<el-select
v-model="hygieneForm.disciplineTypeId"
placeholder="请选择违纪类型"
style="width: 100%"
@change="handleDisciplineTypeChange"
>
<el-option
v-for="item in disciplineTypeOptions"
:key="item.id"
:label="item.typeName"
:value="item.id"
:data-score="item.minScore"
/>
</el-select>
<!-- 违纪类型说明展示 -->
<div v-if="hygieneForm.disciplineTypeId && selectedDisciplineTypeRemark" class="discipline-type-remark">
<el-icon class="remark-icon"><InfoFilled /></el-icon>
<span class="remark-text">类型说明:{{ selectedDisciplineTypeRemark }}</span>
</div>
</el-form-item>
<el-col :span="24">
<DisciplineDeductionMultiSelect
v-model="deductionItems"
:options="disciplineTypeOptions"
@update:total-score="handleDeductionTotalChange"
/>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="8">
<el-form-item label="宿舍扣分" prop="totalScore">
<el-input-number
@@ -43,9 +29,9 @@
:min="0"
:max="100"
:precision="2"
placeholder="请输入扣分"
placeholder="自动合计"
style="width: 100%"
@change="handleTotalScoreChange"
disabled
/>
</el-form-item>
</el-col>
@@ -151,8 +137,8 @@
<div class="student-basic-info">
<div class="student-name-with-gender">
<h4>{{ student.studentName }}</h4>
<el-tag v-if="student.gender === '0'" type="primary" size="small">男</el-tag>
<el-tag v-else class="female-tag" size="small">女</el-tag>
<el-tag v-if="isMaleGender(student.gender)" type="primary" size="small">男</el-tag>
<el-tag v-else-if="isFemaleGender(student.gender)" class="female-tag" size="small">女</el-tag>
</div>
<p>{{ student.studentNo }}</p>
</div>
@@ -311,6 +297,11 @@ import request from '@/utils/request';
import ViolationRecordDialog from './components/ViolationRecordDialog.vue';
// @ts-expect-error - Component import without type declarations
import LeaveProcessDialog from './components/LeaveProcessDialog.vue';
import DisciplineDeductionMultiSelect from './components/DisciplineDeductionMultiSelect.vue';
import type { HygieneDeductionItem } from '@/api/xg/xgss/dormHygieneCheck/dormHygieneCheck/types';
import { isFemaleGender, isMaleGender } from './genderUtils';
import { normalizeStudentId } from './studentIdUtils';
import { calcStudentViolationScoreTotal } from './violationScoreUtils';
// 组件实例
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
@@ -339,6 +330,7 @@ const buttonLoading = ref(false);
const studentsLoading = ref(false);
const attachmentList = ref<any[]>([]);
const disciplineTypeOptions = ref<any[]>([]);
const deductionItems = ref<HygieneDeductionItem[]>([]);
// 宿舍卫生检查表单
const hygieneForm = reactive({
@@ -448,21 +440,8 @@ const loadDisciplineTypes = async () => {
}
};
// 处理违纪类型变化
const handleDisciplineTypeChange = () => {
if (hygieneForm.disciplineTypeId) {
const selectedType = disciplineTypeOptions.value.find((item) => item.id === hygieneForm.disciplineTypeId);
if (selectedType) {
hygieneForm.disciplineTypeName = selectedType.typeName;
// 自动填入最低分
if (selectedType.minScore !== null && selectedType.minScore !== undefined) {
hygieneForm.totalScore = selectedType.minScore;
ElMessage.success(`已自动填入最低扣分:${selectedType.minScore}分`);
}
}
} else {
hygieneForm.disciplineTypeName = '';
}
const handleDeductionTotalChange = (total: number) => {
hygieneForm.totalScore = total;
};
// 加载房间学生信息
@@ -483,6 +462,7 @@ const loadRoomStudents = async () => {
if (res.code === 200 && res.data) {
roomStudents.value = res.data.map((student: any) => ({
...student,
studentId: normalizeStudentId(student.studentId),
student_score: 0,
attendance_status: '1',
student_grade: 'A'
@@ -520,9 +500,9 @@ const loadStudentLeaves = async () => {
if (res.code === 200 && res.data) {
studentLeaves.value.clear();
Object.keys(res.data).forEach((studentId) => {
studentLeaves.value.set(Number(studentId), res.data[studentId]);
// 如果学生有请假信息,自动设置出勤状态为3(请假)
const student = roomStudents.value.find((s) => s.studentId === Number(studentId));
const normalizedId = normalizeStudentId(studentId);
studentLeaves.value.set(normalizedId, res.data[studentId]);
const student = roomStudents.value.find((s) => normalizeStudentId(s.studentId) === normalizedId);
if (student) {
student.attendance_status = '3';
}
@@ -534,23 +514,32 @@ const loadStudentLeaves = async () => {
}
};
// 获取违纪类型说明
const selectedDisciplineTypeRemark = computed(() => {
if (hygieneForm.disciplineTypeId) {
const selectedType = disciplineTypeOptions.value.find((item) => item.id === hygieneForm.disciplineTypeId);
return selectedType ? selectedType.remark : '';
}
return '';
});
// 获取学生的违纪记录
const getStudentViolations = (studentId: string | number) => {
return violationRecords.value.get(studentId) || [];
return violationRecords.value.get(normalizeStudentId(studentId)) || [];
};
const syncStudentScoreFromViolations = (studentId?: string | number) => {
const syncOne = (sid: string) => {
const student = roomStudents.value.find((item) => normalizeStudentId(item.studentId) === sid);
if (student) {
student.student_score = calcStudentViolationScoreTotal(getStudentViolations(sid));
}
};
if (studentId != null && studentId !== '') {
syncOne(normalizeStudentId(studentId));
return;
}
roomStudents.value.forEach((student) => {
syncOne(normalizeStudentId(student.studentId));
});
};
// 获取学生的请假信息
const getStudentLeave = (studentId: string | number) => {
return studentLeaves.value.get(studentId) || null;
return studentLeaves.value.get(normalizeStudentId(studentId)) || null;
};
// 格式化日期时间
@@ -584,14 +573,16 @@ const removeViolationRecord = async (studentId: string | number, index: number)
type: 'warning'
});
const violations = violationRecords.value.get(studentId) || [];
const normalizedId = normalizeStudentId(studentId);
const violations = violationRecords.value.get(normalizedId) || [];
violations.splice(index, 1);
if (violations.length === 0) {
violationRecords.value.delete(studentId);
violationRecords.value.delete(normalizedId);
} else {
violationRecords.value.set(studentId, violations);
violationRecords.value.set(normalizedId, violations);
}
syncStudentScoreFromViolations(normalizedId);
ElMessage.success('违纪记录删除成功');
} catch {
@@ -601,21 +592,23 @@ const removeViolationRecord = async (studentId: string | number, index: number)
// 违纪记录确认
const handleViolationConfirm = (violationData: any) => {
const studentId = currentStudent.value.studentId;
const studentId = normalizeStudentId(currentStudent.value.studentId);
const violations = violationRecords.value.get(studentId) || [];
if (currentViolationIndex.value >= 0) {
// 编辑模式
if (Array.isArray(violationData)) {
violations.push(...violationData);
ElMessage.success(`已添加 ${violationData.length} 条违纪记录`);
} else if (currentViolationIndex.value >= 0) {
violations[currentViolationIndex.value] = violationData;
ElMessage.success('违纪记录保存成功');
} else {
// 新增模式
violations.push(violationData);
ElMessage.success('违纪记录保存成功');
}
violationRecords.value.set(studentId, violations);
syncStudentScoreFromViolations(studentId);
violationDialogVisible.value = false;
ElMessage.success('违纪记录保存成功');
};
// 违纪记录弹窗关闭
@@ -880,8 +873,15 @@ const submitForm = async () => {
try {
await hygieneFormRef.value?.validate();
if ((hygieneForm.totalScore || 0) > 100) {
ElMessage.error('宿舍合计扣分不能超过100分');
return;
}
buttonLoading.value = true;
syncStudentScoreFromViolations();
// 处理附件数据
const attachmentOssIds = attachmentList.value.filter((file) => file.status === 'success' && file.ossId).map((file) => file.ossId);
hygieneForm.attachmentIds = attachmentOssIds.join(',');
@@ -938,6 +938,7 @@ const submitForm = async () => {
// 宿舍整体评分
...hygieneForm,
deductionItems: deductionItems.value,
// 学生评分数据
studentScores,
@@ -1003,6 +1004,7 @@ const resetForm = () => {
checkRemarks: '',
attachmentIds: ''
});
deductionItems.value = [];
roomStudents.value = [];
violationRecords.value.clear();
@@ -0,0 +1,231 @@
<template>
<div class="deduction-multi-select">
<el-form-item label="扣分项" class="discipline-form-item">
<el-select
v-if="!disabled"
v-model="selectedTypeIds"
multiple
collapse-tags
collapse-tags-tooltip
filterable
clearable
placeholder="请选择扣分项(可多选)"
style="width: 100%"
@change="handleTypeSelectionChange"
>
<el-option v-for="item in options" :key="item.id" :label="formatOptionLabel(item)" :value="item.id" />
</el-select>
<div v-else-if="!items.length" class="empty-text">无扣分项</div>
</el-form-item>
<div v-if="items.length > 0" class="deduction-list">
<div v-for="(item, index) in items" :key="item.disciplineTypeId" class="deduction-item">
<div class="deduction-item-main">
<span class="deduction-name">{{ item.disciplineTypeName }}</span>
<el-input-number
v-model="item.score"
:min="getMinScore(item)"
:max="getMaxScore(item)"
:precision="2"
:disabled="disabled"
controls-position="right"
size="small"
@change="handleScoreChange"
/>
<span class="deduction-range">({{ getMinScore(item) }}-{{ getMaxScore(item) }}分)</span>
<el-button v-if="!disabled" link type="danger" @click="removeItem(index)">删除</el-button>
</div>
<div v-if="getTypeRemark(item.disciplineTypeId)" class="deduction-remark">
<el-icon class="remark-icon"><InfoFilled /></el-icon>
<span>{{ getTypeRemark(item.disciplineTypeId) }}</span>
</div>
</div>
<div class="deduction-total">
合计扣分:<strong>{{ totalScore }}</strong> 分
<span v-if="totalScore > 100" class="total-warning">(已超过100分上限)</span>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { InfoFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import type { HygieneDeductionItem } from '@/api/xg/xgss/dormHygieneCheck/dormHygieneCheck/types';
interface DisciplineTypeOption {
id: number | string;
typeName: string;
minScore?: number | string;
maxScore?: number | string;
remark?: string;
}
const props = withDefaults(
defineProps<{
modelValue: HygieneDeductionItem[];
options: DisciplineTypeOption[];
disabled?: boolean;
}>(),
{
modelValue: () => [],
options: () => [],
disabled: false
}
);
const emit = defineEmits<{
(e: 'update:modelValue', value: HygieneDeductionItem[]): void;
(e: 'update:totalScore', value: number): void;
}>();
const selectedTypeIds = ref<Array<number | string>>([]);
const items = computed({
get: () => props.modelValue || [],
set: (value: HygieneDeductionItem[]) => emit('update:modelValue', value)
});
const totalScore = computed(() => {
const sum = (props.modelValue || []).reduce((acc, item) => acc + (Number(item.score) || 0), 0);
return Number(sum.toFixed(2));
});
watch(
() => props.modelValue,
(value) => {
selectedTypeIds.value = (value || []).map((item) => item.disciplineTypeId).filter((id) => id !== undefined && id !== null);
emit('update:totalScore', totalScore.value);
},
{ deep: true, immediate: true }
);
const formatOptionLabel = (item: DisciplineTypeOption) => {
const min = item.minScore ?? 0;
return `${item.typeName}(${min}分起)`;
};
const getTypeOption = (typeId?: number | string) => props.options.find((item) => String(item.id) === String(typeId));
const getMinScore = (item: HygieneDeductionItem) => {
const option = getTypeOption(item.disciplineTypeId);
return Number(option?.minScore ?? item.minScore ?? 0);
};
const getMaxScore = (item: HygieneDeductionItem) => {
const option = getTypeOption(item.disciplineTypeId);
return Number(option?.maxScore ?? item.maxScore ?? 100);
};
const getTypeRemark = (typeId?: number | string) => getTypeOption(typeId)?.remark || '';
const emitItems = (nextItems: HygieneDeductionItem[]) => {
items.value = nextItems;
emit('update:totalScore', nextItems.reduce((acc, item) => acc + (Number(item.score) || 0), 0));
};
const handleTypeSelectionChange = (typeIds: Array<number | string>) => {
const currentMap = new Map((props.modelValue || []).map((item) => [String(item.disciplineTypeId), item]));
const nextItems: HygieneDeductionItem[] = [];
typeIds.forEach((typeId, index) => {
const option = getTypeOption(typeId);
if (!option) {
return;
}
const existing = currentMap.get(String(typeId));
nextItems.push({
disciplineTypeId: option.id,
disciplineTypeName: option.typeName,
score: existing?.score ?? Number(option.minScore ?? 0),
minScore: Number(option.minScore ?? 0),
maxScore: Number(option.maxScore ?? 100),
sortOrder: index + 1
});
});
emitItems(nextItems);
if (nextItems.length > typeIds.length - 1) {
ElMessage.success('已添加扣分项');
}
};
const handleScoreChange = () => {
if (totalScore.value > 100) {
ElMessage.warning('合计扣分不能超过100分');
}
emit('update:totalScore', totalScore.value);
};
const removeItem = (index: number) => {
const nextItems = [...(props.modelValue || [])];
nextItems.splice(index, 1);
selectedTypeIds.value = nextItems.map((item) => item.disciplineTypeId);
emitItems(nextItems);
};
</script>
<style scoped>
.deduction-list {
margin-top: 8px;
padding: 12px;
background: #f8f9fb;
border-radius: 8px;
}
.deduction-item + .deduction-item {
margin-top: 10px;
padding-top: 10px;
border-top: 1px dashed #e4e7ed;
}
.deduction-item-main {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.deduction-name {
min-width: 120px;
font-weight: 500;
color: #303133;
}
.deduction-range {
color: #909399;
font-size: 12px;
}
.deduction-remark {
display: flex;
align-items: flex-start;
gap: 6px;
margin-top: 6px;
color: #909399;
font-size: 12px;
line-height: 1.5;
}
.deduction-total {
margin-top: 12px;
padding-top: 10px;
border-top: 1px solid #e4e7ed;
color: #606266;
}
.deduction-total strong {
color: #f56c6c;
font-size: 16px;
}
.total-warning {
color: #f56c6c;
margin-left: 8px;
}
.empty-text {
color: #909399;
}
</style>
@@ -11,8 +11,8 @@
</div>
</el-form-item>
<!-- 违纪类型选择 -->
<el-form-item label="违纪类型" prop="disciplineTypeId" class="discipline-form-item">
<!-- 违纪类型选择:编辑模式单选 -->
<el-form-item v-if="isEditMode" label="违纪类型" prop="disciplineTypeId" class="discipline-form-item">
<el-select v-model="form.disciplineTypeId" placeholder="请选择违纪类型" style="width: 100%" @change="handleDisciplineTypeChange" filterable>
<el-option
v-for="item in allViolationTypes"
@@ -31,13 +31,70 @@
</el-option>
</el-select>
<!-- 违纪类型说明展示 -->
<div v-if="form.disciplineTypeId && selectedDisciplineTypeRemark" class="discipline-type-remark">
<el-icon class="remark-icon"><InfoFilled /></el-icon>
<span class="remark-text">类型说明:{{ selectedDisciplineTypeRemark }}</span>
</div>
</el-form-item>
<!-- 违纪类型选择:新增模式多选 -->
<template v-else>
<el-form-item label="违纪类型" class="discipline-form-item">
<el-select
v-model="selectedTypeIds"
multiple
collapse-tags
collapse-tags-tooltip
filterable
clearable
placeholder="请选择违纪类型(可多选)"
style="width: 100%"
@change="handleTypeSelectionChange"
>
<el-option
v-for="item in allViolationTypes"
:key="item.id"
:label="getViolationTypeLabel(item)"
:value="item.id"
:disabled="item.status !== '0'"
>
<div class="violation-type-option">
<span class="violation-type-name" :title="getViolationTypeLabel(item)">
<span class="area-tag" :class="getAreaTypeClass(item.areaType)">{{ getAreaTypeText(item.areaType) }}</span>
{{ getShortTypeName(item.typeName) }}
</span>
<span class="score-range">{{ item.minScore }}-{{ item.maxScore }}分</span>
</div>
</el-option>
</el-select>
</el-form-item>
<div v-if="violationItems.length > 0" class="violation-item-list">
<div v-for="(item, index) in violationItems" :key="item.disciplineTypeId" class="violation-item-row">
<div class="violation-item-main">
<span class="violation-item-name">{{ item.disciplineTypeName }}</span>
<el-input-number
v-model="item.scoreDeduction"
:min="getItemMinScore(item)"
:max="getItemMaxScore(item)"
:precision="2"
controls-position="right"
size="small"
/>
<span class="score-range">({{ getItemMinScore(item) }}-{{ getItemMaxScore(item) }}分)</span>
<el-button link type="danger" @click="removeViolationItem(index)">删除</el-button>
</div>
<div v-if="getItemRemark(item.disciplineTypeId)" class="discipline-type-remark inline-remark">
<el-icon class="remark-icon"><InfoFilled /></el-icon>
<span class="remark-text">类型说明:{{ getItemRemark(item.disciplineTypeId) }}</span>
</div>
</div>
<div class="violation-item-total">
合计扣分:<strong>{{ violationItemsTotalScore }}</strong> 分
</div>
</div>
</template>
<!-- 违纪日期和扣分分值 - 同一行显示 -->
<el-row :gutter="16">
<el-col :span="12">
@@ -53,12 +110,8 @@
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="扣分分值" prop="scoreDeduction">
<el-form-item v-if="isEditMode" label="扣分分值" prop="scoreDeduction">
<el-input-number v-model="form.scoreDeduction" :precision="2" placeholder="请输入扣分" style="width: 100%" />
<!-- 违纪类型参考范围提示 -->
<!-- <div v-if="form.disciplineTypeId" class="score-range-reference" style="font-size: 12px; color: #999; margin-top: 4px">
参考范围:{{ currentTypeMinScore }} - {{ currentTypeMaxScore }}分
</div> -->
</el-form-item>
</el-col>
</el-row>
@@ -186,7 +239,7 @@ interface Props {
// 组件事件
interface Emits {
(e: 'update:modelValue', value: boolean): void;
(e: 'confirm', data: any): void;
(e: 'confirm', data: any | any[]): void;
(e: 'close'): void;
}
@@ -207,6 +260,15 @@ const attachmentList = ref<any[]>([]);
// 所有违纪类型列表
const allViolationTypes = ref<any[]>([]);
interface ViolationItem {
disciplineTypeId: string | number;
disciplineTypeName: string;
scoreDeduction: number;
}
const selectedTypeIds = ref<Array<string | number>>([]);
const violationItems = ref<ViolationItem[]>([]);
// 当前选择的违纪类型扣分范围
const currentTypeMinScore = ref(0);
const currentTypeMaxScore = ref(100);
@@ -236,8 +298,7 @@ const form = reactive({
const rules = reactive({
disciplineTypeId: [{ required: true, message: '请选择违纪类型', trigger: 'change' }],
disciplineDate: [{ required: true, message: '请选择违纪日期', trigger: 'change' }],
scoreDeduction: [{ required: true, message: '请输入扣分分值', trigger: 'blur' }],
disciplineReason: [{ required: true, message: '请输入违纪原因', trigger: 'blur' }]
scoreDeduction: [{ required: true, message: '请输入扣分分值', trigger: 'blur' }]
});
// 计算属性
@@ -248,6 +309,13 @@ const dialogVisible = computed({
const dialogTitle = computed(() => props.title);
const isEditMode = computed(() => !!props.violationData);
const violationItemsTotalScore = computed(() => {
const sum = violationItems.value.reduce((acc, item) => acc + (Number(item.scoreDeduction) || 0), 0);
return Number(sum.toFixed(2));
});
// 上传配置
const uploadAction = computed(() => {
return import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';
@@ -314,6 +382,67 @@ const getAllViolationTypes = async () => {
}
};
const getTypeOption = (typeId?: string | number) =>
allViolationTypes.value.find((item) => String(item.id) === String(typeId));
const parseScore = (value: unknown, fallback = 0) => {
if (value === null || value === undefined) return fallback;
return typeof value === 'number' ? value : parseFloat(String(value)) || fallback;
};
const getItemMinScore = (item: ViolationItem) => parseScore(getTypeOption(item.disciplineTypeId)?.minScore, 0);
const getItemMaxScore = (item: ViolationItem) => parseScore(getTypeOption(item.disciplineTypeId)?.maxScore, 100);
const getItemRemark = (typeId?: string | number) => getTypeOption(typeId)?.remark || '';
const handleTypeSelectionChange = (typeIds: Array<string | number>) => {
const currentMap = new Map(violationItems.value.map((item) => [String(item.disciplineTypeId), item]));
const nextItems: ViolationItem[] = [];
typeIds.forEach((typeId) => {
const option = getTypeOption(typeId);
if (!option) return;
const existing = currentMap.get(String(typeId));
nextItems.push({
disciplineTypeId: option.id,
disciplineTypeName: option.typeName,
scoreDeduction: existing?.scoreDeduction ?? parseScore(option.minScore, 0)
});
});
violationItems.value = nextItems;
};
const removeViolationItem = (index: number) => {
violationItems.value.splice(index, 1);
selectedTypeIds.value = violationItems.value.map((item) => item.disciplineTypeId);
};
const buildSharedViolationFields = () => {
const attachmentOssIds = attachmentList.value
.filter((file) => file.status === 'success' && file.ossId)
.map((file) => file.ossId)
.join(',');
return {
studentId: form.studentId,
studentNo: form.studentNo,
studentName: form.studentName,
collegeId: form.collegeId,
collegeName: form.collegeName,
majorId: form.majorId,
majorName: form.majorName,
classId: form.classId,
className: form.className,
disciplineDate: form.disciplineDate,
disciplineReason: form.disciplineReason,
disciplineContent: form.disciplineContent,
attachmentOssIds,
violationSource: form.violationSource || '1'
};
};
// 违纪类型变化处理
const handleDisciplineTypeChange = (typeId: string | number) => {
const selectedType = allViolationTypes.value.find((item) => item.id === typeId);
@@ -414,8 +543,9 @@ const initForm = () => {
}
} else {
console.log('违纪记录:新增模式,重置附件列表');
// 重置附件列表
attachmentList.value = [];
selectedTypeIds.value = [];
violationItems.value = [];
}
};
@@ -695,15 +825,49 @@ const handleDownloadAttachment = async (file: any) => {
// 确认提交
const handleConfirm = async () => {
try {
await violationFormRef.value?.validate();
buttonLoading.value = true;
// 处理附件数据
const attachmentOssIds = attachmentList.value.filter((file) => file.status === 'success' && file.ossId).map((file) => file.ossId);
form.attachmentOssIds = attachmentOssIds.join(',');
if (isEditMode.value) {
await violationFormRef.value?.validate();
const attachmentOssIds = attachmentList.value
.filter((file) => file.status === 'success' && file.ossId)
.map((file) => file.ossId);
form.attachmentOssIds = attachmentOssIds.join(',');
emit('confirm', { ...form });
return;
}
emit('confirm', { ...form });
if (!form.disciplineDate) {
ElMessage.warning('请选择违纪日期');
return;
}
if (violationItems.value.length === 0) {
ElMessage.warning('请至少选择一个违纪类型');
return;
}
for (const item of violationItems.value) {
const min = getItemMinScore(item);
const max = getItemMaxScore(item);
const score = Number(item.scoreDeduction);
if (Number.isNaN(score)) {
ElMessage.warning(`请填写「${item.disciplineTypeName}」的扣分分值`);
return;
}
if (score < min || score > max) {
ElMessage.warning(`「${item.disciplineTypeName}」扣分须在 ${min}-${max} 分之间`);
return;
}
}
const sharedFields = buildSharedViolationFields();
const records = violationItems.value.map((item) => ({
...sharedFields,
disciplineTypeId: item.disciplineTypeId,
disciplineTypeName: item.disciplineTypeName,
scoreDeduction: item.scoreDeduction
}));
emit('confirm', records);
} catch (error) {
console.error('提交失败:', error);
ElMessage.error('请检查表单填写是否完整');
@@ -729,6 +893,8 @@ const handleClose = () => {
attachmentList.value = [];
currentTypeMinScore.value = 0;
currentTypeMaxScore.value = 100;
selectedTypeIds.value = [];
violationItems.value = [];
};
// 重置表单
@@ -775,6 +941,8 @@ const resetForm = () => {
attachmentList.value = [];
currentTypeMinScore.value = 0;
currentTypeMaxScore.value = 100;
selectedTypeIds.value = [];
violationItems.value = [];
};
// 获取违纪类型说明
@@ -898,6 +1066,46 @@ onMounted(() => {
line-height: 1.4;
}
.violation-item-list {
margin: 0 0 16px 120px;
padding: 12px;
background: #f8f9fb;
border-radius: 8px;
}
.violation-item-row + .violation-item-row {
margin-top: 10px;
padding-top: 10px;
border-top: 1px dashed #e4e7ed;
}
.violation-item-main {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.violation-item-name {
min-width: 120px;
font-weight: 500;
color: #303133;
}
.violation-item-total {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #e4e7ed;
font-size: 13px;
color: #606266;
}
.inline-remark {
margin-left: 0;
padding-left: 0;
margin-top: 6px;
}
/* 区域标签样式 */
.area-tag {
display: inline-block;
@@ -0,0 +1,58 @@
/** 归一化性别值:0=男,1=女 */
export function normalizeGender(gender: unknown): string | undefined {
if (gender === null || gender === undefined || gender === '') {
return undefined;
}
const value = String(gender);
if (value === '0' || value === '男') {
return '0';
}
if (value === '1' || value === '女') {
return '1';
}
return value;
}
export function isMaleGender(gender: unknown): boolean {
return normalizeGender(gender) === '0';
}
export function isFemaleGender(gender: unknown): boolean {
return normalizeGender(gender) === '1';
}
/** 用房间在住学生信息补全缺失的性别 */
export function mergeGenderFromRoomStudents<T extends { studentId?: unknown; studentNo?: string; gender?: unknown }>(
students: T[],
roomStudents: Array<{ studentId?: unknown; studentNo?: string; gender?: unknown }>
): T[] {
if (!students.length || !roomStudents.length) {
return students;
}
const genderByStudentId = new Map<string, string>();
const genderByStudentNo = new Map<string, string>();
roomStudents.forEach((student) => {
const gender = normalizeGender(student.gender);
if (!gender) {
return;
}
if (student.studentId !== undefined && student.studentId !== null) {
genderByStudentId.set(String(student.studentId), gender);
}
if (student.studentNo) {
genderByStudentNo.set(student.studentNo, gender);
}
});
return students.map((student) => {
if (normalizeGender(student.gender)) {
return { ...student, gender: normalizeGender(student.gender) };
}
const gender =
(student.studentId !== undefined && student.studentId !== null
? genderByStudentId.get(String(student.studentId))
: undefined) || (student.studentNo ? genderByStudentNo.get(student.studentNo) : undefined);
return gender ? { ...student, gender } : student;
});
}
@@ -107,6 +107,7 @@
<el-table-column label="房间名称" align="center" prop="roomName" />
<el-table-column label="宿舍楼名称" align="center" prop="buildingName" />
<el-table-column label="校区名称" align="center" prop="campusName" />
<el-table-column label="扣分项" align="center" prop="disciplineTypeName" min-width="160" show-overflow-tooltip />
<el-table-column label="宿舍扣分" align="center" prop="totalScore">
<template #default="scope">
<span>-{{ scope.row.totalScore }}</span>
@@ -163,6 +164,7 @@
<!-- 编辑宿舍卫生检查弹窗组件(修改使用) -->
<DormHygieneCheckEditDialog
:key="editDialogKey"
:visible="editDialog.visible"
:title="editDialog.title"
:form-data="currentEditData"
@@ -186,7 +188,8 @@ import {
delDormHygieneCheck,
addDormHygieneCheck,
updateDormHygieneCheck,
exportDormHygieneCheck
exportDormHygieneCheck,
getViolationsByCheckId
} from '@/api/xg/xgss/dormHygieneCheck/dormHygieneCheck/index';
import {
DormHygieneCheckVO,
@@ -196,6 +199,7 @@ import {
} from '@/api/xg/xgss/dormHygieneCheck/dormHygieneCheck/types';
import DormHygieneCheckMainDialog from './DormHygieneCheckMainDialog.vue';
import DormHygieneCheckEditDialog from './DormHygieneCheckEditDialog.vue';
import { normalizeId } from './studentIdUtils';
// 类型定义
interface DialogOption {
@@ -238,6 +242,7 @@ const editDialog = reactive<DialogOption>({
// 存储当前编辑的数据
const currentEditData = ref<any>(null);
const editDialogKey = ref(0);
const initFormData: DormHygieneCheckForm = {
id: undefined,
@@ -311,7 +316,10 @@ const getList = async () => {
loading.value = true;
try {
const res = await listDormHygieneCheck(queryParams.value);
dormHygieneCheckList.value = res.rows;
dormHygieneCheckList.value = (res.rows || []).map((row: DormHygieneCheckVO) => ({
...row,
id: row.id != null ? normalizeId(row.id) : row.id
}));
total.value = res.total;
} catch (error) {
console.error('查询列表失败:', error);
@@ -407,7 +415,6 @@ const handleAdd = () => {
/** 修改按钮操作 */
const handleUpdate = async (row?: DormHygieneCheckVO) => {
editDialog.visible = true;
editDialog.title = '修改宿舍卫生检查';
const loadingInstance = ElLoading.service({
@@ -417,9 +424,15 @@ const handleUpdate = async (row?: DormHygieneCheckVO) => {
});
try {
const _id = row?.id || ids.value[0];
const res = await getDormHygieneCheck(_id);
currentEditData.value = res.data;
const _id = normalizeId(row?.id || ids.value[0]);
const [res, violationsRes] = await Promise.all([getDormHygieneCheck(_id), getViolationsByCheckId(_id)]);
currentEditData.value = {
...res.data,
id: res.data?.id != null ? normalizeId(res.data.id) : res.data?.id,
_prefetchedViolations: violationsRes.data || []
};
editDialogKey.value += 1;
editDialog.visible = true;
} catch (error) {
console.error('加载编辑数据失败:', error);
ElMessage.error('加载数据失败,请重试');
@@ -0,0 +1,10 @@
/** 雪花ID统一转字符串,避免 JS Number 精度丢失导致 Map/接口匹配失败 */
export function normalizeStudentId(studentId: unknown): string {
if (studentId === null || studentId === undefined || studentId === '') {
return '';
}
return String(studentId);
}
/** 通用雪花ID归一化(检查ID、学生ID等) */
export const normalizeId = normalizeStudentId;
@@ -0,0 +1,7 @@
/** 计算学生有效违纪记录的扣分合计(已撤销 status=2 不计入) */
export function calcStudentViolationScoreTotal(violations: any[] | undefined | null): number {
const total = (violations || [])
.filter((item) => item?.status !== '2')
.reduce((sum, item) => sum + (parseFloat(String(item?.scoreDeduction ?? 0)) || 0), 0);
return parseFloat(total.toFixed(2));
}