forked from wangziqi/gongxue-base
feat: complete remaining PRD tasks — RBAC nodes and staff split, schedule month view, auto-generate attendance from schedules, plus fix TypeORM name
This commit is contained in:
@@ -1,7 +1,8 @@
|
|||||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
||||||
import {
|
import {
|
||||||
Card, Button, Select, Modal, Form, Input, DatePicker, TimePicker,
|
Card, Button, Select, Modal, Form, Input, DatePicker, TimePicker,
|
||||||
Popconfirm, message, Space, Spin, Empty, Tag, Tooltip,
|
Popconfirm, message, Space, Spin, Empty, Tag, Tooltip, Segmented,
|
||||||
|
Badge,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import {
|
import {
|
||||||
CalendarOutlined,
|
CalendarOutlined,
|
||||||
@@ -61,8 +62,12 @@ const WEEKDAY_NUMBERS = [1, 2, 3, 4, 5, 6, 7];
|
|||||||
// ---- Component ----
|
// ---- Component ----
|
||||||
|
|
||||||
const SchedulesPage: React.FC = () => {
|
const SchedulesPage: React.FC = () => {
|
||||||
// Week navigation
|
// View mode and navigation
|
||||||
const [weekStart, setWeekStart] = useState<Dayjs>(() => dayjs().weekday(1).startOf('day'));
|
const [viewMode, setViewMode] = useState<'week' | 'month'>('week');
|
||||||
|
const [viewDate, setViewDate] = useState<Dayjs>(() => dayjs().weekday(1).startOf('day'));
|
||||||
|
|
||||||
|
// Modal date selection (month view)
|
||||||
|
const [selectedDate, setSelectedDate] = useState<Dayjs | null>(null);
|
||||||
|
|
||||||
// Data
|
// Data
|
||||||
const [classrooms, setClassrooms] = useState<ClassroomItem[]>([]);
|
const [classrooms, setClassrooms] = useState<ClassroomItem[]>([]);
|
||||||
@@ -85,12 +90,48 @@ const SchedulesPage: React.FC = () => {
|
|||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [form] = Form.useForm<ScheduleFormValues>();
|
const [form] = Form.useForm<ScheduleFormValues>();
|
||||||
|
|
||||||
// Derived week info
|
// Derived week/month info
|
||||||
|
const weekStart = useMemo(() => viewDate.weekday(1).startOf('day'), [viewDate]);
|
||||||
|
const monthStart = useMemo(() => viewDate.startOf('month'), [viewDate]);
|
||||||
const weekEnd = useMemo(() => weekStart.add(6, 'day'), [weekStart]);
|
const weekEnd = useMemo(() => weekStart.add(6, 'day'), [weekStart]);
|
||||||
const weekNum = useMemo(() => weekStart.week(), [weekStart]);
|
const weekNum = useMemo(() => weekStart.week(), [weekStart]);
|
||||||
const weekYear = useMemo(() => weekStart.year(), [weekStart]);
|
const weekYear = useMemo(() => weekStart.year(), [weekStart]);
|
||||||
const startDateStr = useMemo(() => weekStart.format('YYYY-MM-DD'), [weekStart]);
|
const calendarDays = useMemo(() => {
|
||||||
const endDateStr = useMemo(() => weekEnd.format('YYYY-MM-DD'), [weekEnd]);
|
const monthEnd = monthStart.endOf('month');
|
||||||
|
const startOffset = (monthStart.day() + 6) % 7;
|
||||||
|
const endOffset = (7 - monthEnd.day()) % 7;
|
||||||
|
const start = monthStart.subtract(startOffset, 'day');
|
||||||
|
const end = monthEnd.add(endOffset, 'day');
|
||||||
|
const totalDays = end.diff(start, 'day') + 1;
|
||||||
|
const days: Dayjs[] = [];
|
||||||
|
for (let i = 0; i < totalDays; i++) {
|
||||||
|
days.push(start.add(i, 'day'));
|
||||||
|
}
|
||||||
|
return days;
|
||||||
|
}, [monthStart]);
|
||||||
|
|
||||||
|
const weeks = useMemo(() => {
|
||||||
|
const result: Dayjs[][] = [];
|
||||||
|
for (let i = 0; i < calendarDays.length; i += 7) {
|
||||||
|
result.push(calendarDays.slice(i, i + 7));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}, [calendarDays]);
|
||||||
|
|
||||||
|
const startDateStr = useMemo(() => {
|
||||||
|
if (viewMode === 'month') {
|
||||||
|
return calendarDays[0].format('YYYY-MM-DD');
|
||||||
|
}
|
||||||
|
return weekStart.format('YYYY-MM-DD');
|
||||||
|
}, [viewMode, weekStart, calendarDays]);
|
||||||
|
|
||||||
|
const endDateStr = useMemo(() => {
|
||||||
|
if (viewMode === 'month') {
|
||||||
|
return calendarDays[calendarDays.length - 1].format('YYYY-MM-DD');
|
||||||
|
}
|
||||||
|
return weekEnd.format('YYYY-MM-DD');
|
||||||
|
}, [viewMode, weekEnd, calendarDays]);
|
||||||
|
|
||||||
|
|
||||||
// ---- Data fetching ----
|
// ---- Data fetching ----
|
||||||
|
|
||||||
@@ -159,10 +200,30 @@ const SchedulesPage: React.FC = () => {
|
|||||||
return filtered;
|
return filtered;
|
||||||
}, [matrix, filterClassId]);
|
}, [matrix, filterClassId]);
|
||||||
|
|
||||||
|
const monthScheduleMap = useMemo(() => {
|
||||||
|
const map: Record<string, ClassScheduleItem[]> = {};
|
||||||
|
for (const day of calendarDays) {
|
||||||
|
const wd = day.day() === 0 ? 7 : day.day();
|
||||||
|
const dateStr = day.format('YYYY-MM-DD');
|
||||||
|
const result: ClassScheduleItem[] = [];
|
||||||
|
for (const classroom of filteredClassrooms) {
|
||||||
|
const daySchedules = displayMatrix[classroom.id]?.[wd] || [];
|
||||||
|
for (const s of daySchedules) {
|
||||||
|
if (dateStr >= s.startDate && dateStr <= s.endDate) {
|
||||||
|
result.push(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
map[dateStr] = result;
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [calendarDays, displayMatrix, filteredClassrooms]);
|
||||||
|
|
||||||
// ---- Cell click handlers ----
|
// ---- Cell click handlers ----
|
||||||
const handleCellClick = (classroomId: number, weekDay: number) => {
|
const handleCellClick = (classroomId: number, weekDay: number) => {
|
||||||
const schedules = displayMatrix[classroomId]?.[weekDay] || [];
|
const schedules = displayMatrix[classroomId]?.[weekDay] || [];
|
||||||
setSelectedCell({ classroomId, weekDay });
|
setSelectedCell({ classroomId, weekDay });
|
||||||
|
setSelectedDate(null);
|
||||||
|
|
||||||
if (schedules.length > 0) {
|
if (schedules.length > 0) {
|
||||||
setSelectedSchedules(schedules);
|
setSelectedSchedules(schedules);
|
||||||
@@ -175,6 +236,31 @@ const SchedulesPage: React.FC = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getSchedulesForDate = (date: Dayjs): ClassScheduleItem[] => {
|
||||||
|
const wd = date.day() === 0 ? 7 : date.day();
|
||||||
|
const dateStr = date.format('YYYY-MM-DD');
|
||||||
|
const result: ClassScheduleItem[] = [];
|
||||||
|
for (const classroom of filteredClassrooms) {
|
||||||
|
const daySchedules = displayMatrix[classroom.id]?.[wd] || [];
|
||||||
|
for (const s of daySchedules) {
|
||||||
|
if (dateStr >= s.startDate && dateStr <= s.endDate) {
|
||||||
|
result.push(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDateClick = (date: Dayjs) => {
|
||||||
|
const dateKey = date.format('YYYY-MM-DD');
|
||||||
|
const schedules = monthScheduleMap[dateKey] || getSchedulesForDate(date);
|
||||||
|
setSelectedDate(date);
|
||||||
|
setSelectedCell(null);
|
||||||
|
setSelectedSchedules(schedules);
|
||||||
|
setModalMode('detail');
|
||||||
|
setModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
// ---- Create schedule ----
|
// ---- Create schedule ----
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
@@ -214,14 +300,12 @@ const SchedulesPage: React.FC = () => {
|
|||||||
try {
|
try {
|
||||||
await api.delete(`/class-schedules/${id}`);
|
await api.delete(`/class-schedules/${id}`);
|
||||||
message.success('排课已删除');
|
message.success('排课已删除');
|
||||||
// Refresh the cell's schedules
|
// Refresh the displayed schedules
|
||||||
if (selectedCell) {
|
|
||||||
const remaining = selectedSchedules.filter((s) => s.id !== id);
|
const remaining = selectedSchedules.filter((s) => s.id !== id);
|
||||||
setSelectedSchedules(remaining);
|
setSelectedSchedules(remaining);
|
||||||
if (remaining.length === 0) {
|
if (remaining.length === 0) {
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
fetchData();
|
fetchData();
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const err = e as { message?: string };
|
const err = e as { message?: string };
|
||||||
@@ -273,9 +357,22 @@ const SchedulesPage: React.FC = () => {
|
|||||||
<h3 style={{ margin: 0 }}>排课管理</h3>
|
<h3 style={{ margin: 0 }}>排课管理</h3>
|
||||||
</Space>
|
</Space>
|
||||||
<Space>
|
<Space>
|
||||||
|
<Segmented
|
||||||
|
value={viewMode}
|
||||||
|
onChange={(v) => {
|
||||||
|
setViewMode(v as 'week' | 'month');
|
||||||
|
setSelectedDate(null);
|
||||||
|
}}
|
||||||
|
options={[
|
||||||
|
{ label: '周视图', value: 'week' },
|
||||||
|
{ label: '月视图', value: 'month' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
{viewMode === 'week' ? (
|
||||||
|
<>
|
||||||
<Button
|
<Button
|
||||||
icon={<LeftOutlined />}
|
icon={<LeftOutlined />}
|
||||||
onClick={() => setWeekStart(weekStart.subtract(7, 'day'))}
|
onClick={() => setViewDate(viewDate.subtract(7, 'day'))}
|
||||||
>
|
>
|
||||||
上一周
|
上一周
|
||||||
</Button>
|
</Button>
|
||||||
@@ -287,10 +384,30 @@ const SchedulesPage: React.FC = () => {
|
|||||||
</span>
|
</span>
|
||||||
<Button
|
<Button
|
||||||
icon={<RightOutlined />}
|
icon={<RightOutlined />}
|
||||||
onClick={() => setWeekStart(weekStart.add(7, 'day'))}
|
onClick={() => setViewDate(viewDate.add(7, 'day'))}
|
||||||
>
|
>
|
||||||
下一周
|
下一周
|
||||||
</Button>
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
icon={<LeftOutlined />}
|
||||||
|
onClick={() => setViewDate(viewDate.subtract(1, 'month'))}
|
||||||
|
>
|
||||||
|
上一月
|
||||||
|
</Button>
|
||||||
|
<span style={{ fontWeight: 500, fontSize: 15 }}>
|
||||||
|
{monthStart.format('YYYY年 M月')}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
icon={<RightOutlined />}
|
||||||
|
onClick={() => setViewDate(viewDate.add(1, 'month'))}
|
||||||
|
>
|
||||||
|
下一月
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -322,7 +439,7 @@ const SchedulesPage: React.FC = () => {
|
|||||||
<Spin spinning={loading}>
|
<Spin spinning={loading}>
|
||||||
{classrooms.length === 0 ? (
|
{classrooms.length === 0 ? (
|
||||||
<Empty description="暂无教室数据" />
|
<Empty description="暂无教室数据" />
|
||||||
) : (
|
) : (viewMode === 'week' ? (
|
||||||
<div style={{ overflowX: 'auto' }}>
|
<div style={{ overflowX: 'auto' }}>
|
||||||
<table
|
<table
|
||||||
style={{
|
style={{
|
||||||
@@ -455,7 +572,88 @@ const SchedulesPage: React.FC = () => {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ overflowX: 'auto' }}>
|
||||||
|
<table
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
borderCollapse: 'collapse',
|
||||||
|
fontSize: 13,
|
||||||
|
tableLayout: 'fixed',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<thead>
|
||||||
|
<tr style={{ background: '#fafafa' }}>
|
||||||
|
{['周一', '周二', '周三', '周四', '周五', '周六', '周日'].map((d) => (
|
||||||
|
<th
|
||||||
|
key={d}
|
||||||
|
style={{
|
||||||
|
padding: '10px 8px',
|
||||||
|
border: '1px solid #f0f0f0',
|
||||||
|
textAlign: 'center',
|
||||||
|
fontWeight: 500,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{d}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{weeks.map((week, wi) => (
|
||||||
|
<tr key={wi}>
|
||||||
|
{week.map((day, di) => {
|
||||||
|
const isCurrentMonth = day.month() === monthStart.month();
|
||||||
|
const dateKey = day.format('YYYY-MM-DD');
|
||||||
|
const daySchedules = monthScheduleMap[dateKey] || [];
|
||||||
|
const count = daySchedules.length;
|
||||||
|
return (
|
||||||
|
<td
|
||||||
|
key={di}
|
||||||
|
onClick={() => handleDateClick(day)}
|
||||||
|
style={{
|
||||||
|
padding: '6px 8px',
|
||||||
|
border: '1px solid #f0f0f0',
|
||||||
|
verticalAlign: 'top',
|
||||||
|
cursor: 'pointer',
|
||||||
|
height: 90,
|
||||||
|
background: isCurrentMonth ? '#fff' : '#fafafa',
|
||||||
|
transition: 'background 0.15s',
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => {
|
||||||
|
(e.currentTarget as HTMLElement).style.background = isCurrentMonth ? '#f0f5ff' : '#f0f0f0';
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
(e.currentTarget as HTMLElement).style.background = isCurrentMonth ? '' : '#fafafa';
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
fontWeight: isCurrentMonth ? 600 : 400,
|
||||||
|
color: isCurrentMonth ? '#262626' : '#bfbfbf',
|
||||||
|
fontSize: 14,
|
||||||
|
marginBottom: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{day.date()}
|
||||||
|
</div>
|
||||||
|
{count > 0 && (
|
||||||
|
<Badge
|
||||||
|
count={count}
|
||||||
|
size="small"
|
||||||
|
overflowCount={99}
|
||||||
|
style={{ backgroundColor: '#1677ff' }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</Spin>
|
</Spin>
|
||||||
|
|
||||||
{/* Modal */}
|
{/* Modal */}
|
||||||
@@ -463,6 +661,8 @@ const SchedulesPage: React.FC = () => {
|
|||||||
title={
|
title={
|
||||||
modalMode === 'create'
|
modalMode === 'create'
|
||||||
? `新增排课 — ${selectedClassroom?.name || ''} · ${selectedCell ? WEEKDAYS[selectedCell.weekDay - 1] : ''}`
|
? `新增排课 — ${selectedClassroom?.name || ''} · ${selectedCell ? WEEKDAYS[selectedCell.weekDay - 1] : ''}`
|
||||||
|
: selectedDate
|
||||||
|
? `排课详情 — ${selectedDate.format('YYYY-MM-DD')} ${WEEKDAYS[selectedDate.day() === 0 ? 6 : selectedDate.day() - 1]}`
|
||||||
: `排课详情 — ${selectedClassroom?.name || ''} · ${selectedCell ? WEEKDAYS[selectedCell.weekDay - 1] : ''}`
|
: `排课详情 — ${selectedClassroom?.name || ''} · ${selectedCell ? WEEKDAYS[selectedCell.weekDay - 1] : ''}`
|
||||||
}
|
}
|
||||||
open={modalOpen}
|
open={modalOpen}
|
||||||
|
|||||||
@@ -442,8 +442,8 @@ ${this.buildLearningAndResult(learnings, result, now)}
|
|||||||
const sortedExams = [...cultureExams].filter((e) => e.score != null);
|
const sortedExams = [...cultureExams].filter((e) => e.score != null);
|
||||||
let improvement = '—';
|
let improvement = '—';
|
||||||
if (sortedExams.length >= 2) {
|
if (sortedExams.length >= 2) {
|
||||||
const first = sortedExams[0].score!;
|
const first = sortedExams[0].score;
|
||||||
const last = sortedExams[sortedExams.length - 1].score!;
|
const last = sortedExams[sortedExams.length - 1].score;
|
||||||
improvement = (last - first).toFixed(1);
|
improvement = (last - first).toFixed(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,7 +538,7 @@ ${this.buildLearningAndResult(learnings, result, now)}
|
|||||||
const cultureExams = exams.filter((e) => e.score != null);
|
const cultureExams = exams.filter((e) => e.score != null);
|
||||||
if (cultureExams.length === 0) return '';
|
if (cultureExams.length === 0) return '';
|
||||||
|
|
||||||
const scores = cultureExams.map((e) => e.score!);
|
const scores = cultureExams.map((e) => e.score);
|
||||||
const labels = cultureExams.map((e) => {
|
const labels = cultureExams.map((e) => {
|
||||||
const d = e.examDate || '-';
|
const d = e.examDate || '-';
|
||||||
return d.length > 7 ? d.slice(5) : d;
|
return d.length > 7 ? d.slice(5) : d;
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
MatchDingRecordDto,
|
MatchDingRecordDto,
|
||||||
AttendanceReportQueryDto,
|
AttendanceReportQueryDto,
|
||||||
UpdateAttendanceRecordDto,
|
UpdateAttendanceRecordDto,
|
||||||
|
GenerateFromSchedulesDto,
|
||||||
} from './dto/attendance.dto';
|
} from './dto/attendance.dto';
|
||||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||||
@@ -58,6 +59,28 @@ export class AttendanceController {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Generate attendance records from schedules (with optional date range) ──
|
||||||
|
@Post('attendance-records/generate-from-schedules')
|
||||||
|
@RequirePermission('attendance:create')
|
||||||
|
async generateFromSchedules(
|
||||||
|
@Body() dto: GenerateFromSchedulesDto,
|
||||||
|
@Request() req: any,
|
||||||
|
) {
|
||||||
|
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||||
|
const result = await this.service.generateFromSchedules(dto);
|
||||||
|
await this.logService.log({
|
||||||
|
userId: req.user?.id,
|
||||||
|
username: req.user?.username,
|
||||||
|
module: '考勤管理',
|
||||||
|
action: '按课表生成考勤',
|
||||||
|
detail: `班级 ${dto.classId}, 共 ${result.count} 条`,
|
||||||
|
ipAddress,
|
||||||
|
userAgent,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// ── Export attendance records ──
|
// ── Export attendance records ──
|
||||||
@Get('attendance-records/export')
|
@Get('attendance-records/export')
|
||||||
@RequirePermission('attendance:export')
|
@RequirePermission('attendance:export')
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { AttendanceRecord, DingAttendanceRaw, Student, Class } from '../entities';
|
import { AttendanceRecord, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent } from '../entities';
|
||||||
import { AttendanceService } from './attendance.service';
|
import { AttendanceService } from './attendance.service';
|
||||||
import { AttendanceController } from './attendance.controller';
|
import { AttendanceController } from './attendance.controller';
|
||||||
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
|
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
|
||||||
import { CommonModule } from '../common/common.module';
|
import { CommonModule } from '../common/common.module';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
TypeOrmModule.forFeature([AttendanceRecord, DingAttendanceRaw, Student, Class]),
|
TypeOrmModule.forFeature([AttendanceRecord, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent]),
|
||||||
OperationLogsModule,
|
OperationLogsModule,
|
||||||
CommonModule,
|
CommonModule,
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ describe('AttendanceService — batchCreate', () => {
|
|||||||
save: jest
|
save: jest
|
||||||
.fn()
|
.fn()
|
||||||
.mockImplementation((entities: AttendanceRecord[]) => {
|
.mockImplementation((entities: AttendanceRecord[]) => {
|
||||||
const result = entities.map((e, i) => ({ ...e, id: i + 1 } as AttendanceRecord));
|
const result = entities.map((e, i) => ({ ...e, id: i + 1 }));
|
||||||
savedRecords.push(...result);
|
savedRecords.push(...result);
|
||||||
return Promise.resolve(result);
|
return Promise.resolve(result);
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import {
|
|||||||
BadRequestException,
|
BadRequestException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Repository, In, Between } from 'typeorm';
|
import { Repository, In, Between, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
|
||||||
import { AttendanceRecord, DingAttendanceRaw, Class, Student } from '../entities';
|
import { AttendanceRecord, DingAttendanceRaw, Class, Student, ClassSchedule, ClassStudent, ScheduleType } from '../entities';
|
||||||
import { CampusScope } from '../common/campus-scope';
|
import { CampusScope } from '../common/campus-scope';
|
||||||
import {
|
import {
|
||||||
BatchCreateAttendanceDto,
|
BatchCreateAttendanceDto,
|
||||||
@@ -15,6 +15,8 @@ import {
|
|||||||
MatchDingRecordDto,
|
MatchDingRecordDto,
|
||||||
AttendanceReportQueryDto,
|
AttendanceReportQueryDto,
|
||||||
UpdateAttendanceRecordDto,
|
UpdateAttendanceRecordDto,
|
||||||
|
GenerateAttendanceFromSchedulesDto,
|
||||||
|
GenerateFromSchedulesDto,
|
||||||
} from './dto/attendance.dto';
|
} from './dto/attendance.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -28,6 +30,10 @@ export class AttendanceService {
|
|||||||
private classRepo: Repository<Class>,
|
private classRepo: Repository<Class>,
|
||||||
@InjectRepository(Student)
|
@InjectRepository(Student)
|
||||||
private studentRepo: Repository<Student>,
|
private studentRepo: Repository<Student>,
|
||||||
|
@InjectRepository(ClassSchedule)
|
||||||
|
private scheduleRepo: Repository<ClassSchedule>,
|
||||||
|
@InjectRepository(ClassStudent)
|
||||||
|
private classStudentRepo: Repository<ClassStudent>,
|
||||||
private readonly scope: CampusScope,
|
private readonly scope: CampusScope,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -60,6 +66,114 @@ export class AttendanceService {
|
|||||||
return { count: saved.length, records: saved };
|
return { count: saved.length, records: saved };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Generate attendance records from class schedules ──
|
||||||
|
async generateAttendanceFromSchedules(dto: GenerateAttendanceFromSchedulesDto) {
|
||||||
|
const { classId, dateFrom, dateTo } = dto;
|
||||||
|
|
||||||
|
if (dateFrom > dateTo) {
|
||||||
|
throw new BadRequestException('dateFrom must not be later than dateTo');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cls = await this.classRepo.findOne({ where: { id: classId } });
|
||||||
|
if (!cls) {
|
||||||
|
throw new NotFoundException(`Class ${classId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const schedules = await this.scheduleRepo.find({
|
||||||
|
where: {
|
||||||
|
classId,
|
||||||
|
scheduleType: ScheduleType.INTERNAL,
|
||||||
|
status: 'active',
|
||||||
|
startDate: LessThanOrEqual(dateTo),
|
||||||
|
endDate: MoreThanOrEqual(dateFrom),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const classStudents = await this.classStudentRepo.find({
|
||||||
|
where: { classId, status: 'active' },
|
||||||
|
relations: ['student'],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (schedules.length === 0 || classStudents.length === 0) {
|
||||||
|
return { count: 0, records: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingRecords = await this.attendanceRepo.find({
|
||||||
|
where: { classId, attendanceDate: Between(dateFrom, dateTo) },
|
||||||
|
});
|
||||||
|
const existingKeys = new Set(
|
||||||
|
existingRecords.map((r) => `${r.studentId}|${r.attendanceDate}|${r.session}`),
|
||||||
|
);
|
||||||
|
|
||||||
|
const entities: AttendanceRecord[] = [];
|
||||||
|
const end = new Date(dateTo);
|
||||||
|
for (let d = new Date(dateFrom); d <= end; d.setDate(d.getDate() + 1)) {
|
||||||
|
const dateStr = d.toISOString().slice(0, 10);
|
||||||
|
const weekDay = d.getDay() === 0 ? 7 : d.getDay();
|
||||||
|
|
||||||
|
for (const sched of schedules) {
|
||||||
|
if (sched.weekDay !== weekDay) continue;
|
||||||
|
if (dateStr < sched.startDate || dateStr > sched.endDate) continue;
|
||||||
|
|
||||||
|
const session = this.mapScheduleTimeToSession(sched.startTime);
|
||||||
|
for (const cs of classStudents) {
|
||||||
|
const key = `${cs.studentId}|${dateStr}|${session}`;
|
||||||
|
if (existingKeys.has(key)) continue;
|
||||||
|
|
||||||
|
const entity = this.attendanceRepo.create({
|
||||||
|
studentId: cs.studentId,
|
||||||
|
classId,
|
||||||
|
attendanceDate: dateStr,
|
||||||
|
session,
|
||||||
|
status: 'pending',
|
||||||
|
source: 'schedule',
|
||||||
|
});
|
||||||
|
entity.departmentId = cs.student?.departmentId ?? cls.departmentId ?? undefined;
|
||||||
|
entities.push(entity);
|
||||||
|
existingKeys.add(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const saved = await this.attendanceRepo.save(entities);
|
||||||
|
return { count: saved.length, records: saved };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Generate attendance records from schedules (optional date range, defaults to current week) ──
|
||||||
|
async generateFromSchedules(dto: GenerateFromSchedulesDto): Promise<{ count: number; records: AttendanceRecord[] }> {
|
||||||
|
const { classId, startDate, endDate } = dto;
|
||||||
|
|
||||||
|
// Default to current week (Monday–Sunday)
|
||||||
|
const now = new Date();
|
||||||
|
const dayOfWeek = now.getDay();
|
||||||
|
const mondayOffset = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
|
||||||
|
const monday = new Date(now);
|
||||||
|
monday.setDate(now.getDate() + mondayOffset);
|
||||||
|
monday.setHours(0, 0, 0, 0);
|
||||||
|
const sunday = new Date(monday);
|
||||||
|
sunday.setDate(monday.getDate() + 6);
|
||||||
|
sunday.setHours(23, 59, 59, 999);
|
||||||
|
|
||||||
|
const dateFrom = startDate ?? monday.toISOString().slice(0, 10);
|
||||||
|
const dateTo = endDate ?? sunday.toISOString().slice(0, 10);
|
||||||
|
|
||||||
|
return this.generateAttendanceFromSchedules({
|
||||||
|
classId,
|
||||||
|
dateFrom,
|
||||||
|
dateTo,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private mapScheduleTimeToSession(startTime: string): string {
|
||||||
|
const hour = parseInt(startTime.slice(0, 2), 10);
|
||||||
|
if (hour < 8) return 'morning_reading';
|
||||||
|
if (hour < 12) return 'morning';
|
||||||
|
if (hour < 17) return 'afternoon';
|
||||||
|
if (hour < 20) return 'evening_study';
|
||||||
|
return 'night_check';
|
||||||
|
}
|
||||||
|
|
||||||
// ── Attendance summary ──
|
// ── Attendance summary ──
|
||||||
async getSummary(query: AttendanceSummaryQueryDto) {
|
async getSummary(query: AttendanceSummaryQueryDto) {
|
||||||
const qb = this.attendanceRepo.createQueryBuilder('ar');
|
const qb = this.attendanceRepo.createQueryBuilder('ar');
|
||||||
|
|||||||
@@ -151,3 +151,33 @@ export class AttendanceReportQueryDto {
|
|||||||
@IsDateString()
|
@IsDateString()
|
||||||
dateTo?: string;
|
dateTo?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class GenerateAttendanceFromSchedulesDto {
|
||||||
|
@IsInt()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsNotEmpty()
|
||||||
|
classId: number;
|
||||||
|
|
||||||
|
@IsDateString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
dateFrom: string;
|
||||||
|
|
||||||
|
@IsDateString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
dateTo: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GenerateFromSchedulesDto {
|
||||||
|
@IsInt()
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsNotEmpty()
|
||||||
|
classId: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
startDate?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
endDate?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -47,12 +47,12 @@ export class CampusScope {
|
|||||||
if (ids.length === 0) {
|
if (ids.length === 0) {
|
||||||
// Non-super-admin with no scoping → match nothing, never leak unfiltered data
|
// Non-super-admin with no scoping → match nothing, never leak unfiltered data
|
||||||
if (!this.isSuperAdmin) {
|
if (!this.isSuperAdmin) {
|
||||||
return { ...where, departmentId: In([]) } as unknown as T;
|
return { ...where, departmentId: In([]) };
|
||||||
}
|
}
|
||||||
return where;
|
return where;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { ...where, departmentId: In(ids) } as unknown as T;
|
return { ...where, departmentId: In(ids) };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns department IDs for QueryBuilder .andWhere() usage. null = no filtering needed. */
|
/** Returns department IDs for QueryBuilder .andWhere() usage. null = no filtering needed. */
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ export class DingTalkService {
|
|||||||
name: dd.name,
|
name: dd.name,
|
||||||
source: 'dingtalk',
|
source: 'dingtalk',
|
||||||
sourceId,
|
sourceId,
|
||||||
parentSourceId: (dd.parent_id ? String(dd.parent_id) : undefined) as any,
|
parentSourceId: (dd.parent_id ? String(dd.parent_id) : undefined),
|
||||||
type: 'department',
|
type: 'department',
|
||||||
});
|
});
|
||||||
deptCount++;
|
deptCount++;
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ export class WeComService {
|
|||||||
name: wd.name,
|
name: wd.name,
|
||||||
source: 'wecom',
|
source: 'wecom',
|
||||||
sourceId,
|
sourceId,
|
||||||
parentSourceId: (wd.parentid ? String(wd.parentid) : undefined) as any,
|
parentSourceId: (wd.parentid ? String(wd.parentid) : undefined),
|
||||||
type: 'department',
|
type: 'department',
|
||||||
});
|
});
|
||||||
deptCount++;
|
deptCount++;
|
||||||
|
|||||||
@@ -69,6 +69,17 @@ const PRESET_PERMISSIONS: Array<{ code: string; name: string; group: string }> =
|
|||||||
{ code: 'attendance:create', name: '新增考勤', group: 'attendance' },
|
{ code: 'attendance:create', name: '新增考勤', group: 'attendance' },
|
||||||
{ code: 'attendance:edit', name: '编辑考勤', group: 'attendance' },
|
{ code: 'attendance:edit', name: '编辑考勤', group: 'attendance' },
|
||||||
{ code: 'attendance:export', name: '导出考勤', group: 'attendance' },
|
{ code: 'attendance:export', name: '导出考勤', group: 'attendance' },
|
||||||
|
{ code: 'attendance:generate', name: '按课表生成考勤', group: 'attendance' },
|
||||||
|
{ code: 'learning:create', name: '创建学习任务', group: 'learning' },
|
||||||
|
{ code: 'learning:edit', name: '编辑学习任务', group: 'learning' },
|
||||||
|
{ code: 'learning:delete', name: '删除学习任务', group: 'learning' },
|
||||||
|
{ code: 'exam:create', name: '创建考试', group: 'exam' },
|
||||||
|
{ code: 'exam:edit', name: '编辑考试', group: 'exam' },
|
||||||
|
{ code: 'exam:delete', name: '删除考试', group: 'exam' },
|
||||||
|
{ code: 'sync:trigger', name: '触发数据同步', group: 'sync' },
|
||||||
|
{ code: 'sync:read', name: '查看同步状态', group: 'sync' },
|
||||||
|
{ code: 'integration:trigger', name: '触发集成', group: 'integration' },
|
||||||
|
{ code: 'integration:read', name: '查看集成状态', group: 'integration' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const PRESET_ROLES: Array<{
|
const PRESET_ROLES: Array<{
|
||||||
@@ -120,6 +131,27 @@ const PRESET_ROLES: Array<{
|
|||||||
isSystem: true,
|
isSystem: true,
|
||||||
permissionGroups: ['classroom', 'rental', 'tenant'],
|
permissionGroups: ['classroom', 'rental', 'tenant'],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: '财务',
|
||||||
|
code: 'finance',
|
||||||
|
description: '管理费用、账单与押金',
|
||||||
|
isSystem: true,
|
||||||
|
permissionGroups: ['expense', 'bill', 'deposit', 'dashboard'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '宿管',
|
||||||
|
code: 'dorm_manager',
|
||||||
|
description: '管理宿舍入住与宿舍信息',
|
||||||
|
isSystem: true,
|
||||||
|
permissionGroups: ['student', 'room', 'occupancy', 'dashboard'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '教务',
|
||||||
|
code: 'academic',
|
||||||
|
description: '管理班级、排课、考勤、学习与考试',
|
||||||
|
isSystem: true,
|
||||||
|
permissionGroups: ['class', 'schedule', 'attendance', 'classroom', 'learning', 'exam', 'dashboard'],
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
@@ -177,9 +177,9 @@ export class StudentsService {
|
|||||||
// Group attendance by class
|
// Group attendance by class
|
||||||
const attendanceByClass = new Map<number, AttendanceRecord[]>();
|
const attendanceByClass = new Map<number, AttendanceRecord[]>();
|
||||||
for (const r of attendanceRecords) {
|
for (const r of attendanceRecords) {
|
||||||
const list = attendanceByClass.get(r.classId!) || [];
|
const list = attendanceByClass.get(r.classId) || [];
|
||||||
list.push(r);
|
list.push(r);
|
||||||
attendanceByClass.set(r.classId!, list);
|
attendanceByClass.set(r.classId, list);
|
||||||
}
|
}
|
||||||
|
|
||||||
const comparison = enrollments.map((e) => {
|
const comparison = enrollments.map((e) => {
|
||||||
|
|||||||
Reference in New Issue
Block a user