forked from wangziqi/gongxue-base
Merge pull request 'fix: 权限按钮可见性与Modal/Popconfirm撤权一致性修复' (#45) from worktree-audit-permission-ui into main
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import axios, { type AxiosRequestConfig } from 'axios';
|
||||
import { clearPermissions } from '../auth/permission-store';
|
||||
|
||||
const instance = axios.create({
|
||||
baseURL: '/api',
|
||||
@@ -21,7 +22,7 @@ instance.interceptors.response.use(
|
||||
if (err.response?.status === 401 && !isLoginRequest) {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
localStorage.removeItem('permissions');
|
||||
clearPermissions();
|
||||
window.location.href = '/login';
|
||||
}
|
||||
if (err.response?.status === 403) {
|
||||
|
||||
65
apps/admin/src/auth/permission-state.integration.test.tsx
Normal file
65
apps/admin/src/auth/permission-state.integration.test.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
|
||||
import PermissionButton from '../components/PermissionButton';
|
||||
import {
|
||||
beginPermissionVerification,
|
||||
clearPermissions,
|
||||
readPermissionState,
|
||||
writePermissions,
|
||||
} from './permission-store';
|
||||
|
||||
let container: HTMLDivElement | null = null;
|
||||
let root: ReturnType<typeof createRoot> | null = null;
|
||||
|
||||
beforeAll(() => {
|
||||
(
|
||||
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
});
|
||||
|
||||
async function renderPermissionButton() {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
await act(async () => {
|
||||
root?.render(<PermissionButton permission="student:edit">编辑学生</PermissionButton>);
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) await act(async () => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
clearPermissions();
|
||||
});
|
||||
|
||||
describe('permission state', () => {
|
||||
it('ignores cached localStorage permissions until profile verification succeeds', async () => {
|
||||
localStorage.setItem('permissions', JSON.stringify(['student:edit']));
|
||||
beginPermissionVerification();
|
||||
|
||||
expect(readPermissionState()).toEqual({ permissions: [], status: 'loading' });
|
||||
await renderPermissionButton();
|
||||
expect(container?.textContent).not.toContain('编辑学生');
|
||||
});
|
||||
|
||||
it('renders permission actions only after verified permissions are written', async () => {
|
||||
beginPermissionVerification();
|
||||
await renderPermissionButton();
|
||||
expect(container?.textContent).not.toContain('编辑学生');
|
||||
|
||||
await act(async () => writePermissions(['student:edit']));
|
||||
expect(container?.textContent).toContain('编辑学生');
|
||||
});
|
||||
|
||||
it('stays fail-closed while profile verification is retried after a failure', async () => {
|
||||
writePermissions(['student:edit']);
|
||||
beginPermissionVerification();
|
||||
|
||||
expect(readPermissionState()).toEqual({ permissions: [], status: 'loading' });
|
||||
await renderPermissionButton();
|
||||
expect(container?.textContent).not.toContain('编辑学生');
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,40 @@
|
||||
export const PERMISSIONS_UPDATED_EVENT = 'permissions-updated';
|
||||
|
||||
export type PermissionStatus = 'unknown' | 'loading' | 'ready';
|
||||
|
||||
export interface PermissionState {
|
||||
permissions: string[];
|
||||
status: PermissionStatus;
|
||||
}
|
||||
|
||||
let permissionState: PermissionState = { permissions: [], status: 'unknown' };
|
||||
|
||||
function notifyPermissionStateChanged(): void {
|
||||
window.dispatchEvent(new Event(PERMISSIONS_UPDATED_EVENT));
|
||||
}
|
||||
|
||||
export function readPermissionState(): PermissionState {
|
||||
return permissionState;
|
||||
}
|
||||
|
||||
export function readPermissions(): string[] {
|
||||
try {
|
||||
const value = JSON.parse(localStorage.getItem('permissions') || '[]');
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === 'string')
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return permissionState.status === 'ready' ? permissionState.permissions : [];
|
||||
}
|
||||
|
||||
export function beginPermissionVerification(): void {
|
||||
permissionState = { permissions: [], status: 'loading' };
|
||||
notifyPermissionStateChanged();
|
||||
}
|
||||
|
||||
export function writePermissions(permissions: string[]): void {
|
||||
localStorage.setItem('permissions', JSON.stringify([...new Set(permissions)]));
|
||||
window.dispatchEvent(new Event(PERMISSIONS_UPDATED_EVENT));
|
||||
const uniquePermissions = [...new Set(permissions)];
|
||||
localStorage.setItem('permissions', JSON.stringify(uniquePermissions));
|
||||
permissionState = { permissions: uniquePermissions, status: 'ready' };
|
||||
notifyPermissionStateChanged();
|
||||
}
|
||||
|
||||
export function clearPermissions(status: PermissionStatus = 'unknown'): void {
|
||||
localStorage.removeItem('permissions');
|
||||
permissionState = { permissions: [], status };
|
||||
notifyPermissionStateChanged();
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import React from 'react';
|
||||
import { Navigate } from 'react-router-dom';
|
||||
import { Result } from 'antd';
|
||||
import { Result, Spin } from 'antd';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
import { findRoleAwareLandingPath } from '../auth/menu-policy';
|
||||
|
||||
const DefaultRoute: React.FC = () => {
|
||||
const { permissions } = usePermission();
|
||||
const { permissions, permissionsReady } = usePermission();
|
||||
if (!permissionsReady) {
|
||||
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
|
||||
}
|
||||
const roles = (() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem('user') || '{}').roles || [];
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
} from '@ant-design/icons';
|
||||
import api from '../api';
|
||||
import { message } from '../ui/app-message';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
import PermissionButton from './PermissionButton';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
@@ -86,7 +88,12 @@ interface MatchSelectorProps {
|
||||
onChange: (d: MatchDecision) => void;
|
||||
}
|
||||
|
||||
const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentOptions, onChange }) => {
|
||||
const MatchSelector: React.FC<MatchSelectorProps> = ({
|
||||
entry,
|
||||
decision,
|
||||
studentOptions,
|
||||
onChange,
|
||||
}) => {
|
||||
const action = decision?.action ?? 'skip';
|
||||
|
||||
if (action === 'match') {
|
||||
@@ -94,7 +101,9 @@ const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentO
|
||||
const matchedStudent = studentOptions.find((s) => s.id === matchD.matchStudentId);
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
|
||||
<Tag color="blue" icon={<LinkOutlined />}>已匹配</Tag>
|
||||
<Tag color="blue" icon={<LinkOutlined />}>
|
||||
已匹配
|
||||
</Tag>
|
||||
<Text style={{ flex: 1 }}>
|
||||
{matchedStudent?.name ?? '未知'}
|
||||
{matchedStudent?.studentNo && (
|
||||
@@ -103,7 +112,9 @@ const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentO
|
||||
</Text>
|
||||
)}
|
||||
</Text>
|
||||
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>取消</Button>
|
||||
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -112,30 +123,76 @@ const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentO
|
||||
const createD = decision as { action: 'create'; createName: string; createPhone: string };
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
|
||||
<Tag color="green" icon={<PlusOutlined />}>将新建</Tag>
|
||||
<Input size="small" value={createD.createName} placeholder="姓名" style={{ width: 100 }}
|
||||
onChange={(e) => onChange({ action: 'create', createName: e.target.value, createPhone: createD.createPhone })} />
|
||||
<Input size="small" value={createD.createPhone} placeholder="手机号" style={{ width: 120 }}
|
||||
onChange={(e) => onChange({ action: 'create', createName: createD.createName, createPhone: e.target.value })} />
|
||||
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>取消</Button>
|
||||
<Tag color="green" icon={<PlusOutlined />}>
|
||||
将新建
|
||||
</Tag>
|
||||
<Input
|
||||
size="small"
|
||||
value={createD.createName}
|
||||
placeholder="姓名"
|
||||
style={{ width: 100 }}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
action: 'create',
|
||||
createName: e.target.value,
|
||||
createPhone: createD.createPhone,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
size="small"
|
||||
value={createD.createPhone}
|
||||
placeholder="手机号"
|
||||
style={{ width: 120 }}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
action: 'create',
|
||||
createName: createD.createName,
|
||||
createPhone: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
|
||||
<Select showSearch size="small" placeholder="搜索学生…" style={{ flex: 1 }} value={undefined}
|
||||
filterOption={(input, option) => ((option?.label as string) || '').toLowerCase().includes(input.toLowerCase())}
|
||||
<Select
|
||||
showSearch
|
||||
size="small"
|
||||
placeholder="搜索学生…"
|
||||
style={{ flex: 1 }}
|
||||
value={undefined}
|
||||
filterOption={(input, option) =>
|
||||
((option?.label as string) || '').toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
options={studentOptions.map((s) => ({
|
||||
value: s.id,
|
||||
label: `${s.name}${s.phone ? ` (${s.phone})` : ''}${s.studentNo ? ` [${s.studentNo}]` : ''}`,
|
||||
}))}
|
||||
onChange={(studentId: number) => onChange({ action: 'match', matchStudentId: studentId })} />
|
||||
<Button size="small" type="dashed" icon={<PlusOutlined />}
|
||||
onClick={() => onChange({ action: 'create', createName: entry.name || '', createPhone: entry.phone || '' })}>
|
||||
onChange={(studentId: number) => onChange({ action: 'match', matchStudentId: studentId })}
|
||||
/>
|
||||
<Button
|
||||
size="small"
|
||||
type="dashed"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() =>
|
||||
onChange({
|
||||
action: 'create',
|
||||
createName: entry.name || '',
|
||||
createPhone: entry.phone || '',
|
||||
})
|
||||
}
|
||||
>
|
||||
新建
|
||||
</Button>
|
||||
<Button size="small" type="link" onClick={() => onChange({ action: 'skip' })}>跳过</Button>
|
||||
<Button size="small" type="link" onClick={() => onChange({ action: 'skip' })}>
|
||||
跳过
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -151,13 +208,25 @@ interface RuleEditorProps {
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
const RuleEditor: React.FC<RuleEditorProps> = ({ rule, formToken, fields, onSave, onDelete, onCancel }) => {
|
||||
const RuleEditor: React.FC<RuleEditorProps> = ({
|
||||
rule,
|
||||
formToken,
|
||||
fields,
|
||||
onSave,
|
||||
onDelete,
|
||||
onCancel,
|
||||
}) => {
|
||||
const [name, setName] = useState(rule?.name ?? '');
|
||||
const [mappings, setMappings] = useState<Record<string, string>>(rule?.mappings ?? { name: 'field_1', phone: 'field_2' });
|
||||
const [mappings, setMappings] = useState<Record<string, string>>(
|
||||
rule?.mappings ?? { name: 'field_1', phone: 'field_2' },
|
||||
);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!name.trim()) { message.warning('请输入规则名称'); return; }
|
||||
if (!name.trim()) {
|
||||
message.warning('请输入规则名称');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
if (rule) {
|
||||
@@ -170,18 +239,31 @@ const RuleEditor: React.FC<RuleEditorProps> = ({ rule, formToken, fields, onSave
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
if (err?.message) message.error(err.message);
|
||||
} finally { setSaving(false); }
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: '12px 0' }}>
|
||||
<Input placeholder="规则名称" value={name} onChange={(e) => setName(e.target.value)}
|
||||
style={{ marginBottom: 12 }} />
|
||||
<Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>选择金数据字段映射到学生资料</Text>
|
||||
<Input
|
||||
placeholder="规则名称"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
<Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
|
||||
选择金数据字段映射到学生资料
|
||||
</Text>
|
||||
{STUDENT_FIELDS.map((sf) => (
|
||||
<div key={sf.key} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
|
||||
<div
|
||||
key={sf.key}
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}
|
||||
>
|
||||
<Text style={{ width: 100, textAlign: 'right', fontSize: 13 }}>{sf.label}</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>←</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
←
|
||||
</Text>
|
||||
<Select
|
||||
allowClear
|
||||
showSearch
|
||||
@@ -193,20 +275,26 @@ const RuleEditor: React.FC<RuleEditorProps> = ({ rule, formToken, fields, onSave
|
||||
value: field.key,
|
||||
label: `${field.label}(${field.key})`,
|
||||
}))}
|
||||
onChange={(value) => setMappings((prev) => {
|
||||
const next = { ...prev };
|
||||
if (value) next[sf.key] = value;
|
||||
else delete next[sf.key];
|
||||
return next;
|
||||
})}
|
||||
onChange={(value) =>
|
||||
setMappings((prev) => {
|
||||
const next = { ...prev };
|
||||
if (value) next[sf.key] = value;
|
||||
else delete next[sf.key];
|
||||
return next;
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
|
||||
<Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>保存</Button>
|
||||
<Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>
|
||||
保存
|
||||
</Button>
|
||||
{rule && (
|
||||
<Popconfirm title="确定删除此规则?" onConfirm={() => onDelete(rule.id)}>
|
||||
<Button danger icon={<DeleteOutlined />}>删除</Button>
|
||||
<Button danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
<Button onClick={onCancel}>取消</Button>
|
||||
@@ -224,6 +312,9 @@ interface MatchModalProps {
|
||||
}
|
||||
|
||||
const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplied }) => {
|
||||
const { hasPermission, hasAllPermissions, permissionsReady } = usePermission();
|
||||
const canTriggerSync = hasPermission('sync:trigger');
|
||||
const canEnterModal = permissionsReady && hasAllPermissions('sync:read', 'sync:trigger');
|
||||
const [step, setStep] = useState<'connection' | 'rule' | 'match' | 'applying'>('connection');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>();
|
||||
@@ -244,17 +335,34 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
|
||||
// Load rules on open
|
||||
useEffect(() => {
|
||||
if (open) loadRules();
|
||||
}, [open]);
|
||||
if (open && canEnterModal) loadRules();
|
||||
}, [open, canEnterModal]);
|
||||
|
||||
// Close and reset when permission is lost
|
||||
const enteredRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (canEnterModal) {
|
||||
enteredRef.current = true;
|
||||
return;
|
||||
}
|
||||
if (enteredRef.current) {
|
||||
enteredRef.current = false;
|
||||
reset();
|
||||
onClose();
|
||||
}
|
||||
}, [canEnterModal, onClose]);
|
||||
|
||||
const loadRules = async () => {
|
||||
try {
|
||||
const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules');
|
||||
if (res.success) setRules(res.data);
|
||||
} catch { /* ignore */ }
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const handleConnectionNext = async () => {
|
||||
if (!canTriggerSync) return;
|
||||
try {
|
||||
const values = await credForm.validateFields();
|
||||
setLoading(true);
|
||||
@@ -274,6 +382,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
};
|
||||
|
||||
const handlePreview = async () => {
|
||||
if (!canTriggerSync) return;
|
||||
try {
|
||||
const values = await credForm.validateFields();
|
||||
setLoading(true);
|
||||
@@ -286,7 +395,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
const initial = new Map<number, MatchDecision>();
|
||||
for (const entry of res.entries) {
|
||||
if (entry.suggestedStudent) {
|
||||
initial.set(entry.serialNumber, { action: 'match', matchStudentId: entry.suggestedStudent.id });
|
||||
initial.set(entry.serialNumber, {
|
||||
action: 'match',
|
||||
matchStudentId: entry.suggestedStudent.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
setDecisions(initial);
|
||||
@@ -294,22 +406,29 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
if (err?.message) message.error(err.message);
|
||||
} finally { setLoading(false); }
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleApply = async () => {
|
||||
if (!canTriggerSync) return;
|
||||
setLoading(true);
|
||||
setStep('applying');
|
||||
try {
|
||||
const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({ serialNumber, ...d }));
|
||||
const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({
|
||||
serialNumber,
|
||||
...d,
|
||||
}));
|
||||
const body: Record<string, unknown> = {
|
||||
...credForm.getFieldsValue(),
|
||||
decisions: decisionList,
|
||||
};
|
||||
if (selectedRuleId) body.ruleId = selectedRuleId;
|
||||
const res = await api.post<{ success: boolean; log: { recordsCount: number; message?: string } }>(
|
||||
'/sync/jinshuju/apply', body,
|
||||
);
|
||||
const res = await api.post<{
|
||||
success: boolean;
|
||||
log: { recordsCount: number; message?: string };
|
||||
}>('/sync/jinshuju/apply', body);
|
||||
if (res.success) {
|
||||
message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
|
||||
onApplied();
|
||||
@@ -319,7 +438,9 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
const err = e as { message?: string };
|
||||
if (err?.message) message.error(err.message);
|
||||
setStep('match');
|
||||
} finally { setLoading(false); }
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
@@ -334,7 +455,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
credForm.resetFields();
|
||||
};
|
||||
|
||||
const handleClose = () => { reset(); onClose(); };
|
||||
const handleClose = () => {
|
||||
reset();
|
||||
onClose();
|
||||
};
|
||||
const handleScroll = (source: 'left' | 'right') => {
|
||||
const el = source === 'left' ? leftRef.current : rightRef.current;
|
||||
if (el) setScrollTop(el.scrollTop);
|
||||
@@ -346,7 +470,8 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
}, [scrollTop]);
|
||||
|
||||
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial);
|
||||
const setDecision = (serial: number, d: MatchDecision) => setDecisions((prev) => new Map(prev).set(serial, d));
|
||||
const setDecision = (serial: number, d: MatchDecision) =>
|
||||
setDecisions((prev) => new Map(prev).set(serial, d));
|
||||
const total = entries.length;
|
||||
const matched = [...decisions.values()].filter((d) => d.action !== 'skip').length;
|
||||
|
||||
@@ -401,7 +526,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
onChange={(value) => setSelectedRuleId(value)}
|
||||
options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))}
|
||||
/>
|
||||
{selectedRule ? (
|
||||
{canTriggerSync && selectedRule ? (
|
||||
<Button
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
@@ -412,15 +537,17 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
编辑
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
setEditingRule(null);
|
||||
setShowRuleEditor(true);
|
||||
}}
|
||||
>
|
||||
新建规则
|
||||
</Button>
|
||||
{canTriggerSync ? (
|
||||
<Button
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
setEditingRule(null);
|
||||
setShowRuleEditor(true);
|
||||
}}
|
||||
>
|
||||
新建规则
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{visibleRules.length === 0 && !showRuleEditor ? (
|
||||
@@ -429,7 +556,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
{showRuleEditor ? (
|
||||
{canTriggerSync && showRuleEditor ? (
|
||||
<RuleEditor
|
||||
rule={editingRule}
|
||||
formToken={formToken}
|
||||
@@ -459,51 +586,113 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
const d = getDecision(entry.serialNumber);
|
||||
const isMatched = d?.action === 'match';
|
||||
const color = isMatched ? '#1677ff' : '#d9d9d9';
|
||||
lines.push(<line key={entry.serialNumber} x1={LEFT_WIDTH} y1={y} x2={LEFT_WIDTH + GAP} y2={y}
|
||||
stroke={color} strokeWidth={isMatched ? 2 : 1}
|
||||
strokeDasharray={isMatched ? undefined : '4 4'} opacity={isMatched ? 0.7 : 0.3} />);
|
||||
lines.push(
|
||||
<line
|
||||
key={entry.serialNumber}
|
||||
x1={LEFT_WIDTH}
|
||||
y1={y}
|
||||
x2={LEFT_WIDTH + GAP}
|
||||
y2={y}
|
||||
stroke={color}
|
||||
strokeWidth={isMatched ? 2 : 1}
|
||||
strokeDasharray={isMatched ? undefined : '4 4'}
|
||||
opacity={isMatched ? 0.7 : 0.3}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<div style={{ position: 'relative' }}>
|
||||
<div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Text type="secondary">共 {total} 条,已匹配 {matched} 条</Text>
|
||||
<Button size="small" onClick={() => setDecisions(new Map())}>清除全部匹配</Button>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 12,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Text type="secondary">
|
||||
共 {total} 条,已匹配 {matched} 条
|
||||
</Text>
|
||||
<Button size="small" onClick={() => setDecisions(new Map())}>
|
||||
清除全部匹配
|
||||
</Button>
|
||||
</div>
|
||||
<div style={{ display: 'flex', position: 'relative' }}>
|
||||
<svg style={{ position: 'absolute', top: 0, left: 0, width: LEFT_WIDTH + GAP, height: svgHeight, pointerEvents: 'none', zIndex: 1 }}>
|
||||
<svg
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: LEFT_WIDTH + GAP,
|
||||
height: svgHeight,
|
||||
pointerEvents: 'none',
|
||||
zIndex: 1,
|
||||
}}
|
||||
>
|
||||
{lines}
|
||||
</svg>
|
||||
<div ref={leftRef} onScroll={() => handleScroll('left')}
|
||||
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}>
|
||||
<div
|
||||
ref={leftRef}
|
||||
onScroll={() => handleScroll('left')}
|
||||
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}
|
||||
>
|
||||
{entries.map((entry, i) => {
|
||||
const d = getDecision(entry.serialNumber);
|
||||
const isMatched = d?.action === 'match';
|
||||
return (
|
||||
<div key={entry.serialNumber} style={{
|
||||
height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0',
|
||||
display: 'flex', flexDirection: 'column', justifyContent: 'center',
|
||||
background: isMatched ? '#f6ffed' : i % 2 === 0 ? '#fafafa' : '#fff',
|
||||
borderLeft: isMatched ? '3px solid #1677ff' : '3px solid transparent',
|
||||
}}>
|
||||
<Text strong style={{ fontSize: 13 }}>{entry.name || <Text type="secondary">无姓名</Text>}</Text>
|
||||
{entry.phone && <Text type="secondary" style={{ fontSize: 12 }}>{entry.phone}</Text>}
|
||||
<Text type="secondary" style={{ fontSize: 11 }}>#{entry.serialNumber}</Text>
|
||||
<div
|
||||
key={entry.serialNumber}
|
||||
style={{
|
||||
height: ROW_HEIGHT,
|
||||
padding: '8px 12px',
|
||||
borderBottom: '1px solid #f0f0f0',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
background: isMatched ? '#f6ffed' : i % 2 === 0 ? '#fafafa' : '#fff',
|
||||
borderLeft: isMatched ? '3px solid #1677ff' : '3px solid transparent',
|
||||
}}
|
||||
>
|
||||
<Text strong style={{ fontSize: 13 }}>
|
||||
{entry.name || <Text type="secondary">无姓名</Text>}
|
||||
</Text>
|
||||
{entry.phone && (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{entry.phone}
|
||||
</Text>
|
||||
)}
|
||||
<Text type="secondary" style={{ fontSize: 11 }}>
|
||||
#{entry.serialNumber}
|
||||
</Text>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div style={{ width: GAP, flexShrink: 0 }} />
|
||||
<div ref={rightRef} onScroll={() => handleScroll('right')}
|
||||
style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}>
|
||||
<div
|
||||
ref={rightRef}
|
||||
onScroll={() => handleScroll('right')}
|
||||
style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}
|
||||
>
|
||||
{entries.map((entry) => (
|
||||
<div key={entry.serialNumber} style={{
|
||||
height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0',
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
}}>
|
||||
<MatchSelector entry={entry} decision={getDecision(entry.serialNumber)}
|
||||
<div
|
||||
key={entry.serialNumber}
|
||||
style={{
|
||||
height: ROW_HEIGHT,
|
||||
padding: '8px 12px',
|
||||
borderBottom: '1px solid #f0f0f0',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<MatchSelector
|
||||
entry={entry}
|
||||
decision={getDecision(entry.serialNumber)}
|
||||
studentOptions={studentOptions}
|
||||
onChange={(newD) => setDecision(entry.serialNumber, newD)} />
|
||||
onChange={(newD) => setDecision(entry.serialNumber, newD)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -517,47 +706,72 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
|
||||
return (
|
||||
<Modal
|
||||
title="同步金数据"
|
||||
open={open}
|
||||
open={open && canEnterModal}
|
||||
onCancel={handleClose}
|
||||
width={step === 'match' || step === 'applying' ? 900 : 640}
|
||||
maskClosable={false}
|
||||
footer={
|
||||
step === 'connection'
|
||||
? [
|
||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
||||
<Button key="next" type="primary" onClick={handleConnectionNext}>下一步</Button>,
|
||||
<Button key="cancel" onClick={handleClose}>
|
||||
取消
|
||||
</Button>,
|
||||
<Button key="next" type="primary" onClick={handleConnectionNext}>
|
||||
下一步
|
||||
</Button>,
|
||||
]
|
||||
: step === 'rule'
|
||||
? [
|
||||
<Button key="back" onClick={() => setStep('connection')}>上一步</Button>,
|
||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
||||
<Button key="next" type="primary" icon={<SearchOutlined />} loading={loading} onClick={handlePreview}>
|
||||
<Button key="back" onClick={() => setStep('connection')}>
|
||||
上一步
|
||||
</Button>,
|
||||
<Button key="cancel" onClick={handleClose}>
|
||||
取消
|
||||
</Button>,
|
||||
<Button
|
||||
key="next"
|
||||
type="primary"
|
||||
icon={<SearchOutlined />}
|
||||
loading={loading}
|
||||
onClick={handlePreview}
|
||||
>
|
||||
获取数据并下一步
|
||||
</Button>,
|
||||
]
|
||||
: step === 'match'
|
||||
? [
|
||||
<Button key="back" onClick={() => setStep('rule')}>上一步</Button>,
|
||||
<Button key="cancel" onClick={handleClose}>取消</Button>,
|
||||
<Button key="apply" type="primary" icon={<CloudUploadOutlined />} loading={loading} onClick={handleApply}>
|
||||
应用匹配
|
||||
<Button key="back" onClick={() => setStep('rule')}>
|
||||
上一步
|
||||
</Button>,
|
||||
<Button key="cancel" onClick={handleClose}>
|
||||
取消
|
||||
</Button>,
|
||||
canTriggerSync ? (
|
||||
<PermissionButton
|
||||
key="apply"
|
||||
permission="sync:trigger"
|
||||
type="primary"
|
||||
icon={<CloudUploadOutlined />}
|
||||
loading={loading}
|
||||
onClick={handleApply}
|
||||
>
|
||||
应用匹配
|
||||
</PermissionButton>
|
||||
) : null,
|
||||
]
|
||||
: null
|
||||
}
|
||||
>
|
||||
<Steps
|
||||
current={currentStep}
|
||||
items={[
|
||||
{ title: '连接表单' },
|
||||
{ title: '匹配规则' },
|
||||
{ title: '确认匹配' },
|
||||
]}
|
||||
items={[{ title: '连接表单' }, { title: '匹配规则' }, { title: '确认匹配' }]}
|
||||
/>
|
||||
{step === 'connection' ? renderConnectionStep() : null}
|
||||
{step === 'rule' ? renderRuleStep() : null}
|
||||
{step === 'match' ? renderMatchStep() : null}
|
||||
{step === 'applying' ? <Spin tip="正在同步..." style={{ display: 'block', margin: '48px auto' }} /> : null}
|
||||
{step === 'applying' ? (
|
||||
<Spin tip="正在同步..." style={{ display: 'block', margin: '48px auto' }} />
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { Result, Button } from 'antd';
|
||||
import { Result, Button, Spin } from 'antd';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { findRoleAwareLandingPath } from '../auth/menu-policy';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
@@ -10,8 +10,11 @@ interface PermissionRouteProps {
|
||||
}
|
||||
|
||||
const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
|
||||
const { permissions, hasPermission } = usePermission();
|
||||
const { permissions, permissionsReady, hasPermission } = usePermission();
|
||||
const navigate = useNavigate();
|
||||
if (!permissionsReady) {
|
||||
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
|
||||
}
|
||||
if (!hasPermission(permission)) {
|
||||
let roles: string[] = [];
|
||||
try {
|
||||
|
||||
@@ -37,6 +37,8 @@ import { maskPhone, maskIdNumber } from '../../utils/sensitive';
|
||||
import { useViewSensitive } from '../../hooks/useViewSensitive';
|
||||
import { message } from '../../ui/app-message';
|
||||
import EditableCell from '../EditableCell';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import PermissionButton from '../PermissionButton';
|
||||
|
||||
// ---- Types ----
|
||||
|
||||
@@ -318,7 +320,19 @@ const InlineArchiveSummary: React.FC<{
|
||||
organizations: Array<{ id: number; name: string }>;
|
||||
onRefresh: () => void;
|
||||
onViewSensitive: (fieldLabel: string, value: string) => void;
|
||||
}> = ({ studentId, student, profile, result, organizations, onRefresh, onViewSensitive }) => {
|
||||
canViewSensitive: boolean;
|
||||
canChooseOrganization: boolean;
|
||||
}> = ({
|
||||
studentId,
|
||||
student,
|
||||
profile,
|
||||
result,
|
||||
organizations,
|
||||
onRefresh,
|
||||
onViewSensitive,
|
||||
canViewSensitive,
|
||||
canChooseOrganization,
|
||||
}) => {
|
||||
const saveStudent = async (field: keyof StudentInfo, value: unknown) => {
|
||||
await api.put(`/students/${studentId}`, { [field]: value });
|
||||
message.success('学生资料已保存');
|
||||
@@ -356,9 +370,11 @@ const InlineArchiveSummary: React.FC<{
|
||||
{student.phone ? (
|
||||
<span>
|
||||
<span style={{ marginRight: 8 }}>{maskPhone(student.phone)}</span>
|
||||
<a onClick={() => onViewSensitive('电话', student.phone)}>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
{canViewSensitive ? (
|
||||
<a onClick={() => onViewSensitive('电话', student.phone)}>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
) : null}
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
@@ -402,9 +418,11 @@ const InlineArchiveSummary: React.FC<{
|
||||
{student.idNumber ? (
|
||||
<span>
|
||||
<span style={{ marginRight: 8 }}>{maskIdNumber(student.idNumber)}</span>
|
||||
<a onClick={() => onViewSensitive('身份证号', student.idNumber)}>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
{canViewSensitive ? (
|
||||
<a onClick={() => onViewSensitive('身份证号', student.idNumber)}>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
) : null}
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
@@ -438,9 +456,11 @@ const InlineArchiveSummary: React.FC<{
|
||||
{student.emergencyPhone ? (
|
||||
<span>
|
||||
<span style={{ marginRight: 8 }}>{maskPhone(student.emergencyPhone)}</span>
|
||||
<a onClick={() => onViewSensitive('紧急联系人电话', student.emergencyPhone || '')}>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
{canViewSensitive ? (
|
||||
<a onClick={() => onViewSensitive('紧急联系人电话', student.emergencyPhone || '')}>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</a>
|
||||
) : null}
|
||||
</span>
|
||||
) : (
|
||||
'-'
|
||||
@@ -448,15 +468,25 @@ const InlineArchiveSummary: React.FC<{
|
||||
</EditableCell>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="所属机构">
|
||||
<EditableCell
|
||||
value={student.organizationId}
|
||||
editor="select"
|
||||
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="student:edit"
|
||||
onSave={(next) => saveStudent('organizationId', next)}
|
||||
>
|
||||
{student.organization?.name ? <Tag color="purple">{student.organization.name}</Tag> : '-'}
|
||||
</EditableCell>
|
||||
{canChooseOrganization ? (
|
||||
<EditableCell
|
||||
value={student.organizationId}
|
||||
editor="select"
|
||||
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="student:edit"
|
||||
onSave={(next) => saveStudent('organizationId', next)}
|
||||
>
|
||||
{student.organization?.name ? (
|
||||
<Tag color="purple">{student.organization.name}</Tag>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</EditableCell>
|
||||
) : student.organization?.name ? (
|
||||
<Tag color="purple">{student.organization.name}</Tag>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="负责人">
|
||||
<EditableCell
|
||||
@@ -604,6 +634,7 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
studentId,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const { hasPermission } = usePermission();
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -760,7 +791,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button
|
||||
<PermissionButton
|
||||
permission="student:edit"
|
||||
icon={<PlusOutlined />}
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
@@ -770,7 +802,7 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
添加报读记录
|
||||
</Button>
|
||||
</PermissionButton>
|
||||
<Table<EnrollmentRecord>
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
@@ -783,8 +815,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
/>
|
||||
<Modal
|
||||
title="添加报读记录"
|
||||
open={modalOpen}
|
||||
onOk={handleAdd}
|
||||
open={modalOpen && hasPermission('student:edit')}
|
||||
onOk={hasPermission('student:edit') ? handleAdd : undefined}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
@@ -827,6 +859,7 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
const ExamScoresTab: React.FC<
|
||||
TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] }
|
||||
> = ({ data, studentId, enrollments, onRefresh }) => {
|
||||
const { hasPermission } = usePermission();
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -995,7 +1028,8 @@ const ExamScoresTab: React.FC<
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button
|
||||
<PermissionButton
|
||||
permission="student:edit"
|
||||
icon={<PlusOutlined />}
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
@@ -1005,7 +1039,7 @@ const ExamScoresTab: React.FC<
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
添加考试成绩
|
||||
</Button>
|
||||
</PermissionButton>
|
||||
<Table<ExamScoreRecord>
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
@@ -1018,8 +1052,8 @@ const ExamScoresTab: React.FC<
|
||||
/>
|
||||
<Modal
|
||||
title="添加考试成绩"
|
||||
open={modalOpen}
|
||||
onOk={handleAdd}
|
||||
open={modalOpen && hasPermission('student:edit')}
|
||||
onOk={hasPermission('student:edit') ? handleAdd : undefined}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
@@ -1074,6 +1108,7 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
|
||||
studentId,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const { hasPermission } = usePermission();
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -1183,7 +1218,8 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button
|
||||
<PermissionButton
|
||||
permission="student:edit"
|
||||
icon={<PlusOutlined />}
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
@@ -1193,7 +1229,7 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
添加学情记录
|
||||
</Button>
|
||||
</PermissionButton>
|
||||
<Table<LearningRecord>
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
@@ -1206,8 +1242,8 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
|
||||
/>
|
||||
<Modal
|
||||
title="添加学情记录"
|
||||
open={modalOpen}
|
||||
onOk={handleAdd}
|
||||
open={modalOpen && hasPermission('student:edit')}
|
||||
onOk={hasPermission('student:edit') ? handleAdd : undefined}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
@@ -1250,6 +1286,7 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
|
||||
studentId,
|
||||
onRefresh,
|
||||
}) => {
|
||||
const { hasPermission } = usePermission();
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const handleDelete = async (attachmentId: number) => {
|
||||
@@ -1294,11 +1331,13 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
|
||||
>
|
||||
查看
|
||||
</Button>
|
||||
<Popconfirm title="确定归档该附件?" onConfirm={() => handleDelete(record.id)}>
|
||||
<Button size="small" danger icon={<InboxOutlined />}>
|
||||
归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
{hasPermission('student:edit') ? (
|
||||
<Popconfirm title="确定归档该附件?" onConfirm={() => handleDelete(record.id)}>
|
||||
<Button size="small" danger icon={<InboxOutlined />}>
|
||||
归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -1306,37 +1345,39 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Upload
|
||||
showUploadList={false}
|
||||
customRequest={async (options) => {
|
||||
const formData = new FormData();
|
||||
formData.append(
|
||||
'file',
|
||||
options.file instanceof File
|
||||
? options.file
|
||||
: new File([options.file as Blob], 'attachment'),
|
||||
);
|
||||
setUploading(true);
|
||||
try {
|
||||
await api.post(`/archive/${studentId}/attachments`, formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success('上传成功');
|
||||
options.onSuccess?.({});
|
||||
onRefresh();
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : '上传失败';
|
||||
message.error(msg);
|
||||
options.onError?.(e instanceof Error ? e : new Error(msg));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />} loading={uploading}>
|
||||
上传附件
|
||||
</Button>
|
||||
</Upload>
|
||||
{hasPermission('student:edit') ? (
|
||||
<Upload
|
||||
showUploadList={false}
|
||||
customRequest={async (options) => {
|
||||
const formData = new FormData();
|
||||
formData.append(
|
||||
'file',
|
||||
options.file instanceof File
|
||||
? options.file
|
||||
: new File([options.file as Blob], 'attachment'),
|
||||
);
|
||||
setUploading(true);
|
||||
try {
|
||||
await api.post(`/archive/${studentId}/attachments`, formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success('上传成功');
|
||||
options.onSuccess?.({});
|
||||
onRefresh();
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : '上传失败';
|
||||
message.error(msg);
|
||||
options.onError?.(e instanceof Error ? e : new Error(msg));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />} loading={uploading}>
|
||||
上传附件
|
||||
</Button>
|
||||
</Upload>
|
||||
) : null}
|
||||
<Table<AttachmentRecord>
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
@@ -1359,6 +1400,13 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
inDrawer,
|
||||
onClose,
|
||||
}) => {
|
||||
const { hasPermission, hasAnyPermission } = usePermission();
|
||||
const canLoadOrganizations = hasAnyPermission(
|
||||
'organization:view',
|
||||
'student:create',
|
||||
'student:edit',
|
||||
);
|
||||
const canChooseOrganization = hasAnyPermission('student:create', 'student:edit');
|
||||
const [aggregateData, setAggregateData] = useState<StudentProfileAggregate | null>(null);
|
||||
const [organizations, setOrganizations] = useState<Array<{ id: number; name: string }>>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -1381,13 +1429,17 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
}, [fetchData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!canLoadOrganizations) {
|
||||
setOrganizations([]);
|
||||
return;
|
||||
}
|
||||
api
|
||||
.get('/organizations', { params: { includeArchived: 'false' } })
|
||||
.get('/organizations/options')
|
||||
.then((res: unknown) => {
|
||||
setOrganizations(res as Array<{ id: number; name: string }>);
|
||||
setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
}, [canLoadOrganizations]);
|
||||
|
||||
const handlePreviewReport = useCallback(async () => {
|
||||
try {
|
||||
@@ -1402,7 +1454,11 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
}
|
||||
}, [studentId]);
|
||||
|
||||
const handleViewSensitive = useViewSensitive(studentId, '学生档案');
|
||||
const handleViewSensitive = useViewSensitive(
|
||||
studentId,
|
||||
'学生档案',
|
||||
hasPermission('log:create'),
|
||||
);
|
||||
|
||||
const tabItems = useMemo(() => {
|
||||
if (!aggregateData) return [];
|
||||
@@ -1470,7 +1526,8 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
<Space>
|
||||
<Button type="text" icon={<CloseOutlined />} onClick={onClose} aria-label="关闭档案" />
|
||||
<span style={{ fontSize: 16, fontWeight: 500 }}>
|
||||
学员档案 - {student.name}{student.studentNo ? ` (${student.studentNo})` : ''}
|
||||
学员档案 - {student.name}
|
||||
{student.studentNo ? ` (${student.studentNo})` : ''}
|
||||
</span>
|
||||
</Space>
|
||||
<Space>
|
||||
@@ -1507,6 +1564,8 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
organizations={organizations}
|
||||
onRefresh={fetchData}
|
||||
onViewSensitive={handleViewSensitive}
|
||||
canViewSensitive={hasPermission('log:create')}
|
||||
canChooseOrganization={canChooseOrganization}
|
||||
/>
|
||||
|
||||
<Tabs defaultActiveKey="enrollments" items={tabItems} />
|
||||
|
||||
@@ -1,31 +1,40 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { PERMISSIONS_UPDATED_EVENT, readPermissions } from '../auth/permission-store';
|
||||
import { PERMISSIONS_UPDATED_EVENT, readPermissionState } from '../auth/permission-store';
|
||||
|
||||
export function usePermission() {
|
||||
const [permissions, setPermissions] = useState<string[]>(readPermissions);
|
||||
const [state, setState] = useState(readPermissionState);
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setPermissions(readPermissions());
|
||||
const refresh = () => setState(readPermissionState());
|
||||
window.addEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
|
||||
window.addEventListener('storage', refresh);
|
||||
return () => {
|
||||
window.removeEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
|
||||
window.removeEventListener('storage', refresh);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const permissions = state.permissions;
|
||||
const permissionsReady = state.status === 'ready';
|
||||
const hasPermission = useCallback(
|
||||
(code: string): boolean => permissions.includes(code),
|
||||
[permissions],
|
||||
(code: string): boolean => permissionsReady && permissions.includes(code),
|
||||
[permissions, permissionsReady],
|
||||
);
|
||||
const hasAnyPermission = useCallback(
|
||||
(...codes: string[]): boolean => codes.some((code) => permissions.includes(code)),
|
||||
[permissions],
|
||||
(...codes: string[]): boolean =>
|
||||
permissionsReady && codes.some((code) => permissions.includes(code)),
|
||||
[permissions, permissionsReady],
|
||||
);
|
||||
const hasAllPermissions = useCallback(
|
||||
(...codes: string[]): boolean => codes.every((code) => permissions.includes(code)),
|
||||
[permissions],
|
||||
(...codes: string[]): boolean =>
|
||||
permissionsReady && codes.every((code) => permissions.includes(code)),
|
||||
[permissions, permissionsReady],
|
||||
);
|
||||
|
||||
return { permissions, hasPermission, hasAnyPermission, hasAllPermissions };
|
||||
return {
|
||||
permissions,
|
||||
permissionStatus: state.status,
|
||||
permissionsReady,
|
||||
hasPermission,
|
||||
hasAnyPermission,
|
||||
hasAllPermissions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { Modal } from 'antd';
|
||||
import api from '../api';
|
||||
import { message } from '../ui/app-message';
|
||||
@@ -9,16 +9,35 @@ import { message } from '../ui/app-message';
|
||||
*
|
||||
* @param studentId - The student whose data is being viewed
|
||||
* @param module - Audit module label (e.g. '学生管理', '学生档案')
|
||||
* @param canLog - Whether the current user has log:create; when false any
|
||||
* already-open confirm modal is destroyed.
|
||||
*/
|
||||
export function useViewSensitive(studentId: number, module: string) {
|
||||
export function useViewSensitive(studentId: number, module: string, canLog: boolean) {
|
||||
const canLogRef = useRef(canLog);
|
||||
const modalRef = useRef<ReturnType<typeof Modal.confirm> | null>(null);
|
||||
canLogRef.current = canLog;
|
||||
|
||||
useEffect(() => {
|
||||
if (!canLogRef.current && modalRef.current) {
|
||||
modalRef.current.destroy();
|
||||
modalRef.current = null;
|
||||
}
|
||||
return () => {
|
||||
modalRef.current?.destroy();
|
||||
modalRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return useCallback(
|
||||
(field: string, value: string) => {
|
||||
Modal.confirm({
|
||||
if (!canLogRef.current) return;
|
||||
modalRef.current = Modal.confirm({
|
||||
title: '查看敏感信息',
|
||||
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
|
||||
okText: '确认查看',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
if (!canLogRef.current) return;
|
||||
try {
|
||||
await api.post('/operation-logs/audit', {
|
||||
module,
|
||||
@@ -37,6 +56,9 @@ export function useViewSensitive(studentId: number, module: string) {
|
||||
okText: '关闭',
|
||||
});
|
||||
},
|
||||
afterClose: () => {
|
||||
modalRef.current = null;
|
||||
},
|
||||
});
|
||||
},
|
||||
[studentId, module],
|
||||
|
||||
@@ -31,7 +31,11 @@ import {
|
||||
} from '@ant-design/icons';
|
||||
import { usePermission } from '../hooks/usePermission';
|
||||
import api from '../api';
|
||||
import { writePermissions } from '../auth/permission-store';
|
||||
import {
|
||||
beginPermissionVerification,
|
||||
clearPermissions,
|
||||
writePermissions,
|
||||
} from '../auth/permission-store';
|
||||
import NotificationBell from '../components/NotificationBell';
|
||||
import RouteDock from '../components/RouteDock';
|
||||
import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
|
||||
@@ -82,23 +86,57 @@ const MainLayout: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
api
|
||||
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
|
||||
'/auth/profile',
|
||||
)
|
||||
.then((profile) => {
|
||||
if (cancelled) return;
|
||||
writePermissions(profile.permissions || []);
|
||||
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
|
||||
const nextUser = { ...cachedUser, ...profile };
|
||||
localStorage.setItem('user', JSON.stringify(nextUser));
|
||||
setUser(nextUser);
|
||||
})
|
||||
.catch(() => {
|
||||
// The API interceptor handles expired/invalid sessions.
|
||||
});
|
||||
let retryTimer: number | undefined;
|
||||
let verificationInFlight = false;
|
||||
|
||||
const verifyPermissions = () => {
|
||||
if (cancelled || verificationInFlight || !localStorage.getItem('token')) return;
|
||||
if (retryTimer !== undefined) {
|
||||
window.clearTimeout(retryTimer);
|
||||
retryTimer = undefined;
|
||||
}
|
||||
verificationInFlight = true;
|
||||
beginPermissionVerification();
|
||||
api
|
||||
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
|
||||
'/auth/profile',
|
||||
)
|
||||
.then((profile) => {
|
||||
if (cancelled) return;
|
||||
verificationInFlight = false;
|
||||
writePermissions(profile.permissions || []);
|
||||
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
|
||||
const nextUser = { ...cachedUser, ...profile };
|
||||
localStorage.setItem('user', JSON.stringify(nextUser));
|
||||
setUser(nextUser);
|
||||
})
|
||||
.catch(() => {
|
||||
verificationInFlight = false;
|
||||
if (cancelled || !localStorage.getItem('token')) return;
|
||||
retryTimer = window.setTimeout(verifyPermissions, 5_000);
|
||||
});
|
||||
};
|
||||
|
||||
const handleStorage = (event: StorageEvent) => {
|
||||
if (event.key !== 'token' && event.key !== 'permissions') return;
|
||||
beginPermissionVerification();
|
||||
window.location.reload();
|
||||
};
|
||||
const handleOnline = () => verifyPermissions();
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') verifyPermissions();
|
||||
};
|
||||
|
||||
verifyPermissions();
|
||||
window.addEventListener('storage', handleStorage);
|
||||
window.addEventListener('online', handleOnline);
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (retryTimer !== undefined) window.clearTimeout(retryTimer);
|
||||
window.removeEventListener('storage', handleStorage);
|
||||
window.removeEventListener('online', handleOnline);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -116,7 +154,7 @@ const MainLayout: React.FC = () => {
|
||||
const handleLogout = useCallback(() => {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
localStorage.removeItem('permissions');
|
||||
clearPermissions();
|
||||
navigate('/login');
|
||||
}, [navigate]);
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
Spin,
|
||||
Alert,
|
||||
Typography,
|
||||
Tooltip,
|
||||
Space,
|
||||
} from 'antd';
|
||||
import {
|
||||
@@ -442,27 +441,16 @@ const AiConfigPage: React.FC = () => {
|
||||
|
||||
{/* Actions */}
|
||||
<div className={styles.actions}>
|
||||
<Tooltip title={!canWrite ? '当前角色无写入权限' : undefined}>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<SaveOutlined />}
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
disabled={!canWrite}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Button type="primary" icon={<SaveOutlined />} onClick={handleSave} loading={saving}>
|
||||
保存配置
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip title={!canTest ? '当前角色无测试权限' : undefined}>
|
||||
<Button
|
||||
icon={<ApiOutlined />}
|
||||
onClick={handleTest}
|
||||
loading={testing}
|
||||
disabled={!canTest}
|
||||
>
|
||||
) : null}
|
||||
{canTest ? (
|
||||
<Button icon={<ApiOutlined />} onClick={handleTest} loading={testing}>
|
||||
测试连接
|
||||
</Button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type LessonAttendanceFilter,
|
||||
} from './attendance-workspace';
|
||||
import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
interface LessonAttendanceSession {
|
||||
id: number;
|
||||
@@ -76,6 +77,8 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
||||
className,
|
||||
onClose,
|
||||
}) => {
|
||||
const { hasAnyPermission } = usePermission();
|
||||
const canEditAttendance = hasAnyPermission('attendance:edit', 'attendance:self-edit');
|
||||
const [loadedSchedule, setLoadedSchedule] = useState<LessonAttendanceSchedule | null>(null);
|
||||
const [session, setSession] = useState<LessonAttendanceSession | null>(null);
|
||||
const [records, setRecords] = useState<LessonAttendanceRecord[]>([]);
|
||||
@@ -215,6 +218,7 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
|
||||
dataIndex: 'status',
|
||||
width: 230,
|
||||
render: (value: string, record) => {
|
||||
if (!canEditAttendance) return <AttendanceStatus status={value} />;
|
||||
const checkedIn = value === 'present' || value === 'late';
|
||||
return (
|
||||
<div className="attendance-marking-actions">
|
||||
|
||||
@@ -240,13 +240,13 @@ const AttendancePage: React.FC = () => {
|
||||
const experience = getAttendanceExperience(permissions, roles);
|
||||
|
||||
if (experience === 'teacher') {
|
||||
return <TeacherAttendanceWorkspace />;
|
||||
return <TeacherAttendanceWorkspace canCreate={hasPermission('attendance:create')} />;
|
||||
}
|
||||
|
||||
return <AdminAttendanceArchive canEdit={hasPermission('attendance:edit')} />;
|
||||
};
|
||||
|
||||
const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
const TeacherAttendanceWorkspace: React.FC<{ canCreate: boolean }> = ({ canCreate }) => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [workspace, setWorkspace] = useState<TeacherWorkspaceData | null>(null);
|
||||
const [selectedSchedule, setSelectedSchedule] = useState<TodaySchedule | null>(null);
|
||||
@@ -355,7 +355,7 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
phase={phase}
|
||||
className={classNameById.get(schedule.classId) || `班级 ${schedule.classId}`}
|
||||
index={index + 1}
|
||||
onOpen={() => openAttendance(schedule)}
|
||||
onOpen={canCreate ? () => openAttendance(schedule) : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -363,15 +363,17 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
)}
|
||||
</Spin>
|
||||
|
||||
<LessonAttendanceDetail
|
||||
schedule={selectedSchedule}
|
||||
className={
|
||||
selectedSchedule
|
||||
? classNameById.get(selectedSchedule.classId) || `班级 ${selectedSchedule.classId}`
|
||||
: ''
|
||||
}
|
||||
onClose={() => setSelectedSchedule(null)}
|
||||
/>
|
||||
{canCreate ? (
|
||||
<LessonAttendanceDetail
|
||||
schedule={selectedSchedule}
|
||||
className={
|
||||
selectedSchedule
|
||||
? classNameById.get(selectedSchedule.classId) || `班级 ${selectedSchedule.classId}`
|
||||
: ''
|
||||
}
|
||||
onClose={() => setSelectedSchedule(null)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -381,7 +383,7 @@ const LessonCard: React.FC<{
|
||||
phase: SchedulePhase;
|
||||
className: string;
|
||||
index: number;
|
||||
onOpen: () => void;
|
||||
onOpen?: () => void;
|
||||
}> = ({ schedule, phase, className, index, onOpen }) => {
|
||||
const phaseMeta = {
|
||||
upcoming: { label: '待上课', icon: <ClockCircleOutlined />, tone: 'upcoming' },
|
||||
@@ -412,11 +414,11 @@ const LessonCard: React.FC<{
|
||||
<Tooltip title="课程尚未开始">
|
||||
<Button disabled>等待上课</Button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
) : onOpen ? (
|
||||
<Button type="primary" onClick={onOpen}>
|
||||
{phase === 'ongoing' ? '查看当前考勤' : '拉取 / 查看考勤'} <ArrowRightOutlined />
|
||||
</Button>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
@@ -1144,9 +1146,9 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
|
||||
value={studentSearch}
|
||||
onChange={(event) => setStudentSearch(event.target.value)}
|
||||
/>
|
||||
<Button icon={<ExportOutlined />} onClick={handleExport}>
|
||||
<PermissionButton permission="attendance:export" icon={<ExportOutlined />} onClick={handleExport}>
|
||||
导出
|
||||
</Button>
|
||||
</PermissionButton>
|
||||
</div>
|
||||
</header>
|
||||
<div className="student-legend">
|
||||
|
||||
@@ -37,7 +37,7 @@ export const unavailableDatesCacheKey = (classroomId: number, date: Dayjs) =>
|
||||
`${classroomId}:${date.format('YYYY-MM')}`;
|
||||
|
||||
const ClassroomRentalsPage: React.FC = () => {
|
||||
const { hasAnyPermission } = usePermission();
|
||||
const { hasPermission, hasAnyPermission } = usePermission();
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [classrooms, setClassrooms] = useState<any[]>([]);
|
||||
const [organizations, setOrganizations] = useState<any[]>([]);
|
||||
@@ -446,11 +446,13 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
下载
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
|
||||
<Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" />
|
||||
</Popconfirm>
|
||||
{hasPermission('rental:edit') ? (
|
||||
<Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
|
||||
<Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" />
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</Space>
|
||||
) : (
|
||||
) : hasPermission('rental:edit') ? (
|
||||
<Upload
|
||||
accept="application/pdf"
|
||||
showUploadList={false}
|
||||
@@ -479,6 +481,8 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
上传PDF
|
||||
</Button>
|
||||
</Upload>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -538,7 +542,7 @@ const ClassroomRentalsPage: React.FC = () => {
|
||||
),
|
||||
},
|
||||
],
|
||||
[classrooms, organizations],
|
||||
[classrooms, organizations, hasPermission],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -25,6 +25,7 @@ import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '可用', color: 'green' },
|
||||
@@ -48,6 +49,7 @@ const typeColor: Record<string, string> = {
|
||||
};
|
||||
|
||||
const ClassroomsPage: React.FC = () => {
|
||||
const { hasPermission } = usePermission();
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
@@ -402,27 +404,29 @@ const ClassroomsPage: React.FC = () => {
|
||||
>
|
||||
导出报表
|
||||
</PermissionButton>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const res: any = await api.post('/classrooms/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success(res.message);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
{hasPermission('classroom:create') ? (
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const res: any = await api.post('/classrooms/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success(res.message);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="classroom:view"
|
||||
icon={<DownloadOutlined />}
|
||||
|
||||
@@ -8,6 +8,7 @@ import EditableCell from '../../components/EditableCell';
|
||||
import { useViewSensitive } from '../../hooks/useViewSensitive';
|
||||
import { maskPhone } from '../../utils/sensitive';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
import type { ExamItem } from './types';
|
||||
import './style.css';
|
||||
|
||||
@@ -21,12 +22,29 @@ interface ScoreRow {
|
||||
rank: number | null;
|
||||
}
|
||||
|
||||
interface ExamDetail extends ExamItem { scores: ScoreRow[] }
|
||||
interface ExamDetail extends ExamItem {
|
||||
scores: ScoreRow[];
|
||||
}
|
||||
|
||||
const PhoneCell: React.FC<{ row: ScoreRow }> = ({ row }) => {
|
||||
const reveal = useViewSensitive(row.studentId, '考试管理');
|
||||
const { hasPermission } = usePermission();
|
||||
const reveal = useViewSensitive(row.studentId, '考试管理', hasPermission('log:create'));
|
||||
if (!row.phone) return <>-</>;
|
||||
return <Space size={4}><span>{maskPhone(row.phone)}</span><Tooltip title="查看完整手机号"><Button type="text" size="small" icon={<EyeOutlined />} onClick={() => reveal('手机号', row.phone)} /></Tooltip></Space>;
|
||||
return (
|
||||
<Space size={4}>
|
||||
<span>{maskPhone(row.phone)}</span>
|
||||
{hasPermission('log:create') ? (
|
||||
<Tooltip title="查看完整手机号">
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<EyeOutlined />}
|
||||
onClick={() => reveal('手机号', row.phone)}
|
||||
/>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</Space>
|
||||
);
|
||||
};
|
||||
|
||||
const ExamDetailPage: React.FC = () => {
|
||||
@@ -37,12 +55,18 @@ const ExamDetailPage: React.FC = () => {
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try { setDetail(await api.get<ExamDetail>(`/exams/${id}`)); }
|
||||
catch (error) { message.error((error as { message?: string })?.message || '加载考试失败'); }
|
||||
finally { setLoading(false); }
|
||||
try {
|
||||
setDetail(await api.get<ExamDetail>(`/exams/${id}`));
|
||||
} catch (error) {
|
||||
message.error((error as { message?: string })?.message || '加载考试失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const saveScore = async (row: ScoreRow, value: number | undefined) => {
|
||||
await api.put(`/exams/${id}/scores/${row.id}`, { score: value ?? null });
|
||||
message.success('成绩已保存');
|
||||
@@ -52,7 +76,11 @@ const ExamDetailPage: React.FC = () => {
|
||||
const columns = useMemo<ColumnsType<ScoreRow>>(() => {
|
||||
if (!detail) return [];
|
||||
const fixed = [
|
||||
{ title: '手机号*', width: 155, render: (_: unknown, row: ScoreRow) => <PhoneCell row={row} /> },
|
||||
{
|
||||
title: '手机号*',
|
||||
width: 155,
|
||||
render: (_: unknown, row: ScoreRow) => <PhoneCell row={row} />,
|
||||
},
|
||||
{ title: '姓名', dataIndex: 'name', width: 100 },
|
||||
{ title: '考试类型*', width: 110, render: () => detail.examType },
|
||||
{ title: '考试名称', width: 170, render: () => detail.examName },
|
||||
@@ -60,32 +88,84 @@ const ExamDetailPage: React.FC = () => {
|
||||
];
|
||||
return [
|
||||
...fixed,
|
||||
{ title: '成绩*', dataIndex: 'score', width: 100, render: (value: number | null, row: ScoreRow) => <EditableCell<number | undefined> value={value ?? undefined} editor="money" min={0} max={999.99} permission="exam:view" onSave={(next) => saveScore(row, next)}>{value ?? '-'}</EditableCell> },
|
||||
{ title: '班级均分', dataIndex: 'classAvg', width: 110, render: (value: number | null) => value ?? '-' },
|
||||
{ title: '排名', dataIndex: 'rank', width: 80, render: (value: number | null) => value ?? '-' },
|
||||
{
|
||||
title: '成绩*',
|
||||
dataIndex: 'score',
|
||||
width: 100,
|
||||
render: (value: number | null, row: ScoreRow) => (
|
||||
<EditableCell<number | undefined>
|
||||
value={value ?? undefined}
|
||||
editor="money"
|
||||
min={0}
|
||||
max={999.99}
|
||||
permission="exam:view"
|
||||
onSave={(next) => saveScore(row, next)}
|
||||
>
|
||||
{value ?? '-'}
|
||||
</EditableCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '班级均分',
|
||||
dataIndex: 'classAvg',
|
||||
width: 110,
|
||||
render: (value: number | null) => value ?? '-',
|
||||
},
|
||||
{
|
||||
title: '排名',
|
||||
dataIndex: 'rank',
|
||||
width: 80,
|
||||
render: (value: number | null) => value ?? '-',
|
||||
},
|
||||
{ title: '考试日期', width: 110, render: () => detail.examDate },
|
||||
{ title: '关联报读(班级名)', width: 180, render: () => detail.className },
|
||||
];
|
||||
}, [detail]);
|
||||
|
||||
if (loading && !detail) return <div className="exam-detail-loading"><Spin size="large" /></div>;
|
||||
if (loading && !detail)
|
||||
return (
|
||||
<div className="exam-detail-loading">
|
||||
<Spin size="large" />
|
||||
</div>
|
||||
);
|
||||
if (!detail) return <Empty description="考试不存在或无权访问" />;
|
||||
|
||||
const average = detail.scores.find((row) => row.classAvg !== null)?.classAvg ?? null;
|
||||
return (
|
||||
<div className="exam-detail-page">
|
||||
<div className="exam-detail-header"><Space><Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/exams')}>返回</Button><h2>{detail.examName}</h2></Space></div>
|
||||
<div className="exam-detail-header">
|
||||
<Space>
|
||||
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/exams')}>
|
||||
返回
|
||||
</Button>
|
||||
<h2>{detail.examName}</h2>
|
||||
</Space>
|
||||
</div>
|
||||
<Card className="exam-summary">
|
||||
<Descriptions column={{ xs: 1, sm: 2, lg: 5 }}>
|
||||
<Descriptions.Item label="考试类型">{detail.examType}</Descriptions.Item>
|
||||
<Descriptions.Item label="科目">{detail.subject}</Descriptions.Item>
|
||||
<Descriptions.Item label="考试班级">{detail.className}</Descriptions.Item>
|
||||
<Descriptions.Item label="考试日期">{detail.examDate}</Descriptions.Item>
|
||||
<Descriptions.Item label="录入进度">{detail.enteredScores}/{detail.totalStudents},均分 {average ?? '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="录入进度">
|
||||
{detail.enteredScores}/{detail.totalStudents},均分 {average ?? '-'}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
</Card>
|
||||
<Card title="成绩表">
|
||||
<Table<ScoreRow> columns={columns} dataSource={detail.scores} rowKey="id" loading={loading} scroll={{ x: 1310 }} pagination={{ defaultPageSize: 30, showSizeChanger: true, pageSizeOptions: [30, 50, 100] }} locale={{ emptyText: <Empty description="暂无学生名单" /> }} />
|
||||
<Table<ScoreRow>
|
||||
columns={columns}
|
||||
dataSource={detail.scores}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
scroll={{ x: 1310 }}
|
||||
pagination={{
|
||||
defaultPageSize: 30,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [30, 50, 100],
|
||||
}}
|
||||
locale={{ emptyText: <Empty description="暂无学生名单" /> }}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -29,6 +29,7 @@ import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
@@ -38,6 +39,7 @@ const isFormValidationError = (error: unknown) =>
|
||||
Array.isArray((error as { errorFields?: unknown }).errorFields);
|
||||
|
||||
const ExpensesPage: React.FC = () => {
|
||||
const { hasPermission } = usePermission();
|
||||
const [roomExpenses, setRoomExpenses] = useState<any[]>([]);
|
||||
const [personalExpenses, setPersonalExpenses] = useState<any[]>([]);
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
@@ -574,33 +576,35 @@ const ExpensesPage: React.FC = () => {
|
||||
onChange={(v) => setRoomTypeFilter(v)}
|
||||
options={typeOptions}
|
||||
/>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const res: any = await api.post('/expenses/utility/import', formData);
|
||||
if (res.errors?.length > 0) {
|
||||
Modal.warning({
|
||||
title: res.message,
|
||||
content: res.errors.join('\n'),
|
||||
width: 500,
|
||||
});
|
||||
} else {
|
||||
message.success(res.message);
|
||||
{hasPermission('expense:create') ? (
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const res: any = await api.post('/expenses/utility/import', formData);
|
||||
if (res.errors?.length > 0) {
|
||||
Modal.warning({
|
||||
title: res.message,
|
||||
content: res.errors.join('\n'),
|
||||
width: 500,
|
||||
});
|
||||
} else {
|
||||
message.success(res.message);
|
||||
}
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入水电费Excel</Button>
|
||||
</Upload>
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入水电费Excel</Button>
|
||||
</Upload>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="expense:view"
|
||||
icon={<DownloadOutlined />}
|
||||
@@ -697,27 +701,29 @@ const ExpensesPage: React.FC = () => {
|
||||
onChange={(v) => setPersonalTypeFilter(v)}
|
||||
options={personalTypeOptions}
|
||||
/>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const res: any = await api.post('/expenses/personal/import', formData);
|
||||
message.success(res.message || '导入完成');
|
||||
if (res.errors?.length)
|
||||
res.errors.forEach((e: string) => message.warning(e));
|
||||
fetchData();
|
||||
onSuccess?.(res);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入个人附加费</Button>
|
||||
</Upload>
|
||||
{hasPermission('expense:create') ? (
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const res: any = await api.post('/expenses/personal/import', formData);
|
||||
message.success(res.message || '导入完成');
|
||||
if (res.errors?.length)
|
||||
res.errors.forEach((e: string) => message.warning(e));
|
||||
fetchData();
|
||||
onSuccess?.(res);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入个人附加费</Button>
|
||||
</Upload>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="expense:view"
|
||||
icon={<DownloadOutlined />}
|
||||
|
||||
@@ -111,7 +111,8 @@ interface DeleteAttendanceGroupsResponse {
|
||||
}
|
||||
|
||||
const IntegrationConfigPage: React.FC = () => {
|
||||
const { hasAllPermissions } = usePermission();
|
||||
const { hasPermission, hasAllPermissions } = usePermission();
|
||||
const canCreateClass = hasPermission('class:create');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState(false);
|
||||
@@ -458,12 +459,14 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
>
|
||||
加入选中的班级
|
||||
</Button>
|
||||
<Button
|
||||
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
|
||||
onClick={() => setClassModalOpen(true)}
|
||||
>
|
||||
创建班级
|
||||
</Button>
|
||||
{canCreateClass ? (
|
||||
<Button
|
||||
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
|
||||
onClick={() => setClassModalOpen(true)}
|
||||
>
|
||||
创建班级
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
@@ -485,9 +488,11 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
title="班级列表"
|
||||
size="small"
|
||||
extra={
|
||||
<Button size="small" onClick={() => setClassModalOpen(true)}>
|
||||
+ 创建班级
|
||||
</Button>
|
||||
canCreateClass ? (
|
||||
<Button size="small" onClick={() => setClassModalOpen(true)}>
|
||||
+ 创建班级
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
<List
|
||||
@@ -514,45 +519,47 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
</Row>
|
||||
|
||||
{/* Create class Modal */}
|
||||
<Modal
|
||||
title="创建班级"
|
||||
open={classModalOpen}
|
||||
onOk={handleCreateClass}
|
||||
onCancel={() => {
|
||||
setClassModalOpen(false);
|
||||
classForm.resetFields();
|
||||
}}
|
||||
confirmLoading={importing}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={classForm} layout="vertical">
|
||||
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
|
||||
<Input placeholder="如 CS2024-01" />
|
||||
</Form.Item>
|
||||
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'culture', label: '文化课' },
|
||||
{ value: 'professional', label: '专业课' },
|
||||
{ value: 'bootcamp', label: '集训营' },
|
||||
{ value: 'sprint', label: '冲刺班' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="startDate" label="开班日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="endDate" label="结束日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
{canCreateClass ? (
|
||||
<Modal
|
||||
title="创建班级"
|
||||
open={classModalOpen}
|
||||
onOk={handleCreateClass}
|
||||
onCancel={() => {
|
||||
setClassModalOpen(false);
|
||||
classForm.resetFields();
|
||||
}}
|
||||
confirmLoading={importing}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={classForm} layout="vertical">
|
||||
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
|
||||
<Input placeholder="如 CS2024-01" />
|
||||
</Form.Item>
|
||||
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'culture', label: '文化课' },
|
||||
{ value: 'professional', label: '专业课' },
|
||||
{ value: 'bootcamp', label: '集训营' },
|
||||
{ value: 'sprint', label: '冲刺班' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="startDate" label="开班日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="endDate" label="结束日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
) : null}
|
||||
</Drawer>
|
||||
)}
|
||||
<Modal
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Form, Input, Button, Card, Typography } from 'antd';
|
||||
import { UserOutlined, LockOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { writePermissions } from '../../auth/permission-store';
|
||||
import { clearPermissions, writePermissions } from '../../auth/permission-store';
|
||||
import { findRoleAwareLandingPath } from '../../auth/menu-policy';
|
||||
|
||||
const { Title } = Typography;
|
||||
@@ -15,6 +15,7 @@ const LoginPage: React.FC = () => {
|
||||
|
||||
const onFinish = useCallback(
|
||||
async (values: any) => {
|
||||
clearPermissions();
|
||||
setLoading(true);
|
||||
try {
|
||||
const res: any = await api.post('/auth/login', values);
|
||||
@@ -66,11 +67,7 @@ const LoginPage: React.FC = () => {
|
||||
name="username"
|
||||
rules={[{ required: true, message: '请输入用户名' }]}
|
||||
>
|
||||
<Input
|
||||
prefix={<UserOutlined />}
|
||||
placeholder="用户名"
|
||||
autoComplete="username"
|
||||
/>
|
||||
<Input prefix={<UserOutlined />} placeholder="用户名" autoComplete="username" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
label="密码"
|
||||
|
||||
@@ -33,10 +33,16 @@ import { maskPhone, maskIdNumber } from '../../utils/sensitive';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const OccupanciesPage: React.FC = () => {
|
||||
const { hasPermission, permissionsReady } = usePermission();
|
||||
const canCheckIn = permissionsReady && hasPermission('occupancy:checkin');
|
||||
const canCheckOut = permissionsReady && hasPermission('occupancy:checkout');
|
||||
const canTransfer = permissionsReady && hasPermission('occupancy:transfer');
|
||||
const canDelete = permissionsReady && hasPermission('occupancy:delete');
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [students, setStudents] = useState<any[]>([]);
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
@@ -66,6 +72,12 @@ const OccupanciesPage: React.FC = () => {
|
||||
const selectedCheckInRoomId = Form.useWatch('roomId', checkInForm);
|
||||
const selectedTransferRoomId = Form.useWatch('newRoomId', transferForm);
|
||||
|
||||
// Close modals when the user loses the required permission
|
||||
useEffect(() => { if (!canCheckIn) { setCheckInModal(false); checkInForm.resetFields(); } }, [canCheckIn, checkInForm]);
|
||||
useEffect(() => { if (!canCheckOut && checkOutModal) { setCheckOutModal(null); checkOutForm.resetFields(); } }, [canCheckOut, checkOutModal, checkOutForm]);
|
||||
useEffect(() => { if (!canCheckOut) { setBatchCheckOutModal(false); batchCheckOutForm.resetFields(); } }, [canCheckOut, batchCheckOutForm]);
|
||||
useEffect(() => { if (!canTransfer && transferModal) { setTransferModal(null); transferForm.resetFields(); } }, [canTransfer, transferModal, transferForm]);
|
||||
|
||||
const activeOccupancyByStudentId = useMemo(() => {
|
||||
const map = new Map<number, any>();
|
||||
data.forEach((item) => {
|
||||
@@ -93,7 +105,12 @@ const OccupanciesPage: React.FC = () => {
|
||||
[data, selectedRowKeys],
|
||||
);
|
||||
const latestSelectedCheckInDate = useMemo(
|
||||
() => selectedBatchRecords.map((item) => item.checkInDate).filter(Boolean).sort().at(-1),
|
||||
() =>
|
||||
selectedBatchRecords
|
||||
.map((item) => item.checkInDate)
|
||||
.filter(Boolean)
|
||||
.sort()
|
||||
.at(-1),
|
||||
[selectedBatchRecords],
|
||||
);
|
||||
const latestSelectedBillingStartDate = useMemo(
|
||||
@@ -106,7 +123,8 @@ const OccupanciesPage: React.FC = () => {
|
||||
[selectedBatchRecords],
|
||||
);
|
||||
|
||||
const dateNotBefore = (start: string | Dayjs | null | undefined, messageText: string) =>
|
||||
const dateNotBefore =
|
||||
(start: string | Dayjs | null | undefined, messageText: string) =>
|
||||
(_: unknown, value?: Dayjs | null) => {
|
||||
if (!value || !start) return Promise.resolve();
|
||||
const startDate = dayjs.isDayjs(start) ? start : dayjs(start);
|
||||
@@ -363,27 +381,28 @@ const OccupanciesPage: React.FC = () => {
|
||||
) : (
|
||||
<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 />}
|
||||
{canDelete ? (
|
||||
<Popconfirm
|
||||
title="确定归档此记录?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/occupancies/${record.id}`);
|
||||
message.success('归档成功');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '归档失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<Button
|
||||
size="small"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -457,46 +476,77 @@ const OccupanciesPage: React.FC = () => {
|
||||
>
|
||||
入住登记
|
||||
</PermissionButton>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const params = new URLSearchParams();
|
||||
if (autoDeposit) {
|
||||
params.set('autoDeposit', 'true');
|
||||
params.set('depositAmount', String(depositAmount));
|
||||
}
|
||||
try {
|
||||
const res: any = await api.post(
|
||||
`/occupancies/import?${params.toString()}`,
|
||||
formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } },
|
||||
);
|
||||
if (res.errors?.length > 0) {
|
||||
Modal.warning({
|
||||
title: res.message,
|
||||
content: res.errors.join('\n'),
|
||||
width: 500,
|
||||
});
|
||||
} else {
|
||||
message.success(res.message);
|
||||
}
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
|
||||
<Button type="primary" ghost icon={<UploadOutlined />}>
|
||||
导入入住名单
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Upload>
|
||||
{canCheckIn ? (
|
||||
<>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const params = new URLSearchParams();
|
||||
if (autoDeposit) {
|
||||
params.set('autoDeposit', 'true');
|
||||
params.set('depositAmount', String(depositAmount));
|
||||
}
|
||||
try {
|
||||
const res: any = await api.post(
|
||||
`/occupancies/import?${params.toString()}`,
|
||||
formData,
|
||||
{ headers: { 'Content-Type': 'multipart/form-data' } },
|
||||
);
|
||||
if (res.errors?.length > 0) {
|
||||
Modal.warning({
|
||||
title: res.message,
|
||||
content: res.errors.join('\n'),
|
||||
width: 500,
|
||||
});
|
||||
} else {
|
||||
message.success(res.message);
|
||||
}
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
|
||||
<Button type="primary" ghost icon={<UploadOutlined />}>
|
||||
导入入住名单
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Upload>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
|
||||
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
|
||||
导入时自动收押金
|
||||
{autoDeposit && (
|
||||
<Space.Compact>
|
||||
<InputNumber
|
||||
size="small"
|
||||
min={0}
|
||||
value={depositAmount}
|
||||
onChange={(v) => setDepositAmount(v || 500)}
|
||||
style={{ width: 60 }}
|
||||
/>
|
||||
<span
|
||||
style={{
|
||||
padding: '0 8px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
border: '1px solid #d9d9d9',
|
||||
backgroundColor: '#fafafa',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
元
|
||||
</span>
|
||||
</Space.Compact>
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="occupancy:view"
|
||||
icon={<DownloadOutlined />}
|
||||
@@ -521,33 +571,6 @@ const OccupanciesPage: React.FC = () => {
|
||||
>
|
||||
导出记录
|
||||
</PermissionButton>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
|
||||
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
|
||||
导入时自动收押金
|
||||
{autoDeposit && (
|
||||
<Space.Compact>
|
||||
<InputNumber
|
||||
size="small"
|
||||
min={0}
|
||||
value={depositAmount}
|
||||
onChange={(v) => setDepositAmount(v || 500)}
|
||||
style={{ width: 60 }}
|
||||
/>
|
||||
<span
|
||||
style={{
|
||||
padding: '0 8px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
border: '1px solid #d9d9d9',
|
||||
backgroundColor: '#fafafa',
|
||||
fontSize: 12,
|
||||
}}
|
||||
>
|
||||
元
|
||||
</span>
|
||||
</Space.Compact>
|
||||
)}
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
{selectedRowKeys.length > 0 && (
|
||||
@@ -572,23 +595,24 @@ const OccupanciesPage: React.FC = () => {
|
||||
批量退宿
|
||||
</PermissionButton>
|
||||
) : (
|
||||
<Popconfirm
|
||||
title={`确定归档选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`}
|
||||
onConfirm={handleBatchDelete}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton
|
||||
permission="occupancy:delete"
|
||||
danger
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
style={{ marginLeft: 12 }}
|
||||
loading={batchLoading}
|
||||
canDelete ? (
|
||||
<Popconfirm
|
||||
title={`确定归档选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`}
|
||||
onConfirm={handleBatchDelete}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
批量归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
style={{ marginLeft: 12 }}
|
||||
loading={batchLoading}
|
||||
>
|
||||
批量归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null
|
||||
)}
|
||||
<Button size="small" onClick={() => setSelectedRowKeys([])} style={{ marginLeft: 8 }}>
|
||||
取消选择
|
||||
@@ -616,8 +640,8 @@ const OccupanciesPage: React.FC = () => {
|
||||
/>
|
||||
<Modal
|
||||
title="入住登记"
|
||||
open={checkInModal}
|
||||
onOk={handleCheckIn}
|
||||
open={checkInModal && canCheckIn}
|
||||
onOk={canCheckIn ? handleCheckIn : undefined}
|
||||
onCancel={() => {
|
||||
setCheckInModal(false);
|
||||
setAvailableBeds([]);
|
||||
@@ -642,7 +666,11 @@ const OccupanciesPage: React.FC = () => {
|
||||
.filter((s: any) => s.status === 'active')
|
||||
.map((s: any) => {
|
||||
const activeOccupancy = activeOccupancyByStudentId.get(s.id);
|
||||
const identifier = s.idNumber ? maskIdNumber(s.idNumber) : s.phone ? maskPhone(s.phone) : '';
|
||||
const identifier = s.idNumber
|
||||
? maskIdNumber(s.idNumber)
|
||||
: s.phone
|
||||
? maskPhone(s.phone)
|
||||
: '';
|
||||
return {
|
||||
value: s.id,
|
||||
label: `${s.name} (${identifier})${activeOccupancy ? ` · 已入住${activeOccupancy.room?.roomNumber ? ` ${activeOccupancy.room.roomNumber}` : ''}` : ''}`,
|
||||
@@ -668,18 +696,25 @@ const OccupanciesPage: React.FC = () => {
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true, message: '请选择入住日期' }]}>
|
||||
<Form.Item
|
||||
name="checkInDate"
|
||||
label="入住日期"
|
||||
rules={[{ required: true, message: '请选择入住日期' }]}
|
||||
>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择入住日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="billingStartDate"
|
||||
label="计费起始日"
|
||||
dependencies={["checkInDate"]}
|
||||
dependencies={['checkInDate']}
|
||||
extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)"
|
||||
rules={[
|
||||
{ required: true, message: '请选择计费起始日' },
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(getFieldValue('checkInDate'), '计费起始日不能早于入住日期'),
|
||||
validator: dateNotBefore(
|
||||
getFieldValue('checkInDate'),
|
||||
'计费起始日不能早于入住日期',
|
||||
),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
@@ -689,7 +724,11 @@ const OccupanciesPage: React.FC = () => {
|
||||
format="YYYY-MM-DD"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="stayType" label="入住类型" rules={[{ required: true, message: '请选择入住类型' }]}>
|
||||
<Form.Item
|
||||
name="stayType"
|
||||
label="入住类型"
|
||||
rules={[{ required: true, message: '请选择入住类型' }]}
|
||||
>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'short', label: '短租' },
|
||||
@@ -714,7 +753,9 @@ const OccupanciesPage: React.FC = () => {
|
||||
<Select
|
||||
placeholder={selectedCheckInRoomId ? '请选择床位' : '请先选择房间'}
|
||||
loading={availableResourcesLoading}
|
||||
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0}
|
||||
disabled={
|
||||
!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0
|
||||
}
|
||||
options={availableBeds.map((b) => ({
|
||||
value: b.id,
|
||||
label: b.bedNumber,
|
||||
@@ -732,7 +773,9 @@ const OccupanciesPage: React.FC = () => {
|
||||
allowClear
|
||||
placeholder="可选分配柜子"
|
||||
loading={availableResourcesLoading}
|
||||
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0}
|
||||
disabled={
|
||||
!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0
|
||||
}
|
||||
options={availableLockers.map((l) => ({
|
||||
value: l.id,
|
||||
label: l.lockerNumber,
|
||||
@@ -772,8 +815,8 @@ const OccupanciesPage: React.FC = () => {
|
||||
{/* 退宿弹窗 */}
|
||||
<Modal
|
||||
title={`退宿 - ${checkOutModal?.student?.name}`}
|
||||
open={!!checkOutModal}
|
||||
onOk={handleCheckOut}
|
||||
open={!!checkOutModal && canCheckOut}
|
||||
onOk={canCheckOut ? handleCheckOut : undefined}
|
||||
onCancel={() => setCheckOutModal(null)}
|
||||
okText="确认退宿"
|
||||
confirmLoading={saving}
|
||||
@@ -792,12 +835,14 @@ const OccupanciesPage: React.FC = () => {
|
||||
<Form.Item
|
||||
name="billingEndDate"
|
||||
label="计费截止日"
|
||||
dependencies={["checkOutDate"]}
|
||||
dependencies={['checkOutDate']}
|
||||
extra="默认与退宿日期相同"
|
||||
rules={[
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(
|
||||
checkOutModal?.billingStartDate || checkOutModal?.checkInDate || getFieldValue('checkOutDate'),
|
||||
checkOutModal?.billingStartDate ||
|
||||
checkOutModal?.checkInDate ||
|
||||
getFieldValue('checkOutDate'),
|
||||
'计费截止日不能早于计费起始日',
|
||||
),
|
||||
}),
|
||||
@@ -827,8 +872,8 @@ const OccupanciesPage: React.FC = () => {
|
||||
{/* 批量退宿弹窗 */}
|
||||
<Modal
|
||||
title={`批量退宿(${selectedRowKeys.length} 人)`}
|
||||
open={batchCheckOutModal}
|
||||
onOk={handleBatchCheckOut}
|
||||
open={batchCheckOutModal && canCheckOut}
|
||||
onOk={canCheckOut ? handleBatchCheckOut : undefined}
|
||||
onCancel={() => setBatchCheckOutModal(false)}
|
||||
okText="确认批量退宿"
|
||||
width={500}
|
||||
@@ -904,7 +949,7 @@ const OccupanciesPage: React.FC = () => {
|
||||
{/* 换房弹窗 */}
|
||||
<Modal
|
||||
title={`换房 - ${transferModal?.student?.name}`}
|
||||
open={!!transferModal}
|
||||
open={!!transferModal && canTransfer}
|
||||
onOk={handleTransfer}
|
||||
onCancel={() => {
|
||||
setTransferModal(null);
|
||||
@@ -948,7 +993,11 @@ const OccupanciesPage: React.FC = () => {
|
||||
<Select
|
||||
placeholder={selectedTransferRoomId ? '请选择目标床位' : '请先选择目标宿舍'}
|
||||
loading={transferResourcesLoading}
|
||||
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableBeds.length === 0}
|
||||
disabled={
|
||||
!selectedTransferRoomId ||
|
||||
transferResourcesLoading ||
|
||||
transferAvailableBeds.length === 0
|
||||
}
|
||||
options={transferAvailableBeds.map((bed) => ({
|
||||
value: bed.id,
|
||||
label: bed.bedNumber,
|
||||
@@ -966,7 +1015,11 @@ const OccupanciesPage: React.FC = () => {
|
||||
allowClear
|
||||
placeholder="可选分配目标宿舍柜子"
|
||||
loading={transferResourcesLoading}
|
||||
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableLockers.length === 0}
|
||||
disabled={
|
||||
!selectedTransferRoomId ||
|
||||
transferResourcesLoading ||
|
||||
transferAvailableLockers.length === 0
|
||||
}
|
||||
options={transferAvailableLockers.map((locker) => ({
|
||||
value: locker.id,
|
||||
label: locker.lockerNumber,
|
||||
@@ -979,7 +1032,9 @@ const OccupanciesPage: React.FC = () => {
|
||||
label="换房日期"
|
||||
rules={[
|
||||
{ required: true, message: '请选择换房日期' },
|
||||
{ validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期') },
|
||||
{
|
||||
validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期'),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" />
|
||||
@@ -987,12 +1042,14 @@ const OccupanciesPage: React.FC = () => {
|
||||
<Form.Item
|
||||
name="oldBillingEndDate"
|
||||
label="旧房计费截止日"
|
||||
dependencies={["transferDate"]}
|
||||
dependencies={['transferDate']}
|
||||
extra="默认为换房当天"
|
||||
rules={[
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(
|
||||
transferModal?.billingStartDate || transferModal?.checkInDate || getFieldValue('transferDate'),
|
||||
transferModal?.billingStartDate ||
|
||||
transferModal?.checkInDate ||
|
||||
getFieldValue('transferDate'),
|
||||
'旧房计费截止日不能早于计费起始日',
|
||||
),
|
||||
}),
|
||||
@@ -1007,11 +1064,14 @@ const OccupanciesPage: React.FC = () => {
|
||||
<Form.Item
|
||||
name="newBillingStartDate"
|
||||
label="新房计费起始日"
|
||||
dependencies={["transferDate"]}
|
||||
dependencies={['transferDate']}
|
||||
extra="默认为换房次日"
|
||||
rules={[
|
||||
({ getFieldValue }) => ({
|
||||
validator: dateNotBefore(getFieldValue('transferDate'), '新房计费起始日不能早于换房日期'),
|
||||
validator: dateNotBefore(
|
||||
getFieldValue('transferDate'),
|
||||
'新房计费起始日不能早于换房日期',
|
||||
),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
|
||||
@@ -464,7 +464,11 @@ const RoomVisualPage: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
{detailRoom.occupants.map((o: any) => (
|
||||
<Card key={o.occupancyId} size="small" style={{ marginBottom: 8, borderRadius: 8 }}>
|
||||
<Card
|
||||
key={o.occupancyId}
|
||||
size="small"
|
||||
style={{ marginBottom: 8, borderRadius: 8 }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
@@ -502,24 +506,25 @@ const RoomVisualPage: React.FC = () => {
|
||||
<span style={{ color: '#86868b', fontSize: 12 }}>
|
||||
{presentOccupancyIds.includes(o.occupancyId) ? '在寝' : '缺勤'}
|
||||
</span>
|
||||
<Switch
|
||||
checked={presentOccupancyIds.includes(o.occupancyId)}
|
||||
disabled={!hasPermission('room:inspect')}
|
||||
checkedChildren="在寝"
|
||||
unCheckedChildren="缺勤"
|
||||
onChange={(checked) =>
|
||||
setPresentOccupancyIds((current) =>
|
||||
togglePresentOccupancy(current, o.occupancyId, checked),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{hasPermission('room:inspect') ? (
|
||||
<Switch
|
||||
checked={presentOccupancyIds.includes(o.occupancyId)}
|
||||
checkedChildren="在寝"
|
||||
unCheckedChildren="缺勤"
|
||||
onChange={(checked) =>
|
||||
setPresentOccupancyIds((current) =>
|
||||
togglePresentOccupancy(current, o.occupancyId, checked),
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</Space>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ color: '#86868b', fontSize: 12, marginTop: 4 }}>
|
||||
<CalendarOutlined style={{ marginRight: 4 }} />
|
||||
床位:{o.bedNumber || '未分配'} |{' '}
|
||||
入住:{o.checkInDate} | 计费起:{o.billingStartDate}
|
||||
床位:{o.bedNumber || '未分配'} | 入住:{o.checkInDate} | 计费起:
|
||||
{o.billingStartDate}
|
||||
{o.supervisor && (
|
||||
<span style={{ marginLeft: 8 }}>负责人:{o.supervisor}</span>
|
||||
)}
|
||||
|
||||
@@ -31,6 +31,7 @@ import { downloadBlob } from '../../utils/download';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
available: { text: '可入住', color: 'green' },
|
||||
@@ -84,10 +85,15 @@ function parseRoomNumber(input: string) {
|
||||
}
|
||||
|
||||
const RoomsPage: React.FC = () => {
|
||||
const { hasPermission, permissionsReady } = usePermission();
|
||||
const canEditRooms = permissionsReady && hasPermission('room:edit');
|
||||
const canCreateRooms = permissionsReady && hasPermission('room:create');
|
||||
const canDeleteRooms = permissionsReady && hasPermission('room:delete');
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const canSaveRoom = editing ? canEditRooms : canCreateRooms;
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const [archivedCount, setArchivedCount] = useState(0);
|
||||
const [searchText, setSearchText] = useState('');
|
||||
@@ -111,6 +117,9 @@ const RoomsPage: React.FC = () => {
|
||||
const [savingLocker, setSavingLocker] = useState(false);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
|
||||
// Close modals when the required permission is lost
|
||||
useEffect(() => { if (!canSaveRoom && modalOpen) { setModalOpen(false); setEditing(null); form.resetFields(); } }, [canSaveRoom, modalOpen, form]);
|
||||
|
||||
const handleBatchDelete = async () => {
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
@@ -519,16 +528,17 @@ const RoomsPage: React.FC = () => {
|
||||
return (
|
||||
<Space>
|
||||
{r.status === 'archived' ? (
|
||||
<Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
size="small"
|
||||
icon={<UndoOutlined />}
|
||||
type="link"
|
||||
>
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
canEditRooms ? (
|
||||
<Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<UndoOutlined />}
|
||||
type="link"
|
||||
>
|
||||
恢复
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
@@ -556,15 +566,16 @@ const RoomsPage: React.FC = () => {
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
|
||||
<PermissionButton
|
||||
permission="room:delete"
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
{canDeleteRooms ? (
|
||||
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
@@ -635,23 +646,24 @@ const RoomsPage: React.FC = () => {
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="room:delete"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
{canDeleteRooms ? (
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
批量归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<Button
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
批量归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="room:create"
|
||||
type="primary"
|
||||
@@ -664,33 +676,35 @@ const RoomsPage: React.FC = () => {
|
||||
>
|
||||
添加宿舍
|
||||
</PermissionButton>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async (options: UploadRequestOption<{ message?: string }>) => {
|
||||
const { file, onSuccess, onError } = options;
|
||||
if (typeof file === 'string') {
|
||||
message.error('不支持字符串文件');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const res = await api.post<{ message?: string }>('/rooms/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success(res.message || '导入成功');
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '导入失败');
|
||||
onError?.(e as UploadRequestError);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
{hasPermission('room:create') ? (
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async (options: UploadRequestOption<{ message?: string }>) => {
|
||||
const { file, onSuccess, onError } = options;
|
||||
if (typeof file === 'string') {
|
||||
message.error('不支持字符串文件');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
const res = await api.post<{ message?: string }>('/rooms/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success(res.message || '导入成功');
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '导入失败');
|
||||
onError?.(e as UploadRequestError);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="room:view"
|
||||
icon={<DownloadOutlined />}
|
||||
@@ -727,8 +741,8 @@ const RoomsPage: React.FC = () => {
|
||||
|
||||
<Modal
|
||||
title={editing ? '编辑宿舍' : '添加宿舍'}
|
||||
open={modalOpen}
|
||||
onOk={handleSave}
|
||||
open={modalOpen && canSaveRoom}
|
||||
onOk={canSaveRoom ? handleSave : undefined}
|
||||
onCancel={() => {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
@@ -854,56 +868,58 @@ const RoomsPage: React.FC = () => {
|
||||
label: `床位管理 (${beds.length})`,
|
||||
children: (
|
||||
<div>
|
||||
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
onClick={() => {
|
||||
setBedEditing(null);
|
||||
bedForm.resetFields();
|
||||
setBedModalOpen(true);
|
||||
}}
|
||||
>
|
||||
添加床位
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
|
||||
description={
|
||||
remainingBedSlots > 0 ? (
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={remainingBedSlots}
|
||||
defaultValue={defaultBatchBedCount}
|
||||
id="batch-bed-count"
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
) : (
|
||||
'如需增加床位,请先调整宿舍额定人数'
|
||||
)
|
||||
}
|
||||
onConfirm={() => {
|
||||
const input = document.getElementById(
|
||||
'batch-bed-count',
|
||||
) as HTMLInputElement;
|
||||
handleBatchBeds(
|
||||
input
|
||||
? parseInt(input.value) || defaultBatchBedCount
|
||||
: defaultBatchBedCount,
|
||||
);
|
||||
}}
|
||||
okText="生成"
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
>
|
||||
{canEditRooms ? (
|
||||
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
onClick={() => {
|
||||
setBedEditing(null);
|
||||
bedForm.resetFields();
|
||||
setBedModalOpen(true);
|
||||
}}
|
||||
>
|
||||
添加床位
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
|
||||
description={
|
||||
remainingBedSlots > 0 ? (
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={remainingBedSlots}
|
||||
defaultValue={defaultBatchBedCount}
|
||||
id="batch-bed-count"
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
) : (
|
||||
'如需增加床位,请先调整宿舍额定人数'
|
||||
)
|
||||
}
|
||||
onConfirm={() => {
|
||||
const input = document.getElementById(
|
||||
'batch-bed-count',
|
||||
) as HTMLInputElement;
|
||||
handleBatchBeds(
|
||||
input
|
||||
? parseInt(input.value) || defaultBatchBedCount
|
||||
: defaultBatchBedCount,
|
||||
);
|
||||
}}
|
||||
okText="生成"
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
>
|
||||
批量生成
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
|
||||
>
|
||||
批量生成
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
) : null}
|
||||
<Table
|
||||
dataSource={beds}
|
||||
rowKey="id"
|
||||
@@ -987,20 +1003,19 @@ const RoomsPage: React.FC = () => {
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{r.status !== 'occupied' && (
|
||||
{r.status !== 'occupied' && canEditRooms && (
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={() => handleDeleteBed(r.id)}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
<Button
|
||||
size="small"
|
||||
type="link"
|
||||
danger
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
@@ -1016,45 +1031,47 @@ const RoomsPage: React.FC = () => {
|
||||
label: `柜子管理 (${lockers.length})`,
|
||||
children: (
|
||||
<div>
|
||||
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onClick={() => {
|
||||
setLockerEditing(null);
|
||||
lockerForm.resetFields();
|
||||
setLockerModalOpen(true);
|
||||
}}
|
||||
>
|
||||
添加柜子
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="批量生成柜子"
|
||||
description={
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={20}
|
||||
defaultValue={4}
|
||||
id="batch-locker-count"
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
}
|
||||
onConfirm={() => {
|
||||
const input = document.getElementById(
|
||||
'batch-locker-count',
|
||||
) as HTMLInputElement;
|
||||
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
|
||||
}}
|
||||
okText="生成"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
|
||||
批量生成
|
||||
{canEditRooms ? (
|
||||
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlusOutlined />}
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
onClick={() => {
|
||||
setLockerEditing(null);
|
||||
lockerForm.resetFields();
|
||||
setLockerModalOpen(true);
|
||||
}}
|
||||
>
|
||||
添加柜子
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
<Popconfirm
|
||||
title="批量生成柜子"
|
||||
description={
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={20}
|
||||
defaultValue={4}
|
||||
id="batch-locker-count"
|
||||
style={{ width: 80 }}
|
||||
/>
|
||||
}
|
||||
onConfirm={() => {
|
||||
const input = document.getElementById(
|
||||
'batch-locker-count',
|
||||
) as HTMLInputElement;
|
||||
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
|
||||
}}
|
||||
okText="生成"
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
|
||||
批量生成
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
) : null}
|
||||
<Table
|
||||
dataSource={lockers}
|
||||
rowKey="id"
|
||||
@@ -1138,20 +1155,19 @@ const RoomsPage: React.FC = () => {
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{r.status !== 'occupied' && (
|
||||
{r.status !== 'occupied' && canEditRooms && (
|
||||
<Popconfirm
|
||||
title="确定归档?"
|
||||
onConfirm={() => handleDeleteLocker(r.id)}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="room:edit"
|
||||
<Button
|
||||
size="small"
|
||||
type="link"
|
||||
danger
|
||||
disabled={drawerRoom?.status === 'archived'}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
@@ -1168,8 +1184,8 @@ const RoomsPage: React.FC = () => {
|
||||
|
||||
<Modal
|
||||
title={bedEditing ? '编辑床位' : '添加床位'}
|
||||
open={bedModalOpen}
|
||||
onOk={handleSaveBed}
|
||||
open={bedModalOpen && canEditRooms}
|
||||
onOk={canEditRooms ? handleSaveBed : undefined}
|
||||
onCancel={() => {
|
||||
setBedModalOpen(false);
|
||||
setBedEditing(null);
|
||||
@@ -1198,8 +1214,8 @@ const RoomsPage: React.FC = () => {
|
||||
|
||||
<Modal
|
||||
title={lockerEditing ? '编辑柜子' : '添加柜子'}
|
||||
open={lockerModalOpen}
|
||||
onOk={handleSaveLocker}
|
||||
open={lockerModalOpen && canEditRooms}
|
||||
onOk={canEditRooms ? handleSaveLocker : undefined}
|
||||
onCancel={() => {
|
||||
setLockerModalOpen(false);
|
||||
setLockerEditing(null);
|
||||
|
||||
@@ -38,6 +38,7 @@ import EditableCell from '../../components/EditableCell';
|
||||
import JinshujuMatchModal from '../../components/JinshujuMatchModal';
|
||||
import { maskIdNumber, maskPhone } from '../../utils/sensitive';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
active: { text: '在读', color: 'green' },
|
||||
@@ -84,11 +85,24 @@ interface StudentFilterLookups {
|
||||
|
||||
const StudentsPage: React.FC = () => {
|
||||
const { modal } = App.useApp();
|
||||
const { hasPermission, hasAnyPermission, hasAllPermissions } = usePermission();
|
||||
const canViewOrganizations = hasPermission('organization:view');
|
||||
const canLoadOrganizations = hasAnyPermission(
|
||||
'organization:view',
|
||||
'student:create',
|
||||
'student:edit',
|
||||
);
|
||||
const canChooseOrganization = hasAnyPermission('student:create', 'student:edit');
|
||||
const canCreateStudent = hasPermission('student:create');
|
||||
const canEditStudent = hasPermission('student:edit');
|
||||
const canDeleteStudent = hasPermission('student:delete');
|
||||
const canSyncJinshuju = hasAllPermissions('sync:read', 'sync:trigger');
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [organizations, setOrganizations] = useState<any[]>([]);
|
||||
const [editing, setEditing] = useState<any>(null);
|
||||
const canSaveStudent = editing ? canEditStudent : canCreateStudent;
|
||||
const [searchName, setSearchName] = useState('');
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
const [filterOrganizationId, setFilterOrganizationId] = useState<number | undefined>(undefined);
|
||||
@@ -113,13 +127,40 @@ const StudentsPage: React.FC = () => {
|
||||
|
||||
const [jinshujuOpen, setJinshujuOpen] = useState(false);
|
||||
|
||||
// Sensitive info modal — command-style; destroy when log:create is lost or comp unmounts.
|
||||
// Close the student form modal when the user loses the required permission.
|
||||
useEffect(() => {
|
||||
if (!canSaveStudent && modalOpen) {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
}
|
||||
}, [canSaveStudent, modalOpen, form]);
|
||||
|
||||
// Close sensitive modal when log:create is lost (imperative ref already set above).
|
||||
const logCreateRef = React.useRef(hasPermission('log:create'));
|
||||
const sensitiveModalRef = React.useRef<ReturnType<typeof modal.confirm> | null>(null);
|
||||
logCreateRef.current = hasPermission('log:create');
|
||||
useEffect(() => {
|
||||
if (!logCreateRef.current && sensitiveModalRef.current) {
|
||||
sensitiveModalRef.current.destroy();
|
||||
sensitiveModalRef.current = null;
|
||||
}
|
||||
return () => {
|
||||
sensitiveModalRef.current?.destroy();
|
||||
sensitiveModalRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleViewSensitive = (studentId: number, field: string, value: string) => {
|
||||
modal.confirm({
|
||||
if (!logCreateRef.current) return;
|
||||
sensitiveModalRef.current = modal.confirm({
|
||||
title: '查看敏感信息',
|
||||
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
|
||||
okText: '确认查看',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
if (!logCreateRef.current) return;
|
||||
try {
|
||||
await api.post('/operation-logs/audit', {
|
||||
module: '学生管理',
|
||||
@@ -137,6 +178,9 @@ const StudentsPage: React.FC = () => {
|
||||
message.error('审计日志记录失败,请稍后重试');
|
||||
}
|
||||
},
|
||||
afterClose: () => {
|
||||
sensitiveModalRef.current = null;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -189,12 +233,26 @@ const StudentsPage: React.FC = () => {
|
||||
}, [fetchData]);
|
||||
|
||||
useEffect(() => {
|
||||
api
|
||||
.get('/organizations', { params: { includeArchived: 'false' } })
|
||||
.then((res: unknown) => {
|
||||
setOrganizations(res as Array<{ id: number; name: string }>);
|
||||
})
|
||||
.catch(() => {});
|
||||
if (!canLoadOrganizations) {
|
||||
setOrganizations([]);
|
||||
setFilterOrganizationId(undefined);
|
||||
return;
|
||||
}
|
||||
if (canViewOrganizations) {
|
||||
api
|
||||
.get('/organizations', { params: { includeArchived: 'false' } })
|
||||
.then((res: unknown) => {
|
||||
setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
|
||||
})
|
||||
.catch(() => {});
|
||||
} else {
|
||||
api
|
||||
.get('/organizations/options')
|
||||
.then((res: unknown) => {
|
||||
setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
api
|
||||
.get<StudentFilterLookups>('/students/filter-lookups')
|
||||
.then((res) => {
|
||||
@@ -202,7 +260,7 @@ const StudentsPage: React.FC = () => {
|
||||
setTeacherOptions(res.teachers || []);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
}, [canLoadOrganizations]);
|
||||
const handleSave = async () => {
|
||||
const values = await form.validateFields();
|
||||
setSaving(true);
|
||||
@@ -417,15 +475,17 @@ const StudentsPage: React.FC = () => {
|
||||
return (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</Button>
|
||||
{hasPermission('log:create') ? (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</Button>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
@@ -454,15 +514,17 @@ const StudentsPage: React.FC = () => {
|
||||
return (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskIdNumber(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</Button>
|
||||
{hasPermission('log:create') ? (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</Button>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
@@ -506,15 +568,17 @@ const StudentsPage: React.FC = () => {
|
||||
return (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</Button>
|
||||
{hasPermission('log:create') ? (
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
|
||||
</Button>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
@@ -523,28 +587,33 @@ const StudentsPage: React.FC = () => {
|
||||
title: '所属机构',
|
||||
dataIndex: 'organization',
|
||||
width: 100,
|
||||
render: (organization: { name?: string } | null, record: any) => (
|
||||
<EditableCell
|
||||
value={record.organizationId}
|
||||
editor="select"
|
||||
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
required
|
||||
onSave={(next) => saveCell(record, 'organizationId', next)}
|
||||
>
|
||||
{organization?.name ? (
|
||||
<Tag
|
||||
color="purple"
|
||||
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
|
||||
>
|
||||
{organization.name}
|
||||
</Tag>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</EditableCell>
|
||||
),
|
||||
render: (organization: { name?: string } | null, record: any) =>
|
||||
canChooseOrganization ? (
|
||||
<EditableCell
|
||||
value={record.organizationId}
|
||||
editor="select"
|
||||
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
|
||||
permission="student:edit"
|
||||
disabled={record.status === 'archived'}
|
||||
required
|
||||
onSave={(next) => saveCell(record, 'organizationId', next)}
|
||||
>
|
||||
{organization?.name ? (
|
||||
<Tag
|
||||
color="purple"
|
||||
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
|
||||
>
|
||||
{organization.name}
|
||||
</Tag>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</EditableCell>
|
||||
) : organization?.name ? (
|
||||
<Tag color="purple">{organization.name}</Tag>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '负责人',
|
||||
@@ -593,21 +662,18 @@ const StudentsPage: React.FC = () => {
|
||||
render: (_: any, record: any) => (
|
||||
<Space>
|
||||
{record.status === 'archived' ? (
|
||||
<Popconfirm
|
||||
title="确定恢复此学生?恢复后将重新出现在学生列表中。"
|
||||
onConfirm={() => handleRestore(record.id)}
|
||||
okText="恢复"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton
|
||||
permission="student:edit"
|
||||
size="small"
|
||||
icon={<UndoOutlined />}
|
||||
type="link"
|
||||
canEditStudent ? (
|
||||
<Popconfirm
|
||||
title="确定恢复此学生?恢复后将重新出现在学生列表中。"
|
||||
onConfirm={() => handleRestore(record.id)}
|
||||
okText="恢复"
|
||||
cancelText="取消"
|
||||
>
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<Button size="small" icon={<UndoOutlined />} type="link">
|
||||
恢复
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
@@ -629,27 +695,36 @@ const StudentsPage: React.FC = () => {
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="归档后不会删除数据,可随时恢复。确定归档?"
|
||||
onConfirm={() => handleArchive(record.id)}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton
|
||||
permission="student:delete"
|
||||
size="small"
|
||||
{canDeleteStudent ? (
|
||||
<Popconfirm
|
||||
title="归档后不会删除数据,可随时恢复。确定归档?"
|
||||
onConfirm={() => handleArchive(record.id)}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
],
|
||||
[handleViewSensitive, openDrawer, showArchived, organizations, saveCell],
|
||||
[
|
||||
handleViewSensitive,
|
||||
openDrawer,
|
||||
showArchived,
|
||||
organizations,
|
||||
saveCell,
|
||||
hasPermission,
|
||||
canChooseOrganization,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -679,21 +754,23 @@ const StudentsPage: React.FC = () => {
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
<Select
|
||||
placeholder="所属机构"
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
value={filterOrganizationId}
|
||||
onChange={(v) => {
|
||||
setFilterOrganizationId(v);
|
||||
}}
|
||||
>
|
||||
{organizations.map((t: { id: number; name: string }) => (
|
||||
<Select.Option key={t.id} value={t.id}>
|
||||
{t.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
{canViewOrganizations ? (
|
||||
<Select
|
||||
placeholder="所属机构"
|
||||
allowClear
|
||||
style={{ width: 140 }}
|
||||
value={filterOrganizationId}
|
||||
onChange={(v) => {
|
||||
setFilterOrganizationId(v);
|
||||
}}
|
||||
>
|
||||
{organizations.map((t: { id: number; name: string }) => (
|
||||
<Select.Option key={t.id} value={t.id}>
|
||||
{t.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
) : null}
|
||||
<Select
|
||||
placeholder="所属班级"
|
||||
allowClear
|
||||
@@ -734,23 +811,24 @@ const StudentsPage: React.FC = () => {
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="student:delete"
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
{canDeleteStudent ? (
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
okText="归档"
|
||||
cancelText="取消"
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
批量归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<Button
|
||||
danger
|
||||
icon={<InboxOutlined />}
|
||||
disabled={selectedRowKeys.length === 0}
|
||||
loading={batchLoading}
|
||||
>
|
||||
批量归档
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="student:create"
|
||||
type="primary"
|
||||
@@ -765,27 +843,29 @@ const StudentsPage: React.FC = () => {
|
||||
>
|
||||
添加学生
|
||||
</PermissionButton>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={handleCreateStudentsImport}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={handleUpdateExistingStudentsImport}
|
||||
>
|
||||
<Button icon={<SwapOutlined />}>更新已有学生资料</Button>
|
||||
</Upload>
|
||||
<PermissionButton
|
||||
permission="student:edit"
|
||||
icon={<CloudUploadOutlined />}
|
||||
onClick={() => setJinshujuOpen(true)}
|
||||
>
|
||||
同步金数据
|
||||
</PermissionButton>
|
||||
{hasPermission('student:import') ? (
|
||||
<>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={handleCreateStudentsImport}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={handleUpdateExistingStudentsImport}
|
||||
>
|
||||
<Button icon={<SwapOutlined />}>更新已有学生资料</Button>
|
||||
</Upload>
|
||||
</>
|
||||
) : null}
|
||||
{canSyncJinshuju ? (
|
||||
<Button icon={<CloudUploadOutlined />} onClick={() => setJinshujuOpen(true)}>
|
||||
同步金数据
|
||||
</Button>
|
||||
) : null}
|
||||
<PermissionButton
|
||||
permission="student:view"
|
||||
icon={<DownloadOutlined />}
|
||||
@@ -894,8 +974,8 @@ const StudentsPage: React.FC = () => {
|
||||
title={editing ? '编辑学生' : '添加学生'}
|
||||
className="student-form-modal"
|
||||
width={720}
|
||||
open={modalOpen}
|
||||
onOk={handleSave}
|
||||
open={modalOpen && canSaveStudent}
|
||||
onOk={canSaveStudent ? handleSave : undefined}
|
||||
onCancel={() => {
|
||||
setModalOpen(false);
|
||||
setEditing(null);
|
||||
@@ -934,23 +1014,27 @@ const StudentsPage: React.FC = () => {
|
||||
<Form.Item name="emergencyPhone" label="紧急联系人电话">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="organizationId"
|
||||
label="所属机构"
|
||||
rules={[{ required: true, message: '请选择所属机构' }]}
|
||||
>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="选择所属机构"
|
||||
options={organizations.map(
|
||||
(organization: { id: number; name: string; isHost?: boolean }) => ({
|
||||
value: organization.id,
|
||||
label: organization.isHost ? `${organization.name}(本机构)` : organization.name,
|
||||
}),
|
||||
)}
|
||||
/>
|
||||
</Form.Item>
|
||||
{canChooseOrganization ? (
|
||||
<Form.Item
|
||||
name="organizationId"
|
||||
label="所属机构"
|
||||
rules={[{ required: true, message: '请选择所属机构' }]}
|
||||
>
|
||||
<Select
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="选择所属机构"
|
||||
options={organizations.map(
|
||||
(organization: { id: number; name: string; isHost?: boolean }) => ({
|
||||
value: organization.id,
|
||||
label: organization.isHost
|
||||
? `${organization.name}(本机构)`
|
||||
: organization.name,
|
||||
}),
|
||||
)}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Form.Item name="supervisor" label="负责人/班主任">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
@@ -968,11 +1052,16 @@ const StudentsPage: React.FC = () => {
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<JinshujuMatchModal
|
||||
open={jinshujuOpen}
|
||||
onClose={() => setJinshujuOpen(false)}
|
||||
onApplied={() => { setJinshujuOpen(false); fetchData(); }}
|
||||
/>
|
||||
{canSyncJinshuju ? (
|
||||
<JinshujuMatchModal
|
||||
open={jinshujuOpen}
|
||||
onClose={() => setJinshujuOpen(false)}
|
||||
onApplied={() => {
|
||||
setJinshujuOpen(false);
|
||||
fetchData();
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<Drawer
|
||||
title={null}
|
||||
open={drawerOpen}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import React, { useEffect, useState, useCallback, useMemo } from 'react';
|
||||
import { Table, Input, Button, Modal, Form, Select, DatePicker, Tag, Space } from 'antd';
|
||||
import { Table, Input, Modal, Form, Select, DatePicker, Tag, Space } from 'antd';
|
||||
import { EditOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import { message } from '../../ui/app-message';
|
||||
import EditableCell from '../../components/EditableCell';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { usePermission } from '../../hooks/usePermission';
|
||||
|
||||
interface TeacherRow {
|
||||
id: number;
|
||||
@@ -50,6 +52,8 @@ const ROLE_TYPE_LABELS: Record<string, string> = {
|
||||
const DEFAULT_PAGE_SIZE = 20;
|
||||
|
||||
const TeachersPage: React.FC = () => {
|
||||
const { hasPermission } = usePermission();
|
||||
const canEditTeachers = hasPermission('teacher:edit');
|
||||
const [data, setData] = useState<TeacherRow[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [total, setTotal] = useState(0);
|
||||
@@ -190,7 +194,8 @@ const TeachersPage: React.FC = () => {
|
||||
key: 'actions',
|
||||
width: 100,
|
||||
render: (_: unknown, r: TeacherRow) => (
|
||||
<Button
|
||||
<PermissionButton
|
||||
permission="teacher:edit"
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => {
|
||||
@@ -203,11 +208,11 @@ const TeachersPage: React.FC = () => {
|
||||
}}
|
||||
>
|
||||
档案
|
||||
</Button>
|
||||
</PermissionButton>
|
||||
),
|
||||
},
|
||||
],
|
||||
[saveProfileCell],
|
||||
[saveProfileCell, form],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -263,8 +268,8 @@ const TeachersPage: React.FC = () => {
|
||||
/>
|
||||
<Modal
|
||||
title={`编辑档案 — ${profileModal?.name || ''}`}
|
||||
open={!!profileModal}
|
||||
onOk={handleSaveProfile}
|
||||
open={!!profileModal && canEditTeachers}
|
||||
onOk={canEditTeachers ? handleSaveProfile : undefined}
|
||||
onCancel={() => setProfileModal(null)}
|
||||
okText="保存"
|
||||
confirmLoading={saving}
|
||||
|
||||
26
apps/server/src/occupancies/occupancies.controller.spec.ts
Normal file
26
apps/server/src/occupancies/occupancies.controller.spec.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import 'reflect-metadata';
|
||||
import { PERMISSION_KEY } from '../auth/decorators/permission.decorator';
|
||||
import { OccupanciesController } from './occupancies.controller';
|
||||
|
||||
describe('OccupanciesController permissions', () => {
|
||||
it('requires occupancy:delete for single and batch archive actions', () => {
|
||||
expect(Reflect.getMetadata(PERMISSION_KEY, OccupanciesController.prototype.remove)).toEqual([
|
||||
'occupancy:delete',
|
||||
]);
|
||||
expect(
|
||||
Reflect.getMetadata(PERMISSION_KEY, OccupanciesController.prototype.batchRemove),
|
||||
).toEqual(['occupancy:delete']);
|
||||
});
|
||||
|
||||
it('keeps read-only endpoints on occupancy:view', () => {
|
||||
expect(Reflect.getMetadata(PERMISSION_KEY, OccupanciesController.prototype.findAll)).toEqual([
|
||||
'occupancy:view',
|
||||
]);
|
||||
expect(
|
||||
Reflect.getMetadata(PERMISSION_KEY, OccupanciesController.prototype.exportExcel),
|
||||
).toEqual(['occupancy:view']);
|
||||
expect(
|
||||
Reflect.getMetadata(PERMISSION_KEY, OccupanciesController.prototype.downloadTemplate),
|
||||
).toEqual(['occupancy:view']);
|
||||
});
|
||||
});
|
||||
@@ -159,7 +159,7 @@ export class OccupanciesController {
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('occupancy:view')
|
||||
@RequirePermission('occupancy:delete')
|
||||
async remove(@Param('id') id: string, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.remove(+id);
|
||||
@@ -177,7 +177,7 @@ export class OccupanciesController {
|
||||
}
|
||||
|
||||
@Post('batch-delete')
|
||||
@RequirePermission('occupancy:view')
|
||||
@RequirePermission('occupancy:delete')
|
||||
async batchRemove(@Body() body: { ids: number[] }, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.batchRemove(body.ids || []);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'reflect-metadata';
|
||||
import { PERMISSION_KEY } from '../auth/decorators/permission.decorator';
|
||||
import { OrganizationsController } from './organizations.controller';
|
||||
|
||||
describe('OrganizationsController permissions', () => {
|
||||
it('allows student editors to use the options endpoint without full entity exposure', () => {
|
||||
expect(
|
||||
Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findOptions),
|
||||
).toEqual(['organization:view', 'student:create', 'student:edit']);
|
||||
});
|
||||
|
||||
it('keeps the full entity list restricted to organization viewers only', () => {
|
||||
expect(Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findAll)).toEqual([
|
||||
'organization:view',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps organization detail restricted to organization viewers', () => {
|
||||
expect(Reflect.getMetadata(PERMISSION_KEY, OrganizationsController.prototype.findOne)).toEqual([
|
||||
'organization:view',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,12 @@ export class OrganizationsController {
|
||||
private logService: OperationLogsService,
|
||||
) {}
|
||||
|
||||
@Get('options')
|
||||
@RequirePermission('organization:view', 'student:create', 'student:edit')
|
||||
findOptions() {
|
||||
return this.service.findOptions();
|
||||
}
|
||||
|
||||
@Get()
|
||||
@RequirePermission('organization:view')
|
||||
findAll(
|
||||
|
||||
@@ -27,4 +27,21 @@ describe('OrganizationsService — host organization rules', () => {
|
||||
await expect(service.remove(1)).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(repo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('findOptions returns only id, name, isHost for active organizations', async () => {
|
||||
const orgs = [
|
||||
{ id: 1, name: '本机构', isHost: true },
|
||||
{ id: 2, name: '分校', isHost: false },
|
||||
];
|
||||
repo.find.mockResolvedValue(orgs as Organization[]);
|
||||
|
||||
const result = await service.findOptions();
|
||||
|
||||
expect(repo.find).toHaveBeenCalledWith({
|
||||
select: ['id', 'name', 'isHost'],
|
||||
where: { status: 'active' },
|
||||
order: { isHost: 'DESC', name: 'ASC' },
|
||||
});
|
||||
expect(result).toEqual(orgs);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -30,6 +30,14 @@ export class OrganizationsService {
|
||||
return this.repo.find({ where, order: { isHost: 'DESC', name: 'ASC' } });
|
||||
}
|
||||
|
||||
async findOptions() {
|
||||
return this.repo.find({
|
||||
select: ['id', 'name', 'isHost'] as const,
|
||||
where: { status: 'active' },
|
||||
order: { isHost: 'DESC' as const, name: 'ASC' as const },
|
||||
});
|
||||
}
|
||||
|
||||
async findOne(id: number) {
|
||||
const organization = await this.repo.findOne({ where: { id } });
|
||||
if (!organization) throw new NotFoundException('机构不存在');
|
||||
|
||||
Reference in New Issue
Block a user