feat(admin): improve responsive management pages

This commit is contained in:
2026-07-18 16:35:15 +08:00
parent 7f66e9b894
commit f06b114a29
45 changed files with 3596 additions and 2038 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 {
@@ -376,11 +379,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 +677,6 @@
min-width: 54px;
}
.punch-device-cell {
display: flex;
flex-direction: column;
@@ -692,9 +709,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 +774,10 @@
.student-filter-panel {
display: grid;
grid-template-columns: minmax(260px, 1.4fr) repeat(4, minmax(150px, 1fr)) auto;
grid-template-columns: minmax(230px, 1.4fr) repeat(4, minmax(120px, 1fr)) auto;
gap: 12px;
align-items: end;
min-width: 0;
margin-bottom: 16px;
padding: 16px;
border: 1px solid var(--student-line);
@@ -783,13 +803,15 @@
.student-filter-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.student-class-overview {
display: grid;
grid-template-columns: minmax(320px, .9fr) minmax(0, 1.1fr);
grid-template-columns: minmax(280px, 0.9fr) minmax(0, 1.1fr);
gap: 16px;
min-width: 0;
margin-bottom: 16px;
}
@@ -802,6 +824,12 @@
background: var(--student-surface);
}
.student-class-overview > *,
.student-workspace,
.student-record-card {
min-width: 0;
}
.student-class-identity {
display: flex;
flex-direction: column;
@@ -854,7 +882,8 @@
.student-metric-strip {
display: grid;
grid-template-columns: repeat(6, minmax(82px, 1fr));
grid-template-columns: repeat(6, minmax(70px, 1fr));
min-width: 0;
overflow: hidden;
}
@@ -930,18 +959,20 @@
.student-workspace-tools {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
min-width: 0;
}
.student-workspace-tools .ant-input-search {
width: 240px;
width: min(240px, 100%);
}
.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 +991,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);
@@ -989,7 +1030,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,
@@ -1139,34 +1183,53 @@
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: span 2;
}
.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(6, minmax(0, 1fr));
}
}
@media (max-width: 760px) {
.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: stretch;
flex-direction: column;
}
.student-center-title {
align-items: flex-start;
flex-direction: column;
gap: 2px;
}
.student-filter-panel,
@@ -1174,8 +1237,48 @@
grid-template-columns: 1fr;
}
.student-filter-field--date {
grid-column: auto;
}
.student-filter-actions > *,
.student-center-actions .ant-btn,
.student-workspace-tools,
.student-workspace-tools .ant-input-search {
width: 100%;
}
.student-filter-actions > * {
flex: 1;
}
.student-metric-strip {
grid-template-columns: repeat(2, 1fr);
}
.student-metric-card {
min-height: 112px;
border-bottom: 1px solid var(--student-line);
}
.student-workspace {
padding-inline: 12px;
}
.student-card-grid {
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);
}
}

View File

@@ -7,6 +7,7 @@ import {
Col,
DatePicker,
Drawer,
Grid,
Empty,
Form,
Input,
@@ -192,15 +193,24 @@ function LessonCheckinSummaryStrip({ records }: { records: readonly AttendanceRe
<div className="attendance-summary-strip">
<div className="attendance-rate">
<Progress type="circle" percent={rate} size={64} strokeWidth={9} />
<div><span></span><strong>{summary.total} </strong></div>
<div>
<span></span>
<strong>{summary.total} </strong>
</div>
</div>
<div className="attendance-summary-cell">
<span className="attendance-summary-icon is-present"></span>
<div><strong>{summary.checkedIn}</strong><span></span></div>
<div>
<strong>{summary.checkedIn}</strong>
<span></span>
</div>
</div>
<div className="attendance-summary-cell">
<span className="attendance-summary-icon is-absent"></span>
<div><strong>{summary.notCheckedIn}</strong><span></span></div>
<div>
<strong>{summary.notCheckedIn}</strong>
<span></span>
</div>
</div>
</div>
);
@@ -262,7 +272,6 @@ const TeacherAttendanceWorkspace: React.FC = () => {
[workspace],
);
const openAttendance = useCallback(async (schedule: TodaySchedule) => {
setStudentKeyword('');
setCheckinFilter('all');
@@ -288,29 +297,25 @@ const TeacherAttendanceWorkspace: React.FC = () => {
}
}, []);
const updateLessonRecord = useCallback(
async (record: AttendanceRecordItem, status: string) => {
const previous = record.status;
const updateLessonRecord = useCallback(async (record: AttendanceRecordItem, status: string) => {
const previous = record.status;
setLessonRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status } : item)),
);
try {
await api.put(`/attendance-records/${record.id}`, { status });
} catch (error: unknown) {
setLessonRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status } : item)),
items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
);
try {
await api.put(`/attendance-records/${record.id}`, { status });
} catch (error: unknown) {
setLessonRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
);
message.error((error as { message?: string })?.message || '更新课堂考勤失败');
}
},
[],
);
message.error((error as { message?: string })?.message || '更新课堂考勤失败');
}
}, []);
const now = new Date();
const schedules = workspace?.todaySchedules ?? [];
const startedCount = schedules.filter(
(item) => canPullAttendance(getSchedulePhase(item.startTime, item.endTime, now)),
const startedCount = schedules.filter((item) =>
canPullAttendance(getSchedulePhase(item.startTime, item.endTime, now)),
).length;
const nextSchedule = schedules.find(
(item) => getSchedulePhase(item.startTime, item.endTime, now) !== 'ended',
@@ -354,41 +359,98 @@ const TeacherAttendanceWorkspace: React.FC = () => {
<section className="attendance-hero attendance-hero--teacher">
<div>
<span className="attendance-eyebrow">LESSON ATTENDANCE · {dayjs().format('MM月DD日 dddd')}</span>
<span className="attendance-eyebrow">
LESSON ATTENDANCE · {dayjs().format('MM月DD日 dddd')}
</span>
<h1></h1>
<p></p>
<p>
</p>
</div>
<Button type="primary" ghost icon={<FileSearchOutlined />} onClick={() => currentFocusSchedule && void openAttendance(currentFocusSchedule)} disabled={!currentFocusSchedule || getSchedulePhase(currentFocusSchedule.startTime, currentFocusSchedule.endTime, now) === 'upcoming'}>
<Button
type="primary"
ghost
icon={<FileSearchOutlined />}
onClick={() => currentFocusSchedule && void openAttendance(currentFocusSchedule)}
disabled={
!currentFocusSchedule ||
getSchedulePhase(currentFocusSchedule.startTime, currentFocusSchedule.endTime, now) ===
'upcoming'
}
>
</Button>
</section>
<Row gutter={[16, 16]} className="teacher-overview">
<Col xs={24} md={8}>
<div className="teacher-kpi"><span></span><strong>{schedules.length}</strong><small></small></div>
<div className="teacher-kpi">
<span></span>
<strong>{schedules.length}</strong>
<small></small>
</div>
</Col>
<Col xs={24} md={8}>
<div className="teacher-kpi"><span></span><strong>{startedCount}</strong><small></small></div>
<div className="teacher-kpi">
<span></span>
<strong>{startedCount}</strong>
<small></small>
</div>
</Col>
<Col xs={24} md={8}>
<div className="teacher-kpi teacher-kpi--next"><span>/</span><strong>{nextSchedule ? nextSchedule.startTime : '—'}</strong><small>{nextSchedule?.subject || '今天没有更多课程'}</small></div>
<div className="teacher-kpi teacher-kpi--next">
<span>/</span>
<strong>{nextSchedule ? nextSchedule.startTime : '—'}</strong>
<small>{nextSchedule?.subject || '今天没有更多课程'}</small>
</div>
</Col>
</Row>
<div className="teacher-workspace-layout">
<aside className="teacher-filter-rail">
<div className="teacher-filter-title"><FilterOutlined /> </div>
<Button block type={phaseFilter === 'all' && selectedClassId === 'all' ? 'primary' : 'default'} onClick={() => { setPhaseFilter('all'); setSelectedClassId('all'); }}></Button>
<Button block type={phaseFilter === 'ongoing' ? 'primary' : 'default'} onClick={() => setPhaseFilter('ongoing')}></Button>
<Button block type={phaseFilter === 'ended' ? 'primary' : 'default'} onClick={() => setPhaseFilter('ended')}></Button>
<Button block type={phaseFilter === 'upcoming' ? 'primary' : 'default'} onClick={() => setPhaseFilter('upcoming')}></Button>
<div className="teacher-filter-title">
<FilterOutlined />
</div>
<Button
block
type={phaseFilter === 'all' && selectedClassId === 'all' ? 'primary' : 'default'}
onClick={() => {
setPhaseFilter('all');
setSelectedClassId('all');
}}
>
</Button>
<Button
block
type={phaseFilter === 'ongoing' ? 'primary' : 'default'}
onClick={() => setPhaseFilter('ongoing')}
>
</Button>
<Button
block
type={phaseFilter === 'ended' ? 'primary' : 'default'}
onClick={() => setPhaseFilter('ended')}
>
</Button>
<Button
block
type={phaseFilter === 'upcoming' ? 'primary' : 'default'}
onClick={() => setPhaseFilter('upcoming')}
>
</Button>
<Select<number | 'all'>
value={selectedClassId}
onChange={setSelectedClassId}
options={classFilterOptions}
className="teacher-filter-select"
/>
<div className="teacher-filter-hint"></div>
<div className="teacher-filter-hint">
</div>
</aside>
<main className="teacher-main-panel">
@@ -403,15 +465,31 @@ const TeacherAttendanceWorkspace: React.FC = () => {
</p>
</div>
<div className="current-lesson-actions">
<Button type="primary" disabled={!currentFocusSchedule || getSchedulePhase(currentFocusSchedule.startTime, currentFocusSchedule.endTime, now) === 'upcoming'} onClick={() => currentFocusSchedule && void openAttendance(currentFocusSchedule)}>
<Button
type="primary"
disabled={
!currentFocusSchedule ||
getSchedulePhase(
currentFocusSchedule.startTime,
currentFocusSchedule.endTime,
now,
) === 'upcoming'
}
onClick={() => currentFocusSchedule && void openAttendance(currentFocusSchedule)}
>
/
</Button>
<Button icon={<ExportOutlined />} disabled></Button>
<Button icon={<ExportOutlined />} disabled>
</Button>
</div>
</Card>
<div className="attendance-section-heading">
<div><span></span><h2></h2></div>
<div>
<span></span>
<h2></h2>
</div>
<span className="attendance-section-note"></span>
</div>
@@ -420,14 +498,24 @@ const TeacherAttendanceWorkspace: React.FC = () => {
<Card className="attendance-empty-card">
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={<div><strong></strong><p></p></div>}
description={
<div>
<strong></strong>
<p></p>
</div>
}
/>
</Card>
) : filteredSchedules.length === 0 ? (
<Card className="attendance-empty-card">
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={<div><strong></strong><p></p></div>}
description={
<div>
<strong></strong>
<p></p>
</div>
}
/>
</Card>
) : (
@@ -451,17 +539,31 @@ const TeacherAttendanceWorkspace: React.FC = () => {
</main>
</div>
<Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} width={960} title={null} className="attendance-drawer">
<Drawer
open={drawerOpen}
onClose={() => setDrawerOpen(false)}
width={960}
title={null}
className="attendance-drawer"
>
<div className="lesson-record-header">
<span className="attendance-eyebrow">LESSON ATTENDANCE</span>
<h2>{selectedSchedule?.subject || '本节课考勤'}</h2>
<p>{selectedSchedule ? classNameById.get(selectedSchedule.classId) : ''} · {selectedSchedule?.startTime}{selectedSchedule?.endTime} · {dayjs().format('YYYY-MM-DD')}</p>
<p>
{selectedSchedule ? classNameById.get(selectedSchedule.classId) : ''} · {' '}
{selectedSchedule?.startTime}{selectedSchedule?.endTime} ·{' '}
{dayjs().format('YYYY-MM-DD')}
</p>
</div>
{lessonSession && (
<Alert
type={isAttendanceCompleted ? 'success' : 'info'}
showIcon
title={isAttendanceCompleted ? '本节课考勤已结算' : '当前为本节课实时签到结果;课程截止后将自动做最终结算'}
title={
isAttendanceCompleted
? '本节课考勤已结算'
: '当前为本节课实时签到结果;课程截止后将自动做最终结算'
}
style={{ marginBottom: 16 }}
/>
)}
@@ -494,18 +596,30 @@ const TeacherAttendanceWorkspace: React.FC = () => {
dataSource={filteredLessonRecords}
pagination={false}
locale={{
emptyText: <Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={lessonRecords.length === 0 ? '本节课尚未产生签到记录' : '没有符合条件的学生'}
/>,
emptyText: (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={
lessonRecords.length === 0 ? '本节课尚未产生签到记录' : '没有符合条件的学生'
}
/>
),
}}
columns={[
{
title: '学生', dataIndex: ['student', 'name'],
render: (name: string) => <div className="student-cell"><Avatar size={32}>{name?.slice(0, 1)}</Avatar><strong>{name || '-'}</strong></div>,
title: '学生',
dataIndex: ['student', 'name'],
render: (name: string) => (
<div className="student-cell">
<Avatar size={32}>{name?.slice(0, 1)}</Avatar>
<strong>{name || '-'}</strong>
</div>
),
},
{
title: '课堂考勤操作', dataIndex: 'status', width: 250,
title: '课堂考勤操作',
dataIndex: 'status',
width: 250,
render: (value: string, record: AttendanceRecordItem) => {
const checkedIn = value === 'present' || value === 'late';
return (
@@ -529,7 +643,16 @@ const TeacherAttendanceWorkspace: React.FC = () => {
);
},
},
{ title: '当前状态', dataIndex: 'status', width: 118, render: (value: string) => <AttendanceStatusTag status={value === 'present' || value === 'late' ? 'present' : 'absent'} /> },
{
title: '当前状态',
dataIndex: 'status',
width: 118,
render: (value: string) => (
<AttendanceStatusTag
status={value === 'present' || value === 'late' ? 'present' : 'absent'}
/>
),
},
{
title: '签到来源',
width: 220,
@@ -545,7 +668,12 @@ const TeacherAttendanceWorkspace: React.FC = () => {
);
},
},
{ title: '备注/异常处理', dataIndex: 'remark', render: (value: string | null) => value || <span className="muted-text"></span> },
{
title: '备注/异常处理',
dataIndex: 'remark',
render: (value: string | null) =>
value || <span className="muted-text"></span>,
},
]}
/>
</Drawer>
@@ -569,14 +697,26 @@ const LessonCard: React.FC<{
return (
<article className={`lesson-card lesson-card--${phaseMeta.tone}`}>
<div className="lesson-sequence">{String(index).padStart(2, '0')}</div>
<div className="lesson-time"><strong>{schedule.startTime}</strong><span /><strong>{schedule.endTime}</strong></div>
<div className="lesson-time">
<strong>{schedule.startTime}</strong>
<span />
<strong>{schedule.endTime}</strong>
</div>
<div className="lesson-main">
<div className="lesson-title-row"><h3>{schedule.subject}</h3><Tag icon={phaseMeta.icon}>{phaseMeta.label}</Tag></div>
<p><TeamOutlined /> {className}<span> {schedule.classroomId}</span></p>
<div className="lesson-title-row">
<h3>{schedule.subject}</h3>
<Tag icon={phaseMeta.icon}>{phaseMeta.label}</Tag>
</div>
<p>
<TeamOutlined /> {className}
<span> {schedule.classroomId}</span>
</p>
</div>
<div className="lesson-action">
{phase === 'upcoming' ? (
<Tooltip title="课程尚未开始"><Button disabled></Button></Tooltip>
<Tooltip title="课程尚未开始">
<Button disabled></Button>
</Tooltip>
) : (
<Button type="primary" onClick={onOpen}>
{phase === 'ongoing' ? '查看本节考勤' : '拉取 / 查看本节考勤'} <ArrowRightOutlined />
@@ -587,7 +727,6 @@ const LessonCard: React.FC<{
);
};
interface AdminStudentPanel {
key: string;
studentId: number;
@@ -644,7 +783,9 @@ function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminStudentP
}
return Array.from(map.values()).map((item) => {
const checked = item.records.filter((record) => record.status === 'present' || record.status === 'late').length;
const checked = item.records.filter(
(record) => record.status === 'present' || record.status === 'late',
).length;
return {
...item,
primaryStatus: pickPrimaryStatus(item.records),
@@ -654,6 +795,8 @@ function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminStudentP
}
const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) => {
const screens = Grid.useBreakpoint();
const isMobile = !screens.sm;
const [records, setRecords] = useState<AttendanceRecordItem[]>([]);
const [summary, setSummary] = useState<AttendanceSummary>(EMPTY_SUMMARY);
const [alerts, setAlerts] = useState<AlertItem[]>([]);
@@ -781,7 +924,8 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
const selectedClass = classId
? classOptions.find((item) => item.classId === classId)?.className || `班级 ${classId}`
: '全部班级';
const attendanceRate = summary.total > 0 ? Math.round((summary.present / summary.total) * 100) : 0;
const attendanceRate =
summary.total > 0 ? Math.round((summary.present / summary.total) * 100) : 0;
const dateLabel = dateRange?.[0]?.isSame(dateRange?.[1], 'day')
? dateRange?.[0]?.format('YYYY-MM-DD')
: `${dateRange?.[0]?.format('YYYY-MM-DD') || '开始日期'}${dateRange?.[1]?.format('YYYY-MM-DD') || '结束日期'}`;
@@ -790,7 +934,7 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
{
title: '学生',
dataIndex: ['student', 'name'],
fixed: 'left',
fixed: isMobile ? undefined : 'left',
width: 150,
render: (name: string, record) => (
<div className="student-cell">
@@ -841,7 +985,7 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
{
title: '操作',
key: 'action',
fixed: 'right' as const,
fixed: isMobile ? undefined : ('right' as const),
width: 80,
render: (_: unknown, record: AttendanceRecordItem) => (
<Button
@@ -868,9 +1012,18 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<span></span>
</div>
<div className="student-center-actions">
<span className="student-sync-status"><i /> {dayjs().format('HH:mm')}</span>
<Button icon={<ReloadOutlined />} onClick={() => void loadRecords()}></Button>
<PermissionButton permission="attendance:export" icon={<ExportOutlined />} onClick={handleExport}>
<span className="student-sync-status">
<i />
{dayjs().format('HH:mm')}
</span>
<Button icon={<ReloadOutlined />} onClick={() => void loadRecords()}>
</Button>
<PermissionButton
permission="attendance:export"
icon={<ExportOutlined />}
onClick={handleExport}
>
</PermissionButton>
</div>
@@ -935,19 +1088,40 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<div className="student-class-identity">
<div>
<h2>{selectedClass}</h2>
<span>{dateLabel} · {visibleStudents.length} / {total} </span>
<span>
{dateLabel} · {visibleStudents.length} / {total}
</span>
</div>
<div className="student-teacher-list">
<div className="student-teacher-item"><Avatar></Avatar><div><span></span><strong></strong></div></div>
<div className="student-teacher-item"><Avatar></Avatar><div><span></span><strong></strong></div></div>
<div className="student-teacher-item"><Avatar></Avatar><div><span></span><strong>{session ? SESSION_MAP[session] : '全部时段'}</strong></div></div>
<div className="student-teacher-item">
<Avatar></Avatar>
<div>
<span></span>
<strong></strong>
</div>
</div>
<div className="student-teacher-item">
<Avatar></Avatar>
<div>
<span></span>
<strong></strong>
</div>
</div>
<div className="student-teacher-item">
<Avatar></Avatar>
<div>
<span></span>
<strong>{session ? SESSION_MAP[session] : '全部时段'}</strong>
</div>
</div>
</div>
</div>
<div className="student-metric-strip">
{ADMIN_METRIC_META.map((metric) => {
const value = metric.key === 'all'
? `${attendanceRate}%`
: summary[metric.key as keyof AttendanceSummary] ?? 0;
const value =
metric.key === 'all'
? `${attendanceRate}%`
: (summary[metric.key as keyof AttendanceSummary] ?? 0);
const meta = STATUS_META[metric.key] ?? { className: 'is-present' };
return (
<button
@@ -972,7 +1146,12 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<strong>{alerts.length} </strong>
<span> 14 </span>
</div>
<Tooltip title={alerts.slice(0, 5).map((item) => `${item.studentName}${item.type}${item.count}`).join('')}>
<Tooltip
title={alerts
.slice(0, 5)
.map((item) => `${item.studentName}${item.type}${item.count}`)
.join('')}
>
<Button type="link"></Button>
</Tooltip>
</div>
@@ -982,7 +1161,11 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<header className="student-workspace-header">
<div>
<h3></h3>
<span>{metricFilter === 'all' ? `显示全部 ${visibleStudents.length} 名学生` : `筛出 ${ADMIN_METRIC_META.find((item) => item.key === metricFilter)?.label || ''}相关 ${visibleStudents.length} 名学生`}</span>
<span>
{metricFilter === 'all'
? `显示全部 ${visibleStudents.length} 名学生`
: `筛出 ${ADMIN_METRIC_META.find((item) => item.key === metricFilter)?.label || ''}相关 ${visibleStudents.length} 名学生`}
</span>
</div>
<div className="student-workspace-tools">
<Input.Search
@@ -991,20 +1174,40 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
value={studentSearch}
onChange={(event) => setStudentSearch(event.target.value)}
/>
<Button icon={<ExportOutlined />} onClick={handleExport}></Button>
<Button icon={<ExportOutlined />} onClick={handleExport}>
</Button>
</div>
</header>
<div className="student-legend">
<span><i className="is-present" /></span>
<span><i className="is-late" /></span>
<span><i className="is-leave" /></span>
<span><i className="is-absent" /></span>
<span><i className="is-pending" /></span>
<span>
<i className="is-present" />
</span>
<span>
<i className="is-late" />
</span>
<span>
<i className="is-leave" />
</span>
<span>
<i className="is-absent" />
</span>
<span>
<i className="is-pending" />
</span>
<em> / / / </em>
</div>
<Spin spinning={loading}>
{visibleStudents.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="未找到匹配学生,请调整筛选条件或搜索关键词" />
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="未找到匹配学生,请调整筛选条件或搜索关键词"
/>
) : (
<div className="student-card-grid">
{visibleStudents.map((student) => (
@@ -1047,7 +1250,7 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
columns={columns}
dataSource={records}
loading={loading}
scroll={{ x: 950 }}
scroll={{ x: 'max-content' }}
pagination={{
current: page,
pageSize,
@@ -1061,7 +1264,10 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
}}
locale={{
emptyText: (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件下没有历史考勤记录" />
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="当前条件下没有历史考勤记录"
/>
),
}}
/>
@@ -1070,7 +1276,7 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<Drawer
open={Boolean(selectedStudent)}
onClose={() => setSelectedStudent(null)}
width={520}
width={isMobile ? '100%' : 520}
title="学生考勤明细"
className="student-detail-drawer"
>
@@ -1080,15 +1286,25 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<Avatar size={54}>{selectedStudent.studentName.slice(0, 1)}</Avatar>
<div>
<h4>{selectedStudent.studentName}</h4>
<p>{selectedStudent.className} · {selectedStudent.studentId}</p>
<p>
{selectedStudent.className} · {selectedStudent.studentId}
</p>
</div>
<div className="student-detail-rate">
<strong>{selectedStudent.rate}%</strong>
<span></span>
</div>
<div className="student-detail-rate"><strong>{selectedStudent.rate}%</strong><span></span></div>
</section>
<section className="student-detail-rates">
{ADMIN_PERIODS.map((period) => {
const record = selectedStudent.statusBySession[period.key];
const normal = record?.status === 'present' || record?.status === 'late';
return <div key={period.key}><strong>{record ? (normal ? '100%' : '0%') : '—'}</strong><span>{period.label}</span></div>;
return (
<div key={period.key}>
<strong>{record ? (normal ? '100%' : '0%') : '—'}</strong>
<span>{period.label}</span>
</div>
);
})}
</section>
<section className="student-detail-section">
@@ -1096,18 +1312,23 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<div className="student-detail-timeline">
{ADMIN_PERIODS.map((period) => {
const record = selectedStudent.statusBySession[period.key];
return (
return (
<div key={period.key}>
<span>{period.label}</span>
<AttendanceStatusTag status={record?.status || 'pending'} />
<strong>{record?.punchTime ? dayjs(record.punchTime).format('HH:mm:ss') : '未记录'}</strong>
<strong>
{record?.punchTime ? dayjs(record.punchTime).format('HH:mm:ss') : '未记录'}
</strong>
{canEdit && record && (
<Button
size="small"
type="link"
onClick={() => {
setEditRecord(record);
editForm.setFieldsValue({ status: record.status, remark: record.remark });
editForm.setFieldsValue({
status: record.status,
remark: record.remark,
});
}}
>
@@ -1138,12 +1359,7 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
onOk={submitEdit}
onCancel={() => setEditRecord(null)}
>
<Alert
type="info"
showIcon
title="管理员修正会保留操作日志"
style={{ marginBottom: 20 }}
/>
<Alert type="info" showIcon title="管理员修正会保留操作日志" style={{ marginBottom: 20 }} />
<Form form={editForm} layout="vertical">
<Form.Item name="status" label="考勤结果" rules={[{ required: true }]}>
<Select options={STATUS_OPTIONS} />

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="默认由本机构出租">

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 }]}>
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} 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 }]}>
<Form.Item name="amount" label="分期金额(元)" rules={[{ required: true }]}>
<InputNumber min={0} 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>
@@ -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>

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

@@ -66,7 +66,13 @@ const OccupanciesPage: React.FC = () => {
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>[];
@@ -107,7 +113,9 @@ const OccupanciesPage: React.FC = () => {
setAvailableBeds(beds);
setAvailableLockers(lockers);
if (beds.length === 1) checkInForm.setFieldValue('bedId', beds[0].id);
} catch (e) { console.error(e); }
} catch (e) {
console.error(e);
}
};
const handleTransferRoomChange = async (roomId: number) => {
@@ -195,10 +203,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 +251,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 +374,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 +390,11 @@ const OccupanciesPage: React.FC = () => {
icon={<PlusOutlined />}
onClick={() => {
checkInForm.resetFields();
checkInForm.setFieldsValue({ checkInDate: dayjs(), collectDeposit: true, depositAmount: 500 });
checkInForm.setFieldsValue({
checkInDate: dayjs(),
collectDeposit: true,
depositAmount: 500,
});
setCheckInModal(true);
}}
>
@@ -432,26 +469,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>
@@ -543,7 +580,7 @@ const OccupanciesPage: React.FC = () => {
.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) : '')})`,
label: `${s.name} (${s.idNumber ? maskIdNumber(s.idNumber) : s.phone ? maskPhone(s.phone) : ''})`,
}))}
/>
</Form.Item>
@@ -588,11 +625,7 @@ const OccupanciesPage: React.FC = () => {
placeholder="默认为短租"
/>
</Form.Item>
<Form.Item
name="bedId"
label="床位"
rules={[{ required: true, message: '请选择床位' }]}
>
<Form.Item name="bedId" label="床位" rules={[{ required: true, message: '请选择床位' }]}>
<Select
placeholder="请先选择房间"
disabled={availableBeds.length === 0}
@@ -608,10 +641,7 @@ const OccupanciesPage: React.FC = () => {
{availableBeds.length}
</div>
)}
<Form.Item
name="lockerId"
label="柜子(可选)"
>
<Form.Item name="lockerId" label="柜子(可选)">
<Select
allowClear
placeholder="可选分配柜子"
@@ -630,7 +660,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 +671,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
}

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;
@@ -609,7 +608,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 +682,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,17 @@
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,
Space,
Switch,
Table,
Tag,
} from 'antd';
import { HistoryOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import api from '../../api';
@@ -16,7 +28,10 @@ interface WalletRow {
}
const transactionNames: Record<string, string> = {
recharge: '充值', adjustment: '调账', bill_payment: '账单扣款', bill_refund: '账单冲正',
recharge: '充值',
adjustment: '调账',
bill_payment: '账单扣款',
bill_refund: '账单冲正',
};
const WalletsPage: React.FC = () => {
@@ -36,14 +51,20 @@ 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 },
});
setRows(data as WalletRow[]);
} catch (error: any) {
message.error(error?.message || '加载学生余额失败');
} finally { setLoading(false); }
} finally {
setLoading(false);
}
}, [keyword, debtOnly]);
useEffect(() => { void fetchRows(); }, [fetchRows]);
useEffect(() => {
void fetchRows();
}, [fetchRows]);
const openChange = (row: WalletRow) => {
setSelected(row);
@@ -60,13 +81,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 +110,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 +127,236 @@ 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>
</>
),
},
{
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('')}
/>
<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',