fix(admin): complete occupancy check-in form payload #23

Merged
wangziqi merged 4 commits from codex/occupancy-checkin-form into main 2026-07-18 12:54:11 +00:00
64 changed files with 5169 additions and 2404 deletions

View File

@@ -24,7 +24,7 @@ const TeachersPage = lazy(() => import('./pages/Teachers'));
const StudentProfilePage = lazy(() => import('./pages/StudentProfile'));
const ClassesPage = lazy(() => import('./pages/Classes'));
const ClassDetailPage = lazy(() => import('./pages/Classes/detail'));
const OrganizationsPage = lazy(() => import('./pages/Organizations'))
const OrganizationsPage = lazy(() => import('./pages/Organizations'));
const ClassroomRentalsPage = lazy(() => import('./pages/ClassroomRentals'));
const ClassroomSchedulePage = lazy(() => import('./pages/ClassroomSchedule'));
const SchedulesPage = lazy(() => import('./pages/Schedules'));
@@ -59,254 +59,258 @@ const App: React.FC = () => {
<AntdApp>
<AppMessageBridge />
<BrowserRouter>
<Suspense fallback={<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}><Spin size="large" /></div>}>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="/"
element={
<PrivateRoute>
<MainLayout />
</PrivateRoute>
}
>
<Route index element={<DefaultRoute />} />
<Suspense
fallback={
<div style={{ minHeight: '40vh', display: 'grid', placeItems: 'center' }}>
<Spin size="large" />
</div>
}
>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="dashboard"
path="/"
element={
<PermissionRoute permission="dashboard:view">
<DashboardPage />
</PermissionRoute>
<PrivateRoute>
<MainLayout />
</PrivateRoute>
}
/>
<Route
path="room-visual"
element={
<PermissionRoute permission="room:view">
<RoomVisualPage />
</PermissionRoute>
}
/>
<Route
path="students"
element={
<PermissionRoute permission="student:view">
<StudentsPage />
</PermissionRoute>
}
/>
>
<Route index element={<DefaultRoute />} />
<Route
path="dashboard"
element={
<PermissionRoute permission="dashboard:view">
<DashboardPage />
</PermissionRoute>
}
/>
<Route
path="room-visual"
element={
<PermissionRoute permission="room:view">
<RoomVisualPage />
</PermissionRoute>
}
/>
<Route
path="students"
element={
<PermissionRoute permission="student:view">
<StudentsPage />
</PermissionRoute>
}
/>
<Route
path="students/:id/profile"
element={
<PermissionRoute permission="student:view">
<StudentProfilePage />
</PermissionRoute>
}
/>
<Route
path="rooms"
element={
<PermissionRoute permission="room:view">
<RoomsPage />
</PermissionRoute>
}
/>
<Route
path="occupancies"
element={
<PermissionRoute permission="occupancy:view">
<OccupanciesPage />
</PermissionRoute>
}
/>
<Route
path="expenses"
element={
<PermissionRoute permission="expense:view">
<ExpensesPage />
</PermissionRoute>
}
/>
<Route
path="deposits"
element={
<PermissionRoute permission="deposit:view">
<DepositsPage />
</PermissionRoute>
}
/>
<Route
path="wallets"
element={
<PermissionRoute permission="wallet:view">
<WalletsPage />
</PermissionRoute>
}
/>
<Route
path="bills"
element={
<PermissionRoute permission="bill:view">
<BillsPage />
</PermissionRoute>
}
/>
<Route
path="classes"
element={
<PermissionRoute permission="class:view">
<ClassesPage />
</PermissionRoute>
}
/>
<Route
path="classes/:id"
element={
<PermissionRoute permission="class:view">
<ClassDetailPage />
</PermissionRoute>
}
/>
<Route
path="operation-logs"
element={
<PermissionRoute permission="log:view">
<OperationLogsPage />
</PermissionRoute>
}
/>
<Route
path="roles"
element={
<PermissionRoute permission="role:view">
<RolesPage />
</PermissionRoute>
}
/>
<Route
path="permissions"
element={
<PermissionRoute permission="role:view">
<PermissionsPage />
</PermissionRoute>
}
/>
<Route
path="users"
element={
<PermissionRoute permission="user:view">
<UsersPage />
</PermissionRoute>
}
/>
<Route
path="teachers"
element={
<PermissionRoute permission="teacher:view">
<TeachersPage />
</PermissionRoute>
}
/>
<Route
path="classrooms"
element={
<PermissionRoute permission="classroom:view">
<ClassroomsPage />
</PermissionRoute>
}
/>
<Route
path="organizations"
element={
<PermissionRoute permission="organization:view">
<OrganizationsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-rentals"
element={
<PermissionRoute permission="rental:view">
<ClassroomRentalsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-schedule"
element={
<PermissionRoute permission="rental:view">
<ClassroomSchedulePage />
</PermissionRoute>
}
/>
<Route
path="students/:id/profile"
element={
<PermissionRoute permission="student:view">
<StudentProfilePage />
</PermissionRoute>
}
/>
<Route
path="rooms"
element={
<PermissionRoute permission="room:view">
<RoomsPage />
</PermissionRoute>
}
/>
<Route
path="occupancies"
element={
<PermissionRoute permission="occupancy:view">
<OccupanciesPage />
</PermissionRoute>
}
/>
<Route
path="expenses"
element={
<PermissionRoute permission="expense:view">
<ExpensesPage />
</PermissionRoute>
}
/>
<Route
path="deposits"
element={
<PermissionRoute permission="deposit:view">
<DepositsPage />
</PermissionRoute>
}
/>
<Route
path="wallets"
element={
<PermissionRoute permission="wallet:view">
<WalletsPage />
</PermissionRoute>
}
/>
<Route
path="bills"
element={
<PermissionRoute permission="bill:view">
<BillsPage />
</PermissionRoute>
}
/>
<Route
path="classes"
element={
<PermissionRoute permission="class:view">
<ClassesPage />
</PermissionRoute>
}
/>
<Route
path="classes/:id"
element={
<PermissionRoute permission="class:view">
<ClassDetailPage />
</PermissionRoute>
}
/>
<Route
path="operation-logs"
element={
<PermissionRoute permission="log:view">
<OperationLogsPage />
</PermissionRoute>
}
/>
<Route
path="roles"
element={
<PermissionRoute permission="role:view">
<RolesPage />
</PermissionRoute>
}
/>
<Route
path="permissions"
element={
<PermissionRoute permission="role:view">
<PermissionsPage />
</PermissionRoute>
}
/>
<Route
path="users"
element={
<PermissionRoute permission="user:view">
<UsersPage />
</PermissionRoute>
}
/>
<Route
path="teachers"
element={
<PermissionRoute permission="teacher:view">
<TeachersPage />
</PermissionRoute>
}
/>
<Route
path="classrooms"
element={
<PermissionRoute permission="classroom:view">
<ClassroomsPage />
</PermissionRoute>
}
/>
<Route
path="organizations"
element={
<PermissionRoute permission="organization:view">
<OrganizationsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-rentals"
element={
<PermissionRoute permission="rental:view">
<ClassroomRentalsPage />
</PermissionRoute>
}
/>
<Route
path="classroom-schedule"
element={
<PermissionRoute permission="rental:view">
<ClassroomSchedulePage />
</PermissionRoute>
}
/>
<Route
path="attendance-devices"
element={
<PermissionRoute permission="classroom:view">
<AttendanceDevicesPage />
</PermissionRoute>
}
/>
<Route
path="attendance-devices"
element={
<PermissionRoute permission="classroom:view">
<AttendanceDevicesPage />
</PermissionRoute>
}
/>
<Route
path="attendance"
element={
<PermissionRoute permission="attendance:view">
<AttendancePage />
</PermissionRoute>
}
/>
<Route
path="attendance"
element={
<PermissionRoute permission="attendance:view">
<AttendancePage />
</PermissionRoute>
}
/>
<Route
path="schedules"
element={
<PermissionRoute permission="schedule:view">
<SchedulesPage />
</PermissionRoute>
}
/>
<Route
path="schedules"
element={
<PermissionRoute permission="schedule:view">
<SchedulesPage />
</PermissionRoute>
}
/>
<Route
path="teacher-workspace"
element={
<PermissionRoute permission="teacher-workspace:view">
<TeacherWorkspacePage />
</PermissionRoute>
}
/>
<Route
path="teacher-workspace"
element={
<PermissionRoute permission="teacher-workspace:view">
<TeacherWorkspacePage />
</PermissionRoute>
}
/>
<Route
path="notifications"
element={
<PermissionRoute permission="notification:view">
<NotificationsPage />
</PermissionRoute>
}
/>
<Route
path="notifications"
element={
<PermissionRoute permission="notification:view">
<NotificationsPage />
</PermissionRoute>
}
/>
<Route
path="integration-config"
element={
<PermissionRoute permission="integration:read">
<IntegrationConfigPage />
</PermissionRoute>
}
/>
<Route
path="integration-config"
element={
<PermissionRoute permission="integration:read">
<IntegrationConfigPage />
</PermissionRoute>
}
/>
<Route
path="ai-config"
element={
<PermissionRoute permission="ai:config:read">
<AiConfigPage />
</PermissionRoute>
}
/>
</Route>
</Routes>
<Route
path="ai-config"
element={
<PermissionRoute permission="ai:config:read">
<AiConfigPage />
</PermissionRoute>
}
/>
</Route>
</Routes>
</Suspense>
</BrowserRouter>
</AntdApp>

View File

@@ -16,8 +16,7 @@ instance.interceptors.request.use((config) => {
instance.interceptors.response.use(
(res) => res.data,
(err) => {
const isLoginRequest =
err.config?.url === '/auth/login' || err.config?.url === 'auth/login';
const isLoginRequest = err.config?.url === '/auth/login' || err.config?.url === 'auth/login';
if (err.response?.status === 401 && !isLoginRequest) {
localStorage.removeItem('token');

View File

@@ -45,9 +45,7 @@ describe('role-aware menu policy', () => {
'/attendance',
'/notifications',
]);
expect(findRoleAwareLandingPath(['任课老师'], teacherPermissions)).toBe(
'/teacher-workspace',
);
expect(findRoleAwareLandingPath(['任课老师'], teacherPermissions)).toBe('/teacher-workspace');
});
it('places schedules and attendance only once in academic management', () => {

View File

@@ -43,7 +43,12 @@ const SECTIONS: MenuSection[] = [
icon: 'calendar',
roles: ['teacher'],
children: [
{ key: '/teacher-workspace', label: '今日教学', icon: 'workspace', permission: 'teacher-workspace:view' },
{
key: '/teacher-workspace',
label: '今日教学',
icon: 'workspace',
permission: 'teacher-workspace:view',
},
{ key: '/schedules', label: '我的排课', icon: 'calendar', permission: 'schedule:view' },
{ key: '/attendance', label: '课程考勤', icon: 'attendance', permission: 'attendance:view' },
],
@@ -83,11 +88,26 @@ const SECTIONS: MenuSection[] = [
icon: 'classroom',
roles: ['classroom', 'super'],
children: [
{ key: '/classroom-schedule', label: '教室排期', icon: 'calendar', permission: 'rental:view' },
{
key: '/classroom-schedule',
label: '教室排期',
icon: 'calendar',
permission: 'rental:view',
},
{ key: '/classrooms', label: '教室管理', icon: 'classroom', permission: 'classroom:view' },
{ key: '/attendance-devices', label: '考勤机绑定', icon: 'attendance', permission: 'classroom:view' },
{
key: '/attendance-devices',
label: '考勤机绑定',
icon: 'attendance',
permission: 'classroom:view',
},
{ key: '/classroom-rentals', label: '租赁订单', icon: 'rental', permission: 'rental:view' },
{ key: '/organizations', label: '机构管理', icon: 'organization', permission: 'organization:view' },
{
key: '/organizations',
label: '机构管理',
icon: 'organization',
permission: 'organization:view',
},
],
},
{
@@ -100,13 +120,21 @@ const SECTIONS: MenuSection[] = [
{ key: '/roles', label: '角色管理', icon: 'role', permission: 'role:view' },
{ key: '/permissions', label: '权限一览', icon: 'permission', permission: 'role:view' },
{ key: '/operation-logs', label: '操作日志', icon: 'log', permission: 'log:view' },
{ key: '/integration-config', label: '钉钉集成', icon: 'integration', permission: 'integration:read' },
{
key: '/integration-config',
label: '钉钉集成',
icon: 'integration',
permission: 'integration:read',
},
{ key: '/ai-config', label: 'AI 配置', icon: 'ai', permission: 'ai:config:read' },
],
},
];
export function getRoleDomains(roles: readonly string[], permissions: readonly string[]): Set<string> {
export function getRoleDomains(
roles: readonly string[],
permissions: readonly string[],
): Set<string> {
const normalized = new Set(roles.map((role) => ROLE_ALIASES[role]).filter(Boolean));
// 权限可以来自多个叠加角色,因此业务域按能力累加,而不是只选择一个。
if (permissions.includes('student:view') || permissions.includes('class:view')) {
@@ -167,7 +195,8 @@ export function buildMenu(roles: readonly string[], permissions: readonly string
const children = section.children
.filter((child) => permissionSet.has(child.permission))
.map(({ permission: _, ...child }) => child);
if (children.length > 0) sections.push({ ...section, children, roles: undefined } as AppMenuItem);
if (children.length > 0)
sections.push({ ...section, children, roles: undefined } as AppMenuItem);
}
if (permissionSet.has('notification:view')) {

View File

@@ -13,11 +13,7 @@ describe('permission navigation', () => {
it('lands teachers on the teacher workspace without global student or class access', () => {
expect(
findFirstAccessiblePath([
'teacher-workspace:view',
'schedule:view',
'attendance:view',
]),
findFirstAccessiblePath(['teacher-workspace:view', 'schedule:view', 'attendance:view']),
).toBe('/teacher-workspace');
expect(canAccessPath('/students', ['teacher-workspace:view'])).toBe(false);
expect(canAccessPath('/classes', ['teacher-workspace:view'])).toBe(false);

View File

@@ -14,8 +14,16 @@ export const PERMISSION_PAGES: readonly PermissionPage[] = [
{ path: '/rooms', permission: 'room:view' },
{ path: '/occupancies', permission: 'occupancy:view' },
{ path: '/teacher-workspace', permission: 'teacher-workspace:view' },
{ path: '/students', permission: 'student:view', matches: (p) => p === '/students' || /^\/students\/\d+\/profile$/.test(p) },
{ path: '/classes', permission: 'class:view', matches: (p) => p === '/classes' || /^\/classes\/\d+$/.test(p) },
{
path: '/students',
permission: 'student:view',
matches: (p) => p === '/students' || /^\/students\/\d+\/profile$/.test(p),
},
{
path: '/classes',
permission: 'class:view',
matches: (p) => p === '/classes' || /^\/classes\/\d+$/.test(p),
},
{ path: '/attendance', permission: 'attendance:view' },
{ path: '/schedules', permission: 'schedule:view' },
{ path: '/classroom-schedule', permission: 'rental:view' },

View File

@@ -3,7 +3,9 @@ export const PERMISSIONS_UPDATED_EVENT = 'permissions-updated';
export function readPermissions(): string[] {
try {
const value = JSON.parse(localStorage.getItem('permissions') || '[]');
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
return Array.isArray(value)
? value.filter((item): item is string => typeof item === 'string')
: [];
} catch {
return [];
}

View File

@@ -15,7 +15,9 @@ const DefaultRoute: React.FC = () => {
})();
const firstPath = findRoleAwareLandingPath(roles, permissions);
if (firstPath) return <Navigate to={firstPath} replace />;
return <Result status="403" title="暂无可访问功能" subTitle="请联系管理员为当前账号分配功能权限" />;
return (
<Result status="403" title="暂无可访问功能" subTitle="请联系管理员为当前账号分配功能权限" />
);
};
export default DefaultRoute;

View File

@@ -34,16 +34,20 @@ const NotificationBell: React.FC = () => {
const fetchNotifications = async () => {
try {
const data = await api.get('/notifications?limit=20') as unknown as NotificationItem[];
const data = (await api.get('/notifications?limit=20')) as unknown as NotificationItem[];
setNotifications(data);
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
const fetchUnread = async () => {
try {
const data = await api.get('/notifications/unread-count') as unknown as { count: number };
const data = (await api.get('/notifications/unread-count')) as unknown as { count: number };
setUnreadCount(data.count);
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
const openRef = useRef(open);
openRef.current = open;
@@ -60,7 +64,9 @@ const NotificationBell: React.FC = () => {
JSON.parse(event.data);
setUnreadCount((c) => c + 1);
if (openRef.current) fetchNotifications();
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
es.onerror = () => {
es.close();
@@ -84,7 +90,9 @@ const NotificationBell: React.FC = () => {
try {
await api.put(`/notifications/${item.id}/read`);
setUnreadCount((c) => Math.max(0, c - 1));
} catch { /* ignore */ }
} catch {
/* ignore */
}
}
setOpen(false);
if (item.link) navigate(item.link);
@@ -94,10 +102,10 @@ const NotificationBell: React.FC = () => {
try {
await api.put('/notifications/read-all');
setUnreadCount(0);
setNotifications((prev) =>
prev.map((n) => ({ ...n, isRead: true })),
);
} catch { /* ignore */ }
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
} catch {
/* ignore */
}
};
const content = (
@@ -148,18 +156,13 @@ const NotificationBell: React.FC = () => {
)
}
title={
<Typography.Text
strong={!item.isRead}
style={{ fontSize: 14 }}
>
[{notificationTypeLabels[item.type] || item.type}] {formatNotificationText(item.title)}
<Typography.Text strong={!item.isRead} style={{ fontSize: 14 }}>
[{notificationTypeLabels[item.type] || item.type}]{' '}
{formatNotificationText(item.title)}
</Typography.Text>
}
description={
<Typography.Text
type="secondary"
style={{ fontSize: 12 }}
>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{timeAgo(item.createdAt)}
</Typography.Text>
}

View File

@@ -25,7 +25,13 @@ const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children
status="403"
title="无权访问"
subTitle="您没有访问此页面的权限"
extra={firstPath ? <Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>访</Button> : undefined}
extra={
firstPath ? (
<Button type="primary" onClick={() => navigate(firstPath, { replace: true })}>
访
</Button>
) : undefined
}
/>
);
}

View File

@@ -215,7 +215,9 @@ const getStudentStatus = (value?: string | null): { text: string; color: string
const formatEnrollmentDisplayName = (enrollment: EnrollmentRecord): string =>
enrollment.className ||
(enrollment.courseCategory ? getCourseCategoryLabel(enrollment.courseCategory) : String(enrollment.id));
(enrollment.courseCategory
? getCourseCategoryLabel(enrollment.courseCategory)
: String(enrollment.id));
const ATTACHMENT_CATEGORY_OPTIONS = [
{ value: 'id_card', label: '身份证' },
@@ -253,16 +255,31 @@ const SESSION_LABELS: Record<string, string> = {
const AttendanceTab: React.FC<{ data: AttendanceRecordItem[] }> = ({ data }) => {
const columns: ColumnsType<AttendanceRecordItem> = [
{ title: '日期', dataIndex: 'attendanceDate', width: 120 },
{ title: '课程', render: (_: unknown, record) => record.schedule?.subject || record.class?.name || '课程考勤' },
{ title: '时段', dataIndex: 'session', width: 100, render: (value: string) => SESSION_LABELS[value] || value || '-' },
{
title: '结果', dataIndex: 'status', width: 90,
title: '课程',
render: (_: unknown, record) => record.schedule?.subject || record.class?.name || '课程考勤',
},
{
title: '时段',
dataIndex: 'session',
width: 100,
render: (value: string) => SESSION_LABELS[value] || value || '-',
},
{
title: '结果',
dataIndex: 'status',
width: 90,
render: (value: string) => {
const meta = ATTENDANCE_STATUS_MAP[value] || { text: value || '-', color: 'default' };
return <Tag color={meta.color}>{meta.text}</Tag>;
},
},
{ title: '打卡时间', dataIndex: 'punchTime', width: 170, render: (value?: string | null) => value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-' },
{
title: '打卡时间',
dataIndex: 'punchTime',
width: 170,
render: (value?: string | null) => (value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
},
{
title: '打卡设备',
render: (_: unknown, record) => {
@@ -283,7 +300,9 @@ const AttendanceTab: React.FC<{ data: AttendanceRecordItem[] }> = ({ data }) =>
scroll={{ x: 900 }}
pagination={{ defaultPageSize: 15, showSizeChanger: true, pageSizeOptions: [15, 30, 50] }}
/>
) : <Empty description="暂无出勤记录" />;
) : (
<Empty description="暂无出勤记录" />
);
};
interface TabProps {
@@ -291,11 +310,11 @@ interface TabProps {
onRefresh: () => void;
}
const ProfileTab: React.FC<{ data: ProfileData | null; studentId: number; onRefresh: () => void }> = ({
data,
studentId,
onRefresh,
}) => {
const ProfileTab: React.FC<{
data: ProfileData | null;
studentId: number;
onRefresh: () => void;
}> = ({ data, studentId, onRefresh }) => {
const [form] = Form.useForm();
const [saving, setSaving] = useState(false);
@@ -439,10 +458,18 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
confirmLoading={saving}
>
<Form form={form} layout="vertical">
<Form.Item name="courseCategory" label="课程类别" rules={[{ required: true, message: '请选择课程类别' }]}>
<Form.Item
name="courseCategory"
label="课程类别"
rules={[{ required: true, message: '请选择课程类别' }]}
>
<Select options={COURSE_CATEGORY_OPTIONS} placeholder="请选择" />
</Form.Item>
<Form.Item name="classType" label="班型" rules={[{ required: true, message: '请选择班型' }]}>
<Form.Item
name="classType"
label="班型"
rules={[{ required: true, message: '请选择班型' }]}
>
<Select options={CLASS_TYPE_OPTIONS} placeholder="请选择" />
</Form.Item>
<Form.Item name="className" label="班级名称">
@@ -466,12 +493,9 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
);
};
const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] }> = ({
data,
studentId,
enrollments,
onRefresh,
}) => {
const ExamScoresTab: React.FC<
TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] }
> = ({ data, studentId, enrollments, onRefresh }) => {
const [modalOpen, setModalOpen] = useState(false);
const [form] = Form.useForm();
const [saving, setSaving] = useState(false);
@@ -505,8 +529,16 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
{ title: '考试名称', dataIndex: 'examName', render: (v: string) => v || '-' },
{ title: '科目', dataIndex: 'subject' },
{ title: '成绩', dataIndex: 'score' },
{ title: '班级均分', dataIndex: 'classAvg', render: (v: number | undefined) => (v !== undefined ? v : '-') },
{ title: '排名', dataIndex: 'rank', render: (v: number | undefined) => (v !== undefined ? v : '-') },
{
title: '班级均分',
dataIndex: 'classAvg',
render: (v: number | undefined) => (v !== undefined ? v : '-'),
},
{
title: '排名',
dataIndex: 'rank',
render: (v: number | undefined) => (v !== undefined ? v : '-'),
},
{ title: '考试日期', dataIndex: 'examDate', render: (v: string) => v || '-' },
{
title: '关联报读',
@@ -550,13 +582,21 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
confirmLoading={saving}
>
<Form form={form} layout="vertical">
<Form.Item name="examType" label="考试类型" rules={[{ required: true, message: '请选择考试类型' }]}>
<Form.Item
name="examType"
label="考试类型"
rules={[{ required: true, message: '请选择考试类型' }]}
>
<Select options={EXAM_TYPE_OPTIONS} placeholder="请选择" />
</Form.Item>
<Form.Item name="examName" label="考试名称">
<Input placeholder="如2024第一次月考" />
</Form.Item>
<Form.Item name="subject" label="科目" rules={[{ required: true, message: '请输入科目' }]}>
<Form.Item
name="subject"
label="科目"
rules={[{ required: true, message: '请输入科目' }]}
>
<Input placeholder="如:数学" />
</Form.Item>
<Form.Item name="score" label="成绩" rules={[{ required: true, message: '请输入成绩' }]}>
@@ -587,7 +627,11 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
);
};
const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({ data, studentId, onRefresh }) => {
const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
data,
studentId,
onRefresh,
}) => {
const [modalOpen, setModalOpen] = useState(false);
const [form] = Form.useForm();
const [saving, setSaving] = useState(false);
@@ -655,13 +699,25 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({ data, st
confirmLoading={saving}
>
<Form form={form} layout="vertical">
<Form.Item name="recordDate" label="记录日期" rules={[{ required: true, message: '请选择日期' }]}>
<Form.Item
name="recordDate"
label="记录日期"
rules={[{ required: true, message: '请选择日期' }]}
>
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="recordType" label="记录类型" rules={[{ required: true, message: '请选择记录类型' }]}>
<Form.Item
name="recordType"
label="记录类型"
rules={[{ required: true, message: '请选择记录类型' }]}
>
<Select options={RECORD_TYPE_OPTIONS} placeholder="请选择" />
</Form.Item>
<Form.Item name="content" label="内容" rules={[{ required: true, message: '请输入内容' }]}>
<Form.Item
name="content"
label="内容"
rules={[{ required: true, message: '请输入内容' }]}
>
<Input.TextArea rows={4} placeholder="请记录学情内容" />
</Form.Item>
<Form.Item name="followUpMethod" label="跟进方式">
@@ -676,7 +732,11 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({ data, st
);
};
const ResultTab: React.FC<TabProps & { data: ResultData | null }> = ({ data, studentId, onRefresh }) => {
const ResultTab: React.FC<TabProps & { data: ResultData | null }> = ({
data,
studentId,
onRefresh,
}) => {
const [form] = Form.useForm();
const [saving, setSaving] = useState(false);
@@ -741,7 +801,11 @@ const ResultTab: React.FC<TabProps & { data: ResultData | null }> = ({ data, stu
);
};
const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({ data, studentId, onRefresh }) => {
const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
data,
studentId,
onRefresh,
}) => {
const [uploading, setUploading] = useState(false);
const handleDelete = async (attachmentId: number) => {
@@ -802,7 +866,12 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({ dat
showUploadList={false}
customRequest={async (options) => {
const formData = new FormData();
formData.append('file', options.file instanceof File ? options.file : new File([options.file as Blob], 'attachment'));
formData.append(
'file',
options.file instanceof File
? options.file
: new File([options.file as Blob], 'attachment'),
);
setUploading(true);
try {
await api.post(`/archive/${studentId}/attachments`, formData, {
@@ -883,63 +952,60 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
const tabItems = useMemo(() => {
if (!aggregateData) return [];
const { profile, enrollments, examScores, learningRecords, result, attachments, attendances } = aggregateData;
const { profile, enrollments, examScores, learningRecords, result, attachments, attendances } =
aggregateData;
return [
{
key: 'profile',
label: '扩展档案',
children: <ProfileTab data={profile} studentId={studentId} onRefresh={fetchData} />,
},
{
key: 'enrollments',
label: `报读班型 (${enrollments.length})`,
children: (
<EnrollmentsTab data={enrollments} studentId={studentId} onRefresh={fetchData} />
),
},
{
key: 'exams',
label: `考试成绩 (${examScores.length})`,
children: (
<ExamScoresTab
data={examScores}
studentId={studentId}
enrollments={enrollments}
onRefresh={fetchData}
/>
),
},
{
key: 'attendance',
label: `出勤记录 (${attendances.length})`,
children: <AttendanceTab data={attendances} />,
},
{
key: 'learning',
label: `课堂回访 (${learningRecords.length})`,
children: (
<LearningTab data={learningRecords} studentId={studentId} onRefresh={fetchData} />
),
},
{
key: 'result',
label: '录取归档',
children: <ResultTab data={result} studentId={studentId} onRefresh={fetchData} />,
},
{
key: 'attachments',
label: `附件 (${attachments.length})`,
children: (
<AttachmentsTab data={attachments} studentId={studentId} onRefresh={fetchData} />
),
},
{
key: 'reports',
label: '报告版本',
children: <Empty description="暂无报告版本" />,
},
];
}, [aggregateData, studentId, fetchData]);
{
key: 'profile',
label: '扩展档案',
children: <ProfileTab data={profile} studentId={studentId} onRefresh={fetchData} />,
},
{
key: 'enrollments',
label: `报读班型 (${enrollments.length})`,
children: <EnrollmentsTab data={enrollments} studentId={studentId} onRefresh={fetchData} />,
},
{
key: 'exams',
label: `考试成绩 (${examScores.length})`,
children: (
<ExamScoresTab
data={examScores}
studentId={studentId}
enrollments={enrollments}
onRefresh={fetchData}
/>
),
},
{
key: 'attendance',
label: `出勤记录 (${attendances.length})`,
children: <AttendanceTab data={attendances} />,
},
{
key: 'learning',
label: `课堂回访 (${learningRecords.length})`,
children: (
<LearningTab data={learningRecords} studentId={studentId} onRefresh={fetchData} />
),
},
{
key: 'result',
label: '录取归档',
children: <ResultTab data={result} studentId={studentId} onRefresh={fetchData} />,
},
{
key: 'attachments',
label: `附件 (${attachments.length})`,
children: <AttachmentsTab data={attachments} studentId={studentId} onRefresh={fetchData} />,
},
{
key: 'reports',
label: '报告版本',
children: <Empty description="暂无报告版本" />,
},
];
}, [aggregateData, studentId, fetchData]);
if (!aggregateData) {
if (loading) {
@@ -1000,7 +1066,9 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</a>
</span>
) : '-'}
) : (
'-'
)}
</Descriptions.Item>
<Descriptions.Item label="身份证号">
{student.idNumber ? (
@@ -1010,7 +1078,9 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</a>
</span>
) : '-'}
) : (
'-'
)}
</Descriptions.Item>
<Descriptions.Item label="状态">
{(() => {
@@ -1024,18 +1094,13 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
{profile?.targetMajor && (
<Descriptions.Item label="目标专业">{profile.targetMajor}</Descriptions.Item>
)}
{profile?.grade && (
<Descriptions.Item label="年级">{profile.grade}</Descriptions.Item>
)}
{profile?.grade && <Descriptions.Item label="年级">{profile.grade}</Descriptions.Item>}
{profile?.subjectDirection && (
<Descriptions.Item label="选科方向">{profile.subjectDirection}</Descriptions.Item>
)}
</Descriptions>
<Tabs
defaultActiveKey="profile"
items={tabItems}
/>
<Tabs defaultActiveKey="profile" items={tabItems} />
</div>
);
};

View File

@@ -35,6 +35,24 @@ canvas {
min-width: 0;
}
.app-sidebar {
flex: 0 0 auto;
}
.app-content > * {
min-width: 0;
max-width: 100%;
}
.ant-card,
.ant-card-body,
.ant-tabs,
.ant-tabs-content-holder,
.ant-tabs-content,
.ant-tabs-tabpane {
min-width: 0;
}
.app-header {
position: sticky;
top: 0;
@@ -65,11 +83,15 @@ canvas {
row-gap: 8px;
}
/* === 通用:表格容器横向滚动(防双重滚动条) === */
/* Data tables own their horizontal scroll instead of widening the page. */
.ant-table-wrapper {
width: 100%;
min-width: 0;
max-width: 100%;
}
.ant-table-wrapper .ant-table-container {
overflow-x: auto;
overflow-y: hidden;
overscroll-behavior-inline: contain;
-webkit-overflow-scrolling: touch;
}
@@ -231,6 +253,46 @@ canvas {
}
}
@media (max-width: 575px) {
.ant-card-head {
align-items: flex-start;
flex-direction: column;
gap: 8px;
padding-block: 12px;
}
.ant-card-head-wrapper {
width: 100%;
min-width: 0;
}
.ant-card-extra {
max-width: 100%;
margin-inline-start: 0;
}
.ant-card-extra > .ant-space {
flex-wrap: wrap;
}
.ant-form-item-control,
.ant-form-item-control-input,
.ant-form-item-control-input-content,
.ant-picker-range {
min-width: 0;
max-width: 100%;
}
.ant-statistic-content {
overflow-wrap: anywhere;
}
}
@media (max-width: 991px) {
.app-content {
overflow: hidden;
}
}
/* === 平板 (576-991px) === */
@media (min-width: 576px) and (max-width: 991px) {
.ant-modal {

View File

@@ -79,7 +79,10 @@ const MainLayout: React.FC = () => {
useEffect(() => {
let cancelled = false;
api.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>('/auth/profile')
api
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
'/auth/profile',
)
.then((profile) => {
if (cancelled) return;
writePermissions(profile.permissions || []);
@@ -91,13 +94,16 @@ const MainLayout: React.FC = () => {
.catch(() => {
// The API interceptor handles expired/invalid sessions.
});
return () => { cancelled = true; };
return () => {
cancelled = true;
};
}, []);
const screens = Grid.useBreakpoint();
const isMobile = !screens.sm; // < 576px (仅 xs)
const isMobile = !screens.sm; // < 576px (仅 xs)
const isTablet = (screens.sm || screens.md) && !screens.lg; // 576-991px
const isDesktop = !!screens.lg; // >= 992px
const isDesktop = !!screens.lg; // >= 992px
const usesDrawer = !isDesktop;
const menuItems = useMemo(
() => buildMenu(user.roles ?? [], permissions),
@@ -111,10 +117,13 @@ const MainLayout: React.FC = () => {
navigate('/login');
}, [navigate]);
const handleMenuClick = useCallback((key: string) => {
navigate(key);
if (isMobile) setDrawerOpen(false);
}, [navigate, isMobile]);
const handleMenuClick = useCallback(
(key: string) => {
navigate(key);
if (usesDrawer) setDrawerOpen(false);
},
[navigate, usesDrawer],
);
const findSelectedKeys = (items: AppMenuItem[], pathname: string): string[] => {
for (const item of items) {
@@ -130,7 +139,12 @@ const MainLayout: React.FC = () => {
const findOpenKeys = (items: AppMenuItem[], pathname: string): string[] => {
for (const item of items) {
if (item.children) {
if (item.children.some((c) => c.key === pathname || (c.children && c.children.some((gc) => gc.key === pathname)))) {
if (
item.children.some(
(c) =>
c.key === pathname || (c.children && c.children.some((gc) => gc.key === pathname)),
)
) {
return [item.key];
}
}
@@ -138,7 +152,10 @@ const MainLayout: React.FC = () => {
return [];
};
const selectedKeys = useMemo(() => findSelectedKeys(menuItems, location.pathname), [menuItems, location.pathname]);
const selectedKeys = useMemo(
() => findSelectedKeys(menuItems, location.pathname),
[menuItems, location.pathname],
);
// 路径变化时同步展开的菜单(不干扰用户手动展开/收起)
useEffect(() => {
if (location.pathname !== prevPathname.current) {
@@ -153,8 +170,6 @@ const MainLayout: React.FC = () => {
setOpenKeys(latestKey ? [latestKey] : []);
}, []);
const transformToMenuItems = (items: AppMenuItem[]): any[] => {
return items.map((item) => ({
key: item.key,
@@ -163,26 +178,29 @@ const MainLayout: React.FC = () => {
children: item.children ? transformToMenuItems(item.children) : undefined,
}));
};
const menuContent = useMemo(() => (
<Menu
theme="light"
mode="inline"
selectedKeys={selectedKeys}
openKeys={openKeys}
onOpenChange={handleOpenChange}
items={transformToMenuItems(menuItems)}
onClick={({ key }) => handleMenuClick(key)}
style={{ border: 'none' }}
/>
), [selectedKeys, openKeys, menuItems, handleMenuClick]);
const menuContent = useMemo(
() => (
<Menu
theme="light"
mode="inline"
selectedKeys={selectedKeys}
openKeys={openKeys}
onOpenChange={handleOpenChange}
items={transformToMenuItems(menuItems)}
onClick={({ key }) => handleMenuClick(key)}
style={{ border: 'none' }}
/>
),
[selectedKeys, openKeys, menuItems, handleMenuClick],
);
return (
<Layout className="app-shell" style={{ minHeight: '100vh' }}>
{!isMobile && (
{isDesktop && (
<Sider
trigger={null}
collapsible
collapsed={isTablet ? true : collapsed}
collapsed={collapsed}
theme="light"
className="app-sidebar"
style={{ background: '#fff', borderRight: '1px solid #e5e5e7' }}
@@ -194,17 +212,17 @@ const MainLayout: React.FC = () => {
alignItems: 'center',
justifyContent: 'center',
color: '#1d1d1f',
fontSize: (isTablet || collapsed) ? 16 : 17,
fontSize: collapsed ? 16 : 17,
fontWeight: 600,
borderBottom: '1px solid #e5e5e7',
}}
>
{(isTablet || collapsed) ? '恭' : '恭学教育基地'}
{collapsed ? '恭' : '恭学教育基地'}
</div>
{menuContent}
</Sider>
)}
{isMobile && (
{usesDrawer && (
<Drawer
placement="left"
open={drawerOpen}
@@ -232,9 +250,9 @@ const MainLayout: React.FC = () => {
>
<Button
type="text"
aria-label={isMobile || isTablet ? '打开菜单' : collapsed ? '展开侧边栏' : '收起侧边栏'}
aria-label={usesDrawer ? '打开菜单' : collapsed ? '展开侧边栏' : '收起侧边栏'}
icon={
isMobile || isTablet ? (
usesDrawer ? (
<MenuUnfoldOutlined />
) : collapsed ? (
<MenuUnfoldOutlined />
@@ -242,7 +260,7 @@ const MainLayout: React.FC = () => {
<MenuFoldOutlined />
)
}
onClick={() => (isMobile || isTablet ? setDrawerOpen(true) : setCollapsed(!collapsed))}
onClick={() => (usesDrawer ? setDrawerOpen(true) : setCollapsed(!collapsed))}
/>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
{hasPermission('notification:view') && <NotificationBell />}

View File

@@ -17,11 +17,7 @@ describe('AiConfig helpers', () => {
});
it('swaps when current baseUrl matches previous provider default', () => {
const result = shouldAutoSwapBaseUrl(
'DEEPSEEK',
'https://api.openai.com/v1',
'OPENAI',
);
const result = shouldAutoSwapBaseUrl('DEEPSEEK', 'https://api.openai.com/v1', 'OPENAI');
expect(result.shouldSwap).toBe(true);
expect(result.baseUrl).toBe(PROVIDER_DEFAULTS.DEEPSEEK);
});
@@ -32,11 +28,7 @@ describe('AiConfig helpers', () => {
});
it('keeps custom baseUrl unchanged', () => {
const result = shouldAutoSwapBaseUrl(
'OPENAI',
'https://custom.api.com/v1',
'DEEPSEEK',
);
const result = shouldAutoSwapBaseUrl('OPENAI', 'https://custom.api.com/v1', 'DEEPSEEK');
expect(result.shouldSwap).toBe(false);
expect(result.baseUrl).toBe('https://custom.api.com/v1');
});

View File

@@ -68,7 +68,6 @@ describe('lesson check-in summary', () => {
});
});
describe('lesson attendance filters', () => {
const records = [
{ id: 1, student: { name: '张三' }, status: 'present' },
@@ -78,15 +77,21 @@ describe('lesson attendance filters', () => {
];
it('searches students by name and ignores surrounding whitespace', () => {
expect(filterLessonAttendanceRecords(records, ' 张 ', 'all').map((item) => item.id)).toEqual([1]);
expect(filterLessonAttendanceRecords(records, ' 张 ', 'all').map((item) => item.id)).toEqual([
1,
]);
});
it('groups present and late as checked in', () => {
expect(filterLessonAttendanceRecords(records, '', 'checked_in').map((item) => item.id)).toEqual([1, 2]);
expect(filterLessonAttendanceRecords(records, '', 'checked_in').map((item) => item.id)).toEqual(
[1, 2],
);
});
it('groups pending and absent as not checked in and combines with search', () => {
expect(filterLessonAttendanceRecords(records, '王', 'not_checked_in').map((item) => item.id)).toEqual([3]);
expect(
filterLessonAttendanceRecords(records, '王', 'not_checked_in').map((item) => item.id),
).toEqual([3]);
});
});

View File

@@ -8,11 +8,7 @@ export function getAttendanceExperience(
roles: readonly string[],
): AttendanceExperience {
const domains = getRoleDomains(roles, permissions);
if (
permissions.includes('attendance:edit') ||
domains.has('academic') ||
domains.has('super')
) {
if (permissions.includes('attendance:edit') || domains.has('academic') || domains.has('super')) {
return 'admin';
}
return 'teacher';
@@ -83,7 +79,6 @@ export function summarizeLessonCheckins(
};
}
export type LessonAttendanceFilter = 'all' | 'checked_in' | 'not_checked_in';
export interface LessonAttendanceFilterRecord {

View File

@@ -225,7 +225,10 @@
border-left: 4px solid #c9d2df;
border-radius: 14px;
background: white;
transition: transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease;
transition:
transform 180ms ease,
box-shadow 180ms ease,
border-color 180ms ease;
}
.lesson-card:hover {
@@ -366,6 +369,36 @@
font-size: 20px;
}
.lesson-summary-strip {
grid-template-columns: minmax(210px, 1fr) repeat(2, minmax(120px, 0.7fr));
}
.lesson-summary-strip .attendance-rate,
.lesson-summary-strip .attendance-summary-cell {
justify-content: center;
}
.lesson-summary-strip .attendance-rate {
text-align: left;
}
.attendance-correction-segment.ant-segmented {
padding: 2px;
border: 1px solid var(--student-line, #e1e8e5);
background: #f8faf9;
}
.attendance-correction-segment .ant-segmented-item {
min-width: 52px;
}
.attendance-correction-segment .ant-segmented-item-label {
min-height: 28px;
line-height: 28px;
font-size: 12px;
}
.attendance-summary-icon {
display: grid !important;
flex: 0 0 auto;
@@ -376,11 +409,26 @@
font-weight: 700;
}
.is-present { color: #198754 !important; background: #eaf8f1; }
.is-late { color: #b56b00 !important; background: #fff4db; }
.is-absent { color: #cf3030 !important; background: #fff0f0; }
.is-leave { color: #2874c6 !important; background: #edf5ff; }
.is-pending { color: #667085 !important; background: #f1f3f6; }
.is-present {
color: #198754 !important;
background: #eaf8f1;
}
.is-late {
color: #b56b00 !important;
background: #fff4db;
}
.is-absent {
color: #cf3030 !important;
background: #fff0f0;
}
.is-leave {
color: #2874c6 !important;
background: #edf5ff;
}
.is-pending {
color: #667085 !important;
background: #f1f3f6;
}
.lesson-record-filters {
display: flex;
@@ -659,7 +707,6 @@
min-width: 54px;
}
.punch-device-cell {
display: flex;
flex-direction: column;
@@ -692,9 +739,11 @@
--student-line: #e1e8e5;
--student-primary: #157a65;
--student-primary-soft: #e8f4f0;
min-width: 0;
min-height: calc(100vh - 64px);
margin: -24px;
padding: 0 24px 28px;
overflow: hidden;
background: var(--student-bg);
color: var(--student-ink);
}
@@ -755,9 +804,11 @@
.student-filter-panel {
display: grid;
grid-template-columns: minmax(260px, 1.4fr) repeat(4, minmax(150px, 1fr)) auto;
gap: 12px;
grid-template-columns: 176px 220px 142px 142px 142px auto;
gap: 10px;
align-items: end;
justify-content: start;
min-width: 0;
margin-bottom: 16px;
padding: 16px;
border: 1px solid var(--student-line);
@@ -783,13 +834,56 @@
.student-filter-actions {
display: flex;
justify-content: flex-start;
flex-wrap: nowrap;
gap: 8px;
padding-top: 2px;
}
.student-filter-actions .ant-btn {
min-width: 88px;
}
.attendance-period-editor {
display: grid;
gap: 12px;
}
.attendance-period-row {
display: grid;
grid-template-columns: 1.05fr 1fr 132px 132px 92px auto;
gap: 10px;
align-items: start;
padding: 12px;
border: 1px solid var(--student-line);
border-radius: 12px;
background: #fff;
}
.attendance-period-row .ant-form-item {
margin-bottom: 0;
}
.attendance-period-row__delete {
align-self: end;
min-width: 72px;
}
.attendance-period-add {
height: 44px;
border-radius: 12px;
}
.attendance-period-modal .ant-modal-body {
padding-top: 12px;
}
.student-class-overview {
display: grid;
grid-template-columns: minmax(320px, .9fr) minmax(0, 1.1fr);
grid-template-columns: minmax(360px, 0.95fr) minmax(360px, 1.05fr);
gap: 16px;
min-width: 0;
margin-bottom: 16px;
}
@@ -797,32 +891,79 @@
.student-metric-strip,
.student-workspace,
.student-record-card {
border: 1px solid var(--student-line);
border-radius: 10px;
border: 1px solid rgb(21 122 101 / 12%);
border-radius: 18px;
background: var(--student-surface);
box-shadow: 0 14px 36px rgb(24 44 38 / 7%);
}
.student-class-overview > *,
.student-workspace,
.student-record-card {
min-width: 0;
}
.student-class-identity {
position: relative;
display: flex;
flex-direction: column;
justify-content: space-between;
min-height: 156px;
padding: 18px;
min-height: 176px;
overflow: hidden;
padding: 20px;
background:
radial-gradient(circle at 100% 0%, rgb(21 122 101 / 10%), transparent 34%),
linear-gradient(135deg, #ffffff 0%, #f8fcfa 100%);
}
.student-class-identity::after {
content: '';
position: absolute;
right: -36px;
bottom: -44px;
width: 118px;
height: 118px;
border: 18px solid rgb(21 122 101 / 7%);
border-radius: 999px;
pointer-events: none;
}
.student-class-heading {
position: relative;
z-index: 1;
}
.student-overview-kicker {
display: inline-flex;
align-items: center;
min-height: 24px;
margin-bottom: 8px;
padding: 0 9px;
border-radius: 999px;
background: rgb(21 122 101 / 10%);
color: var(--student-primary);
font-size: 12px;
font-weight: 700;
}
.student-class-identity h2 {
margin: 0 0 5px;
font-size: 22px;
margin: 0 0 6px;
color: #111c18;
font-size: 24px;
line-height: 1.2;
}
.student-class-identity span {
.student-class-identity p {
margin: 0;
color: var(--student-muted);
font-size: 12px;
font-size: 13px;
}
.student-teacher-list {
display: flex;
flex-wrap: wrap;
position: relative;
z-index: 1;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: 10px;
margin-top: 20px;
}
@@ -830,77 +971,118 @@
.student-teacher-item {
display: flex;
align-items: center;
gap: 9px;
min-width: 150px;
padding: 9px;
border-radius: 8px;
background: var(--student-soft);
gap: 10px;
min-width: 0;
padding: 10px;
border: 1px solid rgb(21 122 101 / 10%);
border-radius: 12px;
background: rgb(255 255 255 / 76%);
}
.student-teacher-item.is-muted {
opacity: 0.72;
}
.student-teacher-item .ant-avatar {
flex: 0 0 auto;
color: var(--student-primary);
background: var(--student-primary-soft);
}
.student-teacher-item > div {
min-width: 0;
}
.student-teacher-item strong,
.student-teacher-item span {
display: block;
}
.student-teacher-item span {
color: var(--student-muted);
font-size: 12px;
}
.student-teacher-item strong {
min-width: 0;
margin-top: 2px;
overflow-wrap: anywhere;
color: #15231f;
font-size: 13px;
line-height: 1.35;
}
.student-metric-strip {
display: grid;
grid-template-columns: repeat(6, minmax(82px, 1fr));
overflow: hidden;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
min-width: 0;
padding: 10px;
}
.student-metric-card {
appearance: none;
display: grid;
align-content: center;
gap: 6px;
min-height: 156px;
padding: 16px 12px;
border: 0;
border-right: 1px solid var(--student-line);
background: #fff;
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
min-height: 76px;
padding: 13px 14px;
border: 1px solid transparent;
border-radius: 14px;
background: #f9fbfa;
color: inherit;
text-align: left;
cursor: pointer;
}
.student-metric-card:last-child {
border-right: 0;
transition:
background 160ms ease,
border-color 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.student-metric-card:hover,
.student-metric-card.active {
background: var(--student-primary-soft);
transform: translateY(-1px);
border-color: rgb(21 122 101 / 24%);
background: #ffffff;
box-shadow: 0 10px 22px rgb(24 44 38 / 8%);
}
.student-metric-card:focus-visible {
outline: 3px solid rgb(21 122 101 / 22%);
outline-offset: 2px;
}
.student-metric-icon {
display: inline-grid;
width: max-content;
min-width: 34px;
height: 26px;
flex: 0 0 auto;
width: 40px;
height: 40px;
place-items: center;
padding: 0 7px;
border-radius: 999px;
border-radius: 12px;
font-size: 12px;
font-weight: 700;
font-weight: 800;
}
.student-metric-copy {
display: grid;
gap: 4px;
min-width: 0;
}
.student-metric-card strong {
font-size: 24px;
overflow: hidden;
color: #111c18;
font-size: clamp(19px, 3vw, 24px);
line-height: 1;
text-overflow: ellipsis;
white-space: nowrap;
}
.student-metric-card small {
color: var(--student-muted);
font-size: 12px;
}
.student-workspace {
@@ -930,18 +1112,27 @@
.student-workspace-tools {
display: flex;
align-items: center;
flex: 0 0 auto;
flex-wrap: nowrap;
gap: 8px;
min-width: 0;
white-space: nowrap;
}
.student-workspace-tools .ant-input-search {
flex: 0 0 240px;
width: 240px;
}
.student-workspace-tools .ant-btn {
flex: 0 0 auto;
}
.student-legend {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
gap: 8px 12px;
padding: 12px 0;
color: var(--student-muted);
font-size: 12px;
@@ -960,11 +1151,21 @@
border-radius: 2px;
}
.student-legend i.is-present { background: #2f9c78; }
.student-legend i.is-late { background: #d78a18; }
.student-legend i.is-leave { background: #397bbf; }
.student-legend i.is-absent { background: #d44d4d; }
.student-legend i.is-pending { background: #8a9692; }
.student-legend i.is-present {
background: #2f9c78;
}
.student-legend i.is-late {
background: #d78a18;
}
.student-legend i.is-leave {
background: #397bbf;
}
.student-legend i.is-absent {
background: #d44d4d;
}
.student-legend i.is-pending {
background: #8a9692;
}
.student-legend em {
color: var(--student-quiet);
@@ -973,7 +1174,7 @@
.student-card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(184px, 1fr));
grid-template-columns: repeat(auto-fill, minmax(216px, 1fr));
gap: 10px;
}
@@ -989,7 +1190,10 @@
color: inherit;
text-align: left;
cursor: pointer;
transition: border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
transition:
border-color 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.student-attendance-card:hover,
@@ -1011,7 +1215,12 @@
}
.student-attendance-head small {
flex: 0 0 auto;
max-width: 112px;
overflow: hidden;
color: var(--student-quiet);
text-overflow: ellipsis;
white-space: nowrap;
}
.student-status-blocks {
@@ -1139,43 +1348,144 @@
background: linear-gradient(180deg, #56bea3, #157a65);
}
@media (max-width: 1180px) {
.student-filter-panel,
.student-class-overview {
grid-template-columns: 1fr 1fr;
@media (max-width: 1280px) {
.student-filter-panel {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.student-filter-field--date {
grid-column: auto;
}
.student-filter-actions {
grid-column: 1 / -1;
justify-content: flex-end;
}
}
@media (max-width: 1180px) {
.student-class-overview {
grid-template-columns: 1fr;
}
.student-metric-strip {
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 760px) {
.lesson-summary-strip {
grid-template-columns: 1fr;
}
.lesson-summary-strip .attendance-rate,
.lesson-summary-strip .attendance-summary-cell {
justify-content: flex-start;
}
.student-attendance-center {
margin: -16px;
padding: 0 16px 22px;
margin: -12px;
padding: 0 12px 20px;
}
.student-center-topbar {
margin-inline: -12px;
padding: 12px;
}
.student-center-topbar,
.student-workspace-header,
.student-center-actions,
.student-legend {
align-items: flex-start;
align-items: stretch;
flex-direction: column;
}
.student-center-title {
align-items: flex-start;
flex-direction: column;
gap: 2px;
}
.student-filter-panel,
.attendance-period-row {
grid-template-columns: 1fr;
}
.student-class-overview {
grid-template-columns: 1fr;
}
.student-workspace-tools,
.student-workspace-tools .ant-input-search {
.student-filter-field--date {
grid-column: auto;
}
.student-filter-actions > *,
.student-center-actions .ant-btn {
width: 100%;
}
.student-workspace-tools {
align-self: stretch;
width: 100%;
}
.student-workspace-tools .ant-input-search {
flex: 1 1 auto;
min-width: 0;
width: auto;
}
.student-filter-actions > * {
flex: 1;
}
.student-metric-strip {
grid-template-columns: repeat(2, 1fr);
}
.student-metric-card {
min-height: 72px;
}
.student-workspace {
padding-inline: 12px;
}
.student-card-grid {
grid-template-columns: 1fr;
}
.student-teacher-list {
grid-template-columns: 1fr;
}
.student-detail-profile {
grid-template-columns: auto minmax(0, 1fr);
}
.student-detail-rate {
grid-column: 1 / -1;
text-align: left;
}
.student-detail-timeline > div {
grid-template-columns: 56px minmax(0, 1fr);
}
}
@media (max-width: 430px) {
.student-metric-strip {
grid-template-columns: 1fr;
}
.student-attendance-head {
align-items: flex-start;
flex-direction: column;
gap: 4px;
}
.student-attendance-head small {
max-width: 100%;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -59,22 +59,22 @@ const AttendanceDevicesPage: React.FC = () => {
}, []);
const classroomOptions = useMemo(
() => classrooms.map((item) => ({
value: item.id,
label: item.building ? `${item.name}${item.building}` : item.name,
})),
() =>
classrooms.map((item) => ({
value: item.id,
label: item.building ? `${item.name}${item.building}` : item.name,
})),
[classrooms],
);
const filteredData = useMemo(() => {
const text = keyword.trim().toLocaleLowerCase('zh-CN');
if (!text) return data;
return data.filter((item) => [
item.deviceSn,
item.deviceName,
item.classroom?.name,
item.location,
].some((value) => (value || '').toLocaleLowerCase('zh-CN').includes(text)));
return data.filter((item) =>
[item.deviceSn, item.deviceName, item.classroom?.name, item.location].some((value) =>
(value || '').toLocaleLowerCase('zh-CN').includes(text),
),
);
}, [data, keyword]);
const openCreate = () => {
@@ -131,17 +131,48 @@ const AttendanceDevicesPage: React.FC = () => {
const columns: ColumnsType<AttendanceDeviceRow> = [
{ title: '设备名称', dataIndex: 'deviceName', width: 180 },
{ title: 'SN 码', dataIndex: 'deviceSn', width: 220, render: (value) => <span style={{ fontFamily: 'monospace' }}>{value}</span> },
{ title: '绑定教室', dataIndex: ['classroom', 'name'], width: 160, render: (_value, record) => record.classroom?.name || `教室 ${record.classroomId}` },
{ title: '位置', dataIndex: 'location', render: (value) => value || <span style={{ color: '#999' }}></span> },
{ title: '状态', dataIndex: 'status', width: 90, render: (value: keyof typeof statusMeta) => <Tag color={statusMeta[value]?.color}>{statusMeta[value]?.text || value}</Tag> },
{ title: '备注', dataIndex: 'notes', ellipsis: true, render: (value) => value || <span style={{ color: '#999' }}></span> },
{
title: 'SN 码',
dataIndex: 'deviceSn',
width: 220,
render: (value) => <span style={{ fontFamily: 'monospace' }}>{value}</span>,
},
{
title: '绑定教室',
dataIndex: ['classroom', 'name'],
width: 160,
render: (_value, record) => record.classroom?.name || `教室 ${record.classroomId}`,
},
{
title: '位置',
dataIndex: 'location',
render: (value) => value || <span style={{ color: '#999' }}></span>,
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (value: keyof typeof statusMeta) => (
<Tag color={statusMeta[value]?.color}>{statusMeta[value]?.text || value}</Tag>
),
},
{
title: '备注',
dataIndex: 'notes',
ellipsis: true,
render: (value) => value || <span style={{ color: '#999' }}></span>,
},
{
title: '操作',
width: 150,
render: (_, record) => (
<Space>
<PermissionButton permission="classroom:edit" size="small" type="link" onClick={() => openEdit(record)}>
<PermissionButton
permission="classroom:edit"
size="small"
type="link"
onClick={() => openEdit(record)}
>
</PermissionButton>
<Popconfirm title="确定停用此考勤机绑定?" onConfirm={() => handleDelete(record.id)}>
@@ -156,7 +187,15 @@ const AttendanceDevicesPage: React.FC = () => {
return (
<div>
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
<div
style={{
marginBottom: 16,
display: 'flex',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 8,
}}
>
<Input.Search
allowClear
placeholder="搜索设备/SN/教室"
@@ -164,7 +203,12 @@ const AttendanceDevicesPage: React.FC = () => {
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
/>
<PermissionButton permission="classroom:edit" type="primary" icon={<PlusOutlined />} onClick={openCreate}>
<PermissionButton
permission="classroom:edit"
type="primary"
icon={<PlusOutlined />}
onClick={openCreate}
>
</PermissionButton>
</div>
@@ -188,17 +232,39 @@ const AttendanceDevicesPage: React.FC = () => {
okText="保存"
>
<Form form={form} layout="vertical">
<Form.Item name="deviceName" label="设备名称" rules={[{ required: true, message: '请输入设备名称' }]}>
<Form.Item
name="deviceName"
label="设备名称"
rules={[{ required: true, message: '请输入设备名称' }]}
>
<Input placeholder="如彼岸游境_N1604" />
</Form.Item>
<Form.Item name="deviceSn" label="SN 码" rules={[{ required: true, message: '请输入钉钉返回的 deviceSN' }]}>
<Form.Item
name="deviceSn"
label="SN 码"
rules={[{ required: true, message: '请输入钉钉返回的 deviceSN' }]}
>
<Input placeholder="如300419260325WN1604" />
</Form.Item>
<Form.Item name="classroomId" label="绑定教室" rules={[{ required: true, message: '请选择绑定教室' }]}>
<Select showSearch optionFilterProp="label" options={classroomOptions} placeholder="选择教室" />
<Form.Item
name="classroomId"
label="绑定教室"
rules={[{ required: true, message: '请选择绑定教室' }]}
>
<Select
showSearch
optionFilterProp="label"
options={classroomOptions}
placeholder="选择教室"
/>
</Form.Item>
<Form.Item name="status" label="状态" initialValue="active">
<Select options={[{ value: 'active', label: '启用' }, { value: 'disabled', label: '停用' }]} />
<Select
options={[
{ value: 'active', label: '启用' },
{ value: 'disabled', label: '停用' },
]}
/>
</Form.Item>
<Form.Item name="location" label="位置">
<Input placeholder="如:教学楼一楼东侧" />

View File

@@ -27,7 +27,6 @@ import { message } from '../../ui/app-message';
import { buildBillPrintHtml, type BillPrintData } from './bill-print';
import { newOperationId } from '../../utils/operation-id';
const statusMap: Record<string, { text: string; color: string }> = {
unpaid: { text: '待支付', color: 'orange' },
partially_paid: { text: '部分支付', color: 'gold' },
@@ -64,7 +63,7 @@ const BillsPage: React.FC = () => {
const params: Record<string, string | undefined> = {};
if (filterStatus) params.status = filterStatus;
if (filterExpenseType) params.expenseType = filterExpenseType;
const res = await api.get('/bills', { params }) as unknown[];
const res = (await api.get('/bills', { params })) as unknown[];
setBills(res);
} catch (e: any) {
message.error(e?.message || '加载失败,请稍后重试');
@@ -120,17 +119,30 @@ const BillsPage: React.FC = () => {
}
};
const handleCancel = async (id: number) => {
let reason = '';
Modal.confirm({
title: '取消账单并退回已扣余额',
content: <Input.TextArea placeholder="请输入取消原因" maxLength={300} onChange={(event) => { reason = event.target.value; }} />,
okText: '确认取消', cancelText: '返回',
content: (
<Input.TextArea
placeholder="请输入取消原因"
maxLength={300}
onChange={(event) => {
reason = event.target.value;
}}
/>
),
okText: '确认取消',
cancelText: '返回',
onOk: async () => {
if (!reason.trim()) { message.error('请输入取消原因'); throw new Error('reason required'); }
await api.post(`/bills/${id}/cancel`, { operationId: newOperationId(), reason: reason.trim() });
if (!reason.trim()) {
message.error('请输入取消原因');
throw new Error('reason required');
}
await api.post(`/bills/${id}/cancel`, {
operationId: newOperationId(),
reason: reason.trim(),
});
message.success('账单已取消,已扣余额已冲正退回');
fetchData();
},
@@ -142,7 +154,9 @@ const BillsPage: React.FC = () => {
await api.delete(`/bills/${id}`);
message.success('账单已归档');
fetchData();
} catch (error: any) { message.error(error?.message || '归档失败'); }
} catch (error: any) {
message.error(error?.message || '归档失败');
}
};
const batchArchive = async () => {
@@ -175,7 +189,9 @@ const BillsPage: React.FC = () => {
return;
}
printWindow.document.write('<p style="font-family:sans-serif;padding:24px">正在加载账单...</p>');
printWindow.document.write(
'<p style="font-family:sans-serif;padding:24px">正在加载账单...</p>',
);
try {
const bill = await api.get<BillPrintData>(`/bills/${billId}`);
printWindow.document.open();
@@ -187,89 +203,125 @@ const BillsPage: React.FC = () => {
}
};
const columns = useMemo(() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{ title: '账单周期', width: 200, render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}` },
{
title: '分摊费用',
dataIndex: 'sharedAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '个人费用',
dataIndex: 'personalAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '总计',
dataIndex: 'totalAmount',
width: 100,
align: 'right' as const,
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
},
{
title: '已扣余额', dataIndex: 'paidAmount', width: 110,
render: (value: number) => <span style={{ color: '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</span>,
},
{
title: '待补缴', dataIndex: 'outstandingAmount', width: 110,
render: (value: number) => <strong style={{ color: Number(value) > 0 ? '#cf1322' : '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</strong>,
},
{
title: '钱包余额', dataIndex: 'walletBalance', width: 110,
render: (value: number) => `¥${Number(value || 0).toFixed(2)}`,
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text}</Tag>,
},
{
title: '生成时间',
dataIndex: 'generatedAt',
width: 160,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
{
title: '操作',
width: 320,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="bill:view"
size="small"
type="link"
onClick={() => showDetail(record.id)}
>
</PermissionButton>
<PermissionButton
permission="bill:export-pdf"
size="small"
icon={<FilePdfOutlined />}
onClick={() => handleExportPdf(record.id)}
>
PDF
</PermissionButton>
{record.status !== 'cancelled' && (
<PermissionButton permission="bill:delete" size="small" danger onClick={() => handleCancel(record.id)}>
const columns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{
title: '账单周期',
width: 200,
render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}`,
},
{
title: '分摊费用',
dataIndex: 'sharedAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '个人费用',
dataIndex: 'personalAmount',
width: 120,
align: 'right' as const,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '总计',
dataIndex: 'totalAmount',
width: 100,
align: 'right' as const,
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
},
{
title: '已扣余额',
dataIndex: 'paidAmount',
width: 110,
render: (value: number) => (
<span style={{ color: '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</span>
),
},
{
title: '待补缴',
dataIndex: 'outstandingAmount',
width: 110,
render: (value: number) => (
<strong style={{ color: Number(value) > 0 ? '#cf1322' : '#389e0d' }}>
¥{Number(value || 0).toFixed(2)}
</strong>
),
},
{
title: '钱包余额',
dataIndex: 'walletBalance',
width: 110,
render: (value: number) => `¥${Number(value || 0).toFixed(2)}`,
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text}</Tag>,
},
{
title: '生成时间',
dataIndex: 'generatedAt',
width: 160,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
{
title: '操作',
width: 320,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="bill:view"
size="small"
type="link"
onClick={() => showDetail(record.id)}
>
</PermissionButton>
)}
{Number(record.paidAmount || 0) === 0 && record.status !== 'cancelled' && (
<Popconfirm title="确定归档此未支付账单?" onConfirm={() => handleArchive(record.id)} okText="归档" cancelText="取消">
<PermissionButton permission="bill:delete" size="small" danger icon={<InboxOutlined />}></PermissionButton>
</Popconfirm>
)}
</Space>
),
},
], [showDetail, handleArchive, handleCancel, handleExportPdf]);
<PermissionButton
permission="bill:export-pdf"
size="small"
icon={<FilePdfOutlined />}
onClick={() => handleExportPdf(record.id)}
>
PDF
</PermissionButton>
{record.status !== 'cancelled' && (
<PermissionButton
permission="bill:delete"
size="small"
danger
onClick={() => handleCancel(record.id)}
>
</PermissionButton>
)}
{Number(record.paidAmount || 0) === 0 && record.status !== 'cancelled' && (
<Popconfirm
title="确定归档此未支付账单?"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
<PermissionButton
permission="bill:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
],
[showDetail, handleArchive, handleCancel, handleExportPdf],
);
return (
<div>
@@ -297,8 +349,20 @@ const BillsPage: React.FC = () => {
{ value: 'cancelled', label: '已取消' },
]}
/>
<Select placeholder="费用类型" allowClear style={{ width: 120 }} value={filterExpenseType} onChange={setFilterExpenseType}
options={[{value:'water',label:'水费'},{value:'electricity',label:'电费'},{value:'cleaning',label:'保洁费'},{value:'rent',label:'租金'},{value:'other',label:'其他'}]} />
<Select
placeholder="费用类型"
allowClear
style={{ width: 120 }}
value={filterExpenseType}
onChange={setFilterExpenseType}
options={[
{ value: 'water', label: '水费' },
{ value: 'electricity', label: '电费' },
{ value: 'cleaning', label: '保洁费' },
{ value: 'rent', label: '租金' },
{ value: 'other', label: '其他' },
]}
/>
<Popconfirm
title={`确定归档选中的 ${selectedRows.length} 条账单?`}
onConfirm={batchArchive}
@@ -371,7 +435,9 @@ const BillsPage: React.FC = () => {
picker="month"
placeholder="选择月份"
format="YYYY-MM"
disabledDate={(current) => !!current && !current.endOf('month').isBefore(dayjs(), 'day')}
disabledDate={(current) =>
!!current && !current.endOf('month').isBefore(dayjs(), 'day')
}
/>
</Form.Item>
</Form>
@@ -412,9 +478,15 @@ const BillsPage: React.FC = () => {
</Descriptions.Item>
</Descriptions>
<Descriptions bordered size="small" column={3} style={{ marginBottom: 16 }}>
<Descriptions.Item label="已扣余额">¥{Number(detailModal.paidAmount || 0).toFixed(2)}</Descriptions.Item>
<Descriptions.Item label="待补缴">¥{Number(detailModal.outstandingAmount || 0).toFixed(2)}</Descriptions.Item>
<Descriptions.Item label="当前钱包余额">¥{Number(detailModal.walletBalance || 0).toFixed(2)}</Descriptions.Item>
<Descriptions.Item label="已扣余额">
¥{Number(detailModal.paidAmount || 0).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="待补缴">
¥{Number(detailModal.outstandingAmount || 0).toFixed(2)}
</Descriptions.Item>
<Descriptions.Item label="当前钱包余额">
¥{Number(detailModal.walletBalance || 0).toFixed(2)}
</Descriptions.Item>
</Descriptions>
<h4></h4>
<Table

View File

@@ -1,8 +1,23 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
Card, Tabs, Descriptions, Table, Button, Space, Select, Modal, Tag,
Popconfirm, Form, Input, DatePicker, InputNumber, Row, Col, Statistic,
Card,
Tabs,
Descriptions,
Table,
Button,
Space,
Select,
Modal,
Tag,
Popconfirm,
Form,
Input,
DatePicker,
InputNumber,
Row,
Col,
Statistic,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ArrowLeftOutlined, PlusOutlined, DownloadOutlined } from '@ant-design/icons';
@@ -111,7 +126,13 @@ const ROLE_MAP: Record<string, string> = {
};
const WEEK_DAY_MAP: Record<number, string> = {
1: '周一', 2: '周二', 3: '周三', 4: '周四', 5: '周五', 6: '周六', 7: '周日',
1: '周一',
2: '周二',
3: '周三',
4: '周四',
5: '周五',
6: '周六',
7: '周日',
};
const SCHEDULE_TYPE_MAP: Record<string, string> = {
@@ -145,14 +166,18 @@ const ClassDetailPage: React.FC = () => {
// Schedule & attendance state
const [schedules, setSchedules] = useState<ClassScheduleItem[]>([]);
const [scheduleDateRange, setScheduleDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
const [scheduleDateRange, setScheduleDateRange] = useState<
[dayjs.Dayjs | null, dayjs.Dayjs | null]
>([null, null]);
const [attendanceSummary, setAttendanceSummary] = useState<AttendanceSummary | null>(null);
const [attendanceDateRange, setAttendanceDateRange] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
const [attendanceDateRange, setAttendanceDateRange] = useState<
[dayjs.Dayjs | null, dayjs.Dayjs | null]
>([null, null]);
const fetchDetail = useCallback(async () => {
setLoading(true);
try {
const res = await api.get(`/classes/${id}`) as ClassDetail;
const res = (await api.get(`/classes/${id}`)) as ClassDetail;
setDetail(res);
setStudents(res.students || []);
setTeachers(res.teachers || []);
@@ -164,7 +189,9 @@ const ClassDetailPage: React.FC = () => {
}
}, [id]);
useEffect(() => { fetchDetail(); }, [fetchDetail]);
useEffect(() => {
fetchDetail();
}, [fetchDetail]);
const fetchSchedules = useCallback(async () => {
if (!id) return;
@@ -180,7 +207,9 @@ const ClassDetailPage: React.FC = () => {
}
}, [id, scheduleDateRange]);
useEffect(() => { fetchSchedules(); }, [fetchSchedules]);
useEffect(() => {
fetchSchedules();
}, [fetchSchedules]);
const fetchAttendanceSummary = useCallback(async () => {
if (!id) return;
@@ -196,7 +225,9 @@ const ClassDetailPage: React.FC = () => {
}
}, [id, attendanceDateRange]);
useEffect(() => { fetchAttendanceSummary(); }, [fetchAttendanceSummary]);
useEffect(() => {
fetchAttendanceSummary();
}, [fetchAttendanceSummary]);
const handleSaveInfo = async () => {
try {
@@ -275,7 +306,9 @@ const ClassDetailPage: React.FC = () => {
const openStudentModal = async () => {
try {
const res = await api.get('/students', { params: { includeArchived: 'false' } }) as StudentItem[];
const res = (await api.get('/students', {
params: { includeArchived: 'false' },
})) as StudentItem[];
setAllStudents(res || []);
setSelectedStudentIds([]);
setStudentModalOpen(true);
@@ -287,7 +320,7 @@ const ClassDetailPage: React.FC = () => {
const openTeacherModal = async () => {
try {
const res = await api.get('/rbac/users') as UserItem[];
const res = (await api.get('/rbac/users')) as UserItem[];
setAllUsers(res || []);
setTeacherUserId(undefined);
setTeacherRole('subject_teacher');
@@ -310,9 +343,7 @@ const ClassDetailPage: React.FC = () => {
title: '状态',
dataIndex: 'status',
render: (v: string) => (
<Tag color={v === 'active' ? 'green' : 'default'}>
{v === 'active' ? '在读' : '已离班'}
</Tag>
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '在读' : '已离班'}</Tag>
),
},
{
@@ -320,7 +351,9 @@ const ClassDetailPage: React.FC = () => {
render: (_: unknown, r: ClassStudent) =>
r.status === 'active' ? (
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveStudent(r.studentId)}>
<PermissionButton permission="class:edit" size="small" danger></PermissionButton>
<PermissionButton permission="class:edit" size="small" danger>
</PermissionButton>
</Popconfirm>
) : null,
},
@@ -342,7 +375,9 @@ const ClassDetailPage: React.FC = () => {
title: '操作',
render: (_: unknown, r: ClassTeacher) => (
<Popconfirm title="确认移除?" onConfirm={() => handleRemoveTeacher(r.userId)}>
<PermissionButton permission="class:edit" size="small" danger></PermissionButton>
<PermissionButton permission="class:edit" size="small" danger>
</PermissionButton>
</Popconfirm>
),
},
@@ -351,15 +386,27 @@ const ClassDetailPage: React.FC = () => {
const scheduleColumns: ColumnsType<ClassScheduleItem> = [
{ title: '教室', dataIndex: 'classroomName', render: (v: string | null) => v || '-' },
{ title: '星期', dataIndex: 'weekDay', render: (v: number) => WEEK_DAY_MAP[v] || v },
{ title: '时间', render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}` },
{ title: '签到窗口', render: (_: unknown, r: ClassScheduleItem) => `课前 ${r.attendanceAdvanceMinutes ?? 30} 分钟至下课` },
{ title: '日期范围', render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}` },
{
title: '时间',
render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}`,
},
{
title: '签到窗口',
render: (_: unknown, r: ClassScheduleItem) =>
`课前 ${r.attendanceAdvanceMinutes ?? 30} 分钟至下课`,
},
{
title: '日期范围',
render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}`,
},
{ title: '科目', dataIndex: 'subject' },
{ title: '类型', dataIndex: 'scheduleType', render: (v: string) => SCHEDULE_TYPE_MAP[v] || v },
{
title: '状态',
dataIndex: 'status',
render: (v: string) => <Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>,
render: (v: string) => (
<Tag color={v === 'active' ? 'green' : 'default'}>{v === 'active' ? '启用' : v}</Tag>
),
},
];
@@ -368,7 +415,9 @@ const ClassDetailPage: React.FC = () => {
title={
<Space>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/classes')} />
<span>{detail.name} ({detail.code})</span>
<span>
{detail.name} ({detail.code})
</span>
<Tag color={STATUS_MAP[detail.status]?.color}>{STATUS_MAP[detail.status]?.text}</Tag>
</Space>
}
@@ -434,7 +483,11 @@ const ClassDetailPage: React.FC = () => {
<Input.TextArea rows={3} />
</Form.Item>
<Space>
<PermissionButton permission="class:edit" type="primary" onClick={handleSaveInfo}>
<PermissionButton
permission="class:edit"
type="primary"
onClick={handleSaveInfo}
>
</PermissionButton>
<Button onClick={() => setEditingInfo(false)}></Button>
@@ -458,9 +511,7 @@ const ClassDetailPage: React.FC = () => {
<Descriptions.Item label="班主任">
{teachers.find((t) => t.roleType === 'head_teacher')?.username || '-'}
</Descriptions.Item>
<Descriptions.Item label="备注">
{detail.notes || '-'}
</Descriptions.Item>
<Descriptions.Item label="备注">{detail.notes || '-'}</Descriptions.Item>
</Descriptions>
<PermissionButton
permission="class:edit"
@@ -627,10 +678,12 @@ const ClassDetailPage: React.FC = () => {
label: '课表',
children: (
<div>
<Space style={{ marginBottom: 16 }}>
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
<DatePicker.RangePicker
value={scheduleDateRange}
onChange={(dates) => setScheduleDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
onChange={(dates) =>
setScheduleDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
}
placeholder={['开始日期', '结束日期']}
/>
</Space>
@@ -638,6 +691,7 @@ const ClassDetailPage: React.FC = () => {
columns={scheduleColumns}
dataSource={schedules}
rowKey="id"
scroll={{ x: 'max-content' }}
pagination={{
defaultPageSize: 20,
showSizeChanger: true,
@@ -652,31 +706,37 @@ const ClassDetailPage: React.FC = () => {
label: '出勤汇总',
children: (
<div>
<Space style={{ marginBottom: 16 }}>
<Space style={{ marginBottom: 16, maxWidth: '100%' }} wrap>
<DatePicker.RangePicker
value={attendanceDateRange}
onChange={(dates) => setAttendanceDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])}
onChange={(dates) =>
setAttendanceDateRange(dates as [dayjs.Dayjs | null, dayjs.Dayjs | null])
}
placeholder={['开始日期', '结束日期']}
/>
</Space>
{attendanceSummary && (
<Row gutter={16}>
<Col span={6}>
<Row gutter={[16, 16]}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="总记录" value={attendanceSummary.total} />
</Card>
</Col>
<Col span={6}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="出勤率" value={attendanceSummary.presentRate} suffix="%" />
<Statistic
title="出勤率"
value={attendanceSummary.presentRate}
suffix="%"
/>
</Card>
</Col>
<Col span={6}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="缺勤率" value={attendanceSummary.absentRate} suffix="%" />
</Card>
</Col>
<Col span={6}>
<Col xs={12} md={6}>
<Card bordered={false}>
<Statistic title="迟到率" value={attendanceSummary.lateRate} suffix="%" />
</Card>

View File

@@ -1,7 +1,19 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
Table, Button, Input, Select, Space, Tag, Modal, Form, InputNumber,
DatePicker, Popconfirm, Card, Switch, Empty,
Table,
Button,
Input,
Select,
Space,
Tag,
Modal,
Form,
InputNumber,
DatePicker,
Popconfirm,
Card,
Switch,
Empty,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, SearchOutlined, TeamOutlined, InboxOutlined } from '@ant-design/icons';
@@ -96,13 +108,14 @@ const ClassesPage: React.FC = () => {
setData(res);
} catch (e: any) {
message.error(e?.message || '加载失败,请稍后重试');
}
finally {
} finally {
setLoading(false);
}
}, [filterStatus, filterType, showArchived]);
useEffect(() => { fetchData(); }, [fetchData]);
useEffect(() => {
fetchData();
}, [fetchData]);
const filtered = useMemo(() => {
if (!searchText) return data;
@@ -154,58 +167,86 @@ const ClassesPage: React.FC = () => {
}
};
const columns: ColumnsType<ClassItem> = useMemo(() => [
{
title: '班级名称', dataIndex: 'name', width: 120,
sorter: (a, b) => a.name.localeCompare(b.name),
},
{ title: '编码', dataIndex: 'code', width: 140 },
{
title: '班型', dataIndex: 'classType', width: 100,
render: (v: string) => <Tag>{TYPE_MAP[v] || v}</Tag>,
},
{
title: '开班日期', dataIndex: 'startDate', width: 110,
render: (v: string | null) => v || '-',
},
{
title: '学员', width: 100,
render: (_: unknown, r: ClassItem) => `${r.studentCount || 0}/${r.maxStudents || '-'}`,
},
{
title: '状态', dataIndex: 'status', width: 100,
render: (v: string) => {
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
return <Tag color={cfg.color}>{cfg.text}</Tag>;
const columns: ColumnsType<ClassItem> = useMemo(
() => [
{
title: '班级名称',
dataIndex: 'name',
width: 120,
sorter: (a, b) => a.name.localeCompare(b.name),
},
},
{
title: '操作', width: 280,
render: (_: unknown, r: ClassItem) => (
<Space>
<Button size="small" icon={<TeamOutlined />} onClick={() => navigate(`/classes/${r.id}`)}>
</Button>
<PermissionButton permission="class:edit" size="small" onClick={() => handleEdit(r)}>
</PermissionButton>
{r.isArchived ? (
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
<PermissionButton permission="class:edit" size="small"></PermissionButton>
</Popconfirm>
) : (
<Popconfirm title="归档后可恢复,确认归档?" onConfirm={() => handleArchive(r.id, true)}>
<PermissionButton permission="class:edit" size="small"></PermissionButton>
</Popconfirm>
)}
</Space>
),
},
], []);
{ title: '编码', dataIndex: 'code', width: 140 },
{
title: '班型',
dataIndex: 'classType',
width: 100,
render: (v: string) => <Tag>{TYPE_MAP[v] || v}</Tag>,
},
{
title: '开班日期',
dataIndex: 'startDate',
width: 110,
render: (v: string | null) => v || '-',
},
{
title: '学员',
width: 100,
render: (_: unknown, r: ClassItem) => `${r.studentCount || 0}/${r.maxStudents || '-'}`,
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (v: string) => {
const cfg = STATUS_MAP[v] || { color: 'default', text: v };
return <Tag color={cfg.color}>{cfg.text}</Tag>;
},
},
{
title: '操作',
width: 280,
render: (_: unknown, r: ClassItem) => (
<Space>
<Button
size="small"
icon={<TeamOutlined />}
onClick={() => navigate(`/classes/${r.id}`)}
>
</Button>
<PermissionButton permission="class:edit" size="small" onClick={() => handleEdit(r)}>
</PermissionButton>
{r.isArchived ? (
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(r.id, false)}>
<PermissionButton permission="class:edit" size="small">
</PermissionButton>
</Popconfirm>
) : (
<Popconfirm
title="归档后可恢复,确认归档?"
onConfirm={() => handleArchive(r.id, true)}
>
<PermissionButton permission="class:edit" size="small">
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
],
[],
);
return (
<Card>
<Space style={{ marginBottom: 16 }} wrap className="responsive-toolbar responsive-toolbar--single">
<Space
style={{ marginBottom: 16 }}
wrap
className="responsive-toolbar responsive-toolbar--single"
>
<Input
placeholder="搜索名称/编码"
prefix={<SearchOutlined />}
@@ -229,7 +270,12 @@ const ClassesPage: React.FC = () => {
onChange={setFilterStatus}
options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))}
/>
<PermissionButton permission="class:create" type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
<PermissionButton
permission="class:create"
type="primary"
icon={<PlusOutlined />}
onClick={handleCreate}
>
</PermissionButton>
<span style={{ marginLeft: 8 }}>
@@ -287,7 +333,9 @@ const ClassesPage: React.FC = () => {
</Form.Item>
</Space>
<Form.Item name="status" label="状态" initialValue="enrolling">
<Select options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))} />
<Select
options={Object.entries(STATUS_MAP).map(([k, v]) => ({ value: k, label: v.text }))}
/>
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={3} />

View File

@@ -15,7 +15,13 @@ import {
Tooltip,
Empty,
} from 'antd';
import { PlusOutlined, UploadOutlined, FileTextOutlined, StopOutlined, CheckOutlined } from '@ant-design/icons';
import {
PlusOutlined,
UploadOutlined,
FileTextOutlined,
StopOutlined,
CheckOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import api from '../../api';
import { downloadBlob } from '../../utils/download';
@@ -392,17 +398,36 @@ const ClassroomRentalsPage: React.FC = () => {
<Space>
{record.effectiveStatus === 'active' && (
<>
<PermissionButton permission="rental:edit" size="small" onClick={() => openEdit(record)}>
<PermissionButton
permission="rental:edit"
size="small"
onClick={() => openEdit(record)}
>
</PermissionButton>
<Popconfirm title="确定取消该租赁?" onConfirm={() => handleRentalAction(record.id, 'cancel')}>
<PermissionButton permission="rental:edit" size="small" danger icon={<StopOutlined />}>
<Popconfirm
title="确定取消该租赁?"
onConfirm={() => handleRentalAction(record.id, 'cancel')}
>
<PermissionButton
permission="rental:edit"
size="small"
danger
icon={<StopOutlined />}
>
</PermissionButton>
</Popconfirm>
{!dayjs(record.startDate).isAfter(dayjs(), 'day') && (
<Popconfirm title="确定今天结束该租赁?" onConfirm={() => handleRentalAction(record.id, 'end')}>
<PermissionButton permission="rental:edit" size="small" icon={<CheckOutlined />}>
<Popconfirm
title="确定今天结束该租赁?"
onConfirm={() => handleRentalAction(record.id, 'end')}
>
<PermissionButton
permission="rental:edit"
size="small"
icon={<CheckOutlined />}
>
</PermissionButton>
</Popconfirm>
@@ -410,8 +435,13 @@ const ClassroomRentalsPage: React.FC = () => {
</>
)}
{record.effectiveStatus !== 'active' && (
<Popconfirm title="确定归档该租赁订单?合同文件会保留。" onConfirm={() => handleDelete(record.id)}>
<PermissionButton permission="rental:delete" size="small" danger></PermissionButton>
<Popconfirm
title="确定归档该租赁订单?合同文件会保留。"
onConfirm={() => handleDelete(record.id)}
>
<PermissionButton permission="rental:delete" size="small" danger>
</PermissionButton>
</Popconfirm>
)}
</Space>
@@ -511,10 +541,12 @@ const ClassroomRentalsPage: React.FC = () => {
optionFilterProp="label"
placeholder="选择教室"
onChange={handleClassroomChange}
options={classrooms.filter((c) => c.status === 'available').map((c) => ({
value: c.id,
label: `${c.building ? c.building + ' · ' : ''}${c.name}${c.roomType}`,
}))}
options={classrooms
.filter((c) => c.status === 'available')
.map((c) => ({
value: c.id,
label: `${c.building ? c.building + ' · ' : ''}${c.name}${c.roomType}`,
}))}
/>
</Form.Item>
<Form.Item name="lessorOrganizationId" label="出租机构" tooltip="默认由本机构出租">
@@ -559,10 +591,10 @@ const ClassroomRentalsPage: React.FC = () => {
/>
</Form.Item>
<Form.Item name="dailyRate" label="日租金(可选)">
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} prefix="¥" />
</Form.Item>
<Form.Item name="totalAmount" label="合同总额(可选)">
<InputNumber min={0} precision={2} style={{ width: '100%' }} prefix="¥" />
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} prefix="¥" />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />

View File

@@ -60,8 +60,16 @@ const ClassroomsPage: React.FC = () => {
const filteredData = useMemo(() => {
let result = data;
if (searchText) { const s = searchText.toLowerCase(); result = result.filter((d: Record<string, unknown>) => (typeof d.name === 'string' && d.name.toLowerCase().includes(s)) || (typeof d.building === 'string' && d.building.toLowerCase().includes(s))); }
if (filterStatus) result = result.filter((d: Record<string, unknown>) => d.effectiveStatus === filterStatus);
if (searchText) {
const s = searchText.toLowerCase();
result = result.filter(
(d: Record<string, unknown>) =>
(typeof d.name === 'string' && d.name.toLowerCase().includes(s)) ||
(typeof d.building === 'string' && d.building.toLowerCase().includes(s)),
);
}
if (filterStatus)
result = result.filter((d: Record<string, unknown>) => d.effectiveStatus === filterStatus);
return result;
}, [data, searchText, filterStatus]);
@@ -140,72 +148,98 @@ const ClassroomsPage: React.FC = () => {
.catch(() => message.error('下载失败'));
};
const columns = useMemo(() => [
{
title: '教室名', width: 120,
dataIndex: 'name',
sorter: (a: any, b: any) => a.name.localeCompare(b.name),
},
{ title: '楼栋', dataIndex: 'building', width: 80 },
{ title: '楼层', dataIndex: 'floor', width: 80 },
{
title: '类型', width: 90,
dataIndex: 'roomType',
render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>,
},
{ title: '容量', dataIndex: 'capacity', width: 80 },
{
title: '状态', width: 100,
dataIndex: 'status',
render: (_s: string, record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null }) => {
const effectiveStatus = record.effectiveStatus || record.status;
return (
<Tooltip title={record.currentUsage ? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})` : undefined}>
<Tag color={statusMap[effectiveStatus]?.color}>{statusMap[effectiveStatus]?.text || effectiveStatus}</Tag>
</Tooltip>
);
const columns = useMemo(
() => [
{
title: '教室名',
width: 120,
dataIndex: 'name',
sorter: (a: any, b: any) => a.name.localeCompare(b.name),
},
},
{
title: '操作',
width: 180,
render: (_: any, record: any) => (
<Space>
{record.status === 'archived' ? (
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
<PermissionButton permission="classroom:edit" size="small" icon={<UndoOutlined />} type="link">
</PermissionButton>
</Popconfirm>
) : (
<>
<PermissionButton
permission="classroom:edit"
size="small"
onClick={() => {
setEditing(record);
form.setFieldsValue(record);
setModalOpen(true);
}}
>
</PermissionButton>
<Popconfirm
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
<PermissionButton permission="classroom:delete" size="small" icon={<InboxOutlined />}>
{ title: '楼栋', dataIndex: 'building', width: 80 },
{ title: '楼层', dataIndex: 'floor', width: 80 },
{
title: '类型',
width: 90,
dataIndex: 'roomType',
render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>,
},
{ title: '容量', dataIndex: 'capacity', width: 80 },
{
title: '状态',
width: 100,
dataIndex: 'status',
render: (
_s: string,
record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null },
) => {
const effectiveStatus = record.effectiveStatus || record.status;
return (
<Tooltip
title={
record.currentUsage
? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})`
: undefined
}
>
<Tag color={statusMap[effectiveStatus]?.color}>
{statusMap[effectiveStatus]?.text || effectiveStatus}
</Tag>
</Tooltip>
);
},
},
{
title: '操作',
width: 180,
render: (_: any, record: any) => (
<Space>
{record.status === 'archived' ? (
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}>
<PermissionButton
permission="classroom:edit"
size="small"
icon={<UndoOutlined />}
type="link"
>
</PermissionButton>
</Popconfirm>
</>
)}
</Space>
),
},
], []);
) : (
<>
<PermissionButton
permission="classroom:edit"
size="small"
onClick={() => {
setEditing(record);
form.setFieldsValue(record);
setModalOpen(true);
}}
>
</PermissionButton>
<Popconfirm
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。"
onConfirm={() => handleArchive(record.id)}
okText="归档"
cancelText="取消"
>
<PermissionButton
permission="classroom:delete"
size="small"
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</>
)}
</Space>
),
},
],
[],
);
return (
<div>
@@ -228,7 +262,20 @@ const ClassroomsPage: React.FC = () => {
if (!e.target.value) setSearchText('');
}}
/>
<Select placeholder="状态" allowClear style={{ width: 110 }} value={filterStatus} onChange={setFilterStatus} options={[{value:'available',label:'可用'},{value:'in_use',label:'使用中'},{value:'reserved',label:'已预留'},{value:'maintenance',label:'维护中'},{value:'archived',label:'已归档'}]} />
<Select
placeholder="状态"
allowClear
style={{ width: 110 }}
value={filterStatus}
onChange={setFilterStatus}
options={[
{ value: 'available', label: '可用' },
{ value: 'in_use', label: '使用中' },
{ value: 'reserved', label: '已预留' },
{ value: 'maintenance', label: '维护中' },
{ value: 'archived', label: '已归档' },
]}
/>
<Button
type={showArchived ? 'primary' : 'default'}
onClick={() => setShowArchived(!showArchived)}
@@ -249,7 +296,26 @@ const ClassroomsPage: React.FC = () => {
>
</PermissionButton>
<PermissionButton permission="classroom:view" icon={<DownloadOutlined />} onClick={() => { const baseURL = '/api'; const token = localStorage.getItem('token'); fetch(`${baseURL}/classrooms/export`, { headers: { Authorization: `Bearer ${token}` } }).then(r => r.blob()).then(b => { const a = document.createElement('a'); a.href = URL.createObjectURL(b); a.download = '教室使用报表.xlsx'; a.click(); }); }}></PermissionButton>
<PermissionButton
permission="classroom:view"
icon={<DownloadOutlined />}
onClick={() => {
const baseURL = '/api';
const token = localStorage.getItem('token');
fetch(`${baseURL}/classrooms/export`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((r) => r.blob())
.then((b) => {
const a = document.createElement('a');
a.href = URL.createObjectURL(b);
a.download = '教室使用报表.xlsx';
a.click();
});
}}
>
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}

View File

@@ -3,9 +3,7 @@ import { buildDepositStudentOption, buildDepositStudentOptions } from './deposit
describe('deposit student option', () => {
it('uses the student number as the non-sensitive identifier', () => {
expect(
buildDepositStudentOption({ id: 23, name: '张三', studentNo: 'S2026001' }),
).toEqual({
expect(buildDepositStudentOption({ id: 23, name: '张三', studentNo: 'S2026001' })).toEqual({
value: 23,
label: '张三 (S2026001)',
});
@@ -28,7 +26,14 @@ describe('deposit student option', () => {
});
it('includes room type when available', () => {
expect(buildDepositStudentOption({ id: 23, name: '张三', studentNo: 'S2026001', roomType: '四人间' })).toEqual({
expect(
buildDepositStudentOption({
id: 23,
name: '张三',
studentNo: 'S2026001',
roomType: '四人间',
}),
).toEqual({
value: 23,
label: '张三 (S2026001) - 四人间',
});

View File

@@ -50,7 +50,13 @@ interface DepositRecord {
paidDate: string;
refundDate?: string | null;
notes?: string | null;
installments?: Array<{ id: number; amount: number; dueDate: string; paidDate?: string | null; status: string }>;
installments?: Array<{
id: number;
amount: number;
dueDate: string;
paidDate?: string | null;
status: string;
}>;
student?: DepositStudentLookup;
}
@@ -67,9 +73,9 @@ interface EligibleStudent {
}
const isFormValidationError = (error: unknown) =>
typeof error === 'object'
&& error !== null
&& Array.isArray((error as { errorFields?: unknown }).errorFields);
typeof error === 'object' &&
error !== null &&
Array.isArray((error as { errorFields?: unknown }).errorFields);
const DepositsPage: React.FC = () => {
const [data, setData] = useState<DepositRecord[]>([]);
@@ -141,7 +147,12 @@ const DepositsPage: React.FC = () => {
if (filterRoomType) {
const s = searchText.trim().toLowerCase();
return eligibleStudents
.filter((item) => !s || item.studentName.toLowerCase().includes(s) || item.studentNo?.toLowerCase().includes(s))
.filter(
(item) =>
!s ||
item.studentName.toLowerCase().includes(s) ||
item.studentNo?.toLowerCase().includes(s),
)
.map((item) => {
const deposit = depositByStudentId.get(item.studentId);
return {
@@ -176,12 +187,7 @@ const DepositsPage: React.FC = () => {
});
}, [data, depositByStudentId, eligibleStudents, filterRoomType, filterStatus, searchText]);
const studentOptions = useMemo(
() => buildDepositStudentOptions(students),
[students],
);
const studentOptions = useMemo(() => buildDepositStudentOptions(students), [students]);
const openBatchModal = (roomType = filterRoomType || '四人间') => {
const amount = suggestedDepositByRoomType[roomType] ?? 100;
@@ -194,7 +200,9 @@ const DepositsPage: React.FC = () => {
const handleBatchRoomTypeChange = (roomType: string) => {
setBatchRoomType(roomType);
batchForm.setFieldsValue({ amount: suggestedDepositByRoomType[roomType] ?? batchForm.getFieldValue('amount') ?? 100 });
batchForm.setFieldsValue({
amount: suggestedDepositByRoomType[roomType] ?? batchForm.getFieldValue('amount') ?? 100,
});
fetchEligibleStudents(roomType);
};
@@ -316,87 +324,115 @@ const DepositsPage: React.FC = () => {
}
};
const columns = useMemo(() => [
{ title: '学生', width: 120, render: (_: unknown, r: any) => r.student?.name || '-' },
{ title: '当前可用押金', dataIndex: 'amount', width: 130, render: (v: number) => `¥${Number(v || 0).toFixed(2)}` },
{ title: '房间', width: 120, render: (_: unknown, r: any) => r.roomNumber ? `${r.building ? `${r.building}-` : ''}${r.roomNumber}` : '-' },
{ title: '房型', dataIndex: 'roomType', width: 100, render: (v: string) => v || '-' },
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120, render: (v: string) => v || '-' },
{
title: '状态',
dataIndex: 'status',
render: (s: string) => s === 'unpaid'
? <Tag color="default"></Tag>
: <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
},
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: unknown) => v || '-' },
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: unknown) => v || '-' },
{
title: '操作',
width: 240,
render: (_: unknown, record: any) => {
const hasDeposit = typeof record.id === 'number';
return (
<Space>
{hasDeposit && (
<PermissionButton
permission="deposit:view"
size="small"
onClick={() => {
setDetailModal(record);
}}
>
</PermissionButton>
)}
{record.status === 'paid' && hasDeposit && (
<PermissionButton
permission="deposit:refund"
size="small"
type="primary"
onClick={() => {
setRefundModal(record);
refundForm.setFieldsValue({ refundDate: dayjs() });
}}
>
退
</PermissionButton>
)}
{hasDeposit && (
<Popconfirm
title="确定归档?"
onConfirm={async () => {
try {
await api.delete(`/deposits/${record.id}`);
message.success('归档成功');
fetchData();
fetchEligibleStudents(filterRoomType);
} catch (e: any) {
message.error(e?.message || '归档失败');
}
}}
>
<PermissionButton
permission="deposit:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
);
const columns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: unknown, r: any) => r.student?.name || '-' },
{
title: '当前可用押金',
dataIndex: 'amount',
width: 130,
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
},
},
], [fetchData, fetchEligibleStudents, filterRoomType, refundForm]);
{
title: '房间',
width: 120,
render: (_: unknown, r: any) =>
r.roomNumber ? `${r.building ? `${r.building}-` : ''}${r.roomNumber}` : '-',
},
{ title: '房型', dataIndex: 'roomType', width: 100, render: (v: string) => v || '-' },
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120, render: (v: string) => v || '-' },
{
title: '状态',
dataIndex: 'status',
render: (s: string) =>
s === 'unpaid' ? (
<Tag color="default"></Tag>
) : (
<Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
),
},
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: unknown) => v || '-' },
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: unknown) => v || '-' },
{
title: '操作',
width: 240,
render: (_: unknown, record: any) => {
const hasDeposit = typeof record.id === 'number';
return (
<Space>
{hasDeposit && (
<PermissionButton
permission="deposit:view"
size="small"
onClick={() => {
setDetailModal(record);
}}
>
</PermissionButton>
)}
{record.status === 'paid' && hasDeposit && (
<PermissionButton
permission="deposit:refund"
size="small"
type="primary"
onClick={() => {
setRefundModal(record);
refundForm.setFieldsValue({ refundDate: dayjs() });
}}
>
退
</PermissionButton>
)}
{hasDeposit && (
<Popconfirm
title="确定归档?"
onConfirm={async () => {
try {
await api.delete(`/deposits/${record.id}`);
message.success('归档成功');
fetchData();
fetchEligibleStudents(filterRoomType);
} catch (e: any) {
message.error(e?.message || '归档失败');
}
}}
>
<PermissionButton
permission="deposit:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
);
},
},
],
[fetchData, fetchEligibleStudents, filterRoomType, refundForm],
);
const eligibleColumns = [
{ title: '学生', render: (_: unknown, r: EligibleStudent) => `${r.studentName} (${r.studentNo || `#${r.studentId}`})` },
{ title: '房间', render: (_: unknown, r: EligibleStudent) => `${r.building ? `${r.building}-` : ''}${r.roomNumber}` },
{
title: '学生',
render: (_: unknown, r: EligibleStudent) =>
`${r.studentName} (${r.studentNo || `#${r.studentId}`})`,
},
{
title: '房间',
render: (_: unknown, r: EligibleStudent) =>
`${r.building ? `${r.building}-` : ''}${r.roomNumber}`,
},
{ title: '房型', dataIndex: 'roomType' },
{ title: '当前押金', dataIndex: 'depositAmount', render: (v: number) => `¥${Number(v || 0).toFixed(2)}` },
{
title: '当前押金',
dataIndex: 'depositAmount',
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
},
];
return (
@@ -492,13 +528,29 @@ const DepositsPage: React.FC = () => {
>
<Form form={batchForm} layout="vertical">
<Space style={{ width: '100%' }} align="start" wrap>
<Form.Item name="roomType" label="房型" rules={[{ required: true, message: '请选择房型' }]}>
<Select style={{ width: 140 }} options={roomTypeOptions} onChange={handleBatchRoomTypeChange} />
<Form.Item
name="roomType"
label="房型"
rules={[{ required: true, message: '请选择房型' }]}
>
<Select
style={{ width: 140 }}
options={roomTypeOptions}
onChange={handleBatchRoomTypeChange}
/>
</Form.Item>
<Form.Item name="amount" label="每人收取金额(元)" rules={[{ required: true, message: '请输入金额' }]}>
<Form.Item
name="amount"
label="每人收取金额(元)"
rules={[{ required: true, message: '请输入金额' }]}
>
<InputNumber min={0.01} precision={2} style={{ width: 180 }} />
</Form.Item>
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true, message: '请选择日期' }]}>
<Form.Item
name="paidDate"
label="收取日期"
rules={[{ required: true, message: '请选择日期' }]}
>
<DatePicker style={{ width: 180 }} placeholder="选择收取日期" format="YYYY-MM-DD" />
</Form.Item>
</Space>
@@ -509,7 +561,9 @@ const DepositsPage: React.FC = () => {
<div style={{ marginBottom: 8 }}>
<strong>{selectedEligibleStudentIds.length}</strong> / {eligibleStudents.length}
{suggestedDepositByRoomType[batchRoomType] && (
<span style={{ color: '#999', marginLeft: 8 }}>¥{suggestedDepositByRoomType[batchRoomType]}</span>
<span style={{ color: '#999', marginLeft: 8 }}>
¥{suggestedDepositByRoomType[batchRoomType]}
</span>
)}
</div>
<Table
@@ -549,10 +603,10 @@ const DepositsPage: React.FC = () => {
options={studentOptions}
/>
</Form.Item>
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true }]}>
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择收取日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="notes" label="备注">
@@ -574,7 +628,7 @@ const DepositsPage: React.FC = () => {
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
</div>
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="notes" label="备注">
@@ -594,19 +648,34 @@ const DepositsPage: React.FC = () => {
{detailModal && (
<div>
<Card size="small" style={{ marginBottom: 16 }}>
<p><strong>:</strong> ¥{Number(detailModal.amount).toFixed(2)}</p>
<p><strong>:</strong> {detailModal.paidDate}</p>
<p>
<strong>:</strong> ¥{Number(detailModal.amount).toFixed(2)}
</p>
<p>
<strong>:</strong> {detailModal.paidDate}
</p>
<p>
<strong>:</strong>{' '}
<Tag color={statusMap[detailModal.status]?.color}>
{statusMap[detailModal.status]?.text || detailModal.status}
</Tag>
</p>
{detailModal.notes && <p><strong>:</strong> {detailModal.notes}</p>}
{detailModal.notes && (
<p>
<strong>:</strong> {detailModal.notes}
</p>
)}
</Card>
{/* Installments Section */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 8,
}}
>
<h4 style={{ margin: 0 }}></h4>
<PermissionButton
permission="deposit:edit"
@@ -644,7 +713,13 @@ const DepositsPage: React.FC = () => {
title="确定归档?"
onConfirm={() => handleDeleteInstallment(item.id)}
>
<PermissionButton key="del" permission="deposit:delete" size="small" danger icon={<InboxOutlined />}>
<PermissionButton
key="del"
permission="deposit:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>,
@@ -676,10 +751,10 @@ const DepositsPage: React.FC = () => {
okText="确认"
>
<Form form={installmentForm} layout="vertical">
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="dueDate" label="到期日期" rules={[{ required: true }]}>
<Form.Item name="dueDate" label="到期日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择到期日期" format="YYYY-MM-DD" />
</Form.Item>
</Form>

View File

@@ -32,11 +32,9 @@ import { message } from '../../ui/app-message';
const { RangePicker } = DatePicker;
const isFormValidationError = (error: unknown) =>
typeof error === 'object'
&& error !== null
&& Array.isArray((error as { errorFields?: unknown }).errorFields);
typeof error === 'object' &&
error !== null &&
Array.isArray((error as { errorFields?: unknown }).errorFields);
const ExpensesPage: React.FC = () => {
const [roomExpenses, setRoomExpenses] = useState<any[]>([]);
@@ -63,27 +61,32 @@ const ExpensesPage: React.FC = () => {
// Dynamic expense type options from API
const [typeOptions, setTypeOptions] = useState<{ value: string; label: string }[]>([]);
const [personalTypeOptions, setPersonalTypeOptions] = useState<{ value: string; label: string }[]>([]);
const [personalTypeOptions, setPersonalTypeOptions] = useState<
{ value: string; label: string }[]
>([]);
const [typeMap, setTypeMap] = useState<Record<string, string>>({});
useEffect(() => {
api.get<Array<{ code: string; name: string; category: string }>>('/expense-types').then((types) => {
const roomTypes: { value: string; label: string }[] = [];
const personalTypes: { value: string; label: string }[] = [];
const map: Record<string, string> = {};
for (const t of types) {
map[t.code] = t.name;
if (t.category === 'room' || t.category === 'both') {
roomTypes.push({ value: t.code, label: t.name });
api
.get<Array<{ code: string; name: string; category: string }>>('/expense-types')
.then((types) => {
const roomTypes: { value: string; label: string }[] = [];
const personalTypes: { value: string; label: string }[] = [];
const map: Record<string, string> = {};
for (const t of types) {
map[t.code] = t.name;
if (t.category === 'room' || t.category === 'both') {
roomTypes.push({ value: t.code, label: t.name });
}
if (t.category === 'personal' || t.category === 'both') {
personalTypes.push({ value: t.code, label: t.name });
}
}
if (t.category === 'personal' || t.category === 'both') {
personalTypes.push({ value: t.code, label: t.name });
}
}
setTypeOptions(roomTypes);
setPersonalTypeOptions(personalTypes);
setTypeMap(map);
}).catch(() => {});
setTypeOptions(roomTypes);
setPersonalTypeOptions(personalTypes);
setTypeMap(map);
})
.catch(() => {});
}, []);
const handleBatchDeleteRoom = async () => {
@@ -207,12 +210,17 @@ const ExpensesPage: React.FC = () => {
description: values.description,
});
const bill = result.bill;
message.success(`账单已生成,已从余额扣除 ¥${Number(bill.paidAmount || 0).toFixed(2)},待补缴 ¥${Number(bill.outstandingAmount || 0).toFixed(2)}`);
message.success(
`账单已生成,已从余额扣除 ¥${Number(bill.paidAmount || 0).toFixed(2)},待补缴 ¥${Number(bill.outstandingAmount || 0).toFixed(2)}`,
);
setUtilityModal(false);
utilityForm.resetFields();
fetchData();
} catch (e: any) { message.error(e?.message || '水电费出账失败'); }
finally { setSaving(false); }
} catch (e: any) {
message.error(e?.message || '水电费出账失败');
} finally {
setSaving(false);
}
};
const handlePersonalExpense = async () => {
@@ -247,121 +255,139 @@ const ExpensesPage: React.FC = () => {
}
};
const roomColumns = useMemo(() => [
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
{
title: '费用类型', width: 100,
dataIndex: 'expenseType',
render: (v: string) => <Tag>{typeMap[v] || v}</Tag>,
},
{ title: '金额', dataIndex: 'amount', width: 100, render: (v: number) => `¥${Number(v).toFixed(2)}` },
{ title: '账单周期', width: 200, render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}` },
{ title: '说明', dataIndex: 'description', width: 150 },
{
title: '录入时间', width: 160,
dataIndex: 'createdAt',
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
{
title: '操作',
width: 120,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="expense:edit"
size="small"
icon={<EditOutlined />}
onClick={() => {
setEditingRoom(record);
roomForm.setFieldsValue({
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
period: [dayjs(record.periodStart), dayjs(record.periodEnd)],
description: record.description,
});
setRoomModal(true);
}}
>
</PermissionButton>
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/room/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
const roomColumns = useMemo(
() => [
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
{
title: '费用类型',
width: 100,
dataIndex: 'expenseType',
render: (v: string) => <Tag>{typeMap[v] || v}</Tag>,
},
{
title: '金额',
dataIndex: 'amount',
width: 100,
render: (v: number) => `¥${Number(v).toFixed(2)}`,
},
{
title: '账单周期',
width: 200,
render: (_: any, r: any) => `${r.periodStart} ~ ${r.periodEnd}`,
},
{ title: '说明', dataIndex: 'description', width: 150 },
{
title: '录入时间',
width: 160,
dataIndex: 'createdAt',
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
},
{
title: '操作',
width: 120,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="expense:delete"
permission="expense:edit"
size="small"
danger
icon={<InboxOutlined />}
icon={<EditOutlined />}
onClick={() => {
setEditingRoom(record);
roomForm.setFieldsValue({
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
period: [dayjs(record.periodStart), dayjs(record.periodEnd)],
description: record.description,
});
setRoomModal(true);
}}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
], [setEditingRoom, roomForm, setRoomModal, fetchData, typeMap]);
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/room/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
<PermissionButton
permission="expense:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
],
[setEditingRoom, roomForm, setRoomModal, fetchData, typeMap],
);
const personalColumns = useMemo(() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{
title: '费用类型', width: 100,
dataIndex: 'expenseType',
render: (v: string) => <Tag color="orange">{typeMap[v] || v}</Tag>,
},
{ title: '金额', dataIndex: 'amount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
{ title: '日期', dataIndex: 'expenseDate', width: 110 },
{ title: '说明', dataIndex: 'description', width: 150 },
{
title: '操作',
width: 120,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="expense:edit"
size="small"
icon={<EditOutlined />}
onClick={() => {
setEditingPersonal(record);
personalForm.setFieldsValue({
studentId: record.studentId,
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
expenseDate: dayjs(record.expenseDate),
description: record.description,
});
setPersonalModal(true);
}}
>
</PermissionButton>
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/personal/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
const personalColumns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{
title: '费用类型',
width: 100,
dataIndex: 'expenseType',
render: (v: string) => <Tag color="orange">{typeMap[v] || v}</Tag>,
},
{ title: '金额', dataIndex: 'amount', render: (v: number) => `¥${Number(v).toFixed(2)}` },
{ title: '日期', dataIndex: 'expenseDate', width: 110 },
{ title: '说明', dataIndex: 'description', width: 150 },
{
title: '操作',
width: 120,
render: (_: any, record: any) => (
<Space>
<PermissionButton
permission="expense:delete"
permission="expense:edit"
size="small"
danger
icon={<InboxOutlined />}
icon={<EditOutlined />}
onClick={() => {
setEditingPersonal(record);
personalForm.setFieldsValue({
studentId: record.studentId,
roomId: record.roomId,
expenseType: record.expenseType,
amount: Number(record.amount),
expenseDate: dayjs(record.expenseDate),
description: record.description,
});
setPersonalModal(true);
}}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
], [setEditingPersonal, personalForm, setPersonalModal, fetchData, typeMap]);
<Popconfirm
title="确定归档?"
onConfirm={async () => {
await api.delete(`/expenses/personal/${record.id}`);
message.success('归档成功');
fetchData();
}}
>
<PermissionButton
permission="expense:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
],
[setEditingPersonal, personalForm, setPersonalModal, fetchData, typeMap],
);
return (
<div>
@@ -430,8 +456,8 @@ const ExpensesPage: React.FC = () => {
permission="expense:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/expenses/utility/template', '水电费导入模板.xlsx').catch(() =>
message.error('下载失败'),
downloadBlob('/expenses/utility/template', '水电费导入模板.xlsx').catch(
() => message.error('下载失败'),
);
}}
>
@@ -547,9 +573,10 @@ const ExpensesPage: React.FC = () => {
permission="expense:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/expenses/personal/template', '个人附加费导入模板.xlsx').catch(
() => message.error('下载失败'),
);
downloadBlob(
'/expenses/personal/template',
'个人附加费导入模板.xlsx',
).catch(() => message.error('下载失败'));
}}
>
@@ -586,7 +613,10 @@ const ExpensesPage: React.FC = () => {
<PermissionButton
permission="expense:create"
icon={<PlusOutlined />}
onClick={() => { utilityForm.resetFields(); setUtilityModal(true); }}
onClick={() => {
utilityForm.resetFields();
setUtilityModal(true);
}}
>
</PermissionButton>
@@ -654,7 +684,7 @@ const ExpensesPage: React.FC = () => {
<Select options={typeOptions} />
</Form.Item>
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}>
<RangePicker
@@ -669,16 +699,42 @@ const ExpensesPage: React.FC = () => {
</Form>
</Modal>
<Modal title="添加学生水电费并立即出账" open={utilityModal} onOk={handleStudentUtility} onCancel={() => setUtilityModal(false)} okText="生成账单并扣余额" confirmLoading={saving}>
<Modal
title="添加学生水电费并立即出账"
open={utilityModal}
onOk={handleStudentUtility}
onCancel={() => setUtilityModal(false)}
okText="生成账单并扣余额"
confirmLoading={saving}
>
<Form form={utilityForm} layout="vertical">
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
<Select showSearch optionFilterProp="label" options={students.map((student: any) => ({ value: student.id, label: `${student.name} (${student.studentNo || `#${student.id}`})` }))} />
<Select
showSearch
optionFilterProp="label"
options={students.map((student: any) => ({
value: student.id,
label: `${student.name} (${student.studentNo || `#${student.id}`})`,
}))}
/>
</Form.Item>
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}>
<Select
options={[
{ value: 'water', label: '水费' },
{ value: 'electricity', label: '电费' },
]}
/>
</Form.Item>
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}>
<RangePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="description" label="说明">
<Input.TextArea rows={2} maxLength={300} />
</Form.Item>
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}><Select options={[{ value: 'water', label: '水费' }, { value: 'electricity', label: '电费' }]} /></Form.Item>
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}><InputNumber min={0.01} precision={2} style={{ width: '100%' }} /></Form.Item>
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}><RangePicker style={{ width: '100%' }} format="YYYY-MM-DD" /></Form.Item>
<Form.Item name="description" label="说明"><Input.TextArea rows={2} maxLength={300} /></Form.Item>
</Form>
</Modal>
@@ -713,7 +769,7 @@ const ExpensesPage: React.FC = () => {
<Select options={personalTypeOptions} />
</Form.Item>
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
<InputNumber min={0.01} precision={2} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="expenseDate" label="费用日期" rules={[{ required: true }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择日期" format="YYYY-MM-DD" />

View File

@@ -1,12 +1,33 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
Card, Form, Input, Button, Space, Spin, Alert, Descriptions, Tag, Divider,
Drawer, Tree, Select, TreeSelect, Modal, DatePicker,
Row, Col, List,
Card,
Form,
Input,
Button,
Space,
Spin,
Alert,
Descriptions,
Tag,
Divider,
Drawer,
Tree,
Select,
TreeSelect,
Modal,
DatePicker,
Row,
Col,
List,
} from 'antd';
import {
SaveOutlined, ApiOutlined, CheckCircleOutlined, CloseCircleOutlined,
SyncOutlined, BankOutlined, UserOutlined,
SaveOutlined,
ApiOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
SyncOutlined,
BankOutlined,
UserOutlined,
StopOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
@@ -89,7 +110,6 @@ interface DeleteAttendanceGroupsResponse {
};
}
const IntegrationConfigPage: React.FC = () => {
const { hasAllPermissions } = usePermission();
const [loading, setLoading] = useState(false);
@@ -116,11 +136,13 @@ const IntegrationConfigPage: React.FC = () => {
const [loadingGroups, setLoadingGroups] = useState(false);
const [deletingGroups, setDeletingGroups] = useState(false);
const fetchConfig = async () => {
setLoading(true);
try {
const res = await api.get<{ success: boolean; data: Array<{ type: string; verify: boolean; config: DingTalkConfig }> }>('/integration/config');
const res = await api.get<{
success: boolean;
data: Array<{ type: string; verify: boolean; config: DingTalkConfig }>;
}>('/integration/config');
const dt = res.data?.find((c) => c.type === 'DINGTALK');
if (dt) {
setConfig(dt.config);
@@ -159,10 +181,13 @@ const IntegrationConfigPage: React.FC = () => {
const payload = buildDingTalkConfigPayload(values);
setTesting(true);
try {
const res = await api.post<{ success: boolean; message: string }>('/integration/config/test', {
type: 'DINGTALK',
config: payload,
});
const res = await api.post<{ success: boolean; message: string }>(
'/integration/config/test',
{
type: 'DINGTALK',
config: payload,
},
);
setVerified(res.success);
message.success(res.message);
} catch (e: unknown) {
@@ -174,7 +199,6 @@ const IntegrationConfigPage: React.FC = () => {
}
};
const loadDeptTree = async () => {
try {
const res = await api.get<OrgTreeResponse>('/sync/dingtalk/org-tree');
@@ -200,7 +224,9 @@ const IntegrationConfigPage: React.FC = () => {
} else {
setClasses(res.data ?? []);
}
} catch { /* ignore */ }
} catch {
/* ignore */
}
};
const handleFetchOrgTree = async () => {
@@ -208,7 +234,9 @@ const IntegrationConfigPage: React.FC = () => {
try {
const params: Record<string, string> = {};
if (syncRootDeptId) params.rootDeptId = String(syncRootDeptId);
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', { params });
const res = await api.get<OrgTreeWithUsersResponse>('/sync/dingtalk/org-tree-with-users', {
params,
});
if (res.success && res.data) {
setOrgTree(res.data);
setCheckedKeys([]);
@@ -226,7 +254,6 @@ const IntegrationConfigPage: React.FC = () => {
}
};
const buildTreeData = useCallback((nodes: DingOrgTreeNodeExt[]): DataNode[] => {
return nodes.map((node) => {
const users = node.users ?? [];
@@ -262,7 +289,11 @@ const IntegrationConfigPage: React.FC = () => {
const treeData = useMemo(() => buildTreeData(orgTree), [orgTree, buildTreeData]);
const extractCheckedUsers = useCallback((): Array<{ dingUserId: string; name: string; mobile?: string }> => {
const extractCheckedUsers = useCallback((): Array<{
dingUserId: string;
name: string;
mobile?: string;
}> => {
const result: Array<{ dingUserId: string; name: string; mobile?: string }> = [];
const walk = (nodes: DingOrgTreeNodeExt[]) => {
for (const node of nodes) {
@@ -285,9 +316,13 @@ const IntegrationConfigPage: React.FC = () => {
setImporting(true);
try {
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, { users });
const res = await api.post<ImportResult>(`/classes/${selectedClassId}/students/import`, {
users,
});
if (res.conflicts > 0) {
message.warning(`导入 ${res.imported} 人,跳过 ${res.skipped} 人,${res.conflicts} 人需人工绑定`);
message.warning(
`导入 ${res.imported} 人,跳过 ${res.skipped} 人,${res.conflicts} 人需人工绑定`,
);
} else {
message.success(`导入 ${res.imported} 人,跳过 ${res.skipped}`);
}
@@ -354,175 +389,206 @@ const IntegrationConfigPage: React.FC = () => {
}
};
const syncPanel = config && hasAllPermissions('sync:read', 'class:view', 'class:edit')
? (
<div>
<Alert
type="info"
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
style={{ marginBottom: 16 }}
showIcon
/>
const syncPanel =
config && hasAllPermissions('sync:read', 'class:view', 'class:edit') ? (
<div>
<Alert
type="info"
message="从钉钉获取组织架构,勾选用户后批量导入到班级。"
style={{ marginBottom: 16 }}
showIcon
/>
<Space>
<TreeSelect
treeData={deptPickerTree}
value={syncRootDeptId}
onChange={(v) => setSyncRootDeptId(v)}
placeholder="选择起始部门(不选=全部)"
allowClear
treeDefaultExpandAll
style={{ minWidth: 240 }}
onDropdownVisibleChange={(open) => {
if (open) loadDeptTree();
}}
/>
<Button
type="primary"
icon={<SyncOutlined />}
loading={fetchingTree}
onClick={handleFetchOrgTree}
>
</Button>
<PermissionButton
permission="sync:trigger"
danger
icon={<StopOutlined />}
loading={loadingGroups}
onClick={openDeleteAllGroups}
>
</PermissionButton>
</Space>
{drawerOpen && (
<Drawer
title="钉钉组织架构 — 批量导入"
open={drawerOpen}
onClose={() => {
setDrawerOpen(false);
}}
width="min(900px, 100vw)"
footer={
<Space>
<TreeSelect
treeData={deptPickerTree}
value={syncRootDeptId}
onChange={(v) => setSyncRootDeptId(v)}
placeholder="选择起始部门(不选=全部)"
allowClear
treeDefaultExpandAll
style={{ minWidth: 240 }}
onDropdownVisibleChange={(open) => { if (open) loadDeptTree(); }}
/>
<Button
onClick={() => {
setDrawerOpen(false);
}}
>
</Button>
<Button
type="primary"
icon={<SyncOutlined />}
loading={fetchingTree}
onClick={handleFetchOrgTree}
loading={importing}
disabled={
checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 ||
selectedClassId === null
}
onClick={handleJoinClass}
>
</Button>
<PermissionButton
permission="sync:trigger"
danger
icon={<StopOutlined />}
loading={loadingGroups}
onClick={openDeleteAllGroups}
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
>
</PermissionButton>
</Button>
</Space>
{drawerOpen && (
<Drawer
title="钉钉组织架构 — 批量导入"
open={drawerOpen}
onClose={() => { setDrawerOpen(false); }}
width={900}
footer={
<Space>
<Button onClick={() => { setDrawerOpen(false); }}></Button>
<Button
type="primary"
loading={importing}
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0 || selectedClassId === null}
onClick={handleJoinClass}
></Button>
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
></Button>
</Space>
}
>
<Row gutter={[16, 16]}>
<Col xs={24} md={14}>
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
<Tree
checkable
treeData={treeData}
defaultExpandAll
showLine={{ showLeafIcon: false }}
checkedKeys={checkedKeys}
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
/>
</div>
</Col>
<Col xs={24} md={10}>
<Card
title="班级列表"
size="small"
extra={
<Button size="small" onClick={() => setClassModalOpen(true)}>
+
</Button>
}
>
<Row gutter={16}>
<Col span={14}>
<div style={{ maxHeight: '60vh', overflow: 'auto' }}>
<Tree
checkable
treeData={treeData}
defaultExpandAll
showLine={{ showLeafIcon: false }}
checkedKeys={checkedKeys}
onCheck={(checked) => setCheckedKeys(checked as React.Key[])}
<List
dataSource={classes}
renderItem={(cls: ClassItem) => (
<List.Item
onClick={() => setSelectedClassId(cls.id)}
style={{
cursor: 'pointer',
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
borderRadius: 4,
padding: '8px 12px',
}}
>
<List.Item.Meta
title={cls.name}
description={`${cls.code} ${cls.classType || ''}`}
/>
</div>
</Col>
<Col span={10}>
<Card title="班级列表" size="small"
extra={<Button size="small" onClick={() => setClassModalOpen(true)}>+ </Button>}>
<List
dataSource={classes}
renderItem={(cls: ClassItem) => (
<List.Item
onClick={() => setSelectedClassId(cls.id)}
style={{
cursor: 'pointer',
background: selectedClassId === cls.id ? '#e6f4ff' : undefined,
borderRadius: 4,
padding: '8px 12px',
}}
>
<List.Item.Meta title={cls.name} description={`${cls.code} ${cls.classType || ''}`} />
</List.Item>
)}
/>
</Card>
</Col>
</Row>
</List.Item>
)}
/>
</Card>
</Col>
</Row>
{ /* Create class Modal */ }
<Modal
title="创建班级"
open={classModalOpen}
onOk={handleCreateClass}
onCancel={() => { setClassModalOpen(false); classForm.resetFields(); }}
confirmLoading={importing}
destroyOnClose
>
<Form form={classForm} layout="vertical">
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
<Input placeholder="如 CS2024-01" />
</Form.Item>
<Form.Item name="classType" label="班" rules={[{ required: true }]}>
<Select options={[
{ value: 'culture', label: '文化课' },
{ value: 'professional', label: '专业课' },
{ value: 'bootcamp', label: '集训营' },
{ value: 'sprint', label: '冲刺班' },
]} />
</Form.Item>
<Form.Item name="startDate" label="开班日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="endDate" label="结束日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
</Drawer>
)}
<Modal
title="确认清空钉钉全部考勤组"
open={deleteGroupsOpen}
okText="确认全部清空"
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
cancelText="取消"
confirmLoading={deletingGroups}
onOk={deleteAllGroups}
onCancel={() => setDeleteGroupsOpen(false)}
>
<Alert
type="error"
showIcon
message={`将永久清空钉钉上的 ${attendanceGroups.length} 个考勤组`}
description="本地班级和排课不会清空。清空后需在排课管理中重新同步,才能重建考勤组。"
style={{ marginBottom: 12 }}
{/* Create class Modal */}
<Modal
title="创建班级"
open={classModalOpen}
onOk={handleCreateClass}
onCancel={() => {
setClassModalOpen(false);
classForm.resetFields();
}}
confirmLoading={importing}
destroyOnClose
>
<Form form={classForm} layout="vertical">
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
<Input placeholder="如 CS2024-01" />
</Form.Item>
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
<Select
options={[
{ value: 'culture', label: '文化课' },
{ value: 'professional', label: '专业课' },
{ value: 'bootcamp', label: '集训营' },
{ value: 'sprint', label: '冲刺班' },
]}
/>
</Form.Item>
<Form.Item name="startDate" label="开班日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="endDate" label="结束日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
</Drawer>
)}
<Modal
title="确认清空钉钉全部考勤组"
open={deleteGroupsOpen}
okText="确认全部清空"
okButtonProps={{ danger: true, disabled: attendanceGroups.length === 0 }}
cancelText="取消"
confirmLoading={deletingGroups}
onOk={deleteAllGroups}
onCancel={() => setDeleteGroupsOpen(false)}
>
<Alert
type="error"
showIcon
message={`将永久清空钉钉上的 ${attendanceGroups.length} 个考勤组`}
description="本地班级和排课不会清空。清空后需在排课管理中重新同步,才能重建考勤组。"
style={{ marginBottom: 12 }}
/>
<List
size="small"
bordered
dataSource={attendanceGroups}
style={{ maxHeight: 280, overflow: 'auto' }}
renderItem={(group) => (
<List.Item>
<List.Item.Meta
title={group.group_name}
description={`ID ${group.group_id} · ${group.member_count}`}
/>
<List
size="small"
bordered
dataSource={attendanceGroups}
style={{ maxHeight: 280, overflow: 'auto' }}
renderItem={(group) => (
<List.Item>
<List.Item.Meta
title={group.group_name}
description={`ID ${group.group_id} · ${group.member_count}`}
/>
</List.Item>
)}
/>
</Modal>
</div>
)
: null;
</List.Item>
)}
/>
</Modal>
</div>
) : null;
return (
<Card
@@ -588,9 +654,7 @@ const IntegrationConfigPage: React.FC = () => {
: '首次配置需要填写完整 AppSecret'
}
>
<Input.Password
placeholder={config ? '留空保持已保存的密钥' : '从钉钉开放平台获取'}
/>
<Input.Password placeholder={config ? '留空保持已保存的密钥' : '从钉钉开放平台获取'} />
</Form.Item>
<Space>
<PermissionButton

View File

@@ -1,8 +1,5 @@
import { describe, expect, it } from 'vitest';
import {
buildDingTalkConfigPayload,
isAppSecretRequired,
} from './integration-config-form';
import { buildDingTalkConfigPayload, isAppSecretRequired } from './integration-config-form';
describe('DingTalk integration config form', () => {
it('requires AppSecret only for the first configuration', () => {

View File

@@ -13,22 +13,27 @@ const LoginPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const onFinish = useCallback(async (values: any) => {
setLoading(true);
try {
const res: any = await api.post('/auth/login', values);
localStorage.setItem('token', res.access_token);
localStorage.setItem('user', JSON.stringify(res.user));
const permissions = res.user.permissions || [];
writePermissions(permissions);
message.success('登录成功');
navigate(findRoleAwareLandingPath(res.user.roles || [], permissions) || '/', { replace: true });
} catch (err: any) {
message.error(err?.message || '登录失败');
} finally {
setLoading(false);
}
}, [navigate]);
const onFinish = useCallback(
async (values: any) => {
setLoading(true);
try {
const res: any = await api.post('/auth/login', values);
localStorage.setItem('token', res.access_token);
localStorage.setItem('user', JSON.stringify(res.user));
const permissions = res.user.permissions || [];
writePermissions(permissions);
message.success('登录成功');
navigate(findRoleAwareLandingPath(res.user.roles || [], permissions) || '/', {
replace: true,
});
} catch (err: any) {
message.error(err?.message || '登录失败');
} finally {
setLoading(false);
}
},
[navigate],
);
return (
<div
@@ -56,10 +61,18 @@ const LoginPage: React.FC = () => {
<p style={{ color: '#86868b', marginTop: 8 }}></p>
</div>
<Form name="login" onFinish={onFinish} size="large">
<Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
<Form.Item
label="用户名"
name="username"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input prefix={<UserOutlined />} placeholder="用户名" />
</Form.Item>
<Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
<Form.Item
label="密码"
name="password"
rules={[{ required: true, message: '请输入密码' }]}
>
<Input.Password prefix={<LockOutlined />} placeholder="密码" />
</Form.Item>
<Form.Item>

View File

@@ -60,7 +60,7 @@ const NotificationsPage: React.FC = () => {
const fetchData = async () => {
setLoading(true);
try {
const data = await api.get('/notifications?limit=50') as unknown as NotificationItem[];
const data = (await api.get('/notifications?limit=50')) as unknown as NotificationItem[];
setNotifications(data);
} catch (e: any) {
console.error('加载通知失败', e);
@@ -91,18 +91,15 @@ const NotificationsPage: React.FC = () => {
const handleMarkAll = async () => {
try {
await api.put('/notifications/read-all');
setNotifications((prev) =>
prev.map((n) => ({ ...n, isRead: true })),
);
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
} catch (e: any) {
console.error('全部已读失败', e);
message.error(e?.message || '操作失败');
}
};
const filtered = filter === 'all'
? notifications
: notifications.filter((n) => n.type === filter);
const filtered =
filter === 'all' ? notifications : notifications.filter((n) => n.type === filter);
const filterItems = [
{ key: 'all', icon: <BellOutlined />, label: '全部' },
@@ -126,7 +123,9 @@ const NotificationsPage: React.FC = () => {
)}
<Content className="notifications-content" style={{ padding: isMobile ? 0 : 24 }}>
<div className="notifications-header">
<Typography.Title level={4} style={{ margin: 0 }}></Typography.Title>
<Typography.Title level={4} style={{ margin: 0 }}>
</Typography.Title>
<Button onClick={handleMarkAll}></Button>
</div>
{isMobile && (
@@ -181,10 +180,7 @@ const NotificationsPage: React.FC = () => {
}
title={
<Space wrap size={[8, 2]}>
<Typography.Text
strong={!item.isRead}
style={{ fontSize: 15 }}
>
<Typography.Text strong={!item.isRead} style={{ fontSize: 15 }}>
{formatNotificationText(item.title)}
</Typography.Text>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>

View File

@@ -26,13 +26,13 @@ import {
DownloadOutlined,
ExportOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import dayjs, { type Dayjs } from 'dayjs';
import api from '../../api';
import { downloadBlob } from '../../utils/download';
import { maskPhone, maskIdNumber } from '../../utils/sensitive';
import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message';
import { buildTransferPayload } from './occupancy-form';
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
const { RangePicker } = DatePicker;
@@ -59,14 +59,73 @@ const OccupanciesPage: React.FC = () => {
const [batchCheckOutForm] = Form.useForm();
const [availableBeds, setAvailableBeds] = useState<any[]>([]);
const [availableLockers, setAvailableLockers] = useState<any[]>([]);
const [availableResourcesLoading, setAvailableResourcesLoading] = useState(false);
const [transferAvailableBeds, setTransferAvailableBeds] = useState<any[]>([]);
const [transferAvailableLockers, setTransferAvailableLockers] = useState<any[]>([]);
const [transferResourcesLoading, setTransferResourcesLoading] = useState(false);
const selectedCheckInRoomId = Form.useWatch('roomId', checkInForm);
const selectedTransferRoomId = Form.useWatch('newRoomId', transferForm);
const activeOccupancyByStudentId = useMemo(() => {
const map = new Map<number, any>();
data.forEach((item) => {
if (!item.checkOutDate && item.status !== 'archived') map.set(item.studentId, item);
});
return map;
}, [data]);
const isRoomSelectable = useCallback((room: any) => {
const currentCount = Number(room.currentCount || 0);
const capacity = Number(room.capacity || 0);
return room.status !== 'archived' && room.status !== 'maintenance' && currentCount < capacity;
}, []);
const roomOptionLabel = useCallback((room: any) => {
const base = `${room.roomNumber} (${room.building || ''}) [${room.currentCount}/${room.capacity}]`;
if (room.status === 'maintenance') return `${base} · 维修中`;
if (room.status === 'archived') return `${base} · 已归档`;
if (Number(room.currentCount || 0) >= Number(room.capacity || 0)) return `${base} · 已满`;
return base;
}, []);
const selectedBatchRecords = useMemo(
() => data.filter((item) => selectedRowKeys.includes(item.id) && !item.checkOutDate),
[data, selectedRowKeys],
);
const latestSelectedCheckInDate = useMemo(
() => selectedBatchRecords.map((item) => item.checkInDate).filter(Boolean).sort().at(-1),
[selectedBatchRecords],
);
const latestSelectedBillingStartDate = useMemo(
() =>
selectedBatchRecords
.map((item) => item.billingStartDate || item.checkInDate)
.filter(Boolean)
.sort()
.at(-1),
[selectedBatchRecords],
);
const dateNotBefore = (start: string | Dayjs | null | undefined, messageText: string) =>
(_: unknown, value?: Dayjs | null) => {
if (!value || !start) return Promise.resolve();
const startDate = dayjs.isDayjs(start) ? start : dayjs(start);
return value.isBefore(startDate, 'day')
? Promise.reject(new Error(messageText))
: Promise.resolve();
};
const fetchData = useCallback(async () => {
setLoading(true);
try {
const [occRes, stuRes, rmRes] = (await Promise.allSettled([
api.get('/occupancies', { params: { active: showActive ? 'true' : undefined, dateFrom: dateRange?.[0]?.format('YYYY-MM-DD'), dateTo: dateRange?.[1]?.format('YYYY-MM-DD') } }),
api.get('/occupancies', {
params: {
active: showActive ? 'true' : undefined,
dateFrom: dateRange?.[0]?.format('YYYY-MM-DD'),
dateTo: dateRange?.[1]?.format('YYYY-MM-DD'),
},
}),
api.get('/students/basic-lookups'),
api.get('/rooms/overview'),
])) as PromiseSettledResult<any>[];
@@ -94,11 +153,11 @@ const OccupanciesPage: React.FC = () => {
const handleRoomChange = async (roomId: number) => {
checkInForm.setFieldValue('bedId', undefined);
checkInForm.setFieldValue('lockerId', undefined);
if (!roomId) {
setAvailableBeds([]);
setAvailableLockers([]);
return;
}
setAvailableBeds([]);
setAvailableLockers([]);
if (!roomId) return;
setAvailableResourcesLoading(true);
try {
const [beds, lockers] = await Promise.all([
api.get<any[]>(`/rooms/${roomId}/beds/available`),
@@ -107,17 +166,25 @@ const OccupanciesPage: React.FC = () => {
setAvailableBeds(beds);
setAvailableLockers(lockers);
if (beds.length === 1) checkInForm.setFieldValue('bedId', beds[0].id);
} catch (e) { console.error(e); }
if (beds.length === 0) message.warning('该宿舍暂无可用床位,请先在宿舍详情添加或释放床位');
} catch (e: any) {
console.error(e);
setAvailableBeds([]);
setAvailableLockers([]);
message.error(e?.message || '宿舍床位和柜子加载失败');
} finally {
setAvailableResourcesLoading(false);
}
};
const handleTransferRoomChange = async (roomId: number) => {
transferForm.setFieldValue('newBedId', undefined);
transferForm.setFieldValue('newLockerId', undefined);
if (!roomId) {
setTransferAvailableBeds([]);
setTransferAvailableLockers([]);
return;
}
setTransferAvailableBeds([]);
setTransferAvailableLockers([]);
if (!roomId) return;
setTransferResourcesLoading(true);
try {
const [beds, lockers] = await Promise.all([
api.get<any[]>(`/rooms/${roomId}/beds/available`),
@@ -126,11 +193,14 @@ const OccupanciesPage: React.FC = () => {
setTransferAvailableBeds(beds);
setTransferAvailableLockers(lockers);
if (beds.length === 1) transferForm.setFieldValue('newBedId', beds[0].id);
} catch (e) {
if (beds.length === 0) message.warning('目标宿舍暂无可用床位,请先在宿舍详情添加或释放床位');
} catch (e: any) {
console.error(e);
setTransferAvailableBeds([]);
setTransferAvailableLockers([]);
message.error('目标宿舍床位和柜子加载失败');
message.error(e?.message || '目标宿舍床位和柜子加载失败');
} finally {
setTransferResourcesLoading(false);
}
};
@@ -148,18 +218,7 @@ const OccupanciesPage: React.FC = () => {
const values = await checkInForm.validateFields();
setSaving(true);
try {
await api.post('/occupancies/check-in', {
studentId: values.studentId,
roomId: values.roomId,
checkInDate: values.checkInDate.format('YYYY-MM-DD'),
billingStartDate: values.billingStartDate?.format('YYYY-MM-DD'),
stayType: values.stayType,
collectDeposit: values.collectDeposit,
depositAmount: values.collectDeposit ? values.depositAmount : undefined,
notes: values.notes,
bedId: values.bedId,
lockerId: values.lockerId || undefined,
});
await api.post('/occupancies/check-in', buildCheckInPayload(values));
message.success('入住登记成功');
setCheckInModal(false);
checkInForm.resetFields();
@@ -195,10 +254,7 @@ const OccupanciesPage: React.FC = () => {
const values = await transferForm.validateFields();
setSaving(true);
try {
await api.put(
`/occupancies/${transferModal.id}/transfer`,
buildTransferPayload(values),
);
await api.put(`/occupancies/${transferModal.id}/transfer`, buildTransferPayload(values));
message.success('换房成功');
setTransferModal(null);
transferForm.resetFields();
@@ -246,83 +302,104 @@ const OccupanciesPage: React.FC = () => {
}
};
const columns = useMemo(() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
{ title: '床位', width: 80, render: (_: unknown, r: Record<string, unknown>) => (r.bed as Record<string, string> | undefined)?.bedNumber || '-' },
{ title: '柜子', width: 80, render: (_: unknown, r: Record<string, unknown>) => (r.locker as Record<string, string> | undefined)?.lockerNumber || '-' },
{ title: '入住日期', dataIndex: 'checkInDate', width: 110 },
{ title: '计费起始', dataIndex: 'billingStartDate', width: 110 },
{
title: '退宿日期',
dataIndex: 'checkOutDate',
width: 110,
render: (v: any) => v || <Tag color="green"></Tag>,
},
{ title: '计费截止', dataIndex: 'billingEndDate', render: (v: any) => v || '-' },
{ title: '退宿原因', dataIndex: 'checkOutReason', render: (v: any) => v || '-' },
{
title: '操作',
width: 220,
render: (_: any, record: any) =>
!record.checkOutDate ? (
<Space>
<PermissionButton
permission="occupancy:checkout"
size="small"
icon={<LogoutOutlined />}
onClick={() => {
setCheckOutModal(record);
checkOutForm.setFieldsValue({ checkOutDate: dayjs() });
}}
>
退宿
</PermissionButton>
<PermissionButton
permission="occupancy:transfer"
size="small"
icon={<SwapOutlined />}
onClick={() => {
setTransferAvailableBeds([]);
setTransferAvailableLockers([]);
transferForm.resetFields();
setTransferModal(record);
transferForm.setFieldsValue({ transferDate: dayjs() });
}}
>
</PermissionButton>
</Space>
) : (
<Space>
<Tag>退宿</Tag>
<Popconfirm
title="确定归档此记录?"
onConfirm={async () => {
try {
await api.delete(`/occupancies/${record.id}`);
message.success('归档成功');
fetchData();
} catch (e: any) {
message.error(e?.message || '归档失败');
}
}}
>
<PermissionButton permission="occupancy:delete" size="small" danger icon={<InboxOutlined />}>
const columns = useMemo(
() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
{ title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
{
title: '床位',
width: 80,
render: (_: unknown, r: Record<string, unknown>) =>
(r.bed as Record<string, string> | undefined)?.bedNumber || '-',
},
{
title: '柜子',
width: 80,
render: (_: unknown, r: Record<string, unknown>) =>
(r.locker as Record<string, string> | undefined)?.lockerNumber || '-',
},
{ title: '入住日期', dataIndex: 'checkInDate', width: 110 },
{ title: '计费起始', dataIndex: 'billingStartDate', width: 110 },
{
title: '退宿日期',
dataIndex: 'checkOutDate',
width: 110,
render: (v: any) => v || <Tag color="green"></Tag>,
},
{ title: '计费截止', dataIndex: 'billingEndDate', render: (v: any) => v || '-' },
{ title: '退宿原因', dataIndex: 'checkOutReason', render: (v: any) => v || '-' },
{
title: '操作',
width: 220,
render: (_: any, record: any) =>
!record.checkOutDate ? (
<Space>
<PermissionButton
permission="occupancy:checkout"
size="small"
icon={<LogoutOutlined />}
onClick={() => {
setCheckOutModal(record);
checkOutForm.setFieldsValue({ checkOutDate: dayjs() });
}}
>
退宿
</PermissionButton>
</Popconfirm>
</Space>
),
},
], [fetchData, setCheckOutModal, checkOutForm, setTransferModal, transferForm]);
<PermissionButton
permission="occupancy:transfer"
size="small"
icon={<SwapOutlined />}
onClick={() => {
setTransferAvailableBeds([]);
setTransferAvailableLockers([]);
transferForm.resetFields();
setTransferModal(record);
transferForm.setFieldsValue({ transferDate: dayjs() });
}}
>
</PermissionButton>
</Space>
) : (
<Space>
<Tag>退宿</Tag>
<Popconfirm
title="确定归档此记录?"
onConfirm={async () => {
try {
await api.delete(`/occupancies/${record.id}`);
message.success('归档成功');
fetchData();
} catch (e: any) {
message.error(e?.message || '归档失败');
}
}}
>
<PermissionButton
permission="occupancy:delete"
size="small"
danger
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</Space>
),
},
],
[fetchData, setCheckOutModal, checkOutForm, setTransferModal, transferForm],
);
const rowSelection = useMemo(() => ({
selectedRowKeys,
onChange: (keys: any[]) => setSelectedRowKeys(keys),
// 「在住记录」Tab禁用已退宿防止误选用于批量退宿「全部记录」Tab均可选用于批量归档
getCheckboxProps: (record: any) => (showActive ? { disabled: !!record.checkOutDate } : {}),
}), [selectedRowKeys, showActive]);
const rowSelection = useMemo(
() => ({
selectedRowKeys,
onChange: (keys: any[]) => setSelectedRowKeys(keys),
// 「在住记录」Tab禁用已退宿防止误选用于批量退宿「全部记录」Tab均可选用于批量归档
getCheckboxProps: (record: any) => (showActive ? { disabled: !!record.checkOutDate } : {}),
}),
[selectedRowKeys, showActive],
);
return (
<div>
@@ -348,7 +425,14 @@ const OccupanciesPage: React.FC = () => {
allowClear
style={{ width: 200 }}
/>
<RangePicker value={dateRange} onChange={(dates) => { setDateRange(dates ? [dates[0], dates[1]] : null); }} placeholder={['入住开始', '入住结束']} style={{ width: 240 }} />
<RangePicker
value={dateRange}
onChange={(dates) => {
setDateRange(dates ? [dates[0], dates[1]] : null);
}}
placeholder={['入住开始', '入住结束']}
style={{ width: 240 }}
/>
</Space>
<Space wrap className="responsive-toolbar__group">
<PermissionButton
@@ -357,7 +441,17 @@ const OccupanciesPage: React.FC = () => {
icon={<PlusOutlined />}
onClick={() => {
checkInForm.resetFields();
checkInForm.setFieldsValue({ checkInDate: dayjs(), collectDeposit: true, depositAmount: 500 });
setAvailableBeds([]);
setAvailableLockers([]);
setAvailableResourcesLoading(false);
const today = dayjs();
checkInForm.setFieldsValue({
checkInDate: today,
billingStartDate: today,
stayType: 'short',
collectDeposit: true,
depositAmount: 500,
});
setCheckInModal(true);
}}
>
@@ -432,26 +526,26 @@ const OccupanciesPage: React.FC = () => {
{autoDeposit && (
<Space.Compact>
<InputNumber
size="small"
min={0}
value={depositAmount}
onChange={(v) => setDepositAmount(v || 500)}
style={{ width: 60 }}
/>
<span
style={{
padding: '0 8px',
display: 'flex',
alignItems: 'center',
border: '1px solid #d9d9d9',
backgroundColor: '#fafafa',
fontSize: 12,
}}
>
</span>
</Space.Compact>
<InputNumber
size="small"
min={0}
value={depositAmount}
onChange={(v) => setDepositAmount(v || 500)}
style={{ width: 60 }}
/>
<span
style={{
padding: '0 8px',
display: 'flex',
alignItems: 'center',
border: '1px solid #d9d9d9',
backgroundColor: '#fafafa',
fontSize: 12,
}}
>
</span>
</Space.Compact>
)}
</span>
</Space>
@@ -524,7 +618,12 @@ const OccupanciesPage: React.FC = () => {
title="入住登记"
open={checkInModal}
onOk={handleCheckIn}
onCancel={() => setCheckInModal(false)}
onCancel={() => {
setCheckInModal(false);
setAvailableBeds([]);
setAvailableLockers([]);
setAvailableResourcesLoading(false);
}}
okText="确认入住"
confirmLoading={saving}
width={500}
@@ -541,10 +640,15 @@ const OccupanciesPage: React.FC = () => {
placeholder="搜索并选择学生"
options={students
.filter((s: any) => s.status === 'active')
.map((s: any) => ({
value: s.id,
label: `${s.name} (${s.idNumber ? maskIdNumber(s.idNumber) : (s.phone ? maskPhone(s.phone) : '')})`,
}))}
.map((s: any) => {
const activeOccupancy = activeOccupancyByStudentId.get(s.id);
const identifier = s.idNumber ? maskIdNumber(s.idNumber) : s.phone ? maskPhone(s.phone) : '';
return {
value: s.id,
label: `${s.name} (${identifier})${activeOccupancy ? ` · 已入住${activeOccupancy.room?.roomNumber ? ` ${activeOccupancy.room.roomNumber}` : ''}` : ''}`,
disabled: !!activeOccupancy,
};
})}
/>
</Form.Item>
<Form.Item
@@ -559,18 +663,25 @@ const OccupanciesPage: React.FC = () => {
onChange={handleRoomChange}
options={rooms.map((r) => ({
value: r.id,
label: `${r.roomNumber} (${r.building || ''}) [${r.currentCount}/${r.capacity}]`,
disabled: r.currentCount >= r.capacity,
label: roomOptionLabel(r),
disabled: !isRoomSelectable(r),
}))}
/>
</Form.Item>
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true }]}>
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true, message: '请选择入住日期' }]}>
<DatePicker style={{ width: '100%' }} placeholder="选择入住日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item
name="billingStartDate"
label="计费起始日"
dependencies={["checkInDate"]}
extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)"
rules={[
{ required: true, message: '请选择计费起始日' },
({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('checkInDate'), '计费起始日不能早于入住日期'),
}),
]}
>
<DatePicker
style={{ width: '100%' }}
@@ -578,9 +689,8 @@ const OccupanciesPage: React.FC = () => {
format="YYYY-MM-DD"
/>
</Form.Item>
<Form.Item name="stayType" label="入住类型">
<Form.Item name="stayType" label="入住类型" rules={[{ required: true, message: '请选择入住类型' }]}>
<Select
allowClear
options={[
{ value: 'short', label: '短租' },
{ value: 'long', label: '长租' },
@@ -591,16 +701,25 @@ const OccupanciesPage: React.FC = () => {
<Form.Item
name="bedId"
label="床位"
rules={[{ required: true, message: '请选择床位' }]}
rules={[
{ required: true, message: '请选择床位' },
{
validator: (_: unknown, value?: number) =>
!value || availableBeds.some((bed) => bed.id === value)
? Promise.resolve()
: Promise.reject(new Error('请选择当前宿舍下的可用床位')),
},
]}
>
<Select
placeholder="请先选择房间"
disabled={availableBeds.length === 0}
placeholder={selectedCheckInRoomId ? '请选择床位' : '请先选择房间'}
loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0}
options={availableBeds.map((b) => ({
value: b.id,
label: b.bedNumber,
}))}
notFoundContent="该房间暂无可用床位"
notFoundContent={selectedCheckInRoomId ? '该房间暂无可用床位' : '请先选择房间'}
/>
</Form.Item>
{availableBeds.length > 0 && (
@@ -608,14 +727,12 @@ const OccupanciesPage: React.FC = () => {
{availableBeds.length}
</div>
)}
<Form.Item
name="lockerId"
label="柜子(可选)"
>
<Form.Item name="lockerId" label="柜子(可选)">
<Select
allowClear
placeholder="可选分配柜子"
disabled={availableLockers.length === 0}
loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0}
options={availableLockers.map((l) => ({
value: l.id,
label: l.lockerNumber,
@@ -630,7 +747,10 @@ const OccupanciesPage: React.FC = () => {
>
<Switch checkedChildren="已缴" unCheckedChildren="不缴" />
</Form.Item>
<Form.Item noStyle shouldUpdate={(prev, current) => prev.collectDeposit !== current.collectDeposit}>
<Form.Item
noStyle
shouldUpdate={(prev, current) => prev.collectDeposit !== current.collectDeposit}
>
{({ getFieldValue }) =>
getFieldValue('collectDeposit') ? (
<Form.Item
@@ -638,12 +758,7 @@ const OccupanciesPage: React.FC = () => {
label="押金金额"
rules={[{ required: true, message: '请输入押金金额' }]}
>
<InputNumber
min={0.01}
precision={2}
addonAfter="元"
style={{ width: '100%' }}
/>
<InputNumber min={0.01} precision={2} addonAfter="元" style={{ width: '100%' }} />
</Form.Item>
) : null
}
@@ -664,10 +779,30 @@ const OccupanciesPage: React.FC = () => {
confirmLoading={saving}
>
<Form form={checkOutForm} layout="vertical">
<Form.Item name="checkOutDate" label="退宿日期" rules={[{ required: true }]}>
<Form.Item
name="checkOutDate"
label="退宿日期"
rules={[
{ required: true, message: '请选择退宿日期' },
{ validator: dateNotBefore(checkOutModal?.checkInDate, '退宿日期不能早于入住日期') },
]}
>
<DatePicker style={{ width: '100%' }} placeholder="选择退宿日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="billingEndDate" label="计费截止日" extra="默认与退宿日期相同">
<Form.Item
name="billingEndDate"
label="计费截止日"
dependencies={["checkOutDate"]}
extra="默认与退宿日期相同"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(
checkOutModal?.billingStartDate || checkOutModal?.checkInDate || getFieldValue('checkOutDate'),
'计费截止日不能早于计费起始日',
),
}),
]}
>
<DatePicker
style={{ width: '100%' }}
placeholder="选择计费截止日"
@@ -699,10 +834,34 @@ const OccupanciesPage: React.FC = () => {
width={500}
>
<Form form={batchCheckOutForm} layout="vertical">
<Form.Item name="checkOutDate" label="退宿日期" rules={[{ required: true }]}>
<Form.Item
name="checkOutDate"
label="退宿日期"
rules={[
{ required: true, message: '请选择退宿日期' },
{
validator: dateNotBefore(
latestSelectedCheckInDate,
'退宿日期不能早于所选记录中最晚的入住日期',
),
},
]}
>
<DatePicker style={{ width: '100%' }} placeholder="选择退宿日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="billingEndDate" label="计费截止日" extra="默认与退宿日期相同">
<Form.Item
name="billingEndDate"
label="计费截止日"
extra="默认与退宿日期相同"
rules={[
{
validator: dateNotBefore(
latestSelectedBillingStartDate,
'计费截止日不能早于所选记录中最晚的计费起始日',
),
},
]}
>
<DatePicker
style={{ width: '100%' }}
placeholder="选择计费截止日"
@@ -768,24 +927,33 @@ const OccupanciesPage: React.FC = () => {
.filter((r: any) => r.id !== transferModal?.roomId)
.map((r: any) => ({
value: r.id,
label: `${r.roomNumber} (${r.building || ''}) [${r.currentCount}/${r.capacity}]`,
disabled: r.currentCount >= r.capacity,
label: roomOptionLabel(r),
disabled: !isRoomSelectable(r),
}))}
/>
</Form.Item>
<Form.Item
name="newBedId"
label="目标床位"
rules={[{ required: true, message: '请选择目标床位' }]}
rules={[
{ required: true, message: '请选择目标床位' },
{
validator: (_: unknown, value?: number) =>
!value || transferAvailableBeds.some((bed) => bed.id === value)
? Promise.resolve()
: Promise.reject(new Error('请选择目标宿舍下的可用床位')),
},
]}
>
<Select
placeholder="请先选择目标宿舍"
disabled={transferAvailableBeds.length === 0}
placeholder={selectedTransferRoomId ? '请选择目标床位' : '请先选择目标宿舍'}
loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableBeds.length === 0}
options={transferAvailableBeds.map((bed) => ({
value: bed.id,
label: bed.bedNumber,
}))}
notFoundContent="目标宿舍暂无可用床位"
notFoundContent={selectedTransferRoomId ? '目标宿舍暂无可用床位' : '请先选择目标宿舍'}
/>
</Form.Item>
{transferAvailableBeds.length > 0 && (
@@ -797,7 +965,8 @@ const OccupanciesPage: React.FC = () => {
<Select
allowClear
placeholder="可选分配目标宿舍柜子"
disabled={transferAvailableLockers.length === 0}
loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableLockers.length === 0}
options={transferAvailableLockers.map((locker) => ({
value: locker.id,
label: locker.lockerNumber,
@@ -805,17 +974,47 @@ const OccupanciesPage: React.FC = () => {
notFoundContent="目标宿舍暂无可用柜子"
/>
</Form.Item>
<Form.Item name="transferDate" label="换房日期" rules={[{ required: true }]}>
<Form.Item
name="transferDate"
label="换房日期"
rules={[
{ required: true, message: '请选择换房日期' },
{ validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期') },
]}
>
<DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item name="oldBillingEndDate" label="旧房计费截止日" extra="默认为换房当天">
<Form.Item
name="oldBillingEndDate"
label="旧房计费截止日"
dependencies={["transferDate"]}
extra="默认为换房当天"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(
transferModal?.billingStartDate || transferModal?.checkInDate || getFieldValue('transferDate'),
'旧房计费截止日不能早于计费起始日',
),
}),
]}
>
<DatePicker
style={{ width: '100%' }}
placeholder="选择旧房计费截止日"
format="YYYY-MM-DD"
/>
</Form.Item>
<Form.Item name="newBillingStartDate" label="新房计费起始日" extra="默认为换房次日">
<Form.Item
name="newBillingStartDate"
label="新房计费起始日"
dependencies={["transferDate"]}
extra="默认为换房次日"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('transferDate'), '新房计费起始日不能早于换房日期'),
}),
]}
>
<DatePicker
style={{ width: '100%' }}
placeholder="选择新房计费起始日"

View File

@@ -1,6 +1,54 @@
import { describe, expect, it } from 'vitest';
import dayjs from 'dayjs';
import { buildTransferPayload } from './occupancy-form';
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
describe('occupancy check-in form', () => {
it('submits all required manual check-in fields with defaults', () => {
expect(
buildCheckInPayload({
studentId: 1,
roomId: 2,
checkInDate: dayjs('2026-07-18'),
billingStartDate: dayjs('2026-07-18'),
stayType: 'short',
collectDeposit: true,
depositAmount: 500,
bedId: 3,
notes: ' 备注 ',
}),
).toEqual({
studentId: 1,
roomId: 2,
checkInDate: '2026-07-18',
billingStartDate: '2026-07-18',
stayType: 'short',
collectDeposit: true,
depositAmount: 500,
notes: '备注',
bedId: 3,
lockerId: undefined,
});
});
it('falls back to check-in date and short stay type', () => {
expect(
buildCheckInPayload({
studentId: 1,
roomId: 2,
checkInDate: dayjs('2026-07-18'),
collectDeposit: false,
bedId: 3,
}),
).toEqual(
expect.objectContaining({
billingStartDate: '2026-07-18',
stayType: 'short',
collectDeposit: false,
depositAmount: undefined,
}),
);
});
});
describe('occupancy transfer form', () => {
it('submits the target room resources with the transfer dates', () => {

View File

@@ -1,5 +1,34 @@
import type { Dayjs } from 'dayjs';
export interface CheckInFormValues {
studentId: number;
roomId: number;
checkInDate: Dayjs;
billingStartDate?: Dayjs;
stayType?: string;
collectDeposit?: boolean;
depositAmount?: number;
notes?: string;
bedId: number;
lockerId?: number;
}
export const buildCheckInPayload = (values: CheckInFormValues) => {
const collectDeposit = values.collectDeposit ?? false;
return {
studentId: values.studentId,
roomId: values.roomId,
checkInDate: values.checkInDate.format('YYYY-MM-DD'),
billingStartDate: (values.billingStartDate || values.checkInDate).format('YYYY-MM-DD'),
stayType: values.stayType || 'short',
collectDeposit,
depositAmount: collectDeposit ? values.depositAmount ?? 500 : undefined,
notes: values.notes?.trim() || undefined,
bedId: values.bedId,
lockerId: values.lockerId || undefined,
};
};
export interface TransferFormValues {
newRoomId: number;
newBedId: number;

View File

@@ -53,63 +53,67 @@ const OperationLogsPage: React.FC = () => {
fetchData();
}, [fetchData]);
const columns = useMemo(() => [
{
title: '时间',
dataIndex: 'createdAt',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
},
{ title: '操作人', dataIndex: 'username', width: 100 },
{
title: '模块',
dataIndex: 'module',
width: 100,
render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag>,
},
{ title: '操作', dataIndex: 'action', width: 150 },
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (v: string) => {
const s = statusMap[v] || statusMap['success'];
return <Tag color={s.color}>{s.text}</Tag>;
const columns = useMemo(
() => [
{
title: '时间',
dataIndex: 'createdAt',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
},
},
{
title: '详情', width: 200,
dataIndex: 'detail',
ellipsis: true,
render: (v: string) =>
v ? (
<Tooltip title={v}>
<span>{v}</span>
</Tooltip>
) : (
'-'
),
},
{ title: 'IP地址', dataIndex: 'ipAddress', width: 130, render: (v: string) => v || '-' },
{
title: '终端',
dataIndex: 'userAgent',
width: 120,
ellipsis: true,
render: (v: string) => {
if (!v) return '-';
if (v.includes('Mobile')) return <Tag color="blue"></Tag>;
if (v.includes('Windows')) return <Tag>Windows</Tag>;
if (v.includes('Mac')) return <Tag>Mac</Tag>;
if (v.includes('Linux')) return <Tag>Linux</Tag>;
return (
<Tooltip title={v}>
<Tag></Tag>
</Tooltip>
);
{ title: '操作人', dataIndex: 'username', width: 100 },
{
title: '模块',
dataIndex: 'module',
width: 100,
render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag>,
},
},
], []);
{ title: '操作', dataIndex: 'action', width: 150 },
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (v: string) => {
const s = statusMap[v] || statusMap['success'];
return <Tag color={s.color}>{s.text}</Tag>;
},
},
{
title: '详情',
width: 200,
dataIndex: 'detail',
ellipsis: true,
render: (v: string) =>
v ? (
<Tooltip title={v}>
<span>{v}</span>
</Tooltip>
) : (
'-'
),
},
{ title: 'IP地址', dataIndex: 'ipAddress', width: 130, render: (v: string) => v || '-' },
{
title: '终端',
dataIndex: 'userAgent',
width: 120,
ellipsis: true,
render: (v: string) => {
if (!v) return '-';
if (v.includes('Mobile')) return <Tag color="blue"></Tag>;
if (v.includes('Windows')) return <Tag>Windows</Tag>;
if (v.includes('Mac')) return <Tag>Mac</Tag>;
if (v.includes('Linux')) return <Tag>Linux</Tag>;
return (
<Tooltip title={v}>
<Tag></Tag>
</Tooltip>
);
},
},
],
[],
);
return (
<div>

View File

@@ -1,16 +1,5 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
Table,
Modal,
Form,
Input,
Space,
Tag,
Popconfirm,
Card,
Checkbox,
Empty,
} from 'antd';
import { Table, Modal, Form, Input, Space, Tag, Popconfirm, Card, Checkbox, Empty } from 'antd';
import { PlusOutlined, EditOutlined, StopOutlined } from '@ant-design/icons';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
@@ -144,53 +133,61 @@ const RolesPage: React.FC = () => {
ai: 'AI 配置',
};
const columns = useMemo(() => [
{ title: 'ID', dataIndex: 'id', width: 80 },
{ title: '名称', dataIndex: 'name', width: 120 },
{ title: '描述', dataIndex: 'description', width: 200 },
{
title: '权限标签',
dataIndex: 'permissions',
width: 150,
render: (perms: PermissionItem[]) =>
perms?.length > 0 ? (
<Tag color="blue">{perms.length} </Tag>
) : (
<Tag color="default"></Tag>
const columns = useMemo(
() => [
{ title: 'ID', dataIndex: 'id', width: 80 },
{ title: '名称', dataIndex: 'name', width: 120 },
{ title: '描述', dataIndex: 'description', width: 200 },
{
title: '权限标签',
dataIndex: 'permissions',
width: 150,
render: (perms: PermissionItem[]) =>
perms?.length > 0 ? (
<Tag color="blue">{perms.length} </Tag>
) : (
<Tag color="default"></Tag>
),
},
{
title: '系统',
dataIndex: 'isSystem',
width: 80,
render: (v: boolean) => (v ? <Tag color="orange"></Tag> : null),
},
{
title: '操作',
width: 180,
fixed: 'right' as const,
render: (_: any, record: RoleItem) => (
<Space>
<PermissionButton
permission="role:edit"
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
</PermissionButton>
{!record.isSystem && (
<Popconfirm title="确认停用该角色?" onConfirm={() => handleDisable(record.id)}>
<PermissionButton
permission="role:delete"
type="link"
size="small"
icon={<StopOutlined />}
>
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
{
title: '系统',
dataIndex: 'isSystem',
width: 80,
render: (v: boolean) => (v ? <Tag color="orange"></Tag> : null),
},
{
title: '操作',
width: 180,
fixed: 'right' as const,
render: (_: any, record: RoleItem) => (
<Space>
<PermissionButton
permission="role:edit"
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
</PermissionButton>
{!record.isSystem && (
<Popconfirm title="确认停用该角色?" onConfirm={() => handleDisable(record.id)}>
<PermissionButton permission="role:delete" type="link" size="small" icon={<StopOutlined />}>
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
], []);
},
],
[],
);
const handleGroupCheckAll = (group: string, checked: boolean) => {
const groupPermIds =

View File

@@ -1,6 +1,27 @@
import React, { useEffect, useState, useCallback } from 'react';
import { Row, Col, Card, Tag, Select, Statistic, Modal, Spin, Badge, Tooltip, DatePicker, Alert, Button } from 'antd';
import { HomeOutlined, UserOutlined, CalendarOutlined, BankOutlined, HistoryOutlined, ShopOutlined } from '@ant-design/icons';
import {
Row,
Col,
Card,
Tag,
Select,
Statistic,
Modal,
Spin,
Badge,
Tooltip,
DatePicker,
Alert,
Button,
} from 'antd';
import {
HomeOutlined,
UserOutlined,
CalendarOutlined,
BankOutlined,
HistoryOutlined,
ShopOutlined,
} from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import api from '../../api';
import { message } from '../../ui/app-message';
@@ -9,10 +30,14 @@ function getCardStyle(room: any): React.CSSProperties {
let base: React.CSSProperties;
if (room.status === 'maintenance') base = { background: '#f5f5f5', borderColor: '#d9d9d9' };
else if (room.currentCount === 0) base = { background: '#f6ffed', borderColor: '#b7eb8f' };
else if (room.currentCount >= room.capacity) base = { background: '#fff2f0', borderColor: '#ffccc7' };
else if (room.currentCount >= room.capacity)
base = { background: '#fff2f0', borderColor: '#ffccc7' };
else base = { background: '#e6f4ff', borderColor: '#91caff' };
if (room.organizationColor) {
return { ...base, background: `color-mix(in srgb, ${room.organizationColor} 15%, ${base.background || '#fff'} 85%)` };
return {
...base,
background: `color-mix(in srgb, ${room.organizationColor} 15%, ${base.background || '#fff'} 85%)`,
};
}
return base;
}
@@ -29,7 +54,10 @@ function getOrganizationTags(occupants: any[]) {
...new Map(
occupants
.filter((o: any) => o.organizationName)
.map((o: any) => [o.organizationId, { name: o.organizationName, color: o.organizationColor }]),
.map((o: any) => [
o.organizationId,
{ name: o.organizationName, color: o.organizationColor },
]),
).values(),
] as { name: string; color: string | null }[];
if (organizationList.length === 0) return null;
@@ -80,7 +108,8 @@ const RoomVisualPage: React.FC = () => {
const rooms = data.rooms.filter((r: any) => {
if (selectedBuilding !== 'all' && r.building !== selectedBuilding) return false;
if (selectedOrganization !== 'all' && !(r.organizationIds || []).includes(selectedOrganization)) return false;
if (selectedOrganization !== 'all' && !(r.organizationIds || []).includes(selectedOrganization))
return false;
return true;
});
@@ -138,7 +167,15 @@ const RoomVisualPage: React.FC = () => {
label: (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
{t.color && (
<span style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: t.color, display: 'inline-block' }} />
<span
style={{
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: t.color,
display: 'inline-block',
}}
/>
)}
{t.name}
</span>
@@ -175,17 +212,29 @@ const RoomVisualPage: React.FC = () => {
</Col>
<Col xs={12} sm={6}>
<Card size="small">
<Statistic title="空闲房间" value={emptyRooms} styles={{ value: { color: '#34C759' } }} />
<Statistic
title="空闲房间"
value={emptyRooms}
styles={{ value: { color: '#34C759' } }}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card size="small">
<Statistic title="可安排床位" value={availableBedsCount} styles={{ value: { color: '#007AFF' } }} />
<Statistic
title="可安排床位"
value={availableBedsCount}
styles={{ value: { color: '#007AFF' } }}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card size="small">
<Statistic title="满员房间" value={fullRooms} styles={{ value: { color: '#FF3B30' } }} />
<Statistic
title="满员房间"
value={fullRooms}
styles={{ value: { color: '#FF3B30' } }}
/>
</Card>
</Col>
</Row>
@@ -214,13 +263,27 @@ const RoomVisualPage: React.FC = () => {
marginBottom: 8,
}}
>
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 16, fontWeight: 600, color: '#1d1d1f' }}>
<span
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
fontSize: 16,
fontWeight: 600,
color: '#1d1d1f',
}}
>
{room.organizationColor && (
<span style={{
width: 10, height: 10, borderRadius: '50%',
backgroundColor: room.organizationColor, display: 'inline-block',
flexShrink: 0,
}} />
<span
style={{
width: 10,
height: 10,
borderRadius: '50%',
backgroundColor: room.organizationColor,
display: 'inline-block',
flexShrink: 0,
}}
/>
)}
{room.roomNumber}
</span>
@@ -231,7 +294,13 @@ const RoomVisualPage: React.FC = () => {
{room.floor && <span>{room.floor}F</span>}
</div>
{room.totalBeds > 0 && (
<div style={{ fontSize: 12, color: room.occupiedBeds >= room.totalBeds ? '#FF3B30' : '#34C759', marginBottom: 6 }}>
<div
style={{
fontSize: 12,
color: room.occupiedBeds >= room.totalBeds ? '#FF3B30' : '#34C759',
marginBottom: 6,
}}
>
: {room.occupiedBeds}/{room.totalBeds}
</div>
)}
@@ -259,10 +328,16 @@ const RoomVisualPage: React.FC = () => {
)}
{getOrganizationTags(room.occupants)}
{room.occupants.length > 0 && (
<div className="room-card-tag-wrapper" style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 6 }}>
<div
className="room-card-tag-wrapper"
style={{ borderTop: '1px solid rgba(0,0,0,0.06)', paddingTop: 6 }}
>
{room.occupants.slice(0, 4).map((o: any) => (
<Tooltip key={o.studentId} title={`入住 ${o.days} 天 (${o.checkInDate} 起)`}>
<Tag style={{ margin: '0 4px 4px 0', fontSize: 12, maxWidth: '100%' }} icon={<UserOutlined />}>
<Tag
style={{ margin: '0 4px 4px 0', fontSize: 12, maxWidth: '100%' }}
icon={<UserOutlined />}
>
{o.studentName}
</Tag>
</Tooltip>

View File

@@ -70,8 +70,13 @@ function parseRoomNumber(input: string) {
const floor = parseInt(roomPart.charAt(0), 10) || undefined;
let roomType = '四人间';
let capacity = 4;
if (bldgNum === '2') { roomType = '单人间'; capacity = 1; }
else if (bldgNum === '8') { roomType = '爆改房'; capacity = 2; }
if (bldgNum === '2') {
roomType = '单人间';
capacity = 1;
} else if (bldgNum === '8') {
roomType = '爆改房';
capacity = 2;
}
return { building: `${bldgNum}号楼`, floor, roomType, capacity };
}
return null;
@@ -150,12 +155,19 @@ const RoomsPage: React.FC = () => {
let result = data;
if (searchText) {
const keyword = searchText.toLowerCase();
result = result.filter((r: Record<string, unknown>) => typeof r.roomNumber === 'string' && r.roomNumber.toLowerCase().includes(keyword));
result = result.filter(
(r: Record<string, unknown>) =>
typeof r.roomNumber === 'string' && r.roomNumber.toLowerCase().includes(keyword),
);
}
if (filterBuilding) result = result.filter((r: Record<string, unknown>) => r.building === filterBuilding);
if (filterStatus) result = result.filter((r: Record<string, unknown>) => r.status === filterStatus);
if (filterBuilding)
result = result.filter((r: Record<string, unknown>) => r.building === filterBuilding);
if (filterStatus)
result = result.filter((r: Record<string, unknown>) => r.status === filterStatus);
if (filterRentalCategory) {
result = result.filter((r: Record<string, unknown>) => r.rentalCategory === filterRentalCategory);
result = result.filter(
(r: Record<string, unknown>) => r.rentalCategory === filterRentalCategory,
);
}
return result;
}, [data, searchText, filterBuilding, filterStatus, filterRentalCategory]);
@@ -221,8 +233,11 @@ const RoomsPage: React.FC = () => {
bedForm.resetFields();
setBedEditing(null);
fetchBeds(drawerRoom.id);
} catch (e: any) { message.error(e?.message || '操作失败'); }
finally { setSavingBed(false); }
} catch (e: any) {
message.error(e?.message || '操作失败');
} finally {
setSavingBed(false);
}
};
const handleDeleteBed = async (id: number) => {
@@ -230,7 +245,9 @@ const RoomsPage: React.FC = () => {
await api.delete(`/rooms/${drawerRoom.id}/beds/${id}`);
message.success('已归档');
fetchBeds(drawerRoom.id);
} catch (e: any) { message.error(e?.message || '归档失败'); }
} catch (e: any) {
message.error(e?.message || '归档失败');
}
};
const handleBatchBeds = async (count: number) => {
@@ -238,7 +255,9 @@ const RoomsPage: React.FC = () => {
await api.post(`/rooms/${drawerRoom.id}/beds/batch`, { count });
message.success(`已生成 ${count} 张床位`);
fetchBeds(drawerRoom.id);
} catch (e: any) { message.error(e?.message || '批量生成失败'); }
} catch (e: any) {
message.error(e?.message || '批量生成失败');
}
};
const handleSaveLocker = async () => {
@@ -255,8 +274,11 @@ const RoomsPage: React.FC = () => {
lockerForm.resetFields();
setLockerEditing(null);
fetchLockers(drawerRoom.id);
} catch (e: any) { message.error(e?.message || '操作失败'); }
finally { setSavingLocker(false); }
} catch (e: any) {
message.error(e?.message || '操作失败');
} finally {
setSavingLocker(false);
}
};
const handleDeleteLocker = async (id: number) => {
@@ -264,7 +286,9 @@ const RoomsPage: React.FC = () => {
await api.delete(`/rooms/${drawerRoom.id}/lockers/${id}`);
message.success('已归档');
fetchLockers(drawerRoom.id);
} catch (e: any) { message.error(e?.message || '归档失败'); }
} catch (e: any) {
message.error(e?.message || '归档失败');
}
};
const handleBatchLockers = async (count: number) => {
@@ -272,7 +296,9 @@ const RoomsPage: React.FC = () => {
await api.post(`/rooms/${drawerRoom.id}/lockers/batch`, { count });
message.success(`已生成 ${count} 个柜子`);
fetchLockers(drawerRoom.id);
} catch (e: any) { message.error(e?.message || '批量生成失败'); }
} catch (e: any) {
message.error(e?.message || '批量生成失败');
}
};
const handleArchive = async (id: number) => {
@@ -304,109 +330,126 @@ const RoomsPage: React.FC = () => {
downloadBlob('/rooms/export' + params, '房间列表.xlsx').catch(() => message.error('导出失败'));
};
const columns = useMemo(() => [
{
title: '房间号',
dataIndex: 'roomNumber',
width: 100,
sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber),
},
{ title: '楼栋', dataIndex: 'building', width: 80 },
{ title: '楼层', dataIndex: 'floor', width: 80 },
{ title: '类型', dataIndex: 'roomType', width: 90, render: (v: any) => v || '-' },
{
title: '租赁类型',
dataIndex: 'rentalCategory',
width: 100,
render: (v: string) => {
if (v === 'long') return <Tag color="blue"></Tag>;
if (v === 'short') return <Tag color="green"></Tag>;
return '-';
const columns = useMemo(
() => [
{
title: '房间号',
dataIndex: 'roomNumber',
width: 100,
sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber),
},
},
{
title: '月租金',
dataIndex: 'monthlyRate',
width: 100,
render: (v: number) => (v ? `¥${v}` : '-'),
},
{ title: '额定人数', dataIndex: 'capacity', width: 80 },
{
title: '当前入住',
width: 80,
render: (_: any, r: any) =>
r.status === 'archived' ? (
<Tag color="#999">-</Tag>
) : (
<Badge
count={r.currentCount}
showZero
overflowCount={99}
style={{ backgroundColor: r.currentCount >= r.capacity ? '#ff4d4f' : '#52c41a' }}
/>
),
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
},
{
title: '操作',
width: 220,
render: (_: unknown, record: unknown) => {
const r = record as { status?: string; id: number };
return (
<Space>
{r.status === 'archived' ? (
<Popconfirm
title="确定恢复此宿舍?"
onConfirm={() => handleRestore(r.id)}
>
<PermissionButton permission="room:edit" size="small" icon={<UndoOutlined />} type="link">
</PermissionButton>
</Popconfirm>
) : (
<>
<PermissionButton
permission="room:view"
size="small"
type="link"
onClick={async () => {
const rec = record as { id: number };
setDrawerRoom(record);
setDrawerOpen(true);
await Promise.all([fetchBeds(rec.id), fetchLockers(rec.id)]);
}}
>
</PermissionButton>
<PermissionButton
permission="room:edit"
size="small"
onClick={() => {
const rec = record as { id: number };
setEditing(rec);
form.setFieldsValue(rec);
setModalOpen(true);
}}
>
</PermissionButton>
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
<PermissionButton permission="room:delete" size="small" icon={<InboxOutlined />}>
{ title: '楼栋', dataIndex: 'building', width: 80 },
{ title: '楼层', dataIndex: 'floor', width: 80 },
{ title: '类型', dataIndex: 'roomType', width: 90, render: (v: any) => v || '-' },
{
title: '租赁类型',
dataIndex: 'rentalCategory',
width: 100,
render: (v: string) => {
if (v === 'long') return <Tag color="blue"></Tag>;
if (v === 'short') return <Tag color="green"></Tag>;
return '-';
},
},
{
title: '月租金',
dataIndex: 'monthlyRate',
width: 100,
render: (v: number) => (v ? `¥${v}` : '-'),
},
{ title: '额定人数', dataIndex: 'capacity', width: 80 },
{
title: '当前入住',
width: 80,
render: (_: any, r: any) =>
r.status === 'archived' ? (
<Tag color="#999">-</Tag>
) : (
<Badge
count={r.currentCount}
showZero
overflowCount={99}
style={{ backgroundColor: r.currentCount >= r.capacity ? '#ff4d4f' : '#52c41a' }}
/>
),
},
{
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
},
{
title: '操作',
width: 220,
render: (_: unknown, record: unknown) => {
const r = record as { status?: string; id: number };
return (
<Space>
{r.status === 'archived' ? (
<Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}>
<PermissionButton
permission="room:edit"
size="small"
icon={<UndoOutlined />}
type="link"
>
</PermissionButton>
</Popconfirm>
</>
)}
</Space>
);
) : (
<>
<PermissionButton
permission="room:view"
size="small"
type="link"
onClick={async () => {
const rec = record as { id: number };
setDrawerRoom(record);
setDrawerOpen(true);
await Promise.all([fetchBeds(rec.id), fetchLockers(rec.id)]);
}}
>
</PermissionButton>
<PermissionButton
permission="room:edit"
size="small"
onClick={() => {
const rec = record as { id: number };
setEditing(rec);
form.setFieldsValue(rec);
setModalOpen(true);
}}
>
</PermissionButton>
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
<PermissionButton
permission="room:delete"
size="small"
icon={<InboxOutlined />}
>
</PermissionButton>
</Popconfirm>
</>
)}
</Space>
);
},
},
},
], [showArchived, buildings, handleBatchDelete, handleRestore, handleArchive, fetchBeds, fetchLockers]);
],
[
showArchived,
buildings,
handleBatchDelete,
handleRestore,
handleArchive,
fetchBeds,
fetchLockers,
],
);
return (
<div>
@@ -427,8 +470,18 @@ const RoomsPage: React.FC = () => {
onChange={(v) => setFilterBuilding(v)}
options={buildings.map((b) => ({ value: b, label: b }))}
/>
<Select placeholder="状态" allowClear style={{ width: 110 }} value={filterStatus} onChange={setFilterStatus}
options={[{value:'available',label:'可入住'},{value:'full',label:'已满'},{value:'maintenance',label:'维护中'}]} />
<Select
placeholder="状态"
allowClear
style={{ width: 110 }}
value={filterStatus}
onChange={setFilterStatus}
options={[
{ value: 'available', label: '可入住' },
{ value: 'full', label: '已满' },
{ value: 'maintenance', label: '维护中' },
]}
/>
<Select
placeholder="租赁类型"
allowClear
@@ -612,7 +665,10 @@ const RoomsPage: React.FC = () => {
<Drawer
title={`${drawerRoom?.roomNumber} 房间详情`}
open={drawerOpen}
onClose={() => { setDrawerOpen(false); setDrawerRoom(null); }}
onClose={() => {
setDrawerOpen(false);
setDrawerRoom(null);
}}
width={640}
destroyOnClose
>
@@ -624,14 +680,40 @@ const RoomsPage: React.FC = () => {
label: '基本信息',
children: drawerRoom && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div><strong></strong>{drawerRoom.roomNumber}</div>
<div><strong></strong>{drawerRoom.building || '-'}</div>
<div><strong></strong>{drawerRoom.floor ?? '-'}</div>
<div><strong></strong>{drawerRoom.roomType || '-'}</div>
<div><strong></strong>{drawerRoom.capacity}</div>
<div><strong></strong>{drawerRoom.rentalCategory === 'long' ? '长租' : '短租'}</div>
<div><strong></strong>{drawerRoom.monthlyRate ? `¥${drawerRoom.monthlyRate}` : '-'}</div>
<div><strong></strong><Tag color={statusMap[drawerRoom.status]?.color}>{statusMap[drawerRoom.status]?.text}</Tag></div>
<div>
<strong></strong>
{drawerRoom.roomNumber}
</div>
<div>
<strong></strong>
{drawerRoom.building || '-'}
</div>
<div>
<strong></strong>
{drawerRoom.floor ?? '-'}
</div>
<div>
<strong></strong>
{drawerRoom.roomType || '-'}
</div>
<div>
<strong></strong>
{drawerRoom.capacity}
</div>
<div>
<strong></strong>
{drawerRoom.rentalCategory === 'long' ? '长租' : '短租'}
</div>
<div>
<strong></strong>
{drawerRoom.monthlyRate ? `¥${drawerRoom.monthlyRate}` : '-'}
</div>
<div>
<strong></strong>
<Tag color={statusMap[drawerRoom.status]?.color}>
{statusMap[drawerRoom.status]?.text}
</Tag>
</div>
</div>
),
},
@@ -646,25 +728,48 @@ const RoomsPage: React.FC = () => {
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
onClick={() => { setBedEditing(null); bedForm.resetFields(); setBedModalOpen(true); }}
onClick={() => {
setBedEditing(null);
bedForm.resetFields();
setBedModalOpen(true);
}}
>
</Button>
<Popconfirm
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
description={
remainingBedSlots > 0
? <InputNumber min={1} max={remainingBedSlots} defaultValue={defaultBatchBedCount} id="batch-bed-count" style={{ width: 80 }} />
: '如需增加床位,请先调整宿舍额定人数'
remainingBedSlots > 0 ? (
<InputNumber
min={1}
max={remainingBedSlots}
defaultValue={defaultBatchBedCount}
id="batch-bed-count"
style={{ width: 80 }}
/>
) : (
'如需增加床位,请先调整宿舍额定人数'
)
}
onConfirm={() => {
const input = document.getElementById('batch-bed-count') as HTMLInputElement;
handleBatchBeds(input ? parseInt(input.value) || defaultBatchBedCount : defaultBatchBedCount);
const input = document.getElementById(
'batch-bed-count',
) as HTMLInputElement;
handleBatchBeds(
input
? parseInt(input.value) || defaultBatchBedCount
: defaultBatchBedCount,
);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
<Button size="small" disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}></Button>
<Button
size="small"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
</Button>
</Popconfirm>
</div>
<Table
@@ -675,7 +780,9 @@ const RoomsPage: React.FC = () => {
columns={[
{ title: '编号', dataIndex: 'bedNumber', width: 80 },
{
title: '状态', dataIndex: 'status', width: 80,
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => {
const map: Record<string, { text: string; color: string }> = {
available: { text: '空闲', color: 'green' },
@@ -687,7 +794,8 @@ const RoomsPage: React.FC = () => {
},
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
{
title: '操作', width: 120,
title: '操作',
width: 120,
render: (_: any, r: any) => (
<Space size="small">
<PermissionButton
@@ -695,12 +803,19 @@ const RoomsPage: React.FC = () => {
size="small"
type="link"
disabled={drawerRoom?.status === 'archived'}
onClick={() => { setBedEditing(r); bedForm.setFieldsValue(r); setBedModalOpen(true); }}
onClick={() => {
setBedEditing(r);
bedForm.setFieldsValue(r);
setBedModalOpen(true);
}}
>
</PermissionButton>
{r.status !== 'occupied' && (
<Popconfirm title="确定归档?" onConfirm={() => handleDeleteBed(r.id)}>
<Popconfirm
title="确定归档?"
onConfirm={() => handleDeleteBed(r.id)}
>
<PermissionButton
permission="room:edit"
size="small"
@@ -731,23 +846,37 @@ const RoomsPage: React.FC = () => {
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived'}
onClick={() => { setLockerEditing(null); lockerForm.resetFields(); setLockerModalOpen(true); }}
onClick={() => {
setLockerEditing(null);
lockerForm.resetFields();
setLockerModalOpen(true);
}}
>
</Button>
<Popconfirm
title="批量生成柜子"
description={
<InputNumber min={1} max={20} defaultValue={4} id="batch-locker-count" style={{ width: 80 }} />
<InputNumber
min={1}
max={20}
defaultValue={4}
id="batch-locker-count"
style={{ width: 80 }}
/>
}
onConfirm={() => {
const input = document.getElementById('batch-locker-count') as HTMLInputElement;
const input = document.getElementById(
'batch-locker-count',
) as HTMLInputElement;
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived'}
>
<Button size="small" disabled={drawerRoom?.status === 'archived'}></Button>
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
</Button>
</Popconfirm>
</div>
<Table
@@ -758,7 +887,9 @@ const RoomsPage: React.FC = () => {
columns={[
{ title: '编号', dataIndex: 'lockerNumber', width: 80 },
{
title: '状态', dataIndex: 'status', width: 80,
title: '状态',
dataIndex: 'status',
width: 80,
render: (s: string) => {
const map: Record<string, { text: string; color: string }> = {
available: { text: '空闲', color: 'green' },
@@ -770,7 +901,8 @@ const RoomsPage: React.FC = () => {
},
{ title: '备注', dataIndex: 'notes', render: (v: string) => v || '-' },
{
title: '操作', width: 120,
title: '操作',
width: 120,
render: (_: any, r: any) => (
<Space size="small">
<PermissionButton
@@ -778,12 +910,19 @@ const RoomsPage: React.FC = () => {
size="small"
type="link"
disabled={drawerRoom?.status === 'archived'}
onClick={() => { setLockerEditing(r); lockerForm.setFieldsValue(r); setLockerModalOpen(true); }}
onClick={() => {
setLockerEditing(r);
lockerForm.setFieldsValue(r);
setLockerModalOpen(true);
}}
>
</PermissionButton>
{r.status !== 'occupied' && (
<Popconfirm title="确定归档?" onConfirm={() => handleDeleteLocker(r.id)}>
<Popconfirm
title="确定归档?"
onConfirm={() => handleDeleteLocker(r.id)}
>
<PermissionButton
permission="room:edit"
size="small"
@@ -811,7 +950,10 @@ const RoomsPage: React.FC = () => {
title={bedEditing ? '编辑床位' : '添加床位'}
open={bedModalOpen}
onOk={handleSaveBed}
onCancel={() => { setBedModalOpen(false); setBedEditing(null); }}
onCancel={() => {
setBedModalOpen(false);
setBedEditing(null);
}}
confirmLoading={savingBed}
okText="保存"
>
@@ -838,7 +980,10 @@ const RoomsPage: React.FC = () => {
title={lockerEditing ? '编辑柜子' : '添加柜子'}
open={lockerModalOpen}
onOk={handleSaveLocker}
onCancel={() => { setLockerModalOpen(false); setLockerEditing(null); }}
onCancel={() => {
setLockerModalOpen(false);
setLockerEditing(null);
}}
confirmLoading={savingLocker}
okText="保存"
>

View File

@@ -478,7 +478,6 @@ const SchedulesPage: React.FC = () => {
}
};
// ---- Classroom select options ----
const classroomOptions = useMemo(
@@ -1192,17 +1191,17 @@ const SchedulesPage: React.FC = () => {
{syncResult ? (
/* ── 同步结果 ── */
<div>
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={6}>
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col xs={12} sm={6}>
<Statistic title="排课" value={syncResult.scheduleCount} suffix="条" />
</Col>
<Col span={6}>
<Col xs={12} sm={6}>
<Statistic title="班次" value={syncResult.shiftCount} suffix="个" />
</Col>
<Col span={6}>
<Col xs={12} sm={6}>
<Statistic title="考勤组" value={syncResult.groupCount} suffix="个" />
</Col>
<Col span={6}>
<Col xs={12} sm={6}>
<Statistic
title="排班数"
value={syncResult.syncedItems}
@@ -1257,11 +1256,11 @@ const SchedulesPage: React.FC = () => {
) : syncStatus ? (
/* ── 同步确认信息 ── */
<div>
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={8}>
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col xs={24} sm={8}>
<Statistic title="活跃排课" value={syncStatus.activeSchedules} suffix="条" />
</Col>
<Col span={8}>
<Col xs={24} sm={8}>
<Statistic
title="已就绪班级"
value={syncStatus.mappedClasses}
@@ -1272,7 +1271,7 @@ const SchedulesPage: React.FC = () => {
}}
/>
</Col>
<Col span={8}>
<Col xs={24} sm={8}>
<Statistic
title="无绑定学生班级"
value={syncStatus.totalClasses - syncStatus.mappedClasses}

View File

@@ -59,7 +59,6 @@ describe('schedule edit form mapping', () => {
});
});
describe('schedule notes normalization', () => {
it('omits whitespace-only notes from the payload', () => {
expect(

View File

@@ -62,7 +62,6 @@ interface EnrollmentInfo {
};
}
interface StudentCreateImportResult {
message?: string;
imported?: number;
@@ -75,6 +74,11 @@ interface StudentUpdateImportResult {
skipped?: number;
}
interface StudentFilterLookups {
classes: Array<{ id: number; name: string; code?: string }>;
teachers: Array<{ id: number; name: string; username: string }>;
}
const StudentsPage: React.FC = () => {
const { modal } = App.useApp();
const [data, setData] = useState<any[]>([]);
@@ -85,6 +89,10 @@ const StudentsPage: React.FC = () => {
const [searchName, setSearchName] = useState('');
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
const [filterOrganizationId, setFilterOrganizationId] = useState<number | undefined>(undefined);
const [filterClassId, setFilterClassId] = useState<number | undefined>(undefined);
const [filterTeacherId, setFilterTeacherId] = useState<number | undefined>(undefined);
const [classOptions, setClassOptions] = useState<StudentFilterLookups['classes']>([]);
const [teacherOptions, setTeacherOptions] = useState<StudentFilterLookups['teachers']>([]);
const [showArchived, setShowArchived] = useState(false);
const [archivedCount, setArchivedCount] = useState(0);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
@@ -150,6 +158,8 @@ const StudentsPage: React.FC = () => {
};
if (filterStatus) params.status = filterStatus;
if (filterOrganizationId) params.organizationId = filterOrganizationId;
if (filterClassId) params.classId = filterClassId;
if (filterTeacherId) params.teacherId = filterTeacherId;
const res = (await api.get('/students', { params })) as Array<Record<string, unknown>>;
const list = res as Array<Record<string, unknown>>;
const archived = list.filter((r) => r.status === 'archived');
@@ -160,7 +170,7 @@ const StudentsPage: React.FC = () => {
message.error(err?.message || '加载失败,请稍后重试');
}
setLoading(false);
}, [searchName, showArchived, filterStatus, filterOrganizationId]);
}, [searchName, showArchived, filterStatus, filterOrganizationId, filterClassId, filterTeacherId]);
useEffect(() => {
fetchData();
@@ -173,6 +183,13 @@ const StudentsPage: React.FC = () => {
setOrganizations(res as Array<{ id: number; name: string }>);
})
.catch(() => {});
api
.get<StudentFilterLookups>('/students/filter-lookups')
.then((res) => {
setClassOptions(res.classes || []);
setTeacherOptions(res.teachers || []);
})
.catch(() => {});
}, []);
const handleSave = async () => {
const values = await form.validateFields();
@@ -330,8 +347,15 @@ const StudentsPage: React.FC = () => {
? '/api'
: `http://localhost:${import.meta.env.VITE_API_PORT || 3002}/api`;
const token = localStorage.getItem('token');
const params = showArchived ? '?includeArchived=true' : '';
fetch(`${baseURL}/students/export${params}`, { headers: { Authorization: `Bearer ${token}` } })
const params = new URLSearchParams();
if (searchName) params.set('name', searchName);
if (filterStatus) params.set('status', filterStatus);
if (filterOrganizationId) params.set('organizationId', String(filterOrganizationId));
if (showArchived) params.set('includeArchived', 'true');
if (filterClassId) params.set('classId', String(filterClassId));
if (filterTeacherId) params.set('teacherId', String(filterTeacherId));
const query = params.toString() ? `?${params.toString()}` : '';
fetch(`${baseURL}/students/export${query}`, { headers: { Authorization: `Bearer ${token}` } })
.then((res) => res.blob())
.then((blob) => {
const url = URL.createObjectURL(blob);
@@ -568,6 +592,36 @@ const StudentsPage: React.FC = () => {
</Select.Option>
))}
</Select>
<Select
placeholder="所属班级"
allowClear
showSearch
optionFilterProp="label"
style={{ width: 160 }}
value={filterClassId}
onChange={(v) => {
setFilterClassId(v);
}}
options={classOptions.map((item) => ({
value: item.id,
label: item.code ? `${item.name}${item.code}` : item.name,
}))}
/>
<Select
placeholder="所属老师"
allowClear
showSearch
optionFilterProp="label"
style={{ width: 160 }}
value={filterTeacherId}
onChange={(v) => {
setFilterTeacherId(v);
}}
options={teacherOptions.map((item) => ({
value: item.id,
label: item.name === item.username ? item.name : `${item.name}${item.username}`,
}))}
/>
<Button
type={showArchived ? 'primary' : 'default'}
onClick={() => setShowArchived(!showArchived)}
@@ -609,7 +663,11 @@ const StudentsPage: React.FC = () => {
>
</PermissionButton>
<Upload accept=".xlsx,.xls" showUploadList={false} customRequest={handleCreateStudentsImport}>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleCreateStudentsImport}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
<Upload
@@ -679,9 +737,9 @@ const StudentsPage: React.FC = () => {
}
return (
<Card title="多班型对比" size="small" style={{ margin: '8px 0' }}>
<Row gutter={16}>
<Row gutter={[16, 16]}>
{enrollments.map((enr, idx) => (
<Col span={12} key={enr.classId}>
<Col xs={24} md={12} key={enr.classId}>
<Card
size="small"
title={enr.classType || `班型 ${idx + 1}`}

View File

@@ -74,56 +74,65 @@ const TeacherWorkspacePage: React.FC = () => {
fetchData();
}, []);
const classColumns: ColumnsType<AssignedClass> = useMemo(() => [
{
title: '班级名称',
dataIndex: 'className',
render: (v: string, r: AssignedClass) => `${v} (${r.classCode})`,
},
{
title: '角色',
dataIndex: 'roleType',
render: (v: string) => <Tag>{ROLE_LABELS[v] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
render: (v: string | null) => v || '-',
},
], []);
const classColumns: ColumnsType<AssignedClass> = useMemo(
() => [
{
title: '班级名称',
dataIndex: 'className',
render: (v: string, r: AssignedClass) => `${v} (${r.classCode})`,
},
{
title: '角色',
dataIndex: 'roleType',
render: (v: string) => <Tag>{ROLE_LABELS[v] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
render: (v: string | null) => v || '-',
},
],
[],
);
const scheduleColumns: ColumnsType<ScheduleItem> = useMemo(() => [
{
title: '时间',
key: 'time',
render: (_: unknown, r: ScheduleItem) => `${r.startTime} - ${r.endTime}`,
},
{
title: '星期',
dataIndex: 'weekDay',
render: (v: number) => <Tag>{WEEKDAY_LABELS[String(v)] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
},
{
title: '类型',
dataIndex: 'scheduleType',
render: (v: string) => (
<Tag color={v === 'INTERNAL' ? 'blue' : 'orange'}>
{v === 'INTERNAL' ? '内部课程' : '租赁'}
</Tag>
),
},
], []);
const scheduleColumns: ColumnsType<ScheduleItem> = useMemo(
() => [
{
title: '时间',
key: 'time',
render: (_: unknown, r: ScheduleItem) => `${r.startTime} - ${r.endTime}`,
},
{
title: '星期',
dataIndex: 'weekDay',
render: (v: number) => <Tag>{WEEKDAY_LABELS[String(v)] || v}</Tag>,
},
{
title: '科目',
dataIndex: 'subject',
},
{
title: '类型',
dataIndex: 'scheduleType',
render: (v: string) => (
<Tag color={v === 'INTERNAL' ? 'blue' : 'orange'}>
{v === 'INTERNAL' ? '内部课程' : '租赁'}
</Tag>
),
},
],
[],
);
const studentColumns: ColumnsType<StudentItem> = useMemo(() => [
{ title: '姓名', dataIndex: 'studentName' },
{ title: '学号', dataIndex: 'studentNo', render: (v: string) => v || '-' },
{ title: '班级', dataIndex: 'className' },
{ title: '加入日期', dataIndex: 'joinDate', render: (v: string) => v || '-' },
], []);
const studentColumns: ColumnsType<StudentItem> = useMemo(
() => [
{ title: '姓名', dataIndex: 'studentName' },
{ title: '学号', dataIndex: 'studentNo', render: (v: string) => v || '-' },
{ title: '班级', dataIndex: 'className' },
{ title: '加入日期', dataIndex: 'joinDate', render: (v: string) => v || '-' },
],
[],
);
if (loading) {
return (

View File

@@ -101,87 +101,94 @@ const TeachersPage: React.FC = () => {
}
};
const columns = useMemo(() => [
{ title: '姓名', dataIndex: 'name', key: 'name', width: 120 },
{ title: '用户名', dataIndex: 'username', key: 'username', width: 130 },
{
title: '角色',
dataIndex: 'roles',
key: 'roles',
width: 220,
render: (roles: TeacherRow['roles']) =>
roles.map((r) => <Tag key={r.code}>{ROLE_LABELS[r.code] || r.name}</Tag>),
},
{
title: '任课班级',
dataIndex: 'classAssignments',
key: 'classes',
width: 200,
render: (ca: TeacherRow['classAssignments']) =>
ca?.length
? ca.map((a, i) => (
<Tag key={i}>
{a.className || '-'}
{a.subject ? ` (${a.subject})` : ''}
</Tag>
))
: '-',
},
{
title: '科目',
dataIndex: 'profile',
key: 'subjects',
width: 130,
render: (p: TeacherRow['profile']) => p?.subjects?.join('、') || '-',
},
{
title: '入职日期',
dataIndex: 'profile',
key: 'joinedAt',
width: 110,
render: (p: TeacherRow['profile']) => p?.joinedAt || '-',
},
{
title: '状态',
dataIndex: 'isActive',
key: 'status',
width: 90,
render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? '在职' : '停用'}</Tag>,
},
{
title: '最后登录',
dataIndex: 'lastLoginAt',
key: 'login',
width: 160,
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-'),
},
{
title: '操作',
key: 'actions',
width: 100,
render: (_: unknown, r: TeacherRow) => (
<Button
size="small"
icon={<EditOutlined />}
onClick={() => {
setProfileModal(r);
form.setFieldsValue({
subjects: r.profile?.subjects || [],
joinedAt: r.profile?.joinedAt ? dayjs(r.profile.joinedAt) : null,
qualifications: r.profile?.qualifications || '',
});
}}
>
</Button>
),
},
], []);
const columns = useMemo(
() => [
{ title: '名', dataIndex: 'name', key: 'name', width: 120 },
{ title: '用户名', dataIndex: 'username', key: 'username', width: 130 },
{
title: '角色',
dataIndex: 'roles',
key: 'roles',
width: 220,
render: (roles: TeacherRow['roles']) =>
roles.map((r) => <Tag key={r.code}>{ROLE_LABELS[r.code] || r.name}</Tag>),
},
{
title: '任课班级',
dataIndex: 'classAssignments',
key: 'classes',
width: 200,
render: (ca: TeacherRow['classAssignments']) =>
ca?.length
? ca.map((a, i) => (
<Tag key={i}>
{a.className || '-'}
{a.subject ? ` (${a.subject})` : ''}
</Tag>
))
: '-',
},
{
title: '科目',
dataIndex: 'profile',
key: 'subjects',
width: 130,
render: (p: TeacherRow['profile']) => p?.subjects?.join('、') || '-',
},
{
title: '入职日期',
dataIndex: 'profile',
key: 'joinedAt',
width: 110,
render: (p: TeacherRow['profile']) => p?.joinedAt || '-',
},
{
title: '状态',
dataIndex: 'isActive',
key: 'status',
width: 90,
render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? '在职' : '停用'}</Tag>,
},
{
title: '最后登录',
dataIndex: 'lastLoginAt',
key: 'login',
width: 160,
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-'),
},
{
title: '操作',
key: 'actions',
width: 100,
render: (_: unknown, r: TeacherRow) => (
<Button
size="small"
icon={<EditOutlined />}
onClick={() => {
setProfileModal(r);
form.setFieldsValue({
subjects: r.profile?.subjects || [],
joinedAt: r.profile?.joinedAt ? dayjs(r.profile.joinedAt) : null,
qualifications: r.profile?.qualifications || '',
});
}}
>
</Button>
),
},
],
[],
);
return (
<div>
<h2 style={{ marginBottom: 16 }}></h2>
<Space style={{ marginBottom: 16 }} wrap className="responsive-toolbar responsive-toolbar--single">
<Space
style={{ marginBottom: 16 }}
wrap
className="responsive-toolbar responsive-toolbar--single"
>
<Input.Search
placeholder="搜索姓名/用户名"
allowClear

View File

@@ -1,24 +1,17 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { Table, Modal, Form, Input, Select, Switch, Space, Tag, Popconfirm } from 'antd';
import {
Table,
Modal,
Form,
Input,
Select,
Switch,
Space,
Tag,
Popconfirm,
} from 'antd';
import { PlusOutlined, EditOutlined, KeyOutlined, IdcardOutlined, InboxOutlined } from '@ant-design/icons';
PlusOutlined,
EditOutlined,
KeyOutlined,
IdcardOutlined,
InboxOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message';
import {
userProfileResponseToFormValues,
type UserProfileResponse,
} from './user-profile-form';
import { userProfileResponseToFormValues, type UserProfileResponse } from './user-profile-form';
const UsersPage: React.FC = () => {
const [data, setData] = useState<any[]>([]);
@@ -36,7 +29,6 @@ const UsersPage: React.FC = () => {
const [saving, setSaving] = useState(false);
const [showArchived, setShowArchived] = useState(false);
const handleOpenProfile = async (record: any) => {
setProfileUser(record);
try {
@@ -79,7 +71,6 @@ const UsersPage: React.FC = () => {
setLoading(false);
}, [showArchived]);
useEffect(() => {
fetchData();
}, [fetchData]);
@@ -162,89 +153,99 @@ const UsersPage: React.FC = () => {
}
};
const columns = useMemo(() => [
{ title: 'ID', dataIndex: 'id', width: 60 },
{ title: '用户名', dataIndex: 'username', width: 120 },
{ title: '名', dataIndex: 'name', width: 120 },
{
title: '角色',
dataIndex: 'roles',
width: 200,
render: (v: any[]) =>
v && v.length > 0 ? (
v.map((r: any) => (
<Tag key={r.id} color="blue">
{r.name}
</Tag>
))
) : (
<Tag color="default"></Tag>
),
},
{
title: '状态',
dataIndex: 'isActive',
width: 80,
render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
},
{
title: '最后登录',
dataIndex: 'lastLoginAt',
width: 170,
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm:ss') : '-'),
},
{
title: '创建时间',
dataIndex: 'createdAt',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
},
{
title: '操作',
width: 240,
fixed: 'right' as const,
render: (_: unknown, record: any) => (
<Space>
<PermissionButton
permission="user:edit"
type="link"
size="small"
icon={<IdcardOutlined />}
onClick={() => handleOpenProfile(record)}
>
</PermissionButton>
<PermissionButton
permission="user:edit"
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
</PermissionButton>
<PermissionButton
permission="user:reset-password"
type="link"
size="small"
icon={<KeyOutlined />}
onClick={() => handleResetPwd(record)}
>
</PermissionButton>
{record.isArchived ? (
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(record.id, false)}>
<PermissionButton permission="user:edit" type="link" size="small"></PermissionButton>
</Popconfirm>
const columns = useMemo(
() => [
{ title: 'ID', dataIndex: 'id', width: 60 },
{ title: '用户名', dataIndex: 'username', width: 120 },
{ title: '姓名', dataIndex: 'name', width: 120 },
{
title: '角色',
dataIndex: 'roles',
width: 200,
render: (v: any[]) =>
v && v.length > 0 ? (
v.map((r: any) => (
<Tag key={r.id} color="blue">
{r.name}
</Tag>
))
) : (
<Popconfirm title="归档后可恢复,确认归档?" onConfirm={() => handleArchive(record.id, true)}>
<PermissionButton permission="user:edit" type="link" size="small"></PermissionButton>
</Popconfirm>
)}
</Space>
),
},
], []);
<Tag color="default"></Tag>
),
},
{
title: '状态',
dataIndex: 'isActive',
width: 80,
render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
},
{
title: '最后登录',
dataIndex: 'lastLoginAt',
width: 170,
render: (v: string) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm:ss') : '-'),
},
{
title: '创建时间',
dataIndex: 'createdAt',
width: 170,
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'),
},
{
title: '操作',
width: 240,
fixed: 'right' as const,
render: (_: unknown, record: any) => (
<Space>
<PermissionButton
permission="user:edit"
type="link"
size="small"
icon={<IdcardOutlined />}
onClick={() => handleOpenProfile(record)}
>
</PermissionButton>
<PermissionButton
permission="user:edit"
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
</PermissionButton>
<PermissionButton
permission="user:reset-password"
type="link"
size="small"
icon={<KeyOutlined />}
onClick={() => handleResetPwd(record)}
>
</PermissionButton>
{record.isArchived ? (
<Popconfirm title="确认恢复?" onConfirm={() => handleArchive(record.id, false)}>
<PermissionButton permission="user:edit" type="link" size="small">
</PermissionButton>
</Popconfirm>
) : (
<Popconfirm
title="归档后可恢复,确认归档?"
onConfirm={() => handleArchive(record.id, true)}
>
<PermissionButton permission="user:edit" type="link" size="small">
</PermissionButton>
</Popconfirm>
)}
</Space>
),
},
],
[],
);
return (
<div>
@@ -256,7 +257,8 @@ const UsersPage: React.FC = () => {
alignItems: 'center',
flexWrap: 'wrap',
gap: 8,
}}>
}}
>
<h2 style={{ margin: 0 }}></h2>
<Space wrap>
<PermissionButton
@@ -374,10 +376,7 @@ const UsersPage: React.FC = () => {
<Form.Item name="qualifications" label="资质">
<Input.TextArea placeholder="教师资格证号、学历等" rows={2} />
</Form.Item>
<Form.Item
name="subjects"
label="任教学科"
>
<Form.Item name="subjects" label="任教学科">
<Select
mode="tags"
placeholder="输入学科后回车添加"
@@ -396,7 +395,7 @@ const UsersPage: React.FC = () => {
</Form.Item>
</Form>
</Modal>
</div>
</div>
);
};

View File

@@ -1,5 +1,18 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Drawer, Form, Input, InputNumber, Modal, Radio, Space, Switch, Table, Tag } from 'antd';
import {
Button,
Drawer,
Form,
Input,
InputNumber,
Modal,
Radio,
Select,
Space,
Switch,
Table,
Tag,
} from 'antd';
import { HistoryOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import api from '../../api';
@@ -13,10 +26,15 @@ interface WalletRow {
studentNo?: string;
balance: number;
outstandingAmount: number;
roomType?: string;
roomNumber?: string;
}
const transactionNames: Record<string, string> = {
recharge: '充值', adjustment: '调账', bill_payment: '账单扣款', bill_refund: '账单冲正',
recharge: '充值',
adjustment: '调账',
bill_payment: '账单扣款',
bill_refund: '账单冲正',
};
const WalletsPage: React.FC = () => {
@@ -24,6 +42,8 @@ const WalletsPage: React.FC = () => {
const [loading, setLoading] = useState(false);
const [keyword, setKeyword] = useState('');
const [debtOnly, setDebtOnly] = useState(false);
const [roomType, setRoomType] = useState<string | undefined>();
const [roomTypes, setRoomTypes] = useState<string[]>([]);
const [selected, setSelected] = useState<WalletRow | null>(null);
const [transactions, setTransactions] = useState<any[]>([]);
const [drawerOpen, setDrawerOpen] = useState(false);
@@ -36,14 +56,35 @@ const WalletsPage: React.FC = () => {
const fetchRows = useCallback(async () => {
setLoading(true);
try {
const data = await api.get('/wallets', { params: { keyword: keyword || undefined, debtOnly } });
const data = await api.get('/wallets', {
params: { keyword: keyword || undefined, debtOnly, roomType },
});
setRows(data as WalletRow[]);
} catch (error: any) {
message.error(error?.message || '加载学生余额失败');
} finally { setLoading(false); }
}, [keyword, debtOnly]);
} finally {
setLoading(false);
}
}, [keyword, debtOnly, roomType]);
useEffect(() => { void fetchRows(); }, [fetchRows]);
useEffect(() => {
void fetchRows();
}, [fetchRows]);
useEffect(() => {
const fetchRoomTypes = async () => {
try {
setRoomTypes((await api.get('/wallets/room-types')) as string[]);
} catch (error: any) {
message.error(error?.message || '加载房型失败');
}
};
void fetchRoomTypes();
}, []);
useEffect(() => {
setSelectedRowKeys([]);
}, [keyword, debtOnly, roomType]);
const openChange = (row: WalletRow) => {
setSelected(row);
@@ -60,13 +101,23 @@ const WalletsPage: React.FC = () => {
const values = await form.validateFields();
setSaving(true);
try {
const result: any = await api.post('/wallets/change-balance', { operationId: newOperationId(), studentId: selected.studentId, ...values });
const paid = (result.payments || []).reduce((sum: number, bill: any) => sum + Number(bill.paidAmount || 0), 0);
const result: any = await api.post('/wallets/change-balance', {
operationId: newOperationId(),
studentId: selected.studentId,
...values,
});
const paid = (result.payments || []).reduce(
(sum: number, bill: any) => sum + Number(bill.paidAmount || 0),
0,
);
message.success(paid > 0 ? `余额已更新,并自动补扣历史账单` : '余额已更新');
setSelected(null);
await fetchRows();
} catch (error: any) { message.error(error?.message || '余额操作失败'); }
finally { setSaving(false); }
} catch (error: any) {
message.error(error?.message || '余额操作失败');
} finally {
setSaving(false);
}
};
const submitBatchChange = async () => {
@@ -79,7 +130,13 @@ const WalletsPage: React.FC = () => {
...values,
});
const paid = (result.results || []).reduce((sum: number, item: any) => {
return sum + (item.payments || []).reduce((paymentSum: number, bill: any) => paymentSum + Number(bill.paidAmount || 0), 0);
return (
sum +
(item.payments || []).reduce(
(paymentSum: number, bill: any) => paymentSum + Number(bill.paidAmount || 0),
0,
)
);
}, 0);
message.success(
paid > 0
@@ -90,78 +147,247 @@ const WalletsPage: React.FC = () => {
setSelectedRowKeys([]);
batchForm.resetFields();
await fetchRows();
} catch (error: any) { message.error(error?.message || '批量余额操作失败'); }
finally { setSaving(false); }
} catch (error: any) {
message.error(error?.message || '批量余额操作失败');
} finally {
setSaving(false);
}
};
const showTransactions = async (row: WalletRow) => {
setSelected(row); setDrawerOpen(true);
try { setTransactions(await api.get('/wallets/transactions', { params: { studentId: row.studentId } }) as any[]); }
catch (error: any) { message.error(error?.message || '加载流水失败'); }
setSelected(row);
setDrawerOpen(true);
try {
setTransactions(
(await api.get('/wallets/transactions', { params: { studentId: row.studentId } })) as any[],
);
} catch (error: any) {
message.error(error?.message || '加载流水失败');
}
};
const columns = useMemo(() => [
{ title: '学生', render: (_: unknown, row: WalletRow) => <><strong>{row.studentName}</strong><div style={{ color: '#999' }}>{row.studentNo || `#${row.studentId}`}</div></> },
{ title: '可用余额', dataIndex: 'balance', render: (value: number) => <strong style={{ color: Number(value) > 0 ? '#1677ff' : undefined }}>¥{Number(value).toFixed(2)}</strong> },
{ title: '未付账单', dataIndex: 'outstandingAmount', render: (value: number) => Number(value) > 0 ? <Tag color="red">¥{Number(value).toFixed(2)}</Tag> : <Tag color="green"></Tag> },
{ title: '操作', render: (_: unknown, row: WalletRow) => <Space><PermissionButton permission="wallet:edit" type="primary" size="small" icon={<PlusOutlined />} onClick={() => openChange(row)}>/</PermissionButton><Button size="small" icon={<HistoryOutlined />} onClick={() => showTransactions(row)}></Button></Space> },
], []);
const columns = useMemo(
() => [
{
title: '学生',
render: (_: unknown, row: WalletRow) => (
<>
<strong>{row.studentName}</strong>
<div style={{ color: '#999' }}>{row.studentNo || `#${row.studentId}`}</div>
<div style={{ color: '#999' }}>
{row.roomType ? `${row.roomType}${row.roomNumber ? ` · ${row.roomNumber}` : ''}` : '未入住'}
</div>
</>
),
},
{
title: '可用余额',
dataIndex: 'balance',
render: (value: number) => (
<strong style={{ color: Number(value) > 0 ? '#1677ff' : undefined }}>
¥{Number(value).toFixed(2)}
</strong>
),
},
{
title: '未付账单',
dataIndex: 'outstandingAmount',
render: (value: number) =>
Number(value) > 0 ? (
<Tag color="red">¥{Number(value).toFixed(2)}</Tag>
) : (
<Tag color="green"></Tag>
),
},
{
title: '操作',
render: (_: unknown, row: WalletRow) => (
<Space>
<PermissionButton
permission="wallet:edit"
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => openChange(row)}
>
/
</PermissionButton>
<Button size="small" icon={<HistoryOutlined />} onClick={() => showTransactions(row)}>
</Button>
</Space>
),
},
],
[],
);
return <div>
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
<Space wrap><Input.Search allowClear placeholder="搜索姓名或学号" style={{ width: 240 }} onSearch={setKeyword} onChange={(event) => !event.target.value && setKeyword('')} /><span></span><Switch checked={debtOnly} onChange={setDebtOnly} /></Space>
<Space wrap>
<PermissionButton permission="wallet:edit" type="primary" icon={<PlusOutlined />} disabled={selectedRowKeys.length === 0} onClick={openBatchChange}>/</PermissionButton>
<Button icon={<ReloadOutlined />} onClick={fetchRows}></Button>
</Space>
return (
<div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
gap: 12,
marginBottom: 16,
flexWrap: 'wrap',
}}
>
<Space wrap>
<Input.Search
allowClear
placeholder="搜索姓名或学号"
style={{ width: 240 }}
onSearch={setKeyword}
onChange={(event) => !event.target.value && setKeyword('')}
/>
<Select
allowClear
placeholder="按房型筛选"
style={{ width: 180 }}
value={roomType}
onChange={setRoomType}
options={roomTypes.map((type) => ({ label: type, value: type }))}
/>
<span></span>
<Switch checked={debtOnly} onChange={setDebtOnly} />
</Space>
<Space wrap>
<PermissionButton
permission="wallet:edit"
type="primary"
icon={<PlusOutlined />}
disabled={selectedRowKeys.length === 0}
onClick={openBatchChange}
>
/
</PermissionButton>
<Button icon={<ReloadOutlined />} onClick={fetchRows}>
</Button>
</Space>
</div>
<Table
rowKey="studentId"
loading={loading}
dataSource={rows}
columns={columns}
rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
pagination={{ pageSize: 15, showTotal: (total) => `${total}` }}
/>
<Modal
title={`${selected?.studentName || ''} - 余额操作`}
open={!!selected && !drawerOpen}
onCancel={() => setSelected(null)}
onOk={submitChange}
confirmLoading={saving}
okText="确认"
>
<Form form={form} layout="vertical">
<Form.Item name="type" label="操作类型" rules={[{ required: true }]}>
<Radio.Group
options={[
{ label: '充值', value: 'recharge' },
{ label: '调账', value: 'adjustment' },
]}
/>
</Form.Item>
<Form.Item
name="amount"
label="变动金额"
extra="充值填正数;调减余额时填写负数。充值后会按最早账单优先自动补扣。"
rules={[{ required: true, message: '请输入金额' }]}
>
<InputNumber precision={2} style={{ width: '100%' }} addonBefore="¥" />
</Form.Item>
<Form.Item name="description" label="备注">
<Input.TextArea maxLength={300} />
</Form.Item>
</Form>
</Modal>
<Modal
title={`批量余额操作(${selectedRowKeys.length} 人)`}
open={batchModalOpen}
onCancel={() => setBatchModalOpen(false)}
onOk={submitBatchChange}
confirmLoading={saving}
okText="确认批量修改"
>
<Form form={batchForm} layout="vertical">
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
<strong>{selectedRowKeys.length}</strong>{' '}
</div>
<Form.Item name="type" label="操作类型" rules={[{ required: true }]}>
<Radio.Group
options={[
{ label: '充值', value: 'recharge' },
{ label: '调账', value: 'adjustment' },
]}
/>
</Form.Item>
<Form.Item
name="amount"
label="变动金额(元/人)"
extra="充值填正数;调减余额时填写负数。充值后会按最早账单优先自动补扣。"
rules={[{ required: true, message: '请输入金额' }]}
>
<InputNumber precision={2} style={{ width: '100%' }} addonBefore="¥" />
</Form.Item>
<Form.Item name="description" label="备注">
<Input.TextArea maxLength={300} />
</Form.Item>
</Form>
</Modal>
<Drawer
title={`${selected?.studentName || ''} - 余额流水`}
width={680}
open={drawerOpen}
onClose={() => {
setDrawerOpen(false);
setSelected(null);
}}
>
<Table
rowKey="id"
dataSource={transactions}
pagination={{ pageSize: 10 }}
columns={[
{
title: '时间',
dataIndex: 'createdAt',
render: (value: string) => dayjs(value).format('YYYY-MM-DD HH:mm'),
},
{
title: '类型',
dataIndex: 'type',
render: (value: string) => transactionNames[value] || value,
},
{
title: '金额',
dataIndex: 'amount',
render: (value: number) => (
<span style={{ color: Number(value) >= 0 ? '#389e0d' : '#cf1322' }}>
{Number(value) >= 0 ? '+' : ''}¥{Number(value).toFixed(2)}
</span>
),
},
{
title: '变动后余额',
dataIndex: 'balanceAfter',
render: (value: number) => `¥${Number(value).toFixed(2)}`,
},
{
title: '关联账单',
dataIndex: 'billId',
render: (value: number) => (value ? `#${value}` : '-'),
},
{ title: '说明', dataIndex: 'description' },
]}
/>
</Drawer>
</div>
<Table
rowKey="studentId"
loading={loading}
dataSource={rows}
columns={columns}
rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
pagination={{ pageSize: 15, showTotal: (total) => `${total}` }}
/>
<Modal title={`${selected?.studentName || ''} - 余额操作`} open={!!selected && !drawerOpen} onCancel={() => setSelected(null)} onOk={submitChange} confirmLoading={saving} okText="确认">
<Form form={form} layout="vertical">
<Form.Item name="type" label="操作类型" rules={[{ required: true }]}><Radio.Group options={[{ label: '充值', value: 'recharge' }, { label: '调账', value: 'adjustment' }]} /></Form.Item>
<Form.Item name="amount" label="变动金额" extra="充值填正数;调减余额时填写负数。充值后会按最早账单优先自动补扣。" rules={[{ required: true, message: '请输入金额' }]}><InputNumber precision={2} style={{ width: '100%' }} addonBefore="¥" /></Form.Item>
<Form.Item name="description" label="备注"><Input.TextArea maxLength={300} /></Form.Item>
</Form>
</Modal>
<Modal
title={`批量余额操作(${selectedRowKeys.length} 人)`}
open={batchModalOpen}
onCancel={() => setBatchModalOpen(false)}
onOk={submitBatchChange}
confirmLoading={saving}
okText="确认批量修改"
>
<Form form={batchForm} layout="vertical">
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
<strong>{selectedRowKeys.length}</strong>
</div>
<Form.Item name="type" label="操作类型" rules={[{ required: true }]}>
<Radio.Group options={[{ label: '充值', value: 'recharge' }, { label: '调账', value: 'adjustment' }]} />
</Form.Item>
<Form.Item name="amount" label="变动金额(元/人)" extra="充值填正数;调减余额时填写负数。充值后会按最早账单优先自动补扣。" rules={[{ required: true, message: '请输入金额' }]}>
<InputNumber precision={2} style={{ width: '100%' }} addonBefore="¥" />
</Form.Item>
<Form.Item name="description" label="备注"><Input.TextArea maxLength={300} /></Form.Item>
</Form>
</Modal>
<Drawer title={`${selected?.studentName || ''} - 余额流水`} width={680} open={drawerOpen} onClose={() => { setDrawerOpen(false); setSelected(null); }}>
<Table rowKey="id" dataSource={transactions} pagination={{ pageSize: 10 }} columns={[
{ title: '时间', dataIndex: 'createdAt', render: (value: string) => dayjs(value).format('YYYY-MM-DD HH:mm') },
{ title: '类型', dataIndex: 'type', render: (value: string) => transactionNames[value] || value },
{ title: '金额', dataIndex: 'amount', render: (value: number) => <span style={{ color: Number(value) >= 0 ? '#389e0d' : '#cf1322' }}>{Number(value) >= 0 ? '+' : ''}¥{Number(value).toFixed(2)}</span> },
{ title: '变动后余额', dataIndex: 'balanceAfter', render: (value: number) => `¥${Number(value).toFixed(2)}` },
{ title: '关联账单', dataIndex: 'billId', render: (value: number) => value ? `#${value}` : '-' },
{ title: '说明', dataIndex: 'description' },
]} />
</Drawer>
</div>;
);
};
export default WalletsPage;

View File

@@ -202,24 +202,67 @@ export const LOG_ACTIONS = {
// ── Permission nodes (PRD §17) ──────────────────────────────────────
export const PERMISSION_NODES = [
'student:view', 'student:add', 'student:update', 'student:delete',
'student:import', 'student:export',
'room:view', 'room:add', 'room:update', 'room:delete',
'occupancy:view', 'occupancy:add', 'occupancy:update',
'bill:view', 'bill:generate', 'bill:confirm', 'bill:markPaid', 'bill:export',
'expense:view', 'expense:add', 'expense:update', 'expense:delete',
'deposit:view', 'deposit:collect', 'deposit:refund',
'class:view', 'class:add', 'class:update', 'class:delete',
'schedule:view', 'schedule:add', 'schedule:update', 'schedule:delete',
'attendance:view', 'attendance:add', 'attendance:update', 'attendance:delete',
'student:view',
'student:add',
'student:update',
'student:delete',
'student:import',
'student:export',
'room:view',
'room:add',
'room:update',
'room:delete',
'occupancy:view',
'occupancy:add',
'occupancy:update',
'bill:view',
'bill:generate',
'bill:confirm',
'bill:markPaid',
'bill:export',
'expense:view',
'expense:add',
'expense:update',
'expense:delete',
'deposit:view',
'deposit:collect',
'deposit:refund',
'class:view',
'class:add',
'class:update',
'class:delete',
'schedule:view',
'schedule:add',
'schedule:update',
'schedule:delete',
'attendance:view',
'attendance:add',
'attendance:update',
'attendance:delete',
'attendance:batch',
'classroom:view', 'classroom:add', 'classroom:update', 'classroom:delete',
'organization:view', 'organization:create', 'organization:edit', 'organization:delete',
'rental:view', 'rental:add', 'rental:update', 'rental:delete',
'archive:view', 'archive:import', 'archive:export',
'classroom:view',
'classroom:add',
'classroom:update',
'classroom:delete',
'organization:view',
'organization:create',
'organization:edit',
'organization:delete',
'rental:view',
'rental:add',
'rental:update',
'rental:delete',
'archive:view',
'archive:import',
'archive:export',
'report:generate',
'log:view',
'role:view', 'role:add', 'role:update', 'role:delete',
'user:view', 'user:add', 'user:update',
'role:view',
'role:add',
'role:update',
'role:delete',
'user:view',
'user:add',
'user:update',
'dashboard:view',
] as const;

View File

@@ -25,7 +25,9 @@ type Role = keyof typeof CREDENTIALS;
* Login as a specific role and store the token in localStorage.
* Returns the parsed response data.
*/
export async function loginAs(role: Role): Promise<{ token: string; user: Record<string, unknown> }> {
export async function loginAs(
role: Role,
): Promise<{ token: string; user: Record<string, unknown> }> {
const creds = CREDENTIALS[role];
const res = await fetch(`${BASE}/api/auth/login`, {
method: 'POST',

View File

@@ -31,6 +31,7 @@ import {
AttendanceRecord,
AttendanceSession,
AttendanceDevice,
AttendancePeriodConfig,
DingAttendanceRaw,
SyncLog,
SyncState,
@@ -128,6 +129,7 @@ import { IntegrationConfigModule } from './integration/config/config.module';
AttendanceRecord,
AttendanceSession,
AttendanceDevice,
AttendancePeriodConfig,
DingAttendanceRaw,
Notification,
StudentProfile,

View File

@@ -113,6 +113,8 @@ export class AttendanceSettlementService {
const userIds = await this.attendanceService.getTeacherClassDingUserIds(
schedule.teacherId,
schedule.classId,
false,
lessonDate,
);
const importRange = this.attendanceService.getLessonAttendanceImportDateRange(
schedule,

View File

@@ -25,6 +25,7 @@ import {
AttendanceSummaryQueryDto,
AttendanceCalendarQueryDto,
QueryAttendanceRecordsDto,
AttendanceScheduleOptionsQueryDto,
QueryDingRawDto,
MatchDingRecordDto,
AttendanceReportQueryDto,
@@ -33,6 +34,8 @@ import {
GenerateFromSchedulesDto,
LessonAttendanceQueryDto,
StartLessonAttendanceDto,
SaveAttendancePeriodConfigsDto,
RefreshDingTalkAttendanceDto,
} from './dto/attendance.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
@@ -92,6 +95,45 @@ export class AttendanceController {
return this.service.assertClassAccess(req.user.id, classId, this.canManageAllAttendance(req));
}
@Get('attendance-period-configs')
@RequirePermission('attendance:view')
getAttendancePeriodConfigs() {
return this.service.getAttendancePeriodConfigs();
}
@Put('attendance-period-configs')
@RequirePermission('attendance:edit')
async saveAttendancePeriodConfigs(
@Body() dto: SaveAttendancePeriodConfigsDto,
@Request() req: { user: RequestUser },
) {
const result = await this.service.saveAttendancePeriodConfigs(dto);
await this.logService.log({
userId: req.user.id,
username: req.user.username,
module: '考勤管理',
action: '保存考勤时段配置',
targetType: 'attendancePeriodConfig',
detail: dto.periods.map((item) => `${item.label}:${item.startTime}-${item.endTime}`).join(''),
});
return result;
}
@Post('attendance-period-configs/reset')
@RequirePermission('attendance:edit')
async resetAttendancePeriodConfigs(@Request() req: { user: RequestUser }) {
const result = await this.service.resetAttendancePeriodConfigs();
await this.logService.log({
userId: req.user.id,
username: req.user.username,
module: '考勤管理',
action: '重置考勤时段配置',
targetType: 'attendancePeriodConfig',
});
return result;
}
@Get('attendance-lessons/schedules/:scheduleId')
@RequirePermission('attendance:view')
async getLessonAttendance(
@@ -117,6 +159,7 @@ export class AttendanceController {
req.user.id,
schedule.schedule.classId!,
this.canManageAllAttendance(req),
dto.date,
);
const importRange = this.service.getLessonAttendanceImportDateRange(
schedule.schedule,
@@ -128,6 +171,9 @@ export class AttendanceController {
autoMatch: true,
userId: req.user.id,
});
if (!importResult.success || importResult.errors.length > 0) {
throw new BadRequestException(importResult.errors.join('; ') || '钉钉考勤拉取失败');
}
const result = await this.service.createLessonAttendanceFromDingTalk(
scheduleId,
dto.date,
@@ -166,6 +212,84 @@ export class AttendanceController {
return result;
}
@Get('attendance-records/dingtalk-sync-status')
@RequirePermission('attendance:view')
async getDingTalkSyncStatus() {
const latest = await this.logService.findLatestDingTalkAttendancePull();
return {
lastPulledAt: latest?.createdAt ?? null,
action: latest?.action ?? null,
username: latest?.username ?? null,
detail: latest?.detail ?? null,
};
}
@Post('attendance-records/refresh-dingtalk')
@RequirePermission('attendance:create')
async refreshDingTalkAttendance(
@Body() dto: RefreshDingTalkAttendanceDto,
@Request() req: { user: RequestUser },
) {
if (dto.date > this.getTodayDateOnly()) {
throw new BadRequestException('不能查看或刷新未来日期的考勤');
}
if (dto.classId) await this.assertClassAccess(req, dto.classId);
const schedules = await this.service.getRefreshableSchedules(
dto.date,
dto.classId,
dto.session,
await this.getAccessibleClassIds(req),
);
let refreshed = 0;
let imported = 0;
let matched = 0;
const errors: string[] = [];
for (const schedule of schedules) {
try {
const importClassIds = await this.service.getTeacherClassDingUserIds(
req.user.id,
schedule.classId!,
this.canManageAllAttendance(req),
dto.date,
);
const importRange = this.service.getLessonAttendanceImportDateRange(schedule, dto.date);
const importResult = await this.importService.importFromDingTalk({
...importRange,
userIds: importClassIds,
autoMatch: true,
userId: req.user.id,
});
if (!importResult.success || importResult.errors.length > 0) {
errors.push(...importResult.errors);
continue;
}
await this.service.createLessonAttendanceFromDingTalk(schedule.id, dto.date, req.user.id);
refreshed += 1;
imported += importResult.imported;
matched += importResult.matched;
} catch (error: unknown) {
errors.push((error as { message?: string })?.message || `排课 ${schedule.id} 刷新失败`);
}
}
await this.logService.log({
userId: req.user.id,
username: req.user.username,
module: '考勤管理',
action: '刷新钉钉考勤',
targetType: 'attendanceRecord',
detail: `日期${dto.date},排课${schedules.length}节,刷新${refreshed}节,钉钉新增${imported}条,匹配${matched}${errors.length ? `,错误${errors.length}` : ''}`,
status: errors.length > 0 && refreshed === 0 ? 'failure' : 'success',
});
if (schedules.length === 0) {
return { refreshed, imported, matched, errors: ['当前条件下没有可刷新的课程'] };
}
return { refreshed, imported, matched, errors };
}
// ── Batch create attendance records ──
@Post('attendance-records/batch')
@RequirePermission('attendance:create')
@@ -277,6 +401,16 @@ export class AttendanceController {
res.end();
}
@Get('attendance-records/schedules')
@RequirePermission('attendance:view')
async getAttendanceScheduleOptions(
@Query() query: AttendanceScheduleOptionsQueryDto,
@Request() req: { user: RequestUser },
) {
await this.assertClassAccess(req, query.classId);
return this.service.getScheduleOptionsForAttendance(query.classId, query.date);
}
// ── List attendance records with filters ──
@Get('attendance-records')
@RequirePermission('attendance:view')
@@ -522,6 +656,7 @@ export class AttendanceController {
req.user.id,
dto.classId,
canManageAll,
dto.start,
);
}

View File

@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AttendanceRecord, AttendanceSession, AttendanceDevice, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping } from '../entities';
import { AttendanceRecord, AttendanceSession, AttendanceDevice, AttendancePeriodConfig, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping } from '../entities';
import { AttendanceService } from './attendance.service';
import { AttendanceImportService } from './attendance-import.service';
import { AttendanceSettlementService } from './attendance-settlement.service';
@@ -10,7 +10,7 @@ import { IntegrationModule } from '../integration/integration.module';
@Module({
imports: [
TypeOrmModule.forFeature([AttendanceRecord, AttendanceSession, AttendanceDevice, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping]),
TypeOrmModule.forFeature([AttendanceRecord, AttendanceSession, AttendanceDevice, AttendancePeriodConfig, DingAttendanceRaw, Student, Class, ClassSchedule, ClassStudent, ClassTeacher, StudentDingMapping]),
OperationLogsModule,
IntegrationModule,
],

View File

@@ -5,6 +5,7 @@ import {
AttendanceRecord,
AttendanceSession,
AttendanceDevice,
AttendancePeriodConfig,
DingAttendanceRaw,
Class,
Student,
@@ -24,6 +25,7 @@ import {
UpdateAttendanceRecordDto,
GenerateAttendanceFromSchedulesDto,
GenerateFromSchedulesDto,
SaveAttendancePeriodConfigsDto,
} from './dto/attendance.dto';
/** Keyed mutex serializing operations on the same attendance session. */
@@ -69,11 +71,20 @@ export class AttendanceService {
private attendanceSessionRepo: Repository<AttendanceSession>,
@InjectRepository(AttendanceDevice)
private attendanceDeviceRepo: Repository<AttendanceDevice>,
@InjectRepository(AttendancePeriodConfig)
private attendancePeriodConfigRepo: Repository<AttendancePeriodConfig>,
private dataSource: DataSource,
) {}
private sessionMutex = new SessionMutex();
private readonly defaultAttendancePeriods = [
{ periodKey: 'morning_reading', label: '早自习', startTime: '07:30', endTime: '08:30', sortOrder: 1 },
{ periodKey: 'morning', label: '早课', startTime: '09:00', endTime: '12:00', sortOrder: 2 },
{ periodKey: 'afternoon', label: '晚课', startTime: '14:00', endTime: '17:00', sortOrder: 3 },
{ periodKey: 'evening_study', label: '晚自习', startTime: '18:30', endTime: '21:00', sortOrder: 4 },
] as const;
private formatDeviceDetail(device: AttendanceDevice): string {
const classroomName = device.classroom?.name;
return classroomName ? `${device.deviceName} · ${classroomName}` : device.deviceName;
@@ -144,6 +155,28 @@ export class AttendanceService {
if (!assignment) throw new BadRequestException('只能访问自己任教班级的考勤');
}
private isClassStudentActiveOnDate(classStudent: Pick<ClassStudent, 'joinDate' | 'leaveDate' | 'status'>, lessonDate: string): boolean {
const status = classStudent.status ?? 'active';
if (!['active', 'left'].includes(status)) return false;
if (classStudent.joinDate && classStudent.joinDate > lessonDate) return false;
if (classStudent.leaveDate && classStudent.leaveDate < lessonDate) return false;
return true;
}
private async getClassStudentsForLesson(
classId: number,
lessonDate: string,
relations: string[] = [],
): Promise<ClassStudent[]> {
const classStudents = await this.classStudentRepo.find({
where: { classId, status: In(['active', 'left']) },
relations,
});
return classStudents.filter((classStudent) =>
this.isClassStudentActiveOnDate(classStudent, lessonDate),
);
}
/** List classes the current user may select for DingTalk attendance import. */
async getImportableClasses(userId: number, isSuperAdmin = false) {
if (isSuperAdmin) {
@@ -174,6 +207,7 @@ export class AttendanceService {
userId: number,
classId: number,
isSuperAdmin = false,
lessonDate?: string,
): Promise<string[]> {
if (!isSuperAdmin) {
const assignment = await this.classTeacherRepo.findOne({
@@ -187,9 +221,11 @@ export class AttendanceService {
if (!cls) throw new NotFoundException(`Class ${classId} not found`);
}
const classStudents = await this.classStudentRepo.find({
where: { classId, status: 'active' },
});
const classStudents = lessonDate
? await this.getClassStudentsForLesson(classId, lessonDate)
: await this.classStudentRepo.find({
where: { classId, status: 'active' },
});
const studentIds = [...new Set(classStudents.map((item) => item.studentId))];
if (studentIds.length === 0) {
throw new BadRequestException('该班级暂无在读学生');
@@ -375,15 +411,17 @@ export class AttendanceService {
where: { attendanceSessionId: existing.id },
order: { studentId: 'ASC' },
});
const classStudents = await this.classStudentRepo.find({
where: { classId: schedule.classId!, status: 'active' },
relations: ['student'],
});
const classStudents = await this.getClassStudentsForLesson(
schedule.classId!,
lessonDate,
['student'],
);
const studentsById = new Map(
classStudents.map((classStudent) => [classStudent.studentId, classStudent.student]),
);
const existingStudentIds = new Set(existingRecords.map((record) => record.studentId));
const lessonSessionKey = this.mapLessonScheduleTimeToSession(schedule.startTime);
const updatedRecords = existingRecords.map((record) => {
record.student = studentsById.get(record.studentId)!;
// Preserve manual corrections only while the lesson is still in progress.
@@ -422,7 +460,7 @@ export class AttendanceService {
scheduleId,
attendanceSessionId: existing.id,
attendanceDate: lessonDate,
session: this.mapScheduleTimeToSession(schedule.startTime),
session: lessonSessionKey,
status: this.mapDingTalkStatus(raw, finalize),
source: 'dingtalk',
...this.getLessonPunchMetadata(
@@ -456,10 +494,11 @@ export class AttendanceService {
const recordRepo = manager.getRepository(AttendanceRecord);
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, schedule, lessonDate);
const classStudents = await this.classStudentRepo.find({
where: { classId: schedule.classId!, status: 'active' },
relations: ['student'],
});
const classStudents = await this.getClassStudentsForLesson(
schedule.classId!,
lessonDate,
['student'],
);
if (classStudents.length === 0) throw new BadRequestException('该班级暂无在读学生');
let session: AttendanceSession;
@@ -495,6 +534,7 @@ export class AttendanceService {
throw err;
}
const lessonSessionKey = this.mapLessonScheduleTimeToSession(schedule.startTime);
const records = classStudents.map((classStudent) => {
const raw = this.selectDingTalkRecordsForLesson(
rawByStudent.get(classStudent.studentId) ?? [],
@@ -508,7 +548,7 @@ export class AttendanceService {
scheduleId,
attendanceSessionId: session.id,
attendanceDate: lessonDate,
session: this.mapScheduleTimeToSession(schedule.startTime),
session: lessonSessionKey,
status: this.mapDingTalkStatus(raw, finalize),
source: 'dingtalk',
...this.getLessonPunchMetadata(
@@ -539,9 +579,7 @@ export class AttendanceService {
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
lessonDate: string,
): Promise<Map<number, DingAttendanceRaw[]>> {
const classStudents = await this.classStudentRepo.find({
where: { classId, status: 'active' },
});
const classStudents = await this.getClassStudentsForLesson(classId, lessonDate);
if (classStudents.length === 0) return new Map();
const studentIds = classStudents.map((cs) => cs.studentId);
const window = this.getLessonAttendanceWindow(schedule, lessonDate);
@@ -654,7 +692,7 @@ export class AttendanceService {
});
const classStudents = await this.classStudentRepo.find({
where: { classId, status: 'active' },
where: { classId, status: In(['active', 'left']) },
relations: ['student'],
});
@@ -679,8 +717,11 @@ export class AttendanceService {
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 session = await this.mapScheduleTimeToSession(sched.startTime);
const classStudentsForDate = classStudents.filter((cs) =>
this.isClassStudentActiveOnDate(cs, dateStr),
);
for (const cs of classStudentsForDate) {
const key = `${cs.studentId}|${dateStr}|${session}`;
if (existingKeys.has(key)) continue;
@@ -754,7 +795,97 @@ export class AttendanceService {
return shifted.toISOString().slice(0, 10);
}
private mapScheduleTimeToSession(startTime: string): string {
private async ensureAttendancePeriodConfigs() {
const count = await this.attendancePeriodConfigRepo.count();
if (count === 0) {
await this.attendancePeriodConfigRepo.save(
this.defaultAttendancePeriods.map((period) => this.attendancePeriodConfigRepo.create({
...period,
enabled: true,
})),
);
}
return this.attendancePeriodConfigRepo.find({ order: { sortOrder: 'ASC', id: 'ASC' } });
}
async getAttendancePeriodConfigs() {
return this.ensureAttendancePeriodConfigs();
}
async getRefreshableSchedules(date: string, classId?: number, session?: string, accessibleClassIds?: number[]) {
const parsedDate = new Date(`${date}T00:00:00`);
if (Number.isNaN(parsedDate.getTime())) throw new BadRequestException('无效日期');
const weekDay = parsedDate.getDay() === 0 ? 7 : parsedDate.getDay();
const qb = this.scheduleRepo
.createQueryBuilder('schedule')
.where('schedule.scheduleType = :scheduleType', { scheduleType: ScheduleType.INTERNAL })
.andWhere('schedule.status = :status', { status: 'active' })
.andWhere('schedule.classId IS NOT NULL')
.andWhere('schedule.weekDay = :weekDay', { weekDay })
.andWhere('schedule.startDate <= :date', { date })
.andWhere('schedule.endDate >= :date', { date });
if (classId) {
qb.andWhere('schedule.classId = :classId', { classId });
} else if (accessibleClassIds) {
if (accessibleClassIds.length === 0) return [];
qb.andWhere('schedule.classId IN (:...accessibleClassIds)', { accessibleClassIds });
}
const schedules = await qb.orderBy('schedule.startTime', 'ASC').getMany();
if (!session) return schedules;
const matchedSchedules: ClassSchedule[] = [];
for (const schedule of schedules) {
if ((await this.mapScheduleTimeToSession(schedule.startTime)) === session) {
matchedSchedules.push(schedule);
}
}
return matchedSchedules;
}
async saveAttendancePeriodConfigs(dto: SaveAttendancePeriodConfigsDto) {
const seen = new Set<string>();
const normalized = dto.periods.map((period, index) => {
const periodKey = period.periodKey.trim();
const label = period.label.trim();
if (!periodKey || !label) throw new BadRequestException('时段标识和名称不能为空');
if (seen.has(periodKey)) throw new BadRequestException(`时段标识 ${periodKey} 重复`);
seen.add(periodKey);
if (this.toMinutes(period.endTime) <= this.toMinutes(period.startTime)) {
throw new BadRequestException(`${label} 的结束时间必须晚于开始时间`);
}
return {
periodKey,
label,
startTime: period.startTime,
endTime: period.endTime,
sortOrder: period.sortOrder ?? index + 1,
enabled: period.enabled ?? true,
};
}).sort((left, right) => left.sortOrder - right.sortOrder);
for (let index = 1; index < normalized.length; index += 1) {
const previous = normalized[index - 1];
const current = normalized[index];
if (previous.enabled && current.enabled && this.toMinutes(current.startTime) < this.toMinutes(previous.endTime)) {
throw new BadRequestException(`${previous.label}${current.label} 时间段不能重叠`);
}
}
await this.attendancePeriodConfigRepo.clear();
await this.attendancePeriodConfigRepo.save(
normalized.map((period) => this.attendancePeriodConfigRepo.create(period)),
);
return this.getAttendancePeriodConfigs();
}
async resetAttendancePeriodConfigs() {
await this.attendancePeriodConfigRepo.clear();
return this.ensureAttendancePeriodConfigs();
}
private mapLessonScheduleTimeToSession(startTime: string): string {
const hour = parseInt(startTime.slice(0, 2), 10);
if (hour < 8) return 'morning_reading';
if (hour < 12) return 'morning';
@@ -763,15 +894,31 @@ export class AttendanceService {
return 'night_check';
}
private async mapScheduleTimeToSession(startTime: string): Promise<string> {
const startMinutes = this.toMinutes(startTime);
const periods = (await this.ensureAttendancePeriodConfigs()).filter((period) => period.enabled);
const matched = periods.find((period) => {
const periodStart = this.toMinutes(period.startTime);
const periodEnd = this.toMinutes(period.endTime);
return startMinutes >= periodStart && startMinutes < periodEnd;
});
if (matched) return matched.periodKey;
throw new BadRequestException(`课程开始时间 ${startTime} 未匹配到考勤时段,请先配置考勤时段`);
}
// ── Attendance summary ──
async getSummary(query: AttendanceSummaryQueryDto, accessibleClassIds?: number[]) {
const qb = this.attendanceRepo.createQueryBuilder('ar');
if (query.classId) {
qb.andWhere('ar.classId = :classId', { classId: query.classId });
} else if (accessibleClassIds) {
}
if (query.scheduleId) {
qb.andWhere('ar.scheduleId = :scheduleId', { scheduleId: query.scheduleId });
}
if (!query.classId && accessibleClassIds) {
if (accessibleClassIds.length === 0)
return { total: 0, present: 0, late: 0, absent: 0, leave: 0, presentRate: 0 };
return { total: 0, present: 0, late: 0, absent: 0, leave: 0, pending: 0, presentRate: 0 };
qb.andWhere('ar.classId IN (:...accessibleClassIds)', { accessibleClassIds });
}
if (query.dateFrom) {
@@ -780,6 +927,9 @@ export class AttendanceService {
if (query.dateTo) {
qb.andWhere('ar.attendanceDate <= :dateTo', { dateTo: query.dateTo });
}
if (query.session) {
qb.andWhere('ar.session = :session', { session: query.session });
}
const rows = await qb.getMany();
@@ -788,9 +938,10 @@ export class AttendanceService {
const late = rows.filter((r) => r.status === 'late').length;
const absent = rows.filter((r) => r.status === 'absent').length;
const leave = rows.filter((r) => r.status === 'leave').length;
const pending = rows.filter((r) => r.status === 'pending').length;
const presentRate = total > 0 ? Number(((present / total) * 100).toFixed(1)) : 0;
return { total, present, late, absent, leave, presentRate };
return { total, present, late, absent, leave, pending, presentRate };
}
// ── Attendance calendar ──
@@ -812,6 +963,25 @@ export class AttendanceService {
return this.buildCalendar(classId, weekStart);
}
private getWeekDayForDate(date: string): number {
const day = new Date(`${date}T00:00:00+08:00`).getUTCDay();
return day === 0 ? 7 : day;
}
async getScheduleOptionsForAttendance(classId: number, date: string) {
const weekDay = this.getWeekDayForDate(date);
return this.scheduleRepo
.createQueryBuilder('cs')
.where('cs.classId = :classId', { classId })
.andWhere('cs.weekDay = :weekDay', { weekDay })
.andWhere('cs.startDate <= :date', { date })
.andWhere('cs.endDate >= :date', { date })
.andWhere('cs.status = :status', { status: 'active' })
.orderBy('cs.startTime', 'ASC')
.addOrderBy('cs.subject', 'ASC')
.getMany();
}
private async buildCalendar(classId: number, weekStart: string) {
// Compute weekEnd (Sunday = weekStart + 6 days)
const start = new Date(weekStart);
@@ -1018,6 +1188,7 @@ export class AttendanceService {
async findAllForExport(
query: {
classId?: number;
scheduleId?: number;
dateFrom?: string;
dateTo?: string;
session?: string;
@@ -1029,6 +1200,9 @@ export class AttendanceService {
const qb = this.attendanceRepo.createQueryBuilder('ar');
qb.leftJoinAndSelect('ar.student', 'student').leftJoinAndSelect('ar.class', 'class');
if (query.scheduleId) {
qb.andWhere('ar.scheduleId = :scheduleId', { scheduleId: query.scheduleId });
}
if (query.classId) {
qb.andWhere('ar.classId = :classId', { classId: query.classId });
} else if (accessibleClassIds) {

View File

@@ -3,16 +3,53 @@ import {
IsOptional,
IsString,
IsInt,
IsBoolean,
IsDateString,
IsIn,
ValidateNested,
IsNotEmpty,
ArrayNotEmpty,
Matches,
Max,
Min,
} from 'class-validator';
import { Type } from 'class-transformer';
export class AttendancePeriodConfigItemDto {
@IsString()
@IsNotEmpty()
periodKey: string;
@IsString()
@IsNotEmpty()
label: string;
@IsString()
@Matches(/^([01]\d|2[0-3]):[0-5]\d$/)
startTime: string;
@IsString()
@Matches(/^([01]\d|2[0-3]):[0-5]\d$/)
endTime: string;
@IsOptional()
@IsInt()
sortOrder?: number;
@IsOptional()
@IsBoolean()
enabled?: boolean;
}
export class SaveAttendancePeriodConfigsDto {
@IsArray()
@ArrayNotEmpty()
@ValidateNested({ each: true })
@Type(() => AttendancePeriodConfigItemDto)
periods: AttendancePeriodConfigItemDto[];
}
export class AttendanceRecordItem {
@IsInt()
@IsNotEmpty()
@@ -27,7 +64,6 @@ export class AttendanceRecordItem {
attendanceDate: string;
@IsString()
@IsIn(['morning_reading', 'morning', 'afternoon', 'evening_study', 'night_check'])
@IsNotEmpty()
session: string;
@@ -59,6 +95,11 @@ export class AttendanceSummaryQueryDto {
@Type(() => Number)
classId?: number;
@IsOptional()
@IsInt()
@Type(() => Number)
scheduleId?: number;
@IsOptional()
@IsDateString()
dateFrom?: string;
@@ -66,6 +107,26 @@ export class AttendanceSummaryQueryDto {
@IsOptional()
@IsDateString()
dateTo?: string;
@IsOptional()
@IsString()
session?: string;
}
export class RefreshDingTalkAttendanceDto {
@IsDateString()
@IsNotEmpty()
date: string;
@IsOptional()
@IsInt()
@Type(() => Number)
classId?: number;
@IsOptional()
@IsString()
session?: string;
}
export class AttendanceCalendarQueryDto {
@@ -112,6 +173,17 @@ export class QueryDingRawDto {
pageSize?: number;
}
export class AttendanceScheduleOptionsQueryDto {
@IsInt()
@Type(() => Number)
@IsNotEmpty()
classId: number;
@IsDateString()
@IsNotEmpty()
date: string;
}
export class QueryAttendanceRecordsDto {
@IsOptional()
@IsInt()
@@ -137,7 +209,7 @@ export class QueryAttendanceRecordsDto {
@IsOptional()
@IsString()
@IsIn(['present', 'late', 'absent', 'leave'])
@IsIn(['present', 'late', 'absent', 'leave', 'pending'])
status?: string;
@IsOptional()

View File

@@ -0,0 +1,33 @@
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';
@Entity('attendance_period_configs')
@Index(['periodKey'], { unique: true })
@Index(['sortOrder'])
export class AttendancePeriodConfig {
@PrimaryGeneratedColumn()
id: number;
@Column({ name: 'period_key', type: 'varchar', length: 40 })
periodKey: string;
@Column({ type: 'varchar', length: 40 })
label: string;
@Column({ name: 'start_time', type: 'varchar', length: 5 })
startTime: string;
@Column({ name: 'end_time', type: 'varchar', length: 5 })
endTime: string;
@Column({ name: 'sort_order', type: 'integer', default: 0 })
sortOrder: number;
@Column({ type: 'boolean', default: true })
enabled: boolean;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}

View File

@@ -23,6 +23,7 @@ export { ClassSchedule, ScheduleType } from './class-schedule.entity';
export { AttendanceRecord } from './attendance-record.entity';
export { AttendanceSession } from './attendance-session.entity';
export { AttendanceDevice, AttendanceDeviceStatus } from './attendance-device.entity';
export { AttendancePeriodConfig } from './attendance-period-config.entity';
export { DingAttendanceRaw } from './ding-attendance-raw.entity';
export { SyncLog } from './sync-log.entity';
export { SyncState } from './sync-state.entity';

View File

@@ -23,6 +23,17 @@ export class OperationLogsService {
return this.repo.save(entry);
}
async findLatestDingTalkAttendancePull() {
return this.repo
.createQueryBuilder('log')
.where('log.module = :module', { module: '考勤管理' })
.andWhere('log.action IN (:...actions)', {
actions: ['拉取钉钉课程考勤', '查看已拉取课程考勤', '钉钉考勤导入', '刷新钉钉考勤'],
})
.orderBy('log.createdAt', 'DESC')
.getOne();
}
async findAll(query?: {
module?: string;
userId?: number;

View File

@@ -143,6 +143,26 @@ const DEPRECATED_PERMISSION_CODES = [
const DEPRECATED_PERMISSION_CODE_SET = new Set<string>(DEPRECATED_PERMISSION_CODES);
function getChinaDateParts(date = new Date()): { date: string; weekDay: number } {
const parts = Object.fromEntries(
new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
weekday: 'short',
})
.formatToParts(date)
.filter((part) => part.type !== 'literal')
.map((part) => [part.type, part.value]),
);
const weekDays: Record<string, number> = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 };
return {
date: `${parts.year}-${parts.month}-${parts.day}`,
weekDay: weekDays[parts.weekday],
};
}
export const PRESET_ROLES: Array<{
name: string;
code: string;
@@ -684,11 +704,8 @@ export class RbacService {
subject: t.subject,
}));
// Get today's day of week (1=Monday, 7=Sunday)
const today = new Date();
const weekDay = today.getDay(); // 0=Sun → convert to 1-7
const adjustedWeekDay = weekDay === 0 ? 7 : weekDay;
const todayStr = today.toISOString().slice(0, 10);
// Get today's China business date and day of week (1=Monday, 7=Sunday)
const { date: todayStr, weekDay: adjustedWeekDay } = getChinaDateParts();
// Get today's schedules for assigned classes
const todaySchedules = await this.classScheduleRepo

View File

@@ -110,4 +110,14 @@ export class QueryStudentDto {
@Type(() => Number)
@IsInt()
organizationId?: number;
@IsOptional()
@Type(() => Number)
@IsInt()
classId?: number;
@IsOptional()
@Type(() => Number)
@IsInt()
teacherId?: number;
}

View File

@@ -175,6 +175,16 @@ export class StudentsController {
return this.service.getBasicLookups();
}
@Get('filter-lookups')
@RequirePermission('student:view')
async getFilterLookups(@Request() req: AuthenticatedRequest) {
const classIds = await this.service.getAccessibleClassIds(
req.user.id,
this.canManageAllStudents(req),
);
return this.service.getFilterLookups(classIds);
}
@Get()
@RequirePermission('student:view')
async findAll(
@@ -194,7 +204,7 @@ export class StudentsController {
@Get('export')
@RequirePermission('student:export')
async exportExcel(
@Query('includeArchived') includeArchived?: string,
@Query() query: QueryStudentDto,
@Res() res?: Response,
@Request() req?: any,
) {
@@ -202,10 +212,7 @@ export class StudentsController {
req.user.id,
this.canManageAllStudents(req),
);
const students = await this.service.findAll(
{ includeArchived: includeArchived === 'true' },
classIds,
);
const students = await this.service.findAll(query, classIds);
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('学生名单');
ws.columns = STUDENT_EXPORT_COLUMNS;

View File

@@ -1,6 +1,6 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Not, In, FindOptionsWhere } from 'typeorm';
import { Repository, Like, Not, In, FindOptionsWhere, IsNull } from 'typeorm';
import { Student } from '../entities/student.entity';
import { Class } from '../entities/class.entity';
import { ClassStudent } from '../entities/class-student.entity';
@@ -41,6 +41,8 @@ export class StudentsService {
status?: string;
includeArchived?: boolean;
organizationId?: number | string;
classId?: number | string;
teacherId?: number | string;
},
accessibleClassIds?: number[],
) {
@@ -52,10 +54,28 @@ export class StudentsService {
} else if (!query?.includeArchived) {
where.status = Not(In(['archived', 'staff']));
}
if (accessibleClassIds) {
if (accessibleClassIds.length === 0) return [];
let scopedClassIds = accessibleClassIds ? [...accessibleClassIds] : undefined;
if (query?.teacherId) {
const teacherAssignments = await this.classTeacherRepo.find({
where: { userId: Number(query.teacherId) },
});
const teacherClassIds = [...new Set(teacherAssignments.map((item) => item.classId))];
scopedClassIds = scopedClassIds
? scopedClassIds.filter((classId) => teacherClassIds.includes(classId))
: teacherClassIds;
}
if (query?.classId) {
const classId = Number(query.classId);
scopedClassIds = scopedClassIds
? scopedClassIds.filter((accessibleClassId) => accessibleClassId === classId)
: [classId];
}
if (scopedClassIds) {
if (scopedClassIds.length === 0) return [];
const classStudents = await this.classStudentRepo.find({
where: { classId: In(accessibleClassIds), status: 'active' },
where: { classId: In(scopedClassIds), status: 'active' },
});
const studentIds = [...new Set(classStudents.map((item) => item.studentId))];
if (studentIds.length === 0) return [];
@@ -64,6 +84,42 @@ export class StudentsService {
return this.repo.find({ where, order: { createdAt: 'DESC' }, relations: ['organization'] });
}
async getFilterLookups(accessibleClassIds?: number[]) {
if (accessibleClassIds && accessibleClassIds.length === 0) {
return { classes: [], teachers: [] };
}
const classWhere = accessibleClassIds
? { id: In(accessibleClassIds), isArchived: false }
: { isArchived: false };
const classes = await this.classRepo.find({
select: ['id', 'name', 'code'],
where: classWhere,
order: { name: 'ASC' },
});
const teacherWhere = accessibleClassIds
? { classId: In(accessibleClassIds) }
: { classId: In(classes.map((item) => item.id)), userId: Not(IsNull()) };
const assignments = classes.length
? await this.classTeacherRepo.find({ where: teacherWhere, relations: ['user'] })
: [];
const teacherMap = new Map<number, { id: number; name: string; username: string }>();
for (const assignment of assignments) {
if (!assignment.user || !assignment.user.isActive || assignment.user.isArchived) continue;
teacherMap.set(assignment.userId, {
id: assignment.userId,
name: assignment.user.name || assignment.user.username,
username: assignment.user.username,
});
}
return {
classes: classes.map((item) => ({ id: item.id, name: item.name, code: item.code })),
teachers: [...teacherMap.values()].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN')),
};
}
async findOne(id: number) {
const student = await this.repo.findOne({
where: { id },

View File

@@ -13,8 +13,18 @@ export class WalletsController {
@Get()
@RequirePermission('wallet:view')
findAll(@Query('keyword') keyword?: string, @Query('debtOnly') debtOnly?: string) {
return this.service.findAll({ keyword, debtOnly: debtOnly === 'true' });
findAll(
@Query('keyword') keyword?: string,
@Query('debtOnly') debtOnly?: string,
@Query('roomType') roomType?: string,
) {
return this.service.findAll({ keyword, debtOnly: debtOnly === 'true', roomType });
}
@Get('room-types')
@RequirePermission('wallet:view')
findRoomTypes() {
return this.service.findRoomTypes();
}
@Get('transactions')

View File

@@ -4,12 +4,14 @@ import { Bill } from '../entities/bill.entity';
import { Student } from '../entities/student.entity';
import { StudentWallet } from '../entities/student-wallet.entity';
import { WalletTransaction } from '../entities/wallet-transaction.entity';
import { Room } from '../entities/room.entity';
import { Occupancy } from '../entities/occupancy.entity';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
import { WalletsController } from './wallets.controller';
import { WalletsService } from './wallets.service';
@Module({
imports: [TypeOrmModule.forFeature([StudentWallet, WalletTransaction, Student, Bill]), OperationLogsModule],
imports: [TypeOrmModule.forFeature([StudentWallet, WalletTransaction, Student, Bill, Room, Occupancy]), OperationLogsModule],
controllers: [WalletsController],
providers: [WalletsService],
exports: [WalletsService],

View File

@@ -8,6 +8,7 @@ import { WalletTransaction } from '../entities/wallet-transaction.entity';
import { In } from 'typeorm';
import { BatchChangeWalletBalanceDto, ChangeWalletBalanceDto } from './dto/wallet.dto';
import { FinancialOperationsService } from '../financial-operations/financial-operations.service';
import { Room } from '../entities/room.entity';
const money = (value: number | string | null | undefined) => Number(Number(value || 0).toFixed(2));
@@ -21,21 +22,41 @@ export class WalletsService {
private financialOperations?: FinancialOperationsService,
) {}
async findAll(query?: { keyword?: string; debtOnly?: boolean }) {
const students = await this.studentRepo
async findAll(query?: { keyword?: string; debtOnly?: boolean; roomType?: string }) {
const qb = this.studentRepo
.createQueryBuilder('student')
.where('student.status = :status', { status: 'active' })
.andWhere(
query?.keyword
? '(student.name LIKE :keyword OR student.studentNo LIKE :keyword)'
: '1 = 1',
query?.keyword ? { keyword: `%${query.keyword}%` } : {},
)
.orderBy('student.name', 'ASC')
.getMany();
if (!students.length) return [];
.leftJoin('student.occupancies', 'occupancy', 'occupancy.checkOutDate IS NULL')
.leftJoin('occupancy.room', 'room')
.where('student.status = :status', { status: 'active' });
const ids = students.map((student) => student.id);
if (query?.keyword) {
qb.andWhere('(student.name LIKE :keyword OR student.studentNo LIKE :keyword)', {
keyword: `%${query.keyword}%`,
});
}
if (query?.roomType) {
qb.andWhere('room.roomType = :roomType', { roomType: query.roomType });
}
const rows = await qb
.select([
'student.id AS studentId',
'student.name AS studentName',
'student.studentNo AS studentNo',
'room.roomType AS roomType',
'room.roomNumber AS roomNumber',
])
.orderBy('student.name', 'ASC')
.getRawMany<{
studentId: number;
studentName: string;
studentNo: string | null;
roomType: string | null;
roomNumber: string | null;
}>();
if (!rows.length) return [];
const ids = rows.map((row) => Number(row.studentId));
const wallets = await this.walletRepo.find({ where: { studentId: In(ids) } });
const bills = await this.dataSource.getRepository(Bill)
.createQueryBuilder('bill')
@@ -47,17 +68,34 @@ export class WalletsService {
.getRawMany<{ studentId: number; outstandingAmount: string }>();
const walletMap = new Map(wallets.map((wallet) => [wallet.studentId, wallet]));
const debtMap = new Map(bills.map((bill) => [Number(bill.studentId), money(bill.outstandingAmount)]));
return students
.map((student) => ({
studentId: student.id,
studentName: student.name,
studentNo: student.studentNo,
balance: money(walletMap.get(student.id)?.balance),
outstandingAmount: debtMap.get(student.id) || 0,
return rows
.map((row) => ({
studentId: Number(row.studentId),
studentName: row.studentName,
studentNo: row.studentNo || undefined,
roomType: row.roomType || undefined,
roomNumber: row.roomNumber || undefined,
balance: money(walletMap.get(Number(row.studentId))?.balance),
outstandingAmount: debtMap.get(Number(row.studentId)) || 0,
}))
.filter((row) => !query?.debtOnly || row.outstandingAmount > 0);
}
async findRoomTypes() {
const rows = await this.dataSource
.getRepository(Room)
.createQueryBuilder('room')
.innerJoin('room.occupancies', 'occupancy', 'occupancy.checkOutDate IS NULL')
.innerJoin('occupancy.student', 'student', 'student.status = :status', { status: 'active' })
.select('room.roomType', 'roomType')
.where('room.roomType IS NOT NULL')
.andWhere("room.roomType <> ''")
.distinct(true)
.orderBy('room.roomType', 'ASC')
.getRawMany<{ roomType: string }>();
return rows.map((row) => row.roomType);
}
async findTransactions(studentId: number) {
return this.transactionRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } });
}

View File

@@ -18,6 +18,7 @@ DROP TABLE IF EXISTS `student_enrollments`;
DROP TABLE IF EXISTS `student_profiles`;
DROP TABLE IF EXISTS `notifications`;
DROP TABLE IF EXISTS `ding_attendance_raw`;
DROP TABLE IF EXISTS `attendance_period_configs`;
DROP TABLE IF EXISTS `attendance_devices`;
DROP TABLE IF EXISTS `attendance_records`;
DROP TABLE IF EXISTS `attendance_sessions`;
@@ -29,6 +30,7 @@ DROP TABLE IF EXISTS `classroom_rentals`;
DROP TABLE IF EXISTS `classrooms`;
DROP TABLE IF EXISTS `deposit_installments`;
DROP TABLE IF EXISTS `deposits`;
DROP TABLE IF EXISTS `financial_operations`;
DROP TABLE IF EXISTS `operation_logs`;
DROP TABLE IF EXISTS `student_wallets`;
DROP TABLE IF EXISTS `wallet_transactions`;
@@ -69,10 +71,12 @@ CREATE TABLE IF NOT EXISTS `permissions` (`id` int NOT NULL AUTO_INCREMENT, `cod
CREATE TABLE IF NOT EXISTS `roles` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL, `code` varchar(30) NULL, `description` varchar(200) NULL, `is_system` tinyint NOT NULL DEFAULT 0, `status` tinyint NOT NULL DEFAULT 1, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), UNIQUE INDEX `IDX_648e3f5447f725579d7d4ffdfb` (`name`), UNIQUE INDEX `IDX_f6d54f95c31b73fb1bdd8e91d0` (`code`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `users` (`id` int NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password_hash` varchar(255) NOT NULL, `name` varchar(50) NULL, `is_active` tinyint NOT NULL DEFAULT 1, `last_login_at` datetime NULL, `is_archived` tinyint NOT NULL DEFAULT 0, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), `profile` text NULL, UNIQUE INDEX `IDX_fe0bb3f6520ee0469504521e71` (`username`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `students` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `student_no` varchar(30) NULL, `phone` varchar(20) NULL, `id_number` varchar(30) NULL, `gender` varchar(10) NULL, `ethnicity` varchar(20) NULL, `emergency_contact` varchar(50) NULL, `emergency_phone` varchar(20) NULL, `status` varchar(20) NOT NULL DEFAULT 'active', `supervisor` varchar(50) NULL, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), `user_id` int NULL, `organization_id` int NULL, UNIQUE INDEX `IDX_fb3eff90b11bddf7285f9b4e28` (`user_id`), UNIQUE INDEX `REL_fb3eff90b11bddf7285f9b4e28` (`user_id`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `financial_operations` (`id` int NOT NULL AUTO_INCREMENT, `operation_id` varchar(64) NOT NULL, `type` varchar(64) NOT NULL, `status` varchar(20) NOT NULL DEFAULT 'running', `result_json` text NULL, `error_message` varchar(500) NULL, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), UNIQUE INDEX `IDX_financial_operations_operation_id` (`operation_id`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `operation_logs` (`id` int NOT NULL AUTO_INCREMENT, `user_id` int NULL, `username` varchar(50) NULL, `module` varchar(50) NOT NULL, `action` varchar(50) NOT NULL, `target_id` int NULL, `target_type` varchar(50) NULL, `detail` text NULL, `ip_address` varchar(50) NULL, `user_agent` varchar(500) NULL, `status` varchar(20) NULL DEFAULT 'success', `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `deposit_installments` (`id` int NOT NULL AUTO_INCREMENT, `deposit_id` int NOT NULL, `amount` decimal(10,2) NOT NULL, `due_date` date NOT NULL, `paid_date` date NULL, `status` varchar(20) NOT NULL DEFAULT 'pending', `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `deposits` (`id` int NOT NULL AUTO_INCREMENT, `student_id` int NOT NULL, `amount` decimal(10,2) NOT NULL DEFAULT '500.00', `status` varchar(20) NOT NULL DEFAULT 'paid', `paid_date` date NOT NULL, `refund_date` date NULL, `refund_amount` decimal(10,2) NULL, `deduction_amount` decimal(10,2) NOT NULL DEFAULT 0.00, `deduction_reason` text NULL, `notes` text NULL, `recorded_by` int NULL, `refunded_by` int NULL, `refunded_at` datetime NULL, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `classrooms` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `building` varchar(50) NULL, `floor` int NULL, `capacity` int NOT NULL DEFAULT '30', `room_type` varchar(20) NOT NULL DEFAULT '', `status` varchar(20) NOT NULL DEFAULT 'available', `notes` text NULL, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `attendance_period_configs` (`id` int NOT NULL AUTO_INCREMENT, `period_key` varchar(40) NOT NULL, `label` varchar(40) NOT NULL, `start_time` varchar(5) NOT NULL, `end_time` varchar(5) NOT NULL, `sort_order` int NOT NULL DEFAULT 0, `enabled` tinyint NOT NULL DEFAULT 1, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), UNIQUE INDEX `IDX_attendance_period_configs_period_key` (`period_key`), INDEX `IDX_attendance_period_configs_sort_order` (`sort_order`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `attendance_devices` (`id` int NOT NULL AUTO_INCREMENT, `device_sn` varchar(100) NOT NULL, `device_name` varchar(100) NOT NULL, `classroom_id` int NOT NULL, `status` varchar(20) NOT NULL DEFAULT 'active', `location` varchar(200) NULL, `notes` text NULL, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), UNIQUE INDEX `IDX_attendance_devices_device_sn` (`device_sn`), INDEX `IDX_attendance_devices_classroom_id` (`classroom_id`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `classroom_rentals` (`id` int NOT NULL AUTO_INCREMENT, `classroom_id` int NOT NULL, `lessor_organization_id` int NULL, `lessee_organization_id` int NULL, `start_date` date NOT NULL, `end_date` date NOT NULL, `contract_path` varchar(255) NULL, `contract_original_name` varchar(255) NULL, `daily_rate` decimal(10,2) NULL, `total_amount` decimal(10,2) NULL, `status` varchar(20) NOT NULL DEFAULT 'active', `notes` text NULL, `created_by` int NULL, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), INDEX `IDX_b748a951d00b3f0c2090d10397` (`classroom_id`, `start_date`, `end_date`), PRIMARY KEY (`id`)) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `classes` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `code` varchar(50) NOT NULL, `class_type` varchar(20) NOT NULL, `start_date` date NULL, `end_date` date NULL, `status` varchar(20) NOT NULL DEFAULT 'enrolling', `head_teacher_id` int NULL, `life_teacher_id` int NULL, `academic_teacher_id` int NULL, `max_students` int NOT NULL DEFAULT 0, `notes` text NULL, `is_archived` tinyint NOT NULL DEFAULT 0, `created_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6), `updated_at` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), UNIQUE INDEX `IDX_cf7491878e0fca859943862998` (`code`), PRIMARY KEY (`id`)) ENGINE=InnoDB;