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

View File

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

View File

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

View File

@@ -43,7 +43,12 @@ const SECTIONS: MenuSection[] = [
icon: 'calendar', icon: 'calendar',
roles: ['teacher'], roles: ['teacher'],
children: [ 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: '/schedules', label: '我的排课', icon: 'calendar', permission: 'schedule:view' },
{ key: '/attendance', label: '课程考勤', icon: 'attendance', permission: 'attendance:view' }, { key: '/attendance', label: '课程考勤', icon: 'attendance', permission: 'attendance:view' },
], ],
@@ -83,11 +88,26 @@ const SECTIONS: MenuSection[] = [
icon: 'classroom', icon: 'classroom',
roles: ['classroom', 'super'], roles: ['classroom', 'super'],
children: [ 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: '/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: '/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: '/roles', label: '角色管理', icon: 'role', permission: 'role:view' },
{ key: '/permissions', label: '权限一览', icon: 'permission', permission: 'role:view' }, { key: '/permissions', label: '权限一览', icon: 'permission', permission: 'role:view' },
{ key: '/operation-logs', label: '操作日志', icon: 'log', permission: 'log: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' }, { 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)); const normalized = new Set(roles.map((role) => ROLE_ALIASES[role]).filter(Boolean));
// 权限可以来自多个叠加角色,因此业务域按能力累加,而不是只选择一个。 // 权限可以来自多个叠加角色,因此业务域按能力累加,而不是只选择一个。
if (permissions.includes('student:view') || permissions.includes('class:view')) { 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 const children = section.children
.filter((child) => permissionSet.has(child.permission)) .filter((child) => permissionSet.has(child.permission))
.map(({ permission: _, ...child }) => child); .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')) { 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', () => { it('lands teachers on the teacher workspace without global student or class access', () => {
expect( expect(
findFirstAccessiblePath([ findFirstAccessiblePath(['teacher-workspace:view', 'schedule:view', 'attendance:view']),
'teacher-workspace:view',
'schedule:view',
'attendance:view',
]),
).toBe('/teacher-workspace'); ).toBe('/teacher-workspace');
expect(canAccessPath('/students', ['teacher-workspace:view'])).toBe(false); expect(canAccessPath('/students', ['teacher-workspace:view'])).toBe(false);
expect(canAccessPath('/classes', ['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: '/rooms', permission: 'room:view' },
{ path: '/occupancies', permission: 'occupancy:view' }, { path: '/occupancies', permission: 'occupancy:view' },
{ path: '/teacher-workspace', permission: 'teacher-workspace: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: '/attendance', permission: 'attendance:view' },
{ path: '/schedules', permission: 'schedule:view' }, { path: '/schedules', permission: 'schedule:view' },
{ path: '/classroom-schedule', permission: 'rental:view' }, { path: '/classroom-schedule', permission: 'rental:view' },

View File

@@ -3,7 +3,9 @@ export const PERMISSIONS_UPDATED_EVENT = 'permissions-updated';
export function readPermissions(): string[] { export function readPermissions(): string[] {
try { try {
const value = JSON.parse(localStorage.getItem('permissions') || '[]'); 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 { } catch {
return []; return [];
} }

View File

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

View File

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

View File

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

View File

@@ -35,6 +35,24 @@ canvas {
min-width: 0; 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 { .app-header {
position: sticky; position: sticky;
top: 0; top: 0;
@@ -65,11 +83,15 @@ canvas {
row-gap: 8px; row-gap: 8px;
} }
/* === 通用:表格容器横向滚动(防双重滚动条) === */ /* Data tables own their horizontal scroll instead of widening the page. */
.ant-table-wrapper { .ant-table-wrapper {
width: 100%;
min-width: 0;
max-width: 100%; max-width: 100%;
}
.ant-table-wrapper .ant-table-container {
overflow-x: auto; overflow-x: auto;
overflow-y: hidden;
overscroll-behavior-inline: contain; overscroll-behavior-inline: contain;
-webkit-overflow-scrolling: touch; -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) === */ /* === 平板 (576-991px) === */
@media (min-width: 576px) and (max-width: 991px) { @media (min-width: 576px) and (max-width: 991px) {
.ant-modal { .ant-modal {

View File

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

View File

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

View File

@@ -68,7 +68,6 @@ describe('lesson check-in summary', () => {
}); });
}); });
describe('lesson attendance filters', () => { describe('lesson attendance filters', () => {
const records = [ const records = [
{ id: 1, student: { name: '张三' }, status: 'present' }, { id: 1, student: { name: '张三' }, status: 'present' },
@@ -78,15 +77,21 @@ describe('lesson attendance filters', () => {
]; ];
it('searches students by name and ignores surrounding whitespace', () => { 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', () => { 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', () => { 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[], roles: readonly string[],
): AttendanceExperience { ): AttendanceExperience {
const domains = getRoleDomains(roles, permissions); const domains = getRoleDomains(roles, permissions);
if ( if (permissions.includes('attendance:edit') || domains.has('academic') || domains.has('super')) {
permissions.includes('attendance:edit') ||
domains.has('academic') ||
domains.has('super')
) {
return 'admin'; return 'admin';
} }
return 'teacher'; return 'teacher';
@@ -83,7 +79,6 @@ export function summarizeLessonCheckins(
}; };
} }
export type LessonAttendanceFilter = 'all' | 'checked_in' | 'not_checked_in'; export type LessonAttendanceFilter = 'all' | 'checked_in' | 'not_checked_in';
export interface LessonAttendanceFilterRecord { export interface LessonAttendanceFilterRecord {

View File

@@ -225,7 +225,10 @@
border-left: 4px solid #c9d2df; border-left: 4px solid #c9d2df;
border-radius: 14px; border-radius: 14px;
background: white; 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 { .lesson-card:hover {
@@ -376,11 +379,26 @@
font-weight: 700; font-weight: 700;
} }
.is-present { color: #198754 !important; background: #eaf8f1; } .is-present {
.is-late { color: #b56b00 !important; background: #fff4db; } color: #198754 !important;
.is-absent { color: #cf3030 !important; background: #fff0f0; } background: #eaf8f1;
.is-leave { color: #2874c6 !important; background: #edf5ff; } }
.is-pending { color: #667085 !important; background: #f1f3f6; } .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 { .lesson-record-filters {
display: flex; display: flex;
@@ -659,7 +677,6 @@
min-width: 54px; min-width: 54px;
} }
.punch-device-cell { .punch-device-cell {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -692,9 +709,11 @@
--student-line: #e1e8e5; --student-line: #e1e8e5;
--student-primary: #157a65; --student-primary: #157a65;
--student-primary-soft: #e8f4f0; --student-primary-soft: #e8f4f0;
min-width: 0;
min-height: calc(100vh - 64px); min-height: calc(100vh - 64px);
margin: -24px; margin: -24px;
padding: 0 24px 28px; padding: 0 24px 28px;
overflow: hidden;
background: var(--student-bg); background: var(--student-bg);
color: var(--student-ink); color: var(--student-ink);
} }
@@ -755,9 +774,10 @@
.student-filter-panel { .student-filter-panel {
display: grid; 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; gap: 12px;
align-items: end; align-items: end;
min-width: 0;
margin-bottom: 16px; margin-bottom: 16px;
padding: 16px; padding: 16px;
border: 1px solid var(--student-line); border: 1px solid var(--student-line);
@@ -783,13 +803,15 @@
.student-filter-actions { .student-filter-actions {
display: flex; display: flex;
flex-wrap: wrap;
gap: 8px; gap: 8px;
} }
.student-class-overview { .student-class-overview {
display: grid; 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; gap: 16px;
min-width: 0;
margin-bottom: 16px; margin-bottom: 16px;
} }
@@ -802,6 +824,12 @@
background: var(--student-surface); background: var(--student-surface);
} }
.student-class-overview > *,
.student-workspace,
.student-record-card {
min-width: 0;
}
.student-class-identity { .student-class-identity {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -854,7 +882,8 @@
.student-metric-strip { .student-metric-strip {
display: grid; display: grid;
grid-template-columns: repeat(6, minmax(82px, 1fr)); grid-template-columns: repeat(6, minmax(70px, 1fr));
min-width: 0;
overflow: hidden; overflow: hidden;
} }
@@ -930,18 +959,20 @@
.student-workspace-tools { .student-workspace-tools {
display: flex; display: flex;
align-items: center; align-items: center;
flex-wrap: wrap;
gap: 8px; gap: 8px;
min-width: 0;
} }
.student-workspace-tools .ant-input-search { .student-workspace-tools .ant-input-search {
width: 240px; width: min(240px, 100%);
} }
.student-legend { .student-legend {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; flex-wrap: wrap;
gap: 12px; gap: 8px 12px;
padding: 12px 0; padding: 12px 0;
color: var(--student-muted); color: var(--student-muted);
font-size: 12px; font-size: 12px;
@@ -960,11 +991,21 @@
border-radius: 2px; border-radius: 2px;
} }
.student-legend i.is-present { background: #2f9c78; } .student-legend i.is-present {
.student-legend i.is-late { background: #d78a18; } background: #2f9c78;
.student-legend i.is-leave { background: #397bbf; } }
.student-legend i.is-absent { background: #d44d4d; } .student-legend i.is-late {
.student-legend i.is-pending { background: #8a9692; } 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 { .student-legend em {
color: var(--student-quiet); color: var(--student-quiet);
@@ -989,7 +1030,10 @@
color: inherit; color: inherit;
text-align: left; text-align: left;
cursor: pointer; 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, .student-attendance-card:hover,
@@ -1139,34 +1183,53 @@
background: linear-gradient(180deg, #56bea3, #157a65); background: linear-gradient(180deg, #56bea3, #157a65);
} }
@media (max-width: 1180px) { @media (max-width: 1280px) {
.student-filter-panel, .student-filter-panel {
.student-class-overview { grid-template-columns: repeat(3, minmax(0, 1fr));
grid-template-columns: 1fr 1fr; }
.student-filter-field--date {
grid-column: span 2;
} }
.student-filter-actions { .student-filter-actions {
grid-column: 1 / -1;
justify-content: flex-end; justify-content: flex-end;
} }
}
@media (max-width: 1180px) {
.student-class-overview {
grid-template-columns: 1fr;
}
.student-metric-strip { .student-metric-strip {
grid-template-columns: repeat(3, 1fr); grid-template-columns: repeat(6, minmax(0, 1fr));
} }
} }
@media (max-width: 760px) { @media (max-width: 760px) {
.student-attendance-center { .student-attendance-center {
margin: -16px; margin: -12px;
padding: 0 16px 22px; padding: 0 12px 20px;
}
.student-center-topbar {
margin-inline: -12px;
padding: 12px;
} }
.student-center-topbar, .student-center-topbar,
.student-workspace-header, .student-workspace-header,
.student-center-actions, .student-center-actions,
.student-legend { .student-legend {
align-items: stretch;
flex-direction: column;
}
.student-center-title {
align-items: flex-start; align-items: flex-start;
flex-direction: column; flex-direction: column;
gap: 2px;
} }
.student-filter-panel, .student-filter-panel,
@@ -1174,8 +1237,48 @@
grid-template-columns: 1fr; 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,
.student-workspace-tools .ant-input-search { .student-workspace-tools .ant-input-search {
width: 100%; 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, Col,
DatePicker, DatePicker,
Drawer, Drawer,
Grid,
Empty, Empty,
Form, Form,
Input, Input,
@@ -192,15 +193,24 @@ function LessonCheckinSummaryStrip({ records }: { records: readonly AttendanceRe
<div className="attendance-summary-strip"> <div className="attendance-summary-strip">
<div className="attendance-rate"> <div className="attendance-rate">
<Progress type="circle" percent={rate} size={64} strokeWidth={9} /> <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>
<div className="attendance-summary-cell"> <div className="attendance-summary-cell">
<span className="attendance-summary-icon is-present"></span> <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>
<div className="attendance-summary-cell"> <div className="attendance-summary-cell">
<span className="attendance-summary-icon is-absent"></span> <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>
</div> </div>
); );
@@ -262,7 +272,6 @@ const TeacherAttendanceWorkspace: React.FC = () => {
[workspace], [workspace],
); );
const openAttendance = useCallback(async (schedule: TodaySchedule) => { const openAttendance = useCallback(async (schedule: TodaySchedule) => {
setStudentKeyword(''); setStudentKeyword('');
setCheckinFilter('all'); setCheckinFilter('all');
@@ -288,29 +297,25 @@ const TeacherAttendanceWorkspace: React.FC = () => {
} }
}, []); }, []);
const updateLessonRecord = useCallback( const updateLessonRecord = useCallback(async (record: AttendanceRecordItem, status: string) => {
async (record: AttendanceRecordItem, status: string) => { const previous = record.status;
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) => setLessonRecords((items) =>
items.map((item) => (item.id === record.id ? { ...item, status } : item)), items.map((item) => (item.id === record.id ? { ...item, status: previous } : item)),
); );
try { message.error((error as { message?: string })?.message || '更新课堂考勤失败');
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 || '更新课堂考勤失败');
}
},
[],
);
const now = new Date(); const now = new Date();
const schedules = workspace?.todaySchedules ?? []; const schedules = workspace?.todaySchedules ?? [];
const startedCount = schedules.filter( const startedCount = schedules.filter((item) =>
(item) => canPullAttendance(getSchedulePhase(item.startTime, item.endTime, now)), canPullAttendance(getSchedulePhase(item.startTime, item.endTime, now)),
).length; ).length;
const nextSchedule = schedules.find( const nextSchedule = schedules.find(
(item) => getSchedulePhase(item.startTime, item.endTime, now) !== 'ended', (item) => getSchedulePhase(item.startTime, item.endTime, now) !== 'ended',
@@ -354,41 +359,98 @@ const TeacherAttendanceWorkspace: React.FC = () => {
<section className="attendance-hero attendance-hero--teacher"> <section className="attendance-hero attendance-hero--teacher">
<div> <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> <h1></h1>
<p></p> <p>
</p>
</div> </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> </Button>
</section> </section>
<Row gutter={[16, 16]} className="teacher-overview"> <Row gutter={[16, 16]} className="teacher-overview">
<Col xs={24} md={8}> <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>
<Col xs={24} md={8}> <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>
<Col xs={24} md={8}> <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> </Col>
</Row> </Row>
<div className="teacher-workspace-layout"> <div className="teacher-workspace-layout">
<aside className="teacher-filter-rail"> <aside className="teacher-filter-rail">
<div className="teacher-filter-title"><FilterOutlined /> </div> <div className="teacher-filter-title">
<Button block type={phaseFilter === 'all' && selectedClassId === 'all' ? 'primary' : 'default'} onClick={() => { setPhaseFilter('all'); setSelectedClassId('all'); }}></Button> <FilterOutlined />
<Button block type={phaseFilter === 'ongoing' ? 'primary' : 'default'} onClick={() => setPhaseFilter('ongoing')}></Button> </div>
<Button block type={phaseFilter === 'ended' ? 'primary' : 'default'} onClick={() => setPhaseFilter('ended')}></Button> <Button
<Button block type={phaseFilter === 'upcoming' ? 'primary' : 'default'} onClick={() => setPhaseFilter('upcoming')}></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'> <Select<number | 'all'>
value={selectedClassId} value={selectedClassId}
onChange={setSelectedClassId} onChange={setSelectedClassId}
options={classFilterOptions} options={classFilterOptions}
className="teacher-filter-select" className="teacher-filter-select"
/> />
<div className="teacher-filter-hint"></div> <div className="teacher-filter-hint">
</div>
</aside> </aside>
<main className="teacher-main-panel"> <main className="teacher-main-panel">
@@ -403,15 +465,31 @@ const TeacherAttendanceWorkspace: React.FC = () => {
</p> </p>
</div> </div>
<div className="current-lesson-actions"> <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>
<Button icon={<ExportOutlined />} disabled></Button> <Button icon={<ExportOutlined />} disabled>
</Button>
</div> </div>
</Card> </Card>
<div className="attendance-section-heading"> <div className="attendance-section-heading">
<div><span></span><h2></h2></div> <div>
<span></span>
<h2></h2>
</div>
<span className="attendance-section-note"></span> <span className="attendance-section-note"></span>
</div> </div>
@@ -420,14 +498,24 @@ const TeacherAttendanceWorkspace: React.FC = () => {
<Card className="attendance-empty-card"> <Card className="attendance-empty-card">
<Empty <Empty
image={Empty.PRESENTED_IMAGE_SIMPLE} image={Empty.PRESENTED_IMAGE_SIMPLE}
description={<div><strong></strong><p></p></div>} description={
<div>
<strong></strong>
<p></p>
</div>
}
/> />
</Card> </Card>
) : filteredSchedules.length === 0 ? ( ) : filteredSchedules.length === 0 ? (
<Card className="attendance-empty-card"> <Card className="attendance-empty-card">
<Empty <Empty
image={Empty.PRESENTED_IMAGE_SIMPLE} image={Empty.PRESENTED_IMAGE_SIMPLE}
description={<div><strong></strong><p></p></div>} description={
<div>
<strong></strong>
<p></p>
</div>
}
/> />
</Card> </Card>
) : ( ) : (
@@ -451,17 +539,31 @@ const TeacherAttendanceWorkspace: React.FC = () => {
</main> </main>
</div> </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"> <div className="lesson-record-header">
<span className="attendance-eyebrow">LESSON ATTENDANCE</span> <span className="attendance-eyebrow">LESSON ATTENDANCE</span>
<h2>{selectedSchedule?.subject || '本节课考勤'}</h2> <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> </div>
{lessonSession && ( {lessonSession && (
<Alert <Alert
type={isAttendanceCompleted ? 'success' : 'info'} type={isAttendanceCompleted ? 'success' : 'info'}
showIcon showIcon
title={isAttendanceCompleted ? '本节课考勤已结算' : '当前为本节课实时签到结果;课程截止后将自动做最终结算'} title={
isAttendanceCompleted
? '本节课考勤已结算'
: '当前为本节课实时签到结果;课程截止后将自动做最终结算'
}
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
/> />
)} )}
@@ -494,18 +596,30 @@ const TeacherAttendanceWorkspace: React.FC = () => {
dataSource={filteredLessonRecords} dataSource={filteredLessonRecords}
pagination={false} pagination={false}
locale={{ locale={{
emptyText: <Empty emptyText: (
image={Empty.PRESENTED_IMAGE_SIMPLE} <Empty
description={lessonRecords.length === 0 ? '本节课尚未产生签到记录' : '没有符合条件的学生'} image={Empty.PRESENTED_IMAGE_SIMPLE}
/>, description={
lessonRecords.length === 0 ? '本节课尚未产生签到记录' : '没有符合条件的学生'
}
/>
),
}} }}
columns={[ columns={[
{ {
title: '学生', dataIndex: ['student', 'name'], title: '学生',
render: (name: string) => <div className="student-cell"><Avatar size={32}>{name?.slice(0, 1)}</Avatar><strong>{name || '-'}</strong></div>, 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) => { render: (value: string, record: AttendanceRecordItem) => {
const checkedIn = value === 'present' || value === 'late'; const checkedIn = value === 'present' || value === 'late';
return ( 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: '签到来源', title: '签到来源',
width: 220, 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> </Drawer>
@@ -569,14 +697,26 @@ const LessonCard: React.FC<{
return ( return (
<article className={`lesson-card lesson-card--${phaseMeta.tone}`}> <article className={`lesson-card lesson-card--${phaseMeta.tone}`}>
<div className="lesson-sequence">{String(index).padStart(2, '0')}</div> <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-main">
<div className="lesson-title-row"><h3>{schedule.subject}</h3><Tag icon={phaseMeta.icon}>{phaseMeta.label}</Tag></div> <div className="lesson-title-row">
<p><TeamOutlined /> {className}<span> {schedule.classroomId}</span></p> <h3>{schedule.subject}</h3>
<Tag icon={phaseMeta.icon}>{phaseMeta.label}</Tag>
</div>
<p>
<TeamOutlined /> {className}
<span> {schedule.classroomId}</span>
</p>
</div> </div>
<div className="lesson-action"> <div className="lesson-action">
{phase === 'upcoming' ? ( {phase === 'upcoming' ? (
<Tooltip title="课程尚未开始"><Button disabled></Button></Tooltip> <Tooltip title="课程尚未开始">
<Button disabled></Button>
</Tooltip>
) : ( ) : (
<Button type="primary" onClick={onOpen}> <Button type="primary" onClick={onOpen}>
{phase === 'ongoing' ? '查看本节考勤' : '拉取 / 查看本节考勤'} <ArrowRightOutlined /> {phase === 'ongoing' ? '查看本节考勤' : '拉取 / 查看本节考勤'} <ArrowRightOutlined />
@@ -587,7 +727,6 @@ const LessonCard: React.FC<{
); );
}; };
interface AdminStudentPanel { interface AdminStudentPanel {
key: string; key: string;
studentId: number; studentId: number;
@@ -644,7 +783,9 @@ function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminStudentP
} }
return Array.from(map.values()).map((item) => { 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 { return {
...item, ...item,
primaryStatus: pickPrimaryStatus(item.records), primaryStatus: pickPrimaryStatus(item.records),
@@ -654,6 +795,8 @@ function buildAdminStudentPanels(records: AttendanceRecordItem[]): AdminStudentP
} }
const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) => { const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) => {
const screens = Grid.useBreakpoint();
const isMobile = !screens.sm;
const [records, setRecords] = useState<AttendanceRecordItem[]>([]); const [records, setRecords] = useState<AttendanceRecordItem[]>([]);
const [summary, setSummary] = useState<AttendanceSummary>(EMPTY_SUMMARY); const [summary, setSummary] = useState<AttendanceSummary>(EMPTY_SUMMARY);
const [alerts, setAlerts] = useState<AlertItem[]>([]); const [alerts, setAlerts] = useState<AlertItem[]>([]);
@@ -781,7 +924,8 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
const selectedClass = classId const selectedClass = classId
? classOptions.find((item) => item.classId === classId)?.className || `班级 ${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') const dateLabel = dateRange?.[0]?.isSame(dateRange?.[1], 'day')
? dateRange?.[0]?.format('YYYY-MM-DD') ? dateRange?.[0]?.format('YYYY-MM-DD')
: `${dateRange?.[0]?.format('YYYY-MM-DD') || '开始日期'}${dateRange?.[1]?.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: '学生', title: '学生',
dataIndex: ['student', 'name'], dataIndex: ['student', 'name'],
fixed: 'left', fixed: isMobile ? undefined : 'left',
width: 150, width: 150,
render: (name: string, record) => ( render: (name: string, record) => (
<div className="student-cell"> <div className="student-cell">
@@ -841,7 +985,7 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
{ {
title: '操作', title: '操作',
key: 'action', key: 'action',
fixed: 'right' as const, fixed: isMobile ? undefined : ('right' as const),
width: 80, width: 80,
render: (_: unknown, record: AttendanceRecordItem) => ( render: (_: unknown, record: AttendanceRecordItem) => (
<Button <Button
@@ -868,9 +1012,18 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<span></span> <span></span>
</div> </div>
<div className="student-center-actions"> <div className="student-center-actions">
<span className="student-sync-status"><i /> {dayjs().format('HH:mm')}</span> <span className="student-sync-status">
<Button icon={<ReloadOutlined />} onClick={() => void loadRecords()}></Button> <i />
<PermissionButton permission="attendance:export" icon={<ExportOutlined />} onClick={handleExport}> {dayjs().format('HH:mm')}
</span>
<Button icon={<ReloadOutlined />} onClick={() => void loadRecords()}>
</Button>
<PermissionButton
permission="attendance:export"
icon={<ExportOutlined />}
onClick={handleExport}
>
</PermissionButton> </PermissionButton>
</div> </div>
@@ -935,19 +1088,40 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<div className="student-class-identity"> <div className="student-class-identity">
<div> <div>
<h2>{selectedClass}</h2> <h2>{selectedClass}</h2>
<span>{dateLabel} · {visibleStudents.length} / {total} </span> <span>
{dateLabel} · {visibleStudents.length} / {total}
</span>
</div> </div>
<div className="student-teacher-list"> <div className="student-teacher-list">
<div className="student-teacher-item"><Avatar></Avatar><div><span></span><strong></strong></div></div> <div className="student-teacher-item">
<div className="student-teacher-item"><Avatar></Avatar><div><span></span><strong></strong></div></div> <Avatar></Avatar>
<div className="student-teacher-item"><Avatar></Avatar><div><span></span><strong>{session ? SESSION_MAP[session] : '全部时段'}</strong></div></div> <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> </div>
<div className="student-metric-strip"> <div className="student-metric-strip">
{ADMIN_METRIC_META.map((metric) => { {ADMIN_METRIC_META.map((metric) => {
const value = metric.key === 'all' const value =
? `${attendanceRate}%` metric.key === 'all'
: summary[metric.key as keyof AttendanceSummary] ?? 0; ? `${attendanceRate}%`
: (summary[metric.key as keyof AttendanceSummary] ?? 0);
const meta = STATUS_META[metric.key] ?? { className: 'is-present' }; const meta = STATUS_META[metric.key] ?? { className: 'is-present' };
return ( return (
<button <button
@@ -972,7 +1146,12 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<strong>{alerts.length} </strong> <strong>{alerts.length} </strong>
<span> 14 </span> <span> 14 </span>
</div> </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> <Button type="link"></Button>
</Tooltip> </Tooltip>
</div> </div>
@@ -982,7 +1161,11 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<header className="student-workspace-header"> <header className="student-workspace-header">
<div> <div>
<h3></h3> <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>
<div className="student-workspace-tools"> <div className="student-workspace-tools">
<Input.Search <Input.Search
@@ -991,20 +1174,40 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
value={studentSearch} value={studentSearch}
onChange={(event) => setStudentSearch(event.target.value)} onChange={(event) => setStudentSearch(event.target.value)}
/> />
<Button icon={<ExportOutlined />} onClick={handleExport}></Button> <Button icon={<ExportOutlined />} onClick={handleExport}>
</Button>
</div> </div>
</header> </header>
<div className="student-legend"> <div className="student-legend">
<span><i className="is-present" /></span> <span>
<span><i className="is-late" /></span> <i className="is-present" />
<span><i className="is-leave" /></span>
<span><i className="is-absent" /></span> </span>
<span><i className="is-pending" /></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> <em> / / / </em>
</div> </div>
<Spin spinning={loading}> <Spin spinning={loading}>
{visibleStudents.length === 0 ? ( {visibleStudents.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="未找到匹配学生,请调整筛选条件或搜索关键词" /> <Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="未找到匹配学生,请调整筛选条件或搜索关键词"
/>
) : ( ) : (
<div className="student-card-grid"> <div className="student-card-grid">
{visibleStudents.map((student) => ( {visibleStudents.map((student) => (
@@ -1047,7 +1250,7 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
columns={columns} columns={columns}
dataSource={records} dataSource={records}
loading={loading} loading={loading}
scroll={{ x: 950 }} scroll={{ x: 'max-content' }}
pagination={{ pagination={{
current: page, current: page,
pageSize, pageSize,
@@ -1061,7 +1264,10 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
}} }}
locale={{ locale={{
emptyText: ( 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 <Drawer
open={Boolean(selectedStudent)} open={Boolean(selectedStudent)}
onClose={() => setSelectedStudent(null)} onClose={() => setSelectedStudent(null)}
width={520} width={isMobile ? '100%' : 520}
title="学生考勤明细" title="学生考勤明细"
className="student-detail-drawer" className="student-detail-drawer"
> >
@@ -1080,15 +1286,25 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<Avatar size={54}>{selectedStudent.studentName.slice(0, 1)}</Avatar> <Avatar size={54}>{selectedStudent.studentName.slice(0, 1)}</Avatar>
<div> <div>
<h4>{selectedStudent.studentName}</h4> <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>
<div className="student-detail-rate"><strong>{selectedStudent.rate}%</strong><span></span></div>
</section> </section>
<section className="student-detail-rates"> <section className="student-detail-rates">
{ADMIN_PERIODS.map((period) => { {ADMIN_PERIODS.map((period) => {
const record = selectedStudent.statusBySession[period.key]; const record = selectedStudent.statusBySession[period.key];
const normal = record?.status === 'present' || record?.status === 'late'; 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>
<section className="student-detail-section"> <section className="student-detail-section">
@@ -1096,18 +1312,23 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
<div className="student-detail-timeline"> <div className="student-detail-timeline">
{ADMIN_PERIODS.map((period) => { {ADMIN_PERIODS.map((period) => {
const record = selectedStudent.statusBySession[period.key]; const record = selectedStudent.statusBySession[period.key];
return ( return (
<div key={period.key}> <div key={period.key}>
<span>{period.label}</span> <span>{period.label}</span>
<AttendanceStatusTag status={record?.status || 'pending'} /> <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 && ( {canEdit && record && (
<Button <Button
size="small" size="small"
type="link" type="link"
onClick={() => { onClick={() => {
setEditRecord(record); 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} onOk={submitEdit}
onCancel={() => setEditRecord(null)} onCancel={() => setEditRecord(null)}
> >
<Alert <Alert type="info" showIcon title="管理员修正会保留操作日志" style={{ marginBottom: 20 }} />
type="info"
showIcon
title="管理员修正会保留操作日志"
style={{ marginBottom: 20 }}
/>
<Form form={editForm} layout="vertical"> <Form form={editForm} layout="vertical">
<Form.Item name="status" label="考勤结果" rules={[{ required: true }]}> <Form.Item name="status" label="考勤结果" rules={[{ required: true }]}>
<Select options={STATUS_OPTIONS} /> <Select options={STATUS_OPTIONS} />

View File

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

View File

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

View File

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

View File

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

View File

@@ -15,7 +15,13 @@ import {
Tooltip, Tooltip,
Empty, Empty,
} from 'antd'; } 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 dayjs, { Dayjs } from 'dayjs';
import api from '../../api'; import api from '../../api';
import { downloadBlob } from '../../utils/download'; import { downloadBlob } from '../../utils/download';
@@ -392,17 +398,36 @@ const ClassroomRentalsPage: React.FC = () => {
<Space> <Space>
{record.effectiveStatus === 'active' && ( {record.effectiveStatus === 'active' && (
<> <>
<PermissionButton permission="rental:edit" size="small" onClick={() => openEdit(record)}> <PermissionButton
permission="rental:edit"
size="small"
onClick={() => openEdit(record)}
>
</PermissionButton> </PermissionButton>
<Popconfirm title="确定取消该租赁?" onConfirm={() => handleRentalAction(record.id, 'cancel')}> <Popconfirm
<PermissionButton permission="rental:edit" size="small" danger icon={<StopOutlined />}> title="确定取消该租赁?"
onConfirm={() => handleRentalAction(record.id, 'cancel')}
>
<PermissionButton
permission="rental:edit"
size="small"
danger
icon={<StopOutlined />}
>
</PermissionButton> </PermissionButton>
</Popconfirm> </Popconfirm>
{!dayjs(record.startDate).isAfter(dayjs(), 'day') && ( {!dayjs(record.startDate).isAfter(dayjs(), 'day') && (
<Popconfirm title="确定今天结束该租赁?" onConfirm={() => handleRentalAction(record.id, 'end')}> <Popconfirm
<PermissionButton permission="rental:edit" size="small" icon={<CheckOutlined />}> title="确定今天结束该租赁?"
onConfirm={() => handleRentalAction(record.id, 'end')}
>
<PermissionButton
permission="rental:edit"
size="small"
icon={<CheckOutlined />}
>
</PermissionButton> </PermissionButton>
</Popconfirm> </Popconfirm>
@@ -410,8 +435,13 @@ const ClassroomRentalsPage: React.FC = () => {
</> </>
)} )}
{record.effectiveStatus !== 'active' && ( {record.effectiveStatus !== 'active' && (
<Popconfirm title="确定归档该租赁订单?合同文件会保留。" onConfirm={() => handleDelete(record.id)}> <Popconfirm
<PermissionButton permission="rental:delete" size="small" danger></PermissionButton> title="确定归档该租赁订单?合同文件会保留。"
onConfirm={() => handleDelete(record.id)}
>
<PermissionButton permission="rental:delete" size="small" danger>
</PermissionButton>
</Popconfirm> </Popconfirm>
)} )}
</Space> </Space>
@@ -511,10 +541,12 @@ const ClassroomRentalsPage: React.FC = () => {
optionFilterProp="label" optionFilterProp="label"
placeholder="选择教室" placeholder="选择教室"
onChange={handleClassroomChange} onChange={handleClassroomChange}
options={classrooms.filter((c) => c.status === 'available').map((c) => ({ options={classrooms
value: c.id, .filter((c) => c.status === 'available')
label: `${c.building ? c.building + ' · ' : ''}${c.name}${c.roomType}`, .map((c) => ({
}))} value: c.id,
label: `${c.building ? c.building + ' · ' : ''}${c.name}${c.roomType}`,
}))}
/> />
</Form.Item> </Form.Item>
<Form.Item name="lessorOrganizationId" label="出租机构" tooltip="默认由本机构出租"> <Form.Item name="lessorOrganizationId" label="出租机构" tooltip="默认由本机构出租">

View File

@@ -60,8 +60,16 @@ const ClassroomsPage: React.FC = () => {
const filteredData = useMemo(() => { const filteredData = useMemo(() => {
let result = data; 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 (searchText) {
if (filterStatus) result = result.filter((d: Record<string, unknown>) => d.effectiveStatus === filterStatus); 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; return result;
}, [data, searchText, filterStatus]); }, [data, searchText, filterStatus]);
@@ -140,72 +148,98 @@ const ClassroomsPage: React.FC = () => {
.catch(() => message.error('下载失败')); .catch(() => message.error('下载失败'));
}; };
const columns = useMemo(() => [ const columns = useMemo(
{ () => [
title: '教室名', width: 120, {
dataIndex: 'name', title: '教室名',
sorter: (a: any, b: any) => a.name.localeCompare(b.name), width: 120,
}, dataIndex: 'name',
{ title: '楼栋', dataIndex: 'building', width: 80 }, sorter: (a: any, b: any) => a.name.localeCompare(b.name),
{ 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: '楼栋', dataIndex: 'building', width: 80 },
{ { title: '楼层', dataIndex: 'floor', width: 80 },
title: '操作', {
width: 180, title: '类型',
render: (_: any, record: any) => ( width: 90,
<Space> dataIndex: 'roomType',
{record.status === 'archived' ? ( render: (v: string) => <Tag color={typeColor[v] || 'default'}>{v || '-'}</Tag>,
<Popconfirm title="确定恢复此教室?" onConfirm={() => handleRestore(record.id)}> },
<PermissionButton permission="classroom:edit" size="small" icon={<UndoOutlined />} type="link"> { title: '容量', dataIndex: 'capacity', width: 80 },
{
</PermissionButton> title: '状态',
</Popconfirm> width: 100,
) : ( dataIndex: 'status',
<> render: (
<PermissionButton _s: string,
permission="classroom:edit" record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null },
size="small" ) => {
onClick={() => { const effectiveStatus = record.effectiveStatus || record.status;
setEditing(record); return (
form.setFieldsValue(record); <Tooltip
setModalOpen(true); title={
}} record.currentUsage
> ? `${record.currentUsage.title} (${record.currentUsage.startTime}-${record.currentUsage.endTime})`
: undefined
</PermissionButton> }
<Popconfirm >
title="归档后数据保留,可随时恢复。存在进行中的租赁将无法归档。" <Tag color={statusMap[effectiveStatus]?.color}>
onConfirm={() => handleArchive(record.id)} {statusMap[effectiveStatus]?.text || effectiveStatus}
okText="归档" </Tag>
cancelText="取消" </Tooltip>
> );
<PermissionButton permission="classroom:delete" size="small" icon={<InboxOutlined />}> },
},
{
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> </PermissionButton>
</Popconfirm> </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 ( return (
<div> <div>
@@ -228,7 +262,20 @@ const ClassroomsPage: React.FC = () => {
if (!e.target.value) setSearchText(''); 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 <Button
type={showArchived ? 'primary' : 'default'} type={showArchived ? 'primary' : 'default'}
onClick={() => setShowArchived(!showArchived)} onClick={() => setShowArchived(!showArchived)}
@@ -249,7 +296,26 @@ const ClassroomsPage: React.FC = () => {
> >
</PermissionButton> </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 <Upload
accept=".xlsx,.xls" accept=".xlsx,.xls"
showUploadList={false} showUploadList={false}

View File

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

View File

@@ -50,7 +50,13 @@ interface DepositRecord {
paidDate: string; paidDate: string;
refundDate?: string | null; refundDate?: string | null;
notes?: 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; student?: DepositStudentLookup;
} }
@@ -67,9 +73,9 @@ interface EligibleStudent {
} }
const isFormValidationError = (error: unknown) => const isFormValidationError = (error: unknown) =>
typeof error === 'object' typeof error === 'object' &&
&& error !== null error !== null &&
&& Array.isArray((error as { errorFields?: unknown }).errorFields); Array.isArray((error as { errorFields?: unknown }).errorFields);
const DepositsPage: React.FC = () => { const DepositsPage: React.FC = () => {
const [data, setData] = useState<DepositRecord[]>([]); const [data, setData] = useState<DepositRecord[]>([]);
@@ -141,7 +147,12 @@ const DepositsPage: React.FC = () => {
if (filterRoomType) { if (filterRoomType) {
const s = searchText.trim().toLowerCase(); const s = searchText.trim().toLowerCase();
return eligibleStudents 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) => { .map((item) => {
const deposit = depositByStudentId.get(item.studentId); const deposit = depositByStudentId.get(item.studentId);
return { return {
@@ -176,12 +187,7 @@ const DepositsPage: React.FC = () => {
}); });
}, [data, depositByStudentId, eligibleStudents, filterRoomType, filterStatus, searchText]); }, [data, depositByStudentId, eligibleStudents, filterRoomType, filterStatus, searchText]);
const studentOptions = useMemo( const studentOptions = useMemo(() => buildDepositStudentOptions(students), [students]);
() => buildDepositStudentOptions(students),
[students],
);
const openBatchModal = (roomType = filterRoomType || '四人间') => { const openBatchModal = (roomType = filterRoomType || '四人间') => {
const amount = suggestedDepositByRoomType[roomType] ?? 100; const amount = suggestedDepositByRoomType[roomType] ?? 100;
@@ -194,7 +200,9 @@ const DepositsPage: React.FC = () => {
const handleBatchRoomTypeChange = (roomType: string) => { const handleBatchRoomTypeChange = (roomType: string) => {
setBatchRoomType(roomType); setBatchRoomType(roomType);
batchForm.setFieldsValue({ amount: suggestedDepositByRoomType[roomType] ?? batchForm.getFieldValue('amount') ?? 100 }); batchForm.setFieldsValue({
amount: suggestedDepositByRoomType[roomType] ?? batchForm.getFieldValue('amount') ?? 100,
});
fetchEligibleStudents(roomType); fetchEligibleStudents(roomType);
}; };
@@ -316,87 +324,115 @@ const DepositsPage: React.FC = () => {
} }
}; };
const columns = useMemo(() => [ 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.student?.name || '-' },
{ 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: '当前可用押金',
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120, render: (v: string) => v || '-' }, dataIndex: 'amount',
{ width: 130,
title: '状态', render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
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]); 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 = [ 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: 'roomType' },
{ title: '当前押金', dataIndex: 'depositAmount', render: (v: number) => `¥${Number(v || 0).toFixed(2)}` }, {
title: '当前押金',
dataIndex: 'depositAmount',
render: (v: number) => `¥${Number(v || 0).toFixed(2)}`,
},
]; ];
return ( return (
@@ -492,13 +528,29 @@ const DepositsPage: React.FC = () => {
> >
<Form form={batchForm} layout="vertical"> <Form form={batchForm} layout="vertical">
<Space style={{ width: '100%' }} align="start" wrap> <Space style={{ width: '100%' }} align="start" wrap>
<Form.Item name="roomType" label="房型" rules={[{ required: true, message: '请选择房型' }]}> <Form.Item
<Select style={{ width: 140 }} options={roomTypeOptions} onChange={handleBatchRoomTypeChange} /> name="roomType"
label="房型"
rules={[{ required: true, message: '请选择房型' }]}
>
<Select
style={{ width: 140 }}
options={roomTypeOptions}
onChange={handleBatchRoomTypeChange}
/>
</Form.Item> </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 }} /> <InputNumber min={0.01} precision={2} style={{ width: 180 }} />
</Form.Item> </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" /> <DatePicker style={{ width: 180 }} placeholder="选择收取日期" format="YYYY-MM-DD" />
</Form.Item> </Form.Item>
</Space> </Space>
@@ -509,7 +561,9 @@ const DepositsPage: React.FC = () => {
<div style={{ marginBottom: 8 }}> <div style={{ marginBottom: 8 }}>
<strong>{selectedEligibleStudentIds.length}</strong> / {eligibleStudents.length} <strong>{selectedEligibleStudentIds.length}</strong> / {eligibleStudents.length}
{suggestedDepositByRoomType[batchRoomType] && ( {suggestedDepositByRoomType[batchRoomType] && (
<span style={{ color: '#999', marginLeft: 8 }}>¥{suggestedDepositByRoomType[batchRoomType]}</span> <span style={{ color: '#999', marginLeft: 8 }}>
¥{suggestedDepositByRoomType[batchRoomType]}
</span>
)} )}
</div> </div>
<Table <Table
@@ -549,10 +603,10 @@ const DepositsPage: React.FC = () => {
options={studentOptions} options={studentOptions}
/> />
</Form.Item> </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%' }} /> <InputNumber min={0} precision={2} style={{ width: '100%' }} />
</Form.Item> </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" /> <DatePicker style={{ width: '100%' }} placeholder="选择收取日期" format="YYYY-MM-DD" />
</Form.Item> </Form.Item>
<Form.Item name="notes" label="备注"> <Form.Item name="notes" label="备注">
@@ -574,7 +628,7 @@ const DepositsPage: React.FC = () => {
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}> <div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong> : <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
</div> </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" /> <DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
</Form.Item> </Form.Item>
<Form.Item name="notes" label="备注"> <Form.Item name="notes" label="备注">
@@ -594,19 +648,34 @@ const DepositsPage: React.FC = () => {
{detailModal && ( {detailModal && (
<div> <div>
<Card size="small" style={{ marginBottom: 16 }}> <Card size="small" style={{ marginBottom: 16 }}>
<p><strong>:</strong> ¥{Number(detailModal.amount).toFixed(2)}</p> <p>
<p><strong>:</strong> {detailModal.paidDate}</p> <strong>:</strong> ¥{Number(detailModal.amount).toFixed(2)}
</p>
<p>
<strong>:</strong> {detailModal.paidDate}
</p>
<p> <p>
<strong>:</strong>{' '} <strong>:</strong>{' '}
<Tag color={statusMap[detailModal.status]?.color}> <Tag color={statusMap[detailModal.status]?.color}>
{statusMap[detailModal.status]?.text || detailModal.status} {statusMap[detailModal.status]?.text || detailModal.status}
</Tag> </Tag>
</p> </p>
{detailModal.notes && <p><strong>:</strong> {detailModal.notes}</p>} {detailModal.notes && (
<p>
<strong>:</strong> {detailModal.notes}
</p>
)}
</Card> </Card>
{/* Installments Section */} {/* 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> <h4 style={{ margin: 0 }}></h4>
<PermissionButton <PermissionButton
permission="deposit:edit" permission="deposit:edit"
@@ -644,7 +713,13 @@ const DepositsPage: React.FC = () => {
title="确定归档?" title="确定归档?"
onConfirm={() => handleDeleteInstallment(item.id)} 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> </PermissionButton>
</Popconfirm>, </Popconfirm>,
@@ -676,10 +751,10 @@ const DepositsPage: React.FC = () => {
okText="确认" okText="确认"
> >
<Form form={installmentForm} layout="vertical"> <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%' }} /> <InputNumber min={0} precision={2} style={{ width: '100%' }} />
</Form.Item> </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" /> <DatePicker style={{ width: '100%' }} placeholder="选择到期日期" format="YYYY-MM-DD" />
</Form.Item> </Form.Item>
</Form> </Form>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -66,7 +66,13 @@ const OccupanciesPage: React.FC = () => {
setLoading(true); setLoading(true);
try { try {
const [occRes, stuRes, rmRes] = (await Promise.allSettled([ 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('/students/basic-lookups'),
api.get('/rooms/overview'), api.get('/rooms/overview'),
])) as PromiseSettledResult<any>[]; ])) as PromiseSettledResult<any>[];
@@ -107,7 +113,9 @@ const OccupanciesPage: React.FC = () => {
setAvailableBeds(beds); setAvailableBeds(beds);
setAvailableLockers(lockers); setAvailableLockers(lockers);
if (beds.length === 1) checkInForm.setFieldValue('bedId', beds[0].id); 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) => { const handleTransferRoomChange = async (roomId: number) => {
@@ -195,10 +203,7 @@ const OccupanciesPage: React.FC = () => {
const values = await transferForm.validateFields(); const values = await transferForm.validateFields();
setSaving(true); setSaving(true);
try { try {
await api.put( await api.put(`/occupancies/${transferModal.id}/transfer`, buildTransferPayload(values));
`/occupancies/${transferModal.id}/transfer`,
buildTransferPayload(values),
);
message.success('换房成功'); message.success('换房成功');
setTransferModal(null); setTransferModal(null);
transferForm.resetFields(); transferForm.resetFields();
@@ -246,83 +251,104 @@ const OccupanciesPage: React.FC = () => {
} }
}; };
const columns = useMemo(() => [ 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: 120, render: (_: any, r: any) => r.student?.name || '-' },
{ title: '床位', width: 80, render: (_: unknown, r: Record<string, unknown>) => (r.bed as Record<string, string> | undefined)?.bedNumber || '-' }, { title: '宿舍', width: 120, render: (_: any, r: any) => r.room?.roomNumber || '-' },
{ title: '柜子', width: 80, render: (_: unknown, r: Record<string, unknown>) => (r.locker as Record<string, string> | undefined)?.lockerNumber || '-' }, {
{ title: '入住日期', dataIndex: 'checkInDate', width: 110 }, title: '床位',
{ title: '计费起始', dataIndex: 'billingStartDate', width: 110 }, width: 80,
{ render: (_: unknown, r: Record<string, unknown>) =>
title: '退宿日期', (r.bed as Record<string, string> | undefined)?.bedNumber || '-',
dataIndex: 'checkOutDate', },
width: 110, {
render: (v: any) => v || <Tag color="green"></Tag>, title: '柜子',
}, width: 80,
{ title: '计费截止', dataIndex: 'billingEndDate', render: (v: any) => v || '-' }, render: (_: unknown, r: Record<string, unknown>) =>
{ title: '退宿原因', dataIndex: 'checkOutReason', render: (v: any) => v || '-' }, (r.locker as Record<string, string> | undefined)?.lockerNumber || '-',
{ },
title: '操作', { title: '入住日期', dataIndex: 'checkInDate', width: 110 },
width: 220, { title: '计费起始', dataIndex: 'billingStartDate', width: 110 },
render: (_: any, record: any) => {
!record.checkOutDate ? ( title: '退宿日期',
<Space> dataIndex: 'checkOutDate',
<PermissionButton width: 110,
permission="occupancy:checkout" render: (v: any) => v || <Tag color="green"></Tag>,
size="small" },
icon={<LogoutOutlined />} { title: '计费截止', dataIndex: 'billingEndDate', render: (v: any) => v || '-' },
onClick={() => { { title: '退宿原因', dataIndex: 'checkOutReason', render: (v: any) => v || '-' },
setCheckOutModal(record); {
checkOutForm.setFieldsValue({ checkOutDate: dayjs() }); title: '操作',
}} width: 220,
> render: (_: any, record: any) =>
退宿 !record.checkOutDate ? (
</PermissionButton> <Space>
<PermissionButton <PermissionButton
permission="occupancy:transfer" permission="occupancy:checkout"
size="small" size="small"
icon={<SwapOutlined />} icon={<LogoutOutlined />}
onClick={() => { onClick={() => {
setTransferAvailableBeds([]); setCheckOutModal(record);
setTransferAvailableLockers([]); checkOutForm.setFieldsValue({ checkOutDate: dayjs() });
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> </PermissionButton>
</Popconfirm> <PermissionButton
</Space> permission="occupancy:transfer"
), size="small"
}, icon={<SwapOutlined />}
], [fetchData, setCheckOutModal, checkOutForm, setTransferModal, transferForm]); 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(() => ({ const rowSelection = useMemo(
selectedRowKeys, () => ({
onChange: (keys: any[]) => setSelectedRowKeys(keys), selectedRowKeys,
// 「在住记录」Tab禁用已退宿防止误选用于批量退宿「全部记录」Tab均可选用于批量归档 onChange: (keys: any[]) => setSelectedRowKeys(keys),
getCheckboxProps: (record: any) => (showActive ? { disabled: !!record.checkOutDate } : {}), // 「在住记录」Tab禁用已退宿防止误选用于批量退宿「全部记录」Tab均可选用于批量归档
}), [selectedRowKeys, showActive]); getCheckboxProps: (record: any) => (showActive ? { disabled: !!record.checkOutDate } : {}),
}),
[selectedRowKeys, showActive],
);
return ( return (
<div> <div>
@@ -348,7 +374,14 @@ const OccupanciesPage: React.FC = () => {
allowClear allowClear
style={{ width: 200 }} 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>
<Space wrap className="responsive-toolbar__group"> <Space wrap className="responsive-toolbar__group">
<PermissionButton <PermissionButton
@@ -357,7 +390,11 @@ const OccupanciesPage: React.FC = () => {
icon={<PlusOutlined />} icon={<PlusOutlined />}
onClick={() => { onClick={() => {
checkInForm.resetFields(); checkInForm.resetFields();
checkInForm.setFieldsValue({ checkInDate: dayjs(), collectDeposit: true, depositAmount: 500 }); checkInForm.setFieldsValue({
checkInDate: dayjs(),
collectDeposit: true,
depositAmount: 500,
});
setCheckInModal(true); setCheckInModal(true);
}} }}
> >
@@ -432,26 +469,26 @@ const OccupanciesPage: React.FC = () => {
{autoDeposit && ( {autoDeposit && (
<Space.Compact> <Space.Compact>
<InputNumber <InputNumber
size="small" size="small"
min={0} min={0}
value={depositAmount} value={depositAmount}
onChange={(v) => setDepositAmount(v || 500)} onChange={(v) => setDepositAmount(v || 500)}
style={{ width: 60 }} style={{ width: 60 }}
/> />
<span <span
style={{ style={{
padding: '0 8px', padding: '0 8px',
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
border: '1px solid #d9d9d9', border: '1px solid #d9d9d9',
backgroundColor: '#fafafa', backgroundColor: '#fafafa',
fontSize: 12, fontSize: 12,
}} }}
> >
</span> </span>
</Space.Compact> </Space.Compact>
)} )}
</span> </span>
</Space> </Space>
@@ -543,7 +580,7 @@ const OccupanciesPage: React.FC = () => {
.filter((s: any) => s.status === 'active') .filter((s: any) => s.status === 'active')
.map((s: any) => ({ .map((s: any) => ({
value: s.id, 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> </Form.Item>
@@ -588,11 +625,7 @@ const OccupanciesPage: React.FC = () => {
placeholder="默认为短租" placeholder="默认为短租"
/> />
</Form.Item> </Form.Item>
<Form.Item <Form.Item name="bedId" label="床位" rules={[{ required: true, message: '请选择床位' }]}>
name="bedId"
label="床位"
rules={[{ required: true, message: '请选择床位' }]}
>
<Select <Select
placeholder="请先选择房间" placeholder="请先选择房间"
disabled={availableBeds.length === 0} disabled={availableBeds.length === 0}
@@ -608,10 +641,7 @@ const OccupanciesPage: React.FC = () => {
{availableBeds.length} {availableBeds.length}
</div> </div>
)} )}
<Form.Item <Form.Item name="lockerId" label="柜子(可选)">
name="lockerId"
label="柜子(可选)"
>
<Select <Select
allowClear allowClear
placeholder="可选分配柜子" placeholder="可选分配柜子"
@@ -630,7 +660,10 @@ const OccupanciesPage: React.FC = () => {
> >
<Switch checkedChildren="已缴" unCheckedChildren="不缴" /> <Switch checkedChildren="已缴" unCheckedChildren="不缴" />
</Form.Item> </Form.Item>
<Form.Item noStyle shouldUpdate={(prev, current) => prev.collectDeposit !== current.collectDeposit}> <Form.Item
noStyle
shouldUpdate={(prev, current) => prev.collectDeposit !== current.collectDeposit}
>
{({ getFieldValue }) => {({ getFieldValue }) =>
getFieldValue('collectDeposit') ? ( getFieldValue('collectDeposit') ? (
<Form.Item <Form.Item
@@ -638,12 +671,7 @@ const OccupanciesPage: React.FC = () => {
label="押金金额" label="押金金额"
rules={[{ required: true, message: '请输入押金金额' }]} rules={[{ required: true, message: '请输入押金金额' }]}
> >
<InputNumber <InputNumber min={0.01} precision={2} addonAfter="元" style={{ width: '100%' }} />
min={0.01}
precision={2}
addonAfter="元"
style={{ width: '100%' }}
/>
</Form.Item> </Form.Item>
) : null ) : null
} }

View File

@@ -53,63 +53,67 @@ const OperationLogsPage: React.FC = () => {
fetchData(); fetchData();
}, [fetchData]); }, [fetchData]);
const columns = useMemo(() => [ const columns = useMemo(
{ () => [
title: '时间', {
dataIndex: 'createdAt', title: '时间',
width: 170, dataIndex: 'createdAt',
render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm:ss'), 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>;
}, },
}, { title: '操作人', dataIndex: 'username', width: 100 },
{ {
title: '详情', width: 200, title: '模块',
dataIndex: 'detail', dataIndex: 'module',
ellipsis: true, width: 100,
render: (v: string) => render: (v: string) => <Tag color={moduleColorMap[v] || 'default'}>{v}</Tag>,
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: '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 ( return (
<div> <div>

View File

@@ -1,16 +1,5 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react'; import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { import { Table, Modal, Form, Input, Space, Tag, Popconfirm, Card, Checkbox, Empty } from 'antd';
Table,
Modal,
Form,
Input,
Space,
Tag,
Popconfirm,
Card,
Checkbox,
Empty,
} from 'antd';
import { PlusOutlined, EditOutlined, StopOutlined } from '@ant-design/icons'; import { PlusOutlined, EditOutlined, StopOutlined } from '@ant-design/icons';
import api from '../../api'; import api from '../../api';
import PermissionButton from '../../components/PermissionButton'; import PermissionButton from '../../components/PermissionButton';
@@ -144,53 +133,61 @@ const RolesPage: React.FC = () => {
ai: 'AI 配置', ai: 'AI 配置',
}; };
const columns = useMemo(() => [ const columns = useMemo(
{ title: 'ID', dataIndex: 'id', width: 80 }, () => [
{ title: '名称', dataIndex: 'name', width: 120 }, { title: 'ID', dataIndex: 'id', width: 80 },
{ title: '描述', dataIndex: 'description', width: 200 }, { title: '名称', dataIndex: 'name', width: 120 },
{ { title: '描述', dataIndex: 'description', width: 200 },
title: '权限标签', {
dataIndex: 'permissions', title: '权限标签',
width: 150, dataIndex: 'permissions',
render: (perms: PermissionItem[]) => width: 150,
perms?.length > 0 ? ( render: (perms: PermissionItem[]) =>
<Tag color="blue">{perms.length} </Tag> perms?.length > 0 ? (
) : ( <Tag color="blue">{perms.length} </Tag>
<Tag color="default"></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 handleGroupCheckAll = (group: string, checked: boolean) => {
const groupPermIds = const groupPermIds =

View File

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

View File

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

View File

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

View File

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

View File

@@ -62,7 +62,6 @@ interface EnrollmentInfo {
}; };
} }
interface StudentCreateImportResult { interface StudentCreateImportResult {
message?: string; message?: string;
imported?: number; imported?: number;
@@ -609,7 +608,11 @@ const StudentsPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
<Upload accept=".xlsx,.xls" showUploadList={false} customRequest={handleCreateStudentsImport}> <Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleCreateStudentsImport}
>
<Button icon={<UploadOutlined />}>Excel</Button> <Button icon={<UploadOutlined />}>Excel</Button>
</Upload> </Upload>
<Upload <Upload
@@ -679,9 +682,9 @@ const StudentsPage: React.FC = () => {
} }
return ( return (
<Card title="多班型对比" size="small" style={{ margin: '8px 0' }}> <Card title="多班型对比" size="small" style={{ margin: '8px 0' }}>
<Row gutter={16}> <Row gutter={[16, 16]}>
{enrollments.map((enr, idx) => ( {enrollments.map((enr, idx) => (
<Col span={12} key={enr.classId}> <Col xs={24} md={12} key={enr.classId}>
<Card <Card
size="small" size="small"
title={enr.classType || `班型 ${idx + 1}`} title={enr.classType || `班型 ${idx + 1}`}

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,17 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react'; 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 { HistoryOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import api from '../../api'; import api from '../../api';
@@ -16,7 +28,10 @@ interface WalletRow {
} }
const transactionNames: Record<string, string> = { const transactionNames: Record<string, string> = {
recharge: '充值', adjustment: '调账', bill_payment: '账单扣款', bill_refund: '账单冲正', recharge: '充值',
adjustment: '调账',
bill_payment: '账单扣款',
bill_refund: '账单冲正',
}; };
const WalletsPage: React.FC = () => { const WalletsPage: React.FC = () => {
@@ -36,14 +51,20 @@ const WalletsPage: React.FC = () => {
const fetchRows = useCallback(async () => { const fetchRows = useCallback(async () => {
setLoading(true); setLoading(true);
try { 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[]); setRows(data as WalletRow[]);
} catch (error: any) { } catch (error: any) {
message.error(error?.message || '加载学生余额失败'); message.error(error?.message || '加载学生余额失败');
} finally { setLoading(false); } } finally {
setLoading(false);
}
}, [keyword, debtOnly]); }, [keyword, debtOnly]);
useEffect(() => { void fetchRows(); }, [fetchRows]); useEffect(() => {
void fetchRows();
}, [fetchRows]);
const openChange = (row: WalletRow) => { const openChange = (row: WalletRow) => {
setSelected(row); setSelected(row);
@@ -60,13 +81,23 @@ const WalletsPage: React.FC = () => {
const values = await form.validateFields(); const values = await form.validateFields();
setSaving(true); setSaving(true);
try { try {
const result: any = await api.post('/wallets/change-balance', { operationId: newOperationId(), studentId: selected.studentId, ...values }); const result: any = await api.post('/wallets/change-balance', {
const paid = (result.payments || []).reduce((sum: number, bill: any) => sum + Number(bill.paidAmount || 0), 0); 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 ? `余额已更新,并自动补扣历史账单` : '余额已更新'); message.success(paid > 0 ? `余额已更新,并自动补扣历史账单` : '余额已更新');
setSelected(null); setSelected(null);
await fetchRows(); await fetchRows();
} catch (error: any) { message.error(error?.message || '余额操作失败'); } } catch (error: any) {
finally { setSaving(false); } message.error(error?.message || '余额操作失败');
} finally {
setSaving(false);
}
}; };
const submitBatchChange = async () => { const submitBatchChange = async () => {
@@ -79,7 +110,13 @@ const WalletsPage: React.FC = () => {
...values, ...values,
}); });
const paid = (result.results || []).reduce((sum: number, item: any) => { 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); }, 0);
message.success( message.success(
paid > 0 paid > 0
@@ -90,78 +127,236 @@ const WalletsPage: React.FC = () => {
setSelectedRowKeys([]); setSelectedRowKeys([]);
batchForm.resetFields(); batchForm.resetFields();
await fetchRows(); await fetchRows();
} catch (error: any) { message.error(error?.message || '批量余额操作失败'); } } catch (error: any) {
finally { setSaving(false); } message.error(error?.message || '批量余额操作失败');
} finally {
setSaving(false);
}
}; };
const showTransactions = async (row: WalletRow) => { const showTransactions = async (row: WalletRow) => {
setSelected(row); setDrawerOpen(true); setSelected(row);
try { setTransactions(await api.get('/wallets/transactions', { params: { studentId: row.studentId } }) as any[]); } setDrawerOpen(true);
catch (error: any) { message.error(error?.message || '加载流水失败'); } try {
setTransactions(
(await api.get('/wallets/transactions', { params: { studentId: row.studentId } })) as any[],
);
} catch (error: any) {
message.error(error?.message || '加载流水失败');
}
}; };
const columns = useMemo(() => [ 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: '学生',
{ 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> }, 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> return (
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}> <div>
<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> <div
<Space wrap> style={{
<PermissionButton permission="wallet:edit" type="primary" icon={<PlusOutlined />} disabled={selectedRowKeys.length === 0} onClick={openBatchChange}>/</PermissionButton> display: 'flex',
<Button icon={<ReloadOutlined />} onClick={fetchRows}></Button> justifyContent: 'space-between',
</Space> 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> </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; export default WalletsPage;

View File

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

View File

@@ -25,7 +25,9 @@ type Role = keyof typeof CREDENTIALS;
* Login as a specific role and store the token in localStorage. * Login as a specific role and store the token in localStorage.
* Returns the parsed response data. * 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 creds = CREDENTIALS[role];
const res = await fetch(`${BASE}/api/auth/login`, { const res = await fetch(`${BASE}/api/auth/login`, {
method: 'POST', method: 'POST',