feat(admin): remove all department/campus scoping from frontend

- Delete CampusSwitcher component and useCampus hook
- Delete Departments page and its route
- Remove campus header interceptor from API client
- Remove departmentId from Class interfaces
- Remove campusLocation from student profile
- Remove department permissions from test fixtures
- Remove currentCampusId from test cleanup

TypeScript compiles clean.
This commit is contained in:
2026-07-09 17:40:57 +08:00
parent 22bc1876d8
commit b0f7883f33
12 changed files with 0 additions and 528 deletions

View File

@@ -28,7 +28,6 @@ import PermissionsPage from './pages/Permissions';
import AttendancePage from './pages/Attendance'; import AttendancePage from './pages/Attendance';
import TeacherWorkspacePage from './pages/TeacherWorkspace'; import TeacherWorkspacePage from './pages/TeacherWorkspace';
import NotificationsPage from './pages/Notifications'; import NotificationsPage from './pages/Notifications';
import DepartmentsPage from './pages/Departments';
import IntegrationConfigPage from './pages/IntegrationConfig'; import IntegrationConfigPage from './pages/IntegrationConfig';
import PermissionRoute from './components/PermissionRoute'; import PermissionRoute from './components/PermissionRoute';
@@ -255,14 +254,6 @@ const App: React.FC = () => {
<Route path="notifications" element={<NotificationsPage />} /> <Route path="notifications" element={<NotificationsPage />} />
<Route
path="departments"
element={
<PermissionRoute permission="department:view">
<DepartmentsPage />
</PermissionRoute>
}
/>
<Route <Route
path="integration-config" path="integration-config"

View File

@@ -10,10 +10,6 @@ instance.interceptors.request.use((config) => {
if (token) { if (token) {
config.headers.Authorization = `Bearer ${token}`; config.headers.Authorization = `Bearer ${token}`;
} }
const campusId = localStorage.getItem('currentCampusId');
if (campusId) {
config.headers['X-Campus-Id'] = campusId;
}
return config; return config;
}); });

View File

@@ -1,36 +0,0 @@
import React from 'react';
import { Select, Typography } from 'antd';
import { EnvironmentOutlined } from '@ant-design/icons';
import { useCampus } from '../hooks/useCampus';
const CampusSwitcher: React.FC = () => {
const { campuses, currentId, switchCampus, loading } = useCampus();
if (campuses.length <= 1) {
return (
<Typography.Text style={{ color: '#fff', marginRight: 24 }}>
<EnvironmentOutlined style={{ marginRight: 4 }} />
{campuses[0]?.name || '主校区'}
</Typography.Text>
);
}
const options = [
...campuses.map((c) => ({ value: String(c.id), label: c.name })),
{ value: '', label: '全部校区' },
];
return (
<Select
value={currentId || undefined}
onChange={switchCampus}
options={options}
loading={loading}
style={{ minWidth: 140, marginRight: 24 }}
variant="borderless"
popupMatchSelectWidth={false}
/>
);
};
export default CampusSwitcher;

View File

@@ -53,7 +53,6 @@ interface ProfileData {
targetMajor?: string; targetMajor?: string;
subjectDirection?: string; subjectDirection?: string;
grade?: string; grade?: string;
campusLocation?: string;
profileDate?: string; profileDate?: string;
notes?: string; notes?: string;
} }
@@ -220,7 +219,6 @@ const ProfileTab: React.FC<{ data: ProfileData | null; studentId: number; onRefr
targetMajor: data?.targetMajor ?? undefined, targetMajor: data?.targetMajor ?? undefined,
subjectDirection: data?.subjectDirection ?? undefined, subjectDirection: data?.subjectDirection ?? undefined,
grade: data?.grade ?? undefined, grade: data?.grade ?? undefined,
campusLocation: data?.campusLocation ?? undefined,
profileDate: data?.profileDate ? dayjs(data.profileDate) : undefined, profileDate: data?.profileDate ? dayjs(data.profileDate) : undefined,
notes: data?.notes ?? undefined, notes: data?.notes ?? undefined,
}} }}
@@ -238,9 +236,6 @@ const ProfileTab: React.FC<{ data: ProfileData | null; studentId: number; onRefr
<Form.Item name="grade" label="年级"> <Form.Item name="grade" label="年级">
<Input placeholder="如:高三" /> <Input placeholder="如:高三" />
</Form.Item> </Form.Item>
<Form.Item name="campusLocation" label="校区">
<Input placeholder="请输入校区" />
</Form.Item>
<Form.Item name="profileDate" label="建档日期"> <Form.Item name="profileDate" label="建档日期">
<DatePicker style={{ width: '100%' }} /> <DatePicker style={{ width: '100%' }} />
</Form.Item> </Form.Item>
@@ -903,9 +898,6 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
{profile?.subjectDirection && ( {profile?.subjectDirection && (
<Descriptions.Item label="选科方向">{profile.subjectDirection}</Descriptions.Item> <Descriptions.Item label="选科方向">{profile.subjectDirection}</Descriptions.Item>
)} )}
{profile?.campusLocation && (
<Descriptions.Item label="校区">{profile.campusLocation}</Descriptions.Item>
)}
</Descriptions> </Descriptions>
<Tabs <Tabs

View File

@@ -1,40 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import api from '../api';
interface Department {
id: number;
name: string;
type: string;
parentId: number | null;
}
export function useCampus() {
const [campuses, setCampuses] = useState<Department[]>([]);
const [currentId, setCurrentId] = useState<string>(
() => localStorage.getItem('currentCampusId') || ''
);
const [loading, setLoading] = useState(true);
const fetchCampuses = useCallback(async () => {
try {
const data = await api.get('/departments') as unknown as Department[];
const campusList = data.filter((d) => d.type === 'campus');
setCampuses(campusList);
if (!currentId && campusList.length > 0) {
setCurrentId(String(campusList[0].id));
localStorage.setItem('currentCampusId', String(campusList[0].id));
}
} catch { /* ignore */ }
finally { setLoading(false); }
}, [currentId]);
useEffect(() => { fetchCampuses(); }, []);
const switchCampus = useCallback((id: string) => {
setCurrentId(id);
localStorage.setItem('currentCampusId', id);
window.dispatchEvent(new CustomEvent('campus-changed', { detail: id }));
}, []);
return { campuses, currentId, switchCampus, loading };
}

View File

@@ -29,7 +29,6 @@ import {
} from '@ant-design/icons'; } from '@ant-design/icons';
import { usePermission } from '../hooks/usePermission'; import { usePermission } from '../hooks/usePermission';
import NotificationBell from '../components/NotificationBell'; import NotificationBell from '../components/NotificationBell';
import CampusSwitcher from '../components/CampusSwitcher';
const { Header, Sider, Content } = Layout; const { Header, Sider, Content } = Layout;
@@ -109,7 +108,6 @@ const allMenuItems: MenuItemType[] = [
label: '系统管理', label: '系统管理',
permission: 'log:view', permission: 'log:view',
children: [ children: [
{ key: '/departments', icon: <HomeOutlined />, label: '校区/部门', permission: 'department:view' },
{ key: '/notifications', icon: <BellOutlined />, label: '通知中心', permission: 'notification:view' }, { key: '/notifications', icon: <BellOutlined />, label: '通知中心', permission: 'notification:view' },
{ key: '/operation-logs', icon: <AuditOutlined />, label: '操作日志', permission: 'log:view' }, { key: '/operation-logs', icon: <AuditOutlined />, label: '操作日志', permission: 'log:view' },
{ key: '/roles', icon: <SafetyOutlined />, label: '角色管理', permission: 'role:view' }, { key: '/roles', icon: <SafetyOutlined />, label: '角色管理', permission: 'role:view' },
@@ -289,7 +287,6 @@ const MainLayout: React.FC = () => {
} }
onClick={() => (isMobile || isTablet ? setDrawerOpen(true) : setCollapsed(!collapsed))} onClick={() => (isMobile || isTablet ? setDrawerOpen(true) : setCollapsed(!collapsed))}
/> />
{isDesktop && <CampusSwitcher />}
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
<NotificationBell /> <NotificationBell />
<Dropdown <Dropdown

View File

@@ -62,7 +62,6 @@ interface ClassDetail {
id: number; id: number;
name: string; name: string;
code: string; code: string;
departmentId: number | null;
classType: string; classType: string;
startDate: string | null; startDate: string | null;
endDate: string | null; endDate: string | null;

View File

@@ -16,7 +16,6 @@ interface ClassItem {
id: number; id: number;
name: string; name: string;
code: string; code: string;
departmentId: number | null;
classType: string; classType: string;
startDate: string | null; startDate: string | null;
endDate: string | null; endDate: string | null;

View File

@@ -1,423 +0,0 @@
import React, { useEffect, useState, useCallback } from 'react';
import {
Tree,
Card,
Button,
Modal,
Form,
Input,
Select,
InputNumber,
Table,
Row,
Col,
Popconfirm,
Space,
message,
Tag,
Descriptions,
Empty,
Spin,
} from 'antd';
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
interface DepartmentItem {
id: number;
name: string;
parentId: number | null;
type: string;
sortOrder: number;
status: string;
children?: DepartmentItem[];
}
interface UserInfo {
id: number;
username: string;
name: string;
isActive: boolean;
}
interface DeptMember {
id: number;
userId: number;
departmentId: number;
isDefault: boolean;
user: UserInfo;
}
function departmentToTreeNode(dept: DepartmentItem): DataNode {
return {
key: String(dept.id),
title: dept.name,
children: dept.children?.map(departmentToTreeNode),
};
}
const TYPE_LABELS: Record<string, string> = {
campus: '校区',
department: '部门',
};
const TYPE_COLORS: Record<string, string> = {
campus: 'blue',
department: 'green',
};
const DepartmentsPage: React.FC = () => {
const [treeData, setTreeData] = useState<DataNode[]>([]);
const [flatDepts, setFlatDepts] = useState<DepartmentItem[]>([]);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [selectedDept, setSelectedDept] = useState<DepartmentItem | null>(null);
const [members, setMembers] = useState<DeptMember[]>([]);
const [membersLoading, setMembersLoading] = useState(false);
const [treeLoading, setTreeLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<DepartmentItem | null>(null);
const [form] = Form.useForm();
const [saving, setSaving] = useState(false);
const fetchTree = useCallback(async () => {
setTreeLoading(true);
try {
const data = await api.get('/departments/tree') as unknown as DepartmentItem[];
const flat = await api.get('/departments') as unknown as DepartmentItem[];
setFlatDepts(flat);
setTreeData(data.map(departmentToTreeNode));
} catch {
message.error('加载部门树失败');
} finally {
setTreeLoading(false);
}
}, []);
useEffect(() => {
fetchTree();
}, [fetchTree]);
const fetchDetail = useCallback(async (id: number) => {
try {
const dept = await api.get(`/departments/${id}`) as unknown as DepartmentItem;
setSelectedDept(dept);
setMembersLoading(true);
const users = await api.get(`/departments/${id}/users`) as unknown as DeptMember[];
setMembers(users);
} catch {
message.error('加载部门详情失败');
} finally {
setMembersLoading(false);
}
}, []);
const handleSelect = useCallback(
(keys: React.Key[]) => {
if (keys.length === 0) {
setSelectedId(null);
setSelectedDept(null);
setMembers([]);
return;
}
const id = String(keys[0]);
setSelectedId(id);
fetchDetail(Number(id));
},
[fetchDetail],
);
const handleAdd = useCallback(() => {
setEditing(null);
form.resetFields();
if (selectedId) {
form.setFieldsValue({ parentId: Number(selectedId) });
}
setModalOpen(true);
}, [selectedId, form]);
const handleAddChild = useCallback(() => {
if (!selectedDept) return;
setEditing(null);
form.resetFields();
form.setFieldsValue({ parentId: selectedDept.id });
setModalOpen(true);
}, [selectedDept, form]);
const handleEdit = useCallback(() => {
if (!selectedDept) return;
setEditing(selectedDept);
form.setFieldsValue({
name: selectedDept.name,
parentId: selectedDept.parentId,
type: selectedDept.type,
sortOrder: selectedDept.sortOrder,
});
setModalOpen(true);
}, [selectedDept, form]);
const handleSubmit = useCallback(async () => {
setSaving(true);
try {
const values = await form.validateFields();
const payload = {
name: values.name,
parentId: values.parentId || null,
type: values.type || 'department',
sortOrder: values.sortOrder ?? 0,
};
if (editing) {
await api.put(`/departments/${editing.id}`, payload);
message.success('更新成功');
} else {
await api.post('/departments', payload);
message.success('创建成功');
}
setModalOpen(false);
await fetchTree();
if (editing && selectedId) {
fetchDetail(editing.id);
}
} catch (err: unknown) {
if (
err &&
typeof err === 'object' &&
'message' in err &&
typeof (err as { message: string }).message === 'string'
) {
message.error((err as { message: string }).message);
}
// form validation error falls through silently
} finally {
setSaving(false);
}
}, [editing, fetchTree, fetchDetail, selectedId, form]);
const handleDelete = useCallback(async () => {
if (!selectedDept) return;
try {
await api.delete(`/departments/${selectedDept.id}`);
message.success('删除成功');
setSelectedId(null);
setSelectedDept(null);
setMembers([]);
await fetchTree();
} catch (err: unknown) {
const msg =
err && typeof err === 'object' && 'message' in err
? (err as { message: string }).message
: '删除失败';
message.error(msg);
}
}, [selectedDept, fetchTree]);
const memberColumns = [
{ title: 'ID', dataIndex: 'userId', key: 'userId', width: 60 },
{ title: '用户名', dataIndex: ['user', 'username'], key: 'username', width: 120 },
{ title: '姓名', dataIndex: ['user', 'name'], key: 'name', width: 120 },
{
title: '默认部门',
dataIndex: 'isDefault',
key: 'isDefault',
width: 80,
render: (v: boolean) => (v ? <Tag color="blue"></Tag> : null),
},
];
return (
<div>
<div
style={{
marginBottom: 16,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<h2 style={{ margin: 0 }}></h2>
<Space>
<Button onClick={fetchTree} loading={treeLoading}>
</Button>
<PermissionButton
permission="department:create"
type="primary"
icon={<PlusOutlined />}
onClick={handleAdd}
>
</PermissionButton>
</Space>
</div>
<Row gutter={16}>
<Col xs={24} sm={24} md={8}>
<Card
title="部门结构"
size="small"
style={{ height: 'calc(100vh - 220px)', overflow: 'auto' }}
>
{treeLoading ? (
<Spin style={{ display: 'block', margin: '40px auto' }} />
) : (
<Tree
treeData={treeData}
showLine={{ showLeafIcon: false }}
selectedKeys={selectedId ? [selectedId] : []}
onSelect={handleSelect}
blockNode
/>
)}
</Card>
</Col>
<Col xs={24} sm={24} md={16}>
{selectedDept ? (
<Space direction="vertical" style={{ width: '100%' }} size="middle">
<Card
title={
<Space>
<span>{selectedDept.name}</span>
<Tag color={TYPE_COLORS[selectedDept.type] || 'default'}>
{TYPE_LABELS[selectedDept.type] || selectedDept.type}
</Tag>
</Space>
}
extra={
<Space>
<PermissionButton
permission="department:update"
size="small"
icon={<EditOutlined />}
onClick={handleEdit}
>
</PermissionButton>
<PermissionButton
permission="department:create"
size="small"
icon={<PlusOutlined />}
onClick={handleAddChild}
>
</PermissionButton>
<Popconfirm
title="确定删除该部门?"
description={selectedDept.children && selectedDept.children.length > 0
? '该部门下存在子部门,可能无法删除'
: undefined}
onConfirm={handleDelete}
okText="确定"
cancelText="取消"
>
<Button
size="small"
danger
icon={<DeleteOutlined />}
disabled={
selectedDept.children && selectedDept.children.length > 0
}
>
</Button>
</Popconfirm>
</Space>
}
>
<Descriptions column={2} size="small" bordered>
<Descriptions.Item label="ID">{selectedDept.id}</Descriptions.Item>
<Descriptions.Item label="类型">
<Tag color={TYPE_COLORS[selectedDept.type] || 'default'}>
{TYPE_LABELS[selectedDept.type] || selectedDept.type}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="排序">
{selectedDept.sortOrder}
</Descriptions.Item>
<Descriptions.Item label="上级部门 ID">
{selectedDept.parentId ?? '无(顶级)'}
</Descriptions.Item>
<Descriptions.Item label="状态">
<Tag color={selectedDept.status === 'active' ? 'green' : 'red'}>
{selectedDept.status}
</Tag>
</Descriptions.Item>
</Descriptions>
</Card>
<Card title="部门成员" size="small">
<Table
columns={memberColumns}
dataSource={members}
rowKey="id"
loading={membersLoading}
pagination={false}
size="small"
scroll={{ x: 1000 }}
locale={{ emptyText: '暂无成员' }}
/>
</Card>
</Space>
) : (
<Card
size="small"
style={{ height: 'calc(100vh - 220px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
>
<Empty description="请在左侧选择一个部门" />
</Card>
)}
</Col>
</Row>
<Modal
title={editing ? '编辑部门' : '新增部门'}
open={modalOpen}
onOk={handleSubmit}
onCancel={() => setModalOpen(false)}
destroyOnHidden
confirmLoading={saving}
>
<Form form={form} layout="vertical">
<Form.Item
name="name"
label="部门名称"
rules={[{ required: true, message: '请输入部门名称' }]}
>
<Input placeholder="例如:数学教研组" />
</Form.Item>
<Form.Item name="parentId" label="上级部门">
<Select
allowClear
placeholder="不选则为顶级部门"
options={flatDepts.map((d) => ({
value: d.id,
label: d.name,
disabled: editing ? d.id === editing.id : false,
}))}
/>
</Form.Item>
<Form.Item name="type" label="类型" initialValue="department">
<Select
options={[
{ value: 'campus', label: '校区' },
{ value: 'department', label: '部门' },
]}
/>
</Form.Item>
<Form.Item name="sortOrder" label="排序序号" initialValue={0}>
<InputNumber min={0} style={{ width: '100%' }} />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default DepartmentsPage;

View File

@@ -221,6 +221,5 @@ export const PERMISSION_NODES = [
'log:view', 'log:view',
'role:view', 'role:add', 'role:update', 'role:delete', 'role:view', 'role:add', 'role:update', 'role:delete',
'user:view', 'user:add', 'user:update', 'user:delete', 'user:view', 'user:add', 'user:update', 'user:delete',
'department:view', 'department:add', 'department:update', 'department:delete',
'dashboard:view', 'dashboard:view',
] as const; ] as const;

View File

@@ -47,7 +47,6 @@ export function logout(): void {
localStorage.removeItem('token'); localStorage.removeItem('token');
localStorage.removeItem('user'); localStorage.removeItem('user');
localStorage.removeItem('permissions'); localStorage.removeItem('permissions');
localStorage.removeItem('currentCampusId');
} }
// ── API helpers (authenticated) ───────────────────────────────────── // ── API helpers (authenticated) ─────────────────────────────────────

View File

@@ -18,7 +18,6 @@ afterEach(() => {
localStorage.removeItem('token'); localStorage.removeItem('token');
localStorage.removeItem('user'); localStorage.removeItem('user');
localStorage.removeItem('permissions'); localStorage.removeItem('permissions');
localStorage.removeItem('currentCampusId');
}); });
export { BASE }; export { BASE };