Merge pull request 'fix: 权限按钮可见性与Modal/Popconfirm撤权一致性修复' (#45) from worktree-audit-permission-ui into main

This commit is contained in:
2026-07-23 06:40:18 +00:00
30 changed files with 1645 additions and 861 deletions

View File

@@ -1,4 +1,5 @@
import axios, { type AxiosRequestConfig } from 'axios'; import axios, { type AxiosRequestConfig } from 'axios';
import { clearPermissions } from '../auth/permission-store';
const instance = axios.create({ const instance = axios.create({
baseURL: '/api', baseURL: '/api',
@@ -21,7 +22,7 @@ instance.interceptors.response.use(
if (err.response?.status === 401 && !isLoginRequest) { if (err.response?.status === 401 && !isLoginRequest) {
localStorage.removeItem('token'); localStorage.removeItem('token');
localStorage.removeItem('user'); localStorage.removeItem('user');
localStorage.removeItem('permissions'); clearPermissions();
window.location.href = '/login'; window.location.href = '/login';
} }
if (err.response?.status === 403) { if (err.response?.status === 403) {

View 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('编辑学生');
});
});

View File

@@ -1,17 +1,40 @@
export const PERMISSIONS_UPDATED_EVENT = 'permissions-updated'; 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[] { export function readPermissions(): string[] {
try { return permissionState.status === 'ready' ? permissionState.permissions : [];
const value = JSON.parse(localStorage.getItem('permissions') || '[]'); }
return Array.isArray(value)
? value.filter((item): item is string => typeof item === 'string') export function beginPermissionVerification(): void {
: []; permissionState = { permissions: [], status: 'loading' };
} catch { notifyPermissionStateChanged();
return [];
}
} }
export function writePermissions(permissions: string[]): void { export function writePermissions(permissions: string[]): void {
localStorage.setItem('permissions', JSON.stringify([...new Set(permissions)])); const uniquePermissions = [...new Set(permissions)];
window.dispatchEvent(new Event(PERMISSIONS_UPDATED_EVENT)); 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();
} }

View File

@@ -1,11 +1,14 @@
import React from 'react'; import React from 'react';
import { Navigate } from 'react-router-dom'; import { Navigate } from 'react-router-dom';
import { Result } from 'antd'; import { Result, Spin } from 'antd';
import { usePermission } from '../hooks/usePermission'; import { usePermission } from '../hooks/usePermission';
import { findRoleAwareLandingPath } from '../auth/menu-policy'; import { findRoleAwareLandingPath } from '../auth/menu-policy';
const DefaultRoute: React.FC = () => { 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 = (() => { const roles = (() => {
try { try {
return JSON.parse(localStorage.getItem('user') || '{}').roles || []; return JSON.parse(localStorage.getItem('user') || '{}').roles || [];

View File

@@ -11,6 +11,8 @@ import {
} from '@ant-design/icons'; } from '@ant-design/icons';
import api from '../api'; import api from '../api';
import { message } from '../ui/app-message'; import { message } from '../ui/app-message';
import { usePermission } from '../hooks/usePermission';
import PermissionButton from './PermissionButton';
const { Text } = Typography; const { Text } = Typography;
@@ -86,7 +88,12 @@ interface MatchSelectorProps {
onChange: (d: MatchDecision) => void; 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'; const action = decision?.action ?? 'skip';
if (action === 'match') { if (action === 'match') {
@@ -94,7 +101,9 @@ const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentO
const matchedStudent = studentOptions.find((s) => s.id === matchD.matchStudentId); const matchedStudent = studentOptions.find((s) => s.id === matchD.matchStudentId);
return ( return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}> <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 }}> <Text style={{ flex: 1 }}>
{matchedStudent?.name ?? '未知'} {matchedStudent?.name ?? '未知'}
{matchedStudent?.studentNo && ( {matchedStudent?.studentNo && (
@@ -103,7 +112,9 @@ const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentO
</Text> </Text>
)} )}
</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> </div>
); );
} }
@@ -112,30 +123,76 @@ const MatchSelector: React.FC<MatchSelectorProps> = ({ entry, decision, studentO
const createD = decision as { action: 'create'; createName: string; createPhone: string }; const createD = decision as { action: 'create'; createName: string; createPhone: string };
return ( return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
<Tag color="green" icon={<PlusOutlined />}></Tag> <Tag color="green" icon={<PlusOutlined />}>
<Input size="small" value={createD.createName} placeholder="姓名" style={{ width: 100 }}
onChange={(e) => onChange({ action: 'create', createName: e.target.value, createPhone: createD.createPhone })} /> </Tag>
<Input size="small" value={createD.createPhone} placeholder="手机号" style={{ width: 120 }} <Input
onChange={(e) => onChange({ action: 'create', createName: createD.createName, createPhone: e.target.value })} /> size="small"
<Button size="small" type="link" danger onClick={() => onChange({ action: 'skip' })}></Button> 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> </div>
); );
} }
return ( return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
<Select showSearch size="small" placeholder="搜索学生…" style={{ flex: 1 }} value={undefined} <Select
filterOption={(input, option) => ((option?.label as string) || '').toLowerCase().includes(input.toLowerCase())} showSearch
size="small"
placeholder="搜索学生…"
style={{ flex: 1 }}
value={undefined}
filterOption={(input, option) =>
((option?.label as string) || '').toLowerCase().includes(input.toLowerCase())
}
options={studentOptions.map((s) => ({ options={studentOptions.map((s) => ({
value: s.id, value: s.id,
label: `${s.name}${s.phone ? ` (${s.phone})` : ''}${s.studentNo ? ` [${s.studentNo}]` : ''}`, label: `${s.name}${s.phone ? ` (${s.phone})` : ''}${s.studentNo ? ` [${s.studentNo}]` : ''}`,
}))} }))}
onChange={(studentId: number) => onChange({ action: 'match', matchStudentId: studentId })} /> 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
size="small"
type="dashed"
icon={<PlusOutlined />}
onClick={() =>
onChange({
action: 'create',
createName: entry.name || '',
createPhone: entry.phone || '',
})
}
>
</Button> </Button>
<Button size="small" type="link" onClick={() => onChange({ action: 'skip' })}></Button> <Button size="small" type="link" onClick={() => onChange({ action: 'skip' })}>
</Button>
</div> </div>
); );
}; };
@@ -151,13 +208,25 @@ interface RuleEditorProps {
onCancel: () => void; 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 [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 [saving, setSaving] = useState(false);
const handleSave = async () => { const handleSave = async () => {
if (!name.trim()) { message.warning('请输入规则名称'); return; } if (!name.trim()) {
message.warning('请输入规则名称');
return;
}
setSaving(true); setSaving(true);
try { try {
if (rule) { if (rule) {
@@ -170,18 +239,31 @@ const RuleEditor: React.FC<RuleEditorProps> = ({ rule, formToken, fields, onSave
} catch (e: unknown) { } catch (e: unknown) {
const err = e as { message?: string }; const err = e as { message?: string };
if (err?.message) message.error(err.message); if (err?.message) message.error(err.message);
} finally { setSaving(false); } } finally {
setSaving(false);
}
}; };
return ( return (
<div style={{ padding: '12px 0' }}> <div style={{ padding: '12px 0' }}>
<Input placeholder="规则名称" value={name} onChange={(e) => setName(e.target.value)} <Input
style={{ marginBottom: 12 }} /> placeholder="规则名称"
<Text type="secondary" style={{ display: 'block', marginBottom: 8 }}></Text> value={name}
onChange={(e) => setName(e.target.value)}
style={{ marginBottom: 12 }}
/>
<Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
</Text>
{STUDENT_FIELDS.map((sf) => ( {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 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 <Select
allowClear allowClear
showSearch showSearch
@@ -193,20 +275,26 @@ const RuleEditor: React.FC<RuleEditorProps> = ({ rule, formToken, fields, onSave
value: field.key, value: field.key,
label: `${field.label}${field.key}`, label: `${field.label}${field.key}`,
}))} }))}
onChange={(value) => setMappings((prev) => { onChange={(value) =>
setMappings((prev) => {
const next = { ...prev }; const next = { ...prev };
if (value) next[sf.key] = value; if (value) next[sf.key] = value;
else delete next[sf.key]; else delete next[sf.key];
return next; return next;
})} })
}
/> />
</div> </div>
))} ))}
<div style={{ marginTop: 12, display: 'flex', gap: 8 }}> <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 && ( {rule && (
<Popconfirm title="确定删除此规则?" onConfirm={() => onDelete(rule.id)}> <Popconfirm title="确定删除此规则?" onConfirm={() => onDelete(rule.id)}>
<Button danger icon={<DeleteOutlined />}></Button> <Button danger icon={<DeleteOutlined />}>
</Button>
</Popconfirm> </Popconfirm>
)} )}
<Button onClick={onCancel}></Button> <Button onClick={onCancel}></Button>
@@ -224,6 +312,9 @@ interface MatchModalProps {
} }
const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplied }) => { 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 [step, setStep] = useState<'connection' | 'rule' | 'match' | 'applying'>('connection');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>(); const [selectedRuleId, setSelectedRuleId] = useState<number | undefined>();
@@ -244,17 +335,34 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
// Load rules on open // Load rules on open
useEffect(() => { useEffect(() => {
if (open) loadRules(); if (open && canEnterModal) loadRules();
}, [open]); }, [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 () => { const loadRules = async () => {
try { try {
const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules'); const res = await api.get<{ success: boolean; data: MatchRule[] }>('/sync/jinshuju/rules');
if (res.success) setRules(res.data); if (res.success) setRules(res.data);
} catch { /* ignore */ } } catch {
/* ignore */
}
}; };
const handleConnectionNext = async () => { const handleConnectionNext = async () => {
if (!canTriggerSync) return;
try { try {
const values = await credForm.validateFields(); const values = await credForm.validateFields();
setLoading(true); setLoading(true);
@@ -274,6 +382,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
}; };
const handlePreview = async () => { const handlePreview = async () => {
if (!canTriggerSync) return;
try { try {
const values = await credForm.validateFields(); const values = await credForm.validateFields();
setLoading(true); setLoading(true);
@@ -286,7 +395,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
const initial = new Map<number, MatchDecision>(); const initial = new Map<number, MatchDecision>();
for (const entry of res.entries) { for (const entry of res.entries) {
if (entry.suggestedStudent) { 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); setDecisions(initial);
@@ -294,22 +406,29 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
} catch (e: unknown) { } catch (e: unknown) {
const err = e as { message?: string }; const err = e as { message?: string };
if (err?.message) message.error(err.message); if (err?.message) message.error(err.message);
} finally { setLoading(false); } } finally {
setLoading(false);
}
}; };
const handleApply = async () => { const handleApply = async () => {
if (!canTriggerSync) return;
setLoading(true); setLoading(true);
setStep('applying'); setStep('applying');
try { try {
const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({ serialNumber, ...d })); const decisionList = [...decisions.entries()].map(([serialNumber, d]) => ({
serialNumber,
...d,
}));
const body: Record<string, unknown> = { const body: Record<string, unknown> = {
...credForm.getFieldsValue(), ...credForm.getFieldsValue(),
decisions: decisionList, decisions: decisionList,
}; };
if (selectedRuleId) body.ruleId = selectedRuleId; if (selectedRuleId) body.ruleId = selectedRuleId;
const res = await api.post<{ success: boolean; log: { recordsCount: number; message?: string } }>( const res = await api.post<{
'/sync/jinshuju/apply', body, success: boolean;
); log: { recordsCount: number; message?: string };
}>('/sync/jinshuju/apply', body);
if (res.success) { if (res.success) {
message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`); message.success(res.log.message || `处理 ${res.log.recordsCount} 条记录`);
onApplied(); onApplied();
@@ -319,7 +438,9 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
const err = e as { message?: string }; const err = e as { message?: string };
if (err?.message) message.error(err.message); if (err?.message) message.error(err.message);
setStep('match'); setStep('match');
} finally { setLoading(false); } } finally {
setLoading(false);
}
}; };
const reset = () => { const reset = () => {
@@ -334,7 +455,10 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
credForm.resetFields(); credForm.resetFields();
}; };
const handleClose = () => { reset(); onClose(); }; const handleClose = () => {
reset();
onClose();
};
const handleScroll = (source: 'left' | 'right') => { const handleScroll = (source: 'left' | 'right') => {
const el = source === 'left' ? leftRef.current : rightRef.current; const el = source === 'left' ? leftRef.current : rightRef.current;
if (el) setScrollTop(el.scrollTop); if (el) setScrollTop(el.scrollTop);
@@ -346,7 +470,8 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
}, [scrollTop]); }, [scrollTop]);
const getDecision = (serial: number): MatchDecision | undefined => decisions.get(serial); 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 total = entries.length;
const matched = [...decisions.values()].filter((d) => d.action !== 'skip').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)} onChange={(value) => setSelectedRuleId(value)}
options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))} options={visibleRules.map((rule) => ({ value: rule.id, label: rule.name }))}
/> />
{selectedRule ? ( {canTriggerSync && selectedRule ? (
<Button <Button
icon={<EditOutlined />} icon={<EditOutlined />}
onClick={() => { onClick={() => {
@@ -412,6 +537,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
</Button> </Button>
) : null} ) : null}
{canTriggerSync ? (
<Button <Button
icon={<PlusOutlined />} icon={<PlusOutlined />}
onClick={() => { onClick={() => {
@@ -421,6 +547,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
> >
</Button> </Button>
) : null}
</div> </div>
{visibleRules.length === 0 && !showRuleEditor ? ( {visibleRules.length === 0 && !showRuleEditor ? (
@@ -429,7 +556,7 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
</Text> </Text>
) : null} ) : null}
{showRuleEditor ? ( {canTriggerSync && showRuleEditor ? (
<RuleEditor <RuleEditor
rule={editingRule} rule={editingRule}
formToken={formToken} formToken={formToken}
@@ -459,51 +586,113 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
const d = getDecision(entry.serialNumber); const d = getDecision(entry.serialNumber);
const isMatched = d?.action === 'match'; const isMatched = d?.action === 'match';
const color = isMatched ? '#1677ff' : '#d9d9d9'; const color = isMatched ? '#1677ff' : '#d9d9d9';
lines.push(<line key={entry.serialNumber} x1={LEFT_WIDTH} y1={y} x2={LEFT_WIDTH + GAP} y2={y} lines.push(
stroke={color} strokeWidth={isMatched ? 2 : 1} <line
strokeDasharray={isMatched ? undefined : '4 4'} opacity={isMatched ? 0.7 : 0.3} />); 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 ( return (
<div style={{ position: 'relative' }}> <div style={{ position: 'relative' }}>
<div style={{ marginBottom: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <div
<Text type="secondary"> {total} {matched} </Text> style={{
<Button size="small" onClick={() => setDecisions(new Map())}></Button> 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>
<div style={{ display: 'flex', position: 'relative' }}> <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} {lines}
</svg> </svg>
<div ref={leftRef} onScroll={() => handleScroll('left')} <div
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}> ref={leftRef}
onScroll={() => handleScroll('left')}
style={{ width: LEFT_WIDTH, maxHeight: 480, overflowY: 'auto', flexShrink: 0 }}
>
{entries.map((entry, i) => { {entries.map((entry, i) => {
const d = getDecision(entry.serialNumber); const d = getDecision(entry.serialNumber);
const isMatched = d?.action === 'match'; const isMatched = d?.action === 'match';
return ( return (
<div key={entry.serialNumber} style={{ <div
height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0', key={entry.serialNumber}
display: 'flex', flexDirection: 'column', justifyContent: 'center', 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', background: isMatched ? '#f6ffed' : i % 2 === 0 ? '#fafafa' : '#fff',
borderLeft: isMatched ? '3px solid #1677ff' : '3px solid transparent', 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 strong style={{ fontSize: 13 }}>
<Text type="secondary" style={{ fontSize: 11 }}>#{entry.serialNumber}</Text> {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> </div>
<div style={{ width: GAP, flexShrink: 0 }} /> <div style={{ width: GAP, flexShrink: 0 }} />
<div ref={rightRef} onScroll={() => handleScroll('right')} <div
style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}> ref={rightRef}
onScroll={() => handleScroll('right')}
style={{ flex: 1, maxHeight: 480, overflowY: 'auto' }}
>
{entries.map((entry) => ( {entries.map((entry) => (
<div key={entry.serialNumber} style={{ <div
height: ROW_HEIGHT, padding: '8px 12px', borderBottom: '1px solid #f0f0f0', key={entry.serialNumber}
display: 'flex', alignItems: 'center', gap: 8, style={{
}}> height: ROW_HEIGHT,
<MatchSelector entry={entry} decision={getDecision(entry.serialNumber)} padding: '8px 12px',
borderBottom: '1px solid #f0f0f0',
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
<MatchSelector
entry={entry}
decision={getDecision(entry.serialNumber)}
studentOptions={studentOptions} studentOptions={studentOptions}
onChange={(newD) => setDecision(entry.serialNumber, newD)} /> onChange={(newD) => setDecision(entry.serialNumber, newD)}
/>
</div> </div>
))} ))}
</div> </div>
@@ -517,47 +706,72 @@ const JinshujuMatchModal: React.FC<MatchModalProps> = ({ open, onClose, onApplie
return ( return (
<Modal <Modal
title="同步金数据" title="同步金数据"
open={open} open={open && canEnterModal}
onCancel={handleClose} onCancel={handleClose}
width={step === 'match' || step === 'applying' ? 900 : 640} width={step === 'match' || step === 'applying' ? 900 : 640}
maskClosable={false} maskClosable={false}
footer={ footer={
step === 'connection' step === 'connection'
? [ ? [
<Button key="cancel" onClick={handleClose}></Button>, <Button key="cancel" onClick={handleClose}>
<Button key="next" type="primary" onClick={handleConnectionNext}></Button>,
</Button>,
<Button key="next" type="primary" onClick={handleConnectionNext}>
</Button>,
] ]
: step === 'rule' : step === 'rule'
? [ ? [
<Button key="back" onClick={() => setStep('connection')}></Button>, <Button key="back" onClick={() => setStep('connection')}>
<Button key="cancel" onClick={handleClose}></Button>,
<Button key="next" type="primary" icon={<SearchOutlined />} loading={loading} onClick={handlePreview}> </Button>,
<Button key="cancel" onClick={handleClose}>
</Button>,
<Button
key="next"
type="primary"
icon={<SearchOutlined />}
loading={loading}
onClick={handlePreview}
>
</Button>, </Button>,
] ]
: step === 'match' : step === 'match'
? [ ? [
<Button key="back" onClick={() => setStep('rule')}></Button>, <Button key="back" onClick={() => setStep('rule')}>
<Button key="cancel" onClick={handleClose}></Button>,
<Button key="apply" type="primary" icon={<CloudUploadOutlined />} loading={loading} onClick={handleApply}>
</Button>, </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 : null
} }
> >
<Steps <Steps
current={currentStep} current={currentStep}
items={[ items={[{ title: '连接表单' }, { title: '匹配规则' }, { title: '确认匹配' }]}
{ title: '连接表单' },
{ title: '匹配规则' },
{ title: '确认匹配' },
]}
/> />
{step === 'connection' ? renderConnectionStep() : null} {step === 'connection' ? renderConnectionStep() : null}
{step === 'rule' ? renderRuleStep() : null} {step === 'rule' ? renderRuleStep() : null}
{step === 'match' ? renderMatchStep() : 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> </Modal>
); );
}; };

View File

@@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { Result, Button } from 'antd'; import { Result, Button, Spin } from 'antd';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { findRoleAwareLandingPath } from '../auth/menu-policy'; import { findRoleAwareLandingPath } from '../auth/menu-policy';
import { usePermission } from '../hooks/usePermission'; import { usePermission } from '../hooks/usePermission';
@@ -10,8 +10,11 @@ interface PermissionRouteProps {
} }
const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => { const PermissionRoute: React.FC<PermissionRouteProps> = ({ permission, children }) => {
const { permissions, hasPermission } = usePermission(); const { permissions, permissionsReady, hasPermission } = usePermission();
const navigate = useNavigate(); const navigate = useNavigate();
if (!permissionsReady) {
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
}
if (!hasPermission(permission)) { if (!hasPermission(permission)) {
let roles: string[] = []; let roles: string[] = [];
try { try {

View File

@@ -37,6 +37,8 @@ import { maskPhone, maskIdNumber } from '../../utils/sensitive';
import { useViewSensitive } from '../../hooks/useViewSensitive'; import { useViewSensitive } from '../../hooks/useViewSensitive';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import EditableCell from '../EditableCell'; import EditableCell from '../EditableCell';
import { usePermission } from '../../hooks/usePermission';
import PermissionButton from '../PermissionButton';
// ---- Types ---- // ---- Types ----
@@ -318,7 +320,19 @@ const InlineArchiveSummary: React.FC<{
organizations: Array<{ id: number; name: string }>; organizations: Array<{ id: number; name: string }>;
onRefresh: () => void; onRefresh: () => void;
onViewSensitive: (fieldLabel: string, value: string) => 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) => { const saveStudent = async (field: keyof StudentInfo, value: unknown) => {
await api.put(`/students/${studentId}`, { [field]: value }); await api.put(`/students/${studentId}`, { [field]: value });
message.success('学生资料已保存'); message.success('学生资料已保存');
@@ -356,9 +370,11 @@ const InlineArchiveSummary: React.FC<{
{student.phone ? ( {student.phone ? (
<span> <span>
<span style={{ marginRight: 8 }}>{maskPhone(student.phone)}</span> <span style={{ marginRight: 8 }}>{maskPhone(student.phone)}</span>
{canViewSensitive ? (
<a onClick={() => onViewSensitive('电话', student.phone)}> <a onClick={() => onViewSensitive('电话', student.phone)}>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} /> <EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</a> </a>
) : null}
</span> </span>
) : ( ) : (
'-' '-'
@@ -402,9 +418,11 @@ const InlineArchiveSummary: React.FC<{
{student.idNumber ? ( {student.idNumber ? (
<span> <span>
<span style={{ marginRight: 8 }}>{maskIdNumber(student.idNumber)}</span> <span style={{ marginRight: 8 }}>{maskIdNumber(student.idNumber)}</span>
{canViewSensitive ? (
<a onClick={() => onViewSensitive('身份证号', student.idNumber)}> <a onClick={() => onViewSensitive('身份证号', student.idNumber)}>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} /> <EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</a> </a>
) : null}
</span> </span>
) : ( ) : (
'-' '-'
@@ -438,9 +456,11 @@ const InlineArchiveSummary: React.FC<{
{student.emergencyPhone ? ( {student.emergencyPhone ? (
<span> <span>
<span style={{ marginRight: 8 }}>{maskPhone(student.emergencyPhone)}</span> <span style={{ marginRight: 8 }}>{maskPhone(student.emergencyPhone)}</span>
{canViewSensitive ? (
<a onClick={() => onViewSensitive('紧急联系人电话', student.emergencyPhone || '')}> <a onClick={() => onViewSensitive('紧急联系人电话', student.emergencyPhone || '')}>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} /> <EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</a> </a>
) : null}
</span> </span>
) : ( ) : (
'-' '-'
@@ -448,6 +468,7 @@ const InlineArchiveSummary: React.FC<{
</EditableCell> </EditableCell>
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="所属机构"> <Descriptions.Item label="所属机构">
{canChooseOrganization ? (
<EditableCell <EditableCell
value={student.organizationId} value={student.organizationId}
editor="select" editor="select"
@@ -455,8 +476,17 @@ const InlineArchiveSummary: React.FC<{
permission="student:edit" permission="student:edit"
onSave={(next) => saveStudent('organizationId', next)} onSave={(next) => saveStudent('organizationId', next)}
> >
{student.organization?.name ? <Tag color="purple">{student.organization.name}</Tag> : '-'} {student.organization?.name ? (
<Tag color="purple">{student.organization.name}</Tag>
) : (
'-'
)}
</EditableCell> </EditableCell>
) : student.organization?.name ? (
<Tag color="purple">{student.organization.name}</Tag>
) : (
'-'
)}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="负责人"> <Descriptions.Item label="负责人">
<EditableCell <EditableCell
@@ -604,6 +634,7 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
studentId, studentId,
onRefresh, onRefresh,
}) => { }) => {
const { hasPermission } = usePermission();
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [form] = Form.useForm(); const [form] = Form.useForm();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -760,7 +791,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
return ( return (
<div> <div>
<Button <PermissionButton
permission="student:edit"
icon={<PlusOutlined />} icon={<PlusOutlined />}
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -770,7 +802,7 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
> >
</Button> </PermissionButton>
<Table<EnrollmentRecord> <Table<EnrollmentRecord>
columns={columns} columns={columns}
dataSource={data} dataSource={data}
@@ -783,8 +815,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
/> />
<Modal <Modal
title="添加报读记录" title="添加报读记录"
open={modalOpen} open={modalOpen && hasPermission('student:edit')}
onOk={handleAdd} onOk={hasPermission('student:edit') ? handleAdd : undefined}
onCancel={() => setModalOpen(false)} onCancel={() => setModalOpen(false)}
confirmLoading={saving} confirmLoading={saving}
> >
@@ -827,6 +859,7 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
const ExamScoresTab: React.FC< const ExamScoresTab: React.FC<
TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] } TabProps & { data: ExamScoreRecord[]; enrollments: EnrollmentRecord[] }
> = ({ data, studentId, enrollments, onRefresh }) => { > = ({ data, studentId, enrollments, onRefresh }) => {
const { hasPermission } = usePermission();
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [form] = Form.useForm(); const [form] = Form.useForm();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -995,7 +1028,8 @@ const ExamScoresTab: React.FC<
return ( return (
<div> <div>
<Button <PermissionButton
permission="student:edit"
icon={<PlusOutlined />} icon={<PlusOutlined />}
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -1005,7 +1039,7 @@ const ExamScoresTab: React.FC<
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
> >
</Button> </PermissionButton>
<Table<ExamScoreRecord> <Table<ExamScoreRecord>
columns={columns} columns={columns}
dataSource={data} dataSource={data}
@@ -1018,8 +1052,8 @@ const ExamScoresTab: React.FC<
/> />
<Modal <Modal
title="添加考试成绩" title="添加考试成绩"
open={modalOpen} open={modalOpen && hasPermission('student:edit')}
onOk={handleAdd} onOk={hasPermission('student:edit') ? handleAdd : undefined}
onCancel={() => setModalOpen(false)} onCancel={() => setModalOpen(false)}
confirmLoading={saving} confirmLoading={saving}
> >
@@ -1074,6 +1108,7 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
studentId, studentId,
onRefresh, onRefresh,
}) => { }) => {
const { hasPermission } = usePermission();
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [form] = Form.useForm(); const [form] = Form.useForm();
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
@@ -1183,7 +1218,8 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
return ( return (
<div> <div>
<Button <PermissionButton
permission="student:edit"
icon={<PlusOutlined />} icon={<PlusOutlined />}
type="primary" type="primary"
onClick={() => { onClick={() => {
@@ -1193,7 +1229,7 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
style={{ marginBottom: 16 }} style={{ marginBottom: 16 }}
> >
</Button> </PermissionButton>
<Table<LearningRecord> <Table<LearningRecord>
columns={columns} columns={columns}
dataSource={data} dataSource={data}
@@ -1206,8 +1242,8 @@ const LearningTab: React.FC<TabProps & { data: LearningRecord[] }> = ({
/> />
<Modal <Modal
title="添加学情记录" title="添加学情记录"
open={modalOpen} open={modalOpen && hasPermission('student:edit')}
onOk={handleAdd} onOk={hasPermission('student:edit') ? handleAdd : undefined}
onCancel={() => setModalOpen(false)} onCancel={() => setModalOpen(false)}
confirmLoading={saving} confirmLoading={saving}
> >
@@ -1250,6 +1286,7 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
studentId, studentId,
onRefresh, onRefresh,
}) => { }) => {
const { hasPermission } = usePermission();
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const handleDelete = async (attachmentId: number) => { const handleDelete = async (attachmentId: number) => {
@@ -1294,11 +1331,13 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
> >
</Button> </Button>
{hasPermission('student:edit') ? (
<Popconfirm title="确定归档该附件?" onConfirm={() => handleDelete(record.id)}> <Popconfirm title="确定归档该附件?" onConfirm={() => handleDelete(record.id)}>
<Button size="small" danger icon={<InboxOutlined />}> <Button size="small" danger icon={<InboxOutlined />}>
</Button> </Button>
</Popconfirm> </Popconfirm>
) : null}
</Space> </Space>
), ),
}, },
@@ -1306,6 +1345,7 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
return ( return (
<div> <div>
{hasPermission('student:edit') ? (
<Upload <Upload
showUploadList={false} showUploadList={false}
customRequest={async (options) => { customRequest={async (options) => {
@@ -1337,6 +1377,7 @@ const AttachmentsTab: React.FC<TabProps & { data: AttachmentRecord[] }> = ({
</Button> </Button>
</Upload> </Upload>
) : null}
<Table<AttachmentRecord> <Table<AttachmentRecord>
columns={columns} columns={columns}
dataSource={data} dataSource={data}
@@ -1359,6 +1400,13 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
inDrawer, inDrawer,
onClose, 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 [aggregateData, setAggregateData] = useState<StudentProfileAggregate | null>(null);
const [organizations, setOrganizations] = useState<Array<{ id: number; name: string }>>([]); const [organizations, setOrganizations] = useState<Array<{ id: number; name: string }>>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -1381,13 +1429,17 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
}, [fetchData]); }, [fetchData]);
useEffect(() => { useEffect(() => {
if (!canLoadOrganizations) {
setOrganizations([]);
return;
}
api api
.get('/organizations', { params: { includeArchived: 'false' } }) .get('/organizations/options')
.then((res: unknown) => { .then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string }>); setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
}) })
.catch(() => {}); .catch(() => {});
}, []); }, [canLoadOrganizations]);
const handlePreviewReport = useCallback(async () => { const handlePreviewReport = useCallback(async () => {
try { try {
@@ -1402,7 +1454,11 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
} }
}, [studentId]); }, [studentId]);
const handleViewSensitive = useViewSensitive(studentId, '学生档案'); const handleViewSensitive = useViewSensitive(
studentId,
'学生档案',
hasPermission('log:create'),
);
const tabItems = useMemo(() => { const tabItems = useMemo(() => {
if (!aggregateData) return []; if (!aggregateData) return [];
@@ -1470,7 +1526,8 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
<Space> <Space>
<Button type="text" icon={<CloseOutlined />} onClick={onClose} aria-label="关闭档案" /> <Button type="text" icon={<CloseOutlined />} onClick={onClose} aria-label="关闭档案" />
<span style={{ fontSize: 16, fontWeight: 500 }}> <span style={{ fontSize: 16, fontWeight: 500 }}>
- {student.name}{student.studentNo ? ` (${student.studentNo})` : ''} - {student.name}
{student.studentNo ? ` (${student.studentNo})` : ''}
</span> </span>
</Space> </Space>
<Space> <Space>
@@ -1507,6 +1564,8 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
organizations={organizations} organizations={organizations}
onRefresh={fetchData} onRefresh={fetchData}
onViewSensitive={handleViewSensitive} onViewSensitive={handleViewSensitive}
canViewSensitive={hasPermission('log:create')}
canChooseOrganization={canChooseOrganization}
/> />
<Tabs defaultActiveKey="enrollments" items={tabItems} /> <Tabs defaultActiveKey="enrollments" items={tabItems} />

View File

@@ -1,31 +1,40 @@
import { useCallback, useEffect, useState } from 'react'; 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() { export function usePermission() {
const [permissions, setPermissions] = useState<string[]>(readPermissions); const [state, setState] = useState(readPermissionState);
useEffect(() => { useEffect(() => {
const refresh = () => setPermissions(readPermissions()); const refresh = () => setState(readPermissionState());
window.addEventListener(PERMISSIONS_UPDATED_EVENT, refresh); window.addEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
window.addEventListener('storage', refresh);
return () => { return () => {
window.removeEventListener(PERMISSIONS_UPDATED_EVENT, refresh); window.removeEventListener(PERMISSIONS_UPDATED_EVENT, refresh);
window.removeEventListener('storage', refresh);
}; };
}, []); }, []);
const permissions = state.permissions;
const permissionsReady = state.status === 'ready';
const hasPermission = useCallback( const hasPermission = useCallback(
(code: string): boolean => permissions.includes(code), (code: string): boolean => permissionsReady && permissions.includes(code),
[permissions], [permissions, permissionsReady],
); );
const hasAnyPermission = useCallback( const hasAnyPermission = useCallback(
(...codes: string[]): boolean => codes.some((code) => permissions.includes(code)), (...codes: string[]): boolean =>
[permissions], permissionsReady && codes.some((code) => permissions.includes(code)),
[permissions, permissionsReady],
); );
const hasAllPermissions = useCallback( const hasAllPermissions = useCallback(
(...codes: string[]): boolean => codes.every((code) => permissions.includes(code)), (...codes: string[]): boolean =>
[permissions], permissionsReady && codes.every((code) => permissions.includes(code)),
[permissions, permissionsReady],
); );
return { permissions, hasPermission, hasAnyPermission, hasAllPermissions }; return {
permissions,
permissionStatus: state.status,
permissionsReady,
hasPermission,
hasAnyPermission,
hasAllPermissions,
};
} }

View File

@@ -1,4 +1,4 @@
import { useCallback } from 'react'; import { useCallback, useEffect, useRef } from 'react';
import { Modal } from 'antd'; import { Modal } from 'antd';
import api from '../api'; import api from '../api';
import { message } from '../ui/app-message'; 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 studentId - The student whose data is being viewed
* @param module - Audit module label (e.g. '学生管理', '学生档案') * @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( return useCallback(
(field: string, value: string) => { (field: string, value: string) => {
Modal.confirm({ if (!canLogRef.current) return;
modalRef.current = Modal.confirm({
title: '查看敏感信息', title: '查看敏感信息',
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`, content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
okText: '确认查看', okText: '确认查看',
cancelText: '取消', cancelText: '取消',
onOk: async () => { onOk: async () => {
if (!canLogRef.current) return;
try { try {
await api.post('/operation-logs/audit', { await api.post('/operation-logs/audit', {
module, module,
@@ -37,6 +56,9 @@ export function useViewSensitive(studentId: number, module: string) {
okText: '关闭', okText: '关闭',
}); });
}, },
afterClose: () => {
modalRef.current = null;
},
}); });
}, },
[studentId, module], [studentId, module],

View File

@@ -31,7 +31,11 @@ import {
} from '@ant-design/icons'; } from '@ant-design/icons';
import { usePermission } from '../hooks/usePermission'; import { usePermission } from '../hooks/usePermission';
import api from '../api'; import api from '../api';
import { writePermissions } from '../auth/permission-store'; import {
beginPermissionVerification,
clearPermissions,
writePermissions,
} from '../auth/permission-store';
import NotificationBell from '../components/NotificationBell'; import NotificationBell from '../components/NotificationBell';
import RouteDock from '../components/RouteDock'; import RouteDock from '../components/RouteDock';
import { buildMenu, type AppMenuItem } from '../auth/menu-policy'; import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
@@ -82,12 +86,24 @@ const MainLayout: React.FC = () => {
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
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 api
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>( .get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
'/auth/profile', '/auth/profile',
) )
.then((profile) => { .then((profile) => {
if (cancelled) return; if (cancelled) return;
verificationInFlight = false;
writePermissions(profile.permissions || []); writePermissions(profile.permissions || []);
const cachedUser = JSON.parse(localStorage.getItem('user') || '{}'); const cachedUser = JSON.parse(localStorage.getItem('user') || '{}');
const nextUser = { ...cachedUser, ...profile }; const nextUser = { ...cachedUser, ...profile };
@@ -95,10 +111,32 @@ const MainLayout: React.FC = () => {
setUser(nextUser); setUser(nextUser);
}) })
.catch(() => { .catch(() => {
// The API interceptor handles expired/invalid sessions. 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 () => { return () => {
cancelled = true; 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(() => { const handleLogout = useCallback(() => {
localStorage.removeItem('token'); localStorage.removeItem('token');
localStorage.removeItem('user'); localStorage.removeItem('user');
localStorage.removeItem('permissions'); clearPermissions();
navigate('/login'); navigate('/login');
}, [navigate]); }, [navigate]);

View File

@@ -13,7 +13,6 @@ import {
Spin, Spin,
Alert, Alert,
Typography, Typography,
Tooltip,
Space, Space,
} from 'antd'; } from 'antd';
import { import {
@@ -442,27 +441,16 @@ const AiConfigPage: React.FC = () => {
{/* Actions */} {/* Actions */}
<div className={styles.actions}> <div className={styles.actions}>
<Tooltip title={!canWrite ? '当前角色无写入权限' : undefined}> {canWrite ? (
<Button <Button type="primary" icon={<SaveOutlined />} onClick={handleSave} loading={saving}>
type="primary"
icon={<SaveOutlined />}
onClick={handleSave}
loading={saving}
disabled={!canWrite}
>
</Button> </Button>
</Tooltip> ) : null}
<Tooltip title={!canTest ? '当前角色无测试权限' : undefined}> {canTest ? (
<Button <Button icon={<ApiOutlined />} onClick={handleTest} loading={testing}>
icon={<ApiOutlined />}
onClick={handleTest}
loading={testing}
disabled={!canTest}
>
</Button> </Button>
</Tooltip> ) : null}
</div> </div>
</Form> </Form>

View File

@@ -10,6 +10,7 @@ import {
type LessonAttendanceFilter, type LessonAttendanceFilter,
} from './attendance-workspace'; } from './attendance-workspace';
import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types'; import type { LessonAttendanceRecord, LessonAttendanceSchedule } from './types';
import { usePermission } from '../../hooks/usePermission';
interface LessonAttendanceSession { interface LessonAttendanceSession {
id: number; id: number;
@@ -76,6 +77,8 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
className, className,
onClose, onClose,
}) => { }) => {
const { hasAnyPermission } = usePermission();
const canEditAttendance = hasAnyPermission('attendance:edit', 'attendance:self-edit');
const [loadedSchedule, setLoadedSchedule] = useState<LessonAttendanceSchedule | null>(null); const [loadedSchedule, setLoadedSchedule] = useState<LessonAttendanceSchedule | null>(null);
const [session, setSession] = useState<LessonAttendanceSession | null>(null); const [session, setSession] = useState<LessonAttendanceSession | null>(null);
const [records, setRecords] = useState<LessonAttendanceRecord[]>([]); const [records, setRecords] = useState<LessonAttendanceRecord[]>([]);
@@ -215,6 +218,7 @@ const LessonAttendanceDetail: React.FC<LessonAttendanceDetailProps> = ({
dataIndex: 'status', dataIndex: 'status',
width: 230, width: 230,
render: (value: string, record) => { render: (value: string, record) => {
if (!canEditAttendance) return <AttendanceStatus status={value} />;
const checkedIn = value === 'present' || value === 'late'; const checkedIn = value === 'present' || value === 'late';
return ( return (
<div className="attendance-marking-actions"> <div className="attendance-marking-actions">

View File

@@ -240,13 +240,13 @@ const AttendancePage: React.FC = () => {
const experience = getAttendanceExperience(permissions, roles); const experience = getAttendanceExperience(permissions, roles);
if (experience === 'teacher') { if (experience === 'teacher') {
return <TeacherAttendanceWorkspace />; return <TeacherAttendanceWorkspace canCreate={hasPermission('attendance:create')} />;
} }
return <AdminAttendanceArchive canEdit={hasPermission('attendance:edit')} />; return <AdminAttendanceArchive canEdit={hasPermission('attendance:edit')} />;
}; };
const TeacherAttendanceWorkspace: React.FC = () => { const TeacherAttendanceWorkspace: React.FC<{ canCreate: boolean }> = ({ canCreate }) => {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [workspace, setWorkspace] = useState<TeacherWorkspaceData | null>(null); const [workspace, setWorkspace] = useState<TeacherWorkspaceData | null>(null);
const [selectedSchedule, setSelectedSchedule] = useState<TodaySchedule | null>(null); const [selectedSchedule, setSelectedSchedule] = useState<TodaySchedule | null>(null);
@@ -355,7 +355,7 @@ const TeacherAttendanceWorkspace: React.FC = () => {
phase={phase} phase={phase}
className={classNameById.get(schedule.classId) || `班级 ${schedule.classId}`} className={classNameById.get(schedule.classId) || `班级 ${schedule.classId}`}
index={index + 1} index={index + 1}
onOpen={() => openAttendance(schedule)} onOpen={canCreate ? () => openAttendance(schedule) : undefined}
/> />
); );
})} })}
@@ -363,6 +363,7 @@ const TeacherAttendanceWorkspace: React.FC = () => {
)} )}
</Spin> </Spin>
{canCreate ? (
<LessonAttendanceDetail <LessonAttendanceDetail
schedule={selectedSchedule} schedule={selectedSchedule}
className={ className={
@@ -372,6 +373,7 @@ const TeacherAttendanceWorkspace: React.FC = () => {
} }
onClose={() => setSelectedSchedule(null)} onClose={() => setSelectedSchedule(null)}
/> />
) : null}
</div> </div>
); );
}; };
@@ -381,7 +383,7 @@ const LessonCard: React.FC<{
phase: SchedulePhase; phase: SchedulePhase;
className: string; className: string;
index: number; index: number;
onOpen: () => void; onOpen?: () => void;
}> = ({ schedule, phase, className, index, onOpen }) => { }> = ({ schedule, phase, className, index, onOpen }) => {
const phaseMeta = { const phaseMeta = {
upcoming: { label: '待上课', icon: <ClockCircleOutlined />, tone: 'upcoming' }, upcoming: { label: '待上课', icon: <ClockCircleOutlined />, tone: 'upcoming' },
@@ -412,11 +414,11 @@ const LessonCard: React.FC<{
<Tooltip title="课程尚未开始"> <Tooltip title="课程尚未开始">
<Button disabled></Button> <Button disabled></Button>
</Tooltip> </Tooltip>
) : ( ) : onOpen ? (
<Button type="primary" onClick={onOpen}> <Button type="primary" onClick={onOpen}>
{phase === 'ongoing' ? '查看当前考勤' : '拉取 / 查看考勤'} <ArrowRightOutlined /> {phase === 'ongoing' ? '查看当前考勤' : '拉取 / 查看考勤'} <ArrowRightOutlined />
</Button> </Button>
)} ) : null}
</div> </div>
</article> </article>
); );
@@ -1144,9 +1146,9 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
value={studentSearch} value={studentSearch}
onChange={(event) => setStudentSearch(event.target.value)} onChange={(event) => setStudentSearch(event.target.value)}
/> />
<Button icon={<ExportOutlined />} onClick={handleExport}> <PermissionButton permission="attendance:export" icon={<ExportOutlined />} onClick={handleExport}>
</Button> </PermissionButton>
</div> </div>
</header> </header>
<div className="student-legend"> <div className="student-legend">

View File

@@ -37,7 +37,7 @@ export const unavailableDatesCacheKey = (classroomId: number, date: Dayjs) =>
`${classroomId}:${date.format('YYYY-MM')}`; `${classroomId}:${date.format('YYYY-MM')}`;
const ClassroomRentalsPage: React.FC = () => { const ClassroomRentalsPage: React.FC = () => {
const { hasAnyPermission } = usePermission(); const { hasPermission, hasAnyPermission } = usePermission();
const [data, setData] = useState<any[]>([]); const [data, setData] = useState<any[]>([]);
const [classrooms, setClassrooms] = useState<any[]>([]); const [classrooms, setClassrooms] = useState<any[]>([]);
const [organizations, setOrganizations] = useState<any[]>([]); const [organizations, setOrganizations] = useState<any[]>([]);
@@ -446,11 +446,13 @@ const ClassroomRentalsPage: React.FC = () => {
</Button> </Button>
</Tooltip> </Tooltip>
{hasPermission('rental:edit') ? (
<Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}> <Popconfirm title="移除合同文件?" onConfirm={() => handleDeleteContract(r.id)}>
<Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" /> <Button size="small" danger icon={<StopOutlined />} aria-label="移除合同文件" />
</Popconfirm> </Popconfirm>
) : null}
</Space> </Space>
) : ( ) : hasPermission('rental:edit') ? (
<Upload <Upload
accept="application/pdf" accept="application/pdf"
showUploadList={false} showUploadList={false}
@@ -479,6 +481,8 @@ const ClassroomRentalsPage: React.FC = () => {
PDF PDF
</Button> </Button>
</Upload> </Upload>
) : (
'-'
), ),
}, },
{ {
@@ -538,7 +542,7 @@ const ClassroomRentalsPage: React.FC = () => {
), ),
}, },
], ],
[classrooms, organizations], [classrooms, organizations, hasPermission],
); );
return ( return (

View File

@@ -25,6 +25,7 @@ import api from '../../api';
import PermissionButton from '../../components/PermissionButton'; import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell'; import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const statusMap: Record<string, { text: string; color: string }> = { const statusMap: Record<string, { text: string; color: string }> = {
available: { text: '可用', color: 'green' }, available: { text: '可用', color: 'green' },
@@ -48,6 +49,7 @@ const typeColor: Record<string, string> = {
}; };
const ClassroomsPage: React.FC = () => { const ClassroomsPage: React.FC = () => {
const { hasPermission } = usePermission();
const [data, setData] = useState<any[]>([]); const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
@@ -402,6 +404,7 @@ const ClassroomsPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
{hasPermission('classroom:create') ? (
<Upload <Upload
accept=".xlsx,.xls" accept=".xlsx,.xls"
showUploadList={false} showUploadList={false}
@@ -423,6 +426,7 @@ const ClassroomsPage: React.FC = () => {
> >
<Button icon={<UploadOutlined />}>Excel</Button> <Button icon={<UploadOutlined />}>Excel</Button>
</Upload> </Upload>
) : null}
<PermissionButton <PermissionButton
permission="classroom:view" permission="classroom:view"
icon={<DownloadOutlined />} icon={<DownloadOutlined />}

View File

@@ -8,6 +8,7 @@ import EditableCell from '../../components/EditableCell';
import { useViewSensitive } from '../../hooks/useViewSensitive'; import { useViewSensitive } from '../../hooks/useViewSensitive';
import { maskPhone } from '../../utils/sensitive'; import { maskPhone } from '../../utils/sensitive';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
import type { ExamItem } from './types'; import type { ExamItem } from './types';
import './style.css'; import './style.css';
@@ -21,12 +22,29 @@ interface ScoreRow {
rank: number | null; rank: number | null;
} }
interface ExamDetail extends ExamItem { scores: ScoreRow[] } interface ExamDetail extends ExamItem {
scores: ScoreRow[];
}
const PhoneCell: React.FC<{ row: ScoreRow }> = ({ row }) => { 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 <>-</>; 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 = () => { const ExamDetailPage: React.FC = () => {
@@ -37,12 +55,18 @@ const ExamDetailPage: React.FC = () => {
const load = useCallback(async () => { const load = useCallback(async () => {
setLoading(true); setLoading(true);
try { setDetail(await api.get<ExamDetail>(`/exams/${id}`)); } try {
catch (error) { message.error((error as { message?: string })?.message || '加载考试失败'); } setDetail(await api.get<ExamDetail>(`/exams/${id}`));
finally { setLoading(false); } } catch (error) {
message.error((error as { message?: string })?.message || '加载考试失败');
} finally {
setLoading(false);
}
}, [id]); }, [id]);
useEffect(() => { void load(); }, [load]); useEffect(() => {
void load();
}, [load]);
const saveScore = async (row: ScoreRow, value: number | undefined) => { const saveScore = async (row: ScoreRow, value: number | undefined) => {
await api.put(`/exams/${id}/scores/${row.id}`, { score: value ?? null }); await api.put(`/exams/${id}/scores/${row.id}`, { score: value ?? null });
message.success('成绩已保存'); message.success('成绩已保存');
@@ -52,7 +76,11 @@ const ExamDetailPage: React.FC = () => {
const columns = useMemo<ColumnsType<ScoreRow>>(() => { const columns = useMemo<ColumnsType<ScoreRow>>(() => {
if (!detail) return []; if (!detail) return [];
const fixed = [ 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: '姓名', dataIndex: 'name', width: 100 },
{ title: '考试类型*', width: 110, render: () => detail.examType }, { title: '考试类型*', width: 110, render: () => detail.examType },
{ title: '考试名称', width: 170, render: () => detail.examName }, { title: '考试名称', width: 170, render: () => detail.examName },
@@ -60,32 +88,84 @@ const ExamDetailPage: React.FC = () => {
]; ];
return [ return [
...fixed, ...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: '成绩*',
{ title: '排名', dataIndex: 'rank', width: 80, render: (value: number | null) => value ?? '-' }, 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: 110, render: () => detail.examDate },
{ title: '关联报读(班级名)', width: 180, render: () => detail.className }, { title: '关联报读(班级名)', width: 180, render: () => detail.className },
]; ];
}, [detail]); }, [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="考试不存在或无权访问" />; if (!detail) return <Empty description="考试不存在或无权访问" />;
const average = detail.scores.find((row) => row.classAvg !== null)?.classAvg ?? null; const average = detail.scores.find((row) => row.classAvg !== null)?.classAvg ?? null;
return ( return (
<div className="exam-detail-page"> <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"> <Card className="exam-summary">
<Descriptions column={{ xs: 1, sm: 2, lg: 5 }}> <Descriptions column={{ xs: 1, sm: 2, lg: 5 }}>
<Descriptions.Item label="考试类型">{detail.examType}</Descriptions.Item> <Descriptions.Item label="考试类型">{detail.examType}</Descriptions.Item>
<Descriptions.Item label="科目">{detail.subject}</Descriptions.Item> <Descriptions.Item label="科目">{detail.subject}</Descriptions.Item>
<Descriptions.Item label="考试班级">{detail.className}</Descriptions.Item> <Descriptions.Item label="考试班级">{detail.className}</Descriptions.Item>
<Descriptions.Item label="考试日期">{detail.examDate}</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> </Descriptions>
</Card> </Card>
<Card title="成绩表"> <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> </Card>
</div> </div>
); );

View File

@@ -29,6 +29,7 @@ import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell'; import EditableCell from '../../components/EditableCell';
import { downloadBlob } from '../../utils/download'; import { downloadBlob } from '../../utils/download';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
@@ -38,6 +39,7 @@ const isFormValidationError = (error: unknown) =>
Array.isArray((error as { errorFields?: unknown }).errorFields); Array.isArray((error as { errorFields?: unknown }).errorFields);
const ExpensesPage: React.FC = () => { const ExpensesPage: React.FC = () => {
const { hasPermission } = usePermission();
const [roomExpenses, setRoomExpenses] = useState<any[]>([]); const [roomExpenses, setRoomExpenses] = useState<any[]>([]);
const [personalExpenses, setPersonalExpenses] = useState<any[]>([]); const [personalExpenses, setPersonalExpenses] = useState<any[]>([]);
const [rooms, setRooms] = useState<any[]>([]); const [rooms, setRooms] = useState<any[]>([]);
@@ -574,6 +576,7 @@ const ExpensesPage: React.FC = () => {
onChange={(v) => setRoomTypeFilter(v)} onChange={(v) => setRoomTypeFilter(v)}
options={typeOptions} options={typeOptions}
/> />
{hasPermission('expense:create') ? (
<Upload <Upload
accept=".xlsx,.xls" accept=".xlsx,.xls"
showUploadList={false} showUploadList={false}
@@ -601,6 +604,7 @@ const ExpensesPage: React.FC = () => {
> >
<Button icon={<UploadOutlined />}>Excel</Button> <Button icon={<UploadOutlined />}>Excel</Button>
</Upload> </Upload>
) : null}
<PermissionButton <PermissionButton
permission="expense:view" permission="expense:view"
icon={<DownloadOutlined />} icon={<DownloadOutlined />}
@@ -697,6 +701,7 @@ const ExpensesPage: React.FC = () => {
onChange={(v) => setPersonalTypeFilter(v)} onChange={(v) => setPersonalTypeFilter(v)}
options={personalTypeOptions} options={personalTypeOptions}
/> />
{hasPermission('expense:create') ? (
<Upload <Upload
accept=".xlsx,.xls" accept=".xlsx,.xls"
showUploadList={false} showUploadList={false}
@@ -718,6 +723,7 @@ const ExpensesPage: React.FC = () => {
> >
<Button icon={<UploadOutlined />}></Button> <Button icon={<UploadOutlined />}></Button>
</Upload> </Upload>
) : null}
<PermissionButton <PermissionButton
permission="expense:view" permission="expense:view"
icon={<DownloadOutlined />} icon={<DownloadOutlined />}

View File

@@ -111,7 +111,8 @@ interface DeleteAttendanceGroupsResponse {
} }
const IntegrationConfigPage: React.FC = () => { const IntegrationConfigPage: React.FC = () => {
const { hasAllPermissions } = usePermission(); const { hasPermission, hasAllPermissions } = usePermission();
const canCreateClass = hasPermission('class:create');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false); const [testing, setTesting] = useState(false);
@@ -458,12 +459,14 @@ const IntegrationConfigPage: React.FC = () => {
> >
</Button> </Button>
{canCreateClass ? (
<Button <Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0} disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)} onClick={() => setClassModalOpen(true)}
> >
</Button> </Button>
) : null}
</Space> </Space>
} }
> >
@@ -485,9 +488,11 @@ const IntegrationConfigPage: React.FC = () => {
title="班级列表" title="班级列表"
size="small" size="small"
extra={ extra={
canCreateClass ? (
<Button size="small" onClick={() => setClassModalOpen(true)}> <Button size="small" onClick={() => setClassModalOpen(true)}>
+ +
</Button> </Button>
) : null
} }
> >
<List <List
@@ -514,6 +519,7 @@ const IntegrationConfigPage: React.FC = () => {
</Row> </Row>
{/* Create class Modal */} {/* Create class Modal */}
{canCreateClass ? (
<Modal <Modal
title="创建班级" title="创建班级"
open={classModalOpen} open={classModalOpen}
@@ -553,6 +559,7 @@ const IntegrationConfigPage: React.FC = () => {
</Form.Item> </Form.Item>
</Form> </Form>
</Modal> </Modal>
) : null}
</Drawer> </Drawer>
)} )}
<Modal <Modal

View File

@@ -4,7 +4,7 @@ import { Form, Input, Button, Card, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons'; import { UserOutlined, LockOutlined } from '@ant-design/icons';
import api from '../../api'; import api from '../../api';
import { message } from '../../ui/app-message'; 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'; import { findRoleAwareLandingPath } from '../../auth/menu-policy';
const { Title } = Typography; const { Title } = Typography;
@@ -15,6 +15,7 @@ const LoginPage: React.FC = () => {
const onFinish = useCallback( const onFinish = useCallback(
async (values: any) => { async (values: any) => {
clearPermissions();
setLoading(true); setLoading(true);
try { try {
const res: any = await api.post('/auth/login', values); const res: any = await api.post('/auth/login', values);
@@ -66,11 +67,7 @@ const LoginPage: React.FC = () => {
name="username" name="username"
rules={[{ required: true, message: '请输入用户名' }]} rules={[{ required: true, message: '请输入用户名' }]}
> >
<Input <Input prefix={<UserOutlined />} placeholder="用户名" autoComplete="username" />
prefix={<UserOutlined />}
placeholder="用户名"
autoComplete="username"
/>
</Form.Item> </Form.Item>
<Form.Item <Form.Item
label="密码" label="密码"

View File

@@ -33,10 +33,16 @@ import { maskPhone, maskIdNumber } from '../../utils/sensitive';
import PermissionButton from '../../components/PermissionButton'; import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form'; import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
import { usePermission } from '../../hooks/usePermission';
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
const OccupanciesPage: React.FC = () => { 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 [data, setData] = useState<any[]>([]);
const [students, setStudents] = useState<any[]>([]); const [students, setStudents] = useState<any[]>([]);
const [rooms, setRooms] = useState<any[]>([]); const [rooms, setRooms] = useState<any[]>([]);
@@ -66,6 +72,12 @@ const OccupanciesPage: React.FC = () => {
const selectedCheckInRoomId = Form.useWatch('roomId', checkInForm); const selectedCheckInRoomId = Form.useWatch('roomId', checkInForm);
const selectedTransferRoomId = Form.useWatch('newRoomId', transferForm); 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 activeOccupancyByStudentId = useMemo(() => {
const map = new Map<number, any>(); const map = new Map<number, any>();
data.forEach((item) => { data.forEach((item) => {
@@ -93,7 +105,12 @@ const OccupanciesPage: React.FC = () => {
[data, selectedRowKeys], [data, selectedRowKeys],
); );
const latestSelectedCheckInDate = useMemo( const latestSelectedCheckInDate = useMemo(
() => selectedBatchRecords.map((item) => item.checkInDate).filter(Boolean).sort().at(-1), () =>
selectedBatchRecords
.map((item) => item.checkInDate)
.filter(Boolean)
.sort()
.at(-1),
[selectedBatchRecords], [selectedBatchRecords],
); );
const latestSelectedBillingStartDate = useMemo( const latestSelectedBillingStartDate = useMemo(
@@ -106,7 +123,8 @@ const OccupanciesPage: React.FC = () => {
[selectedBatchRecords], [selectedBatchRecords],
); );
const dateNotBefore = (start: string | Dayjs | null | undefined, messageText: string) => const dateNotBefore =
(start: string | Dayjs | null | undefined, messageText: string) =>
(_: unknown, value?: Dayjs | null) => { (_: unknown, value?: Dayjs | null) => {
if (!value || !start) return Promise.resolve(); if (!value || !start) return Promise.resolve();
const startDate = dayjs.isDayjs(start) ? start : dayjs(start); const startDate = dayjs.isDayjs(start) ? start : dayjs(start);
@@ -363,6 +381,7 @@ const OccupanciesPage: React.FC = () => {
) : ( ) : (
<Space> <Space>
<Tag>退宿</Tag> <Tag>退宿</Tag>
{canDelete ? (
<Popconfirm <Popconfirm
title="确定归档此记录?" title="确定归档此记录?"
onConfirm={async () => { onConfirm={async () => {
@@ -375,15 +394,15 @@ const OccupanciesPage: React.FC = () => {
} }
}} }}
> >
<PermissionButton <Button
permission="occupancy:delete"
size="small" size="small"
danger danger
icon={<InboxOutlined />} icon={<InboxOutlined />}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null}
</Space> </Space>
), ),
}, },
@@ -457,6 +476,8 @@ const OccupanciesPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
{canCheckIn ? (
<>
<Upload <Upload
accept=".xlsx,.xls" accept=".xlsx,.xls"
showUploadList={false} showUploadList={false}
@@ -497,30 +518,6 @@ const OccupanciesPage: React.FC = () => {
</Button> </Button>
</Tooltip> </Tooltip>
</Upload> </Upload>
<PermissionButton
permission="occupancy:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/occupancies/template', '入住名单导入模板.xlsx').catch(() =>
message.error('下载失败'),
);
}}
>
</PermissionButton>
<PermissionButton
permission="occupancy:view"
icon={<ExportOutlined />}
onClick={() => {
const params = showActive ? '?active=true' : '';
const filename = showActive ? '在住记录.xlsx' : '全部入住记录.xlsx';
downloadBlob('/occupancies/export' + params, filename).catch(() =>
message.error('导出失败'),
);
}}
>
</PermissionButton>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}> <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} /> <Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
@@ -548,6 +545,32 @@ const OccupanciesPage: React.FC = () => {
</Space.Compact> </Space.Compact>
)} )}
</span> </span>
</>
) : null}
<PermissionButton
permission="occupancy:view"
icon={<DownloadOutlined />}
onClick={() => {
downloadBlob('/occupancies/template', '入住名单导入模板.xlsx').catch(() =>
message.error('下载失败'),
);
}}
>
</PermissionButton>
<PermissionButton
permission="occupancy:view"
icon={<ExportOutlined />}
onClick={() => {
const params = showActive ? '?active=true' : '';
const filename = showActive ? '在住记录.xlsx' : '全部入住记录.xlsx';
downloadBlob('/occupancies/export' + params, filename).catch(() =>
message.error('导出失败'),
);
}}
>
</PermissionButton>
</Space> </Space>
</div> </div>
{selectedRowKeys.length > 0 && ( {selectedRowKeys.length > 0 && (
@@ -572,14 +595,14 @@ const OccupanciesPage: React.FC = () => {
退宿 退宿
</PermissionButton> </PermissionButton>
) : ( ) : (
canDelete ? (
<Popconfirm <Popconfirm
title={`确定归档选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`} title={`确定归档选中的 ${selectedRowKeys.length} 条入住记录?在住记录会自动跳过`}
onConfirm={handleBatchDelete} onConfirm={handleBatchDelete}
okText="归档" okText="归档"
cancelText="取消" cancelText="取消"
> >
<PermissionButton <Button
permission="occupancy:delete"
danger danger
size="small" size="small"
icon={<InboxOutlined />} icon={<InboxOutlined />}
@@ -587,8 +610,9 @@ const OccupanciesPage: React.FC = () => {
loading={batchLoading} loading={batchLoading}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null
)} )}
<Button size="small" onClick={() => setSelectedRowKeys([])} style={{ marginLeft: 8 }}> <Button size="small" onClick={() => setSelectedRowKeys([])} style={{ marginLeft: 8 }}>
@@ -616,8 +640,8 @@ const OccupanciesPage: React.FC = () => {
/> />
<Modal <Modal
title="入住登记" title="入住登记"
open={checkInModal} open={checkInModal && canCheckIn}
onOk={handleCheckIn} onOk={canCheckIn ? handleCheckIn : undefined}
onCancel={() => { onCancel={() => {
setCheckInModal(false); setCheckInModal(false);
setAvailableBeds([]); setAvailableBeds([]);
@@ -642,7 +666,11 @@ const OccupanciesPage: React.FC = () => {
.filter((s: any) => s.status === 'active') .filter((s: any) => s.status === 'active')
.map((s: any) => { .map((s: any) => {
const activeOccupancy = activeOccupancyByStudentId.get(s.id); 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 { return {
value: s.id, value: s.id,
label: `${s.name} (${identifier})${activeOccupancy ? ` · 已入住${activeOccupancy.room?.roomNumber ? ` ${activeOccupancy.room.roomNumber}` : ''}` : ''}`, label: `${s.name} (${identifier})${activeOccupancy ? ` · 已入住${activeOccupancy.room?.roomNumber ? ` ${activeOccupancy.room.roomNumber}` : ''}` : ''}`,
@@ -668,18 +696,25 @@ const OccupanciesPage: React.FC = () => {
}))} }))}
/> />
</Form.Item> </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" /> <DatePicker style={{ width: '100%' }} placeholder="选择入住日期" format="YYYY-MM-DD" />
</Form.Item> </Form.Item>
<Form.Item <Form.Item
name="billingStartDate" name="billingStartDate"
label="计费起始日" label="计费起始日"
dependencies={["checkInDate"]} dependencies={['checkInDate']}
extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)" extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)"
rules={[ rules={[
{ required: true, message: '请选择计费起始日' }, { required: true, message: '请选择计费起始日' },
({ getFieldValue }) => ({ ({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('checkInDate'), '计费起始日不能早于入住日期'), validator: dateNotBefore(
getFieldValue('checkInDate'),
'计费起始日不能早于入住日期',
),
}), }),
]} ]}
> >
@@ -689,7 +724,11 @@ const OccupanciesPage: React.FC = () => {
format="YYYY-MM-DD" format="YYYY-MM-DD"
/> />
</Form.Item> </Form.Item>
<Form.Item name="stayType" label="入住类型" rules={[{ required: true, message: '请选择入住类型' }]}> <Form.Item
name="stayType"
label="入住类型"
rules={[{ required: true, message: '请选择入住类型' }]}
>
<Select <Select
options={[ options={[
{ value: 'short', label: '短租' }, { value: 'short', label: '短租' },
@@ -714,7 +753,9 @@ const OccupanciesPage: React.FC = () => {
<Select <Select
placeholder={selectedCheckInRoomId ? '请选择床位' : '请先选择房间'} placeholder={selectedCheckInRoomId ? '请选择床位' : '请先选择房间'}
loading={availableResourcesLoading} loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0} disabled={
!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0
}
options={availableBeds.map((b) => ({ options={availableBeds.map((b) => ({
value: b.id, value: b.id,
label: b.bedNumber, label: b.bedNumber,
@@ -732,7 +773,9 @@ const OccupanciesPage: React.FC = () => {
allowClear allowClear
placeholder="可选分配柜子" placeholder="可选分配柜子"
loading={availableResourcesLoading} loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0} disabled={
!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0
}
options={availableLockers.map((l) => ({ options={availableLockers.map((l) => ({
value: l.id, value: l.id,
label: l.lockerNumber, label: l.lockerNumber,
@@ -772,8 +815,8 @@ const OccupanciesPage: React.FC = () => {
{/* 退宿弹窗 */} {/* 退宿弹窗 */}
<Modal <Modal
title={`退宿 - ${checkOutModal?.student?.name}`} title={`退宿 - ${checkOutModal?.student?.name}`}
open={!!checkOutModal} open={!!checkOutModal && canCheckOut}
onOk={handleCheckOut} onOk={canCheckOut ? handleCheckOut : undefined}
onCancel={() => setCheckOutModal(null)} onCancel={() => setCheckOutModal(null)}
okText="确认退宿" okText="确认退宿"
confirmLoading={saving} confirmLoading={saving}
@@ -792,12 +835,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item <Form.Item
name="billingEndDate" name="billingEndDate"
label="计费截止日" label="计费截止日"
dependencies={["checkOutDate"]} dependencies={['checkOutDate']}
extra="默认与退宿日期相同" extra="默认与退宿日期相同"
rules={[ rules={[
({ getFieldValue }) => ({ ({ getFieldValue }) => ({
validator: dateNotBefore( validator: dateNotBefore(
checkOutModal?.billingStartDate || checkOutModal?.checkInDate || getFieldValue('checkOutDate'), checkOutModal?.billingStartDate ||
checkOutModal?.checkInDate ||
getFieldValue('checkOutDate'),
'计费截止日不能早于计费起始日', '计费截止日不能早于计费起始日',
), ),
}), }),
@@ -827,8 +872,8 @@ const OccupanciesPage: React.FC = () => {
{/* 批量退宿弹窗 */} {/* 批量退宿弹窗 */}
<Modal <Modal
title={`批量退宿(${selectedRowKeys.length} 人)`} title={`批量退宿(${selectedRowKeys.length} 人)`}
open={batchCheckOutModal} open={batchCheckOutModal && canCheckOut}
onOk={handleBatchCheckOut} onOk={canCheckOut ? handleBatchCheckOut : undefined}
onCancel={() => setBatchCheckOutModal(false)} onCancel={() => setBatchCheckOutModal(false)}
okText="确认批量退宿" okText="确认批量退宿"
width={500} width={500}
@@ -904,7 +949,7 @@ const OccupanciesPage: React.FC = () => {
{/* 换房弹窗 */} {/* 换房弹窗 */}
<Modal <Modal
title={`换房 - ${transferModal?.student?.name}`} title={`换房 - ${transferModal?.student?.name}`}
open={!!transferModal} open={!!transferModal && canTransfer}
onOk={handleTransfer} onOk={handleTransfer}
onCancel={() => { onCancel={() => {
setTransferModal(null); setTransferModal(null);
@@ -948,7 +993,11 @@ const OccupanciesPage: React.FC = () => {
<Select <Select
placeholder={selectedTransferRoomId ? '请选择目标床位' : '请先选择目标宿舍'} placeholder={selectedTransferRoomId ? '请选择目标床位' : '请先选择目标宿舍'}
loading={transferResourcesLoading} loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableBeds.length === 0} disabled={
!selectedTransferRoomId ||
transferResourcesLoading ||
transferAvailableBeds.length === 0
}
options={transferAvailableBeds.map((bed) => ({ options={transferAvailableBeds.map((bed) => ({
value: bed.id, value: bed.id,
label: bed.bedNumber, label: bed.bedNumber,
@@ -966,7 +1015,11 @@ const OccupanciesPage: React.FC = () => {
allowClear allowClear
placeholder="可选分配目标宿舍柜子" placeholder="可选分配目标宿舍柜子"
loading={transferResourcesLoading} loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableLockers.length === 0} disabled={
!selectedTransferRoomId ||
transferResourcesLoading ||
transferAvailableLockers.length === 0
}
options={transferAvailableLockers.map((locker) => ({ options={transferAvailableLockers.map((locker) => ({
value: locker.id, value: locker.id,
label: locker.lockerNumber, label: locker.lockerNumber,
@@ -979,7 +1032,9 @@ const OccupanciesPage: React.FC = () => {
label="换房日期" label="换房日期"
rules={[ rules={[
{ required: true, message: '请选择换房日期' }, { required: true, message: '请选择换房日期' },
{ validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期') }, {
validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期'),
},
]} ]}
> >
<DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" /> <DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" />
@@ -987,12 +1042,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item <Form.Item
name="oldBillingEndDate" name="oldBillingEndDate"
label="旧房计费截止日" label="旧房计费截止日"
dependencies={["transferDate"]} dependencies={['transferDate']}
extra="默认为换房当天" extra="默认为换房当天"
rules={[ rules={[
({ getFieldValue }) => ({ ({ getFieldValue }) => ({
validator: dateNotBefore( validator: dateNotBefore(
transferModal?.billingStartDate || transferModal?.checkInDate || getFieldValue('transferDate'), transferModal?.billingStartDate ||
transferModal?.checkInDate ||
getFieldValue('transferDate'),
'旧房计费截止日不能早于计费起始日', '旧房计费截止日不能早于计费起始日',
), ),
}), }),
@@ -1007,11 +1064,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item <Form.Item
name="newBillingStartDate" name="newBillingStartDate"
label="新房计费起始日" label="新房计费起始日"
dependencies={["transferDate"]} dependencies={['transferDate']}
extra="默认为换房次日" extra="默认为换房次日"
rules={[ rules={[
({ getFieldValue }) => ({ ({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('transferDate'), '新房计费起始日不能早于换房日期'), validator: dateNotBefore(
getFieldValue('transferDate'),
'新房计费起始日不能早于换房日期',
),
}), }),
]} ]}
> >

View File

@@ -464,7 +464,11 @@ const RoomVisualPage: React.FC = () => {
)} )}
</div> </div>
{detailRoom.occupants.map((o: any) => ( {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 <div
style={{ style={{
display: 'flex', display: 'flex',
@@ -502,9 +506,9 @@ const RoomVisualPage: React.FC = () => {
<span style={{ color: '#86868b', fontSize: 12 }}> <span style={{ color: '#86868b', fontSize: 12 }}>
{presentOccupancyIds.includes(o.occupancyId) ? '在寝' : '缺勤'} {presentOccupancyIds.includes(o.occupancyId) ? '在寝' : '缺勤'}
</span> </span>
{hasPermission('room:inspect') ? (
<Switch <Switch
checked={presentOccupancyIds.includes(o.occupancyId)} checked={presentOccupancyIds.includes(o.occupancyId)}
disabled={!hasPermission('room:inspect')}
checkedChildren="在寝" checkedChildren="在寝"
unCheckedChildren="缺勤" unCheckedChildren="缺勤"
onChange={(checked) => onChange={(checked) =>
@@ -513,13 +517,14 @@ const RoomVisualPage: React.FC = () => {
) )
} }
/> />
) : null}
</Space> </Space>
)} )}
</div> </div>
<div style={{ color: '#86868b', fontSize: 12, marginTop: 4 }}> <div style={{ color: '#86868b', fontSize: 12, marginTop: 4 }}>
<CalendarOutlined style={{ marginRight: 4 }} /> <CalendarOutlined style={{ marginRight: 4 }} />
{o.bedNumber || '未分配'} |{' '} {o.bedNumber || '未分配'} | {o.checkInDate} |
{o.checkInDate} | {o.billingStartDate} {o.billingStartDate}
{o.supervisor && ( {o.supervisor && (
<span style={{ marginLeft: 8 }}>{o.supervisor}</span> <span style={{ marginLeft: 8 }}>{o.supervisor}</span>
)} )}

View File

@@ -31,6 +31,7 @@ import { downloadBlob } from '../../utils/download';
import PermissionButton from '../../components/PermissionButton'; import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell'; import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const statusMap: Record<string, { text: string; color: string }> = { const statusMap: Record<string, { text: string; color: string }> = {
available: { text: '可入住', color: 'green' }, available: { text: '可入住', color: 'green' },
@@ -84,10 +85,15 @@ function parseRoomNumber(input: string) {
} }
const RoomsPage: React.FC = () => { 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 [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<any>(null); const [editing, setEditing] = useState<any>(null);
const canSaveRoom = editing ? canEditRooms : canCreateRooms;
const [showArchived, setShowArchived] = useState(false); const [showArchived, setShowArchived] = useState(false);
const [archivedCount, setArchivedCount] = useState(0); const [archivedCount, setArchivedCount] = useState(0);
const [searchText, setSearchText] = useState(''); const [searchText, setSearchText] = useState('');
@@ -111,6 +117,9 @@ const RoomsPage: React.FC = () => {
const [savingLocker, setSavingLocker] = useState(false); const [savingLocker, setSavingLocker] = useState(false);
const [batchLoading, setBatchLoading] = 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 () => { const handleBatchDelete = async () => {
setBatchLoading(true); setBatchLoading(true);
try { try {
@@ -519,16 +528,17 @@ const RoomsPage: React.FC = () => {
return ( return (
<Space> <Space>
{r.status === 'archived' ? ( {r.status === 'archived' ? (
canEditRooms ? (
<Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}> <Popconfirm title="确定恢复此宿舍?" onConfirm={() => handleRestore(r.id)}>
<PermissionButton <Button
permission="room:edit"
size="small" size="small"
icon={<UndoOutlined />} icon={<UndoOutlined />}
type="link" type="link"
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null
) : ( ) : (
<> <>
<PermissionButton <PermissionButton
@@ -556,15 +566,16 @@ const RoomsPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
{canDeleteRooms ? (
<Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}> <Popconfirm title="确定归档?" onConfirm={() => handleArchive(r.id)}>
<PermissionButton <Button
permission="room:delete"
size="small" size="small"
icon={<InboxOutlined />} icon={<InboxOutlined />}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null}
</> </>
)} )}
</Space> </Space>
@@ -635,6 +646,7 @@ const RoomsPage: React.FC = () => {
</Button> </Button>
</Space> </Space>
<Space wrap className="responsive-toolbar__group"> <Space wrap className="responsive-toolbar__group">
{canDeleteRooms ? (
<Popconfirm <Popconfirm
title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`} title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`}
onConfirm={handleBatchDelete} onConfirm={handleBatchDelete}
@@ -642,16 +654,16 @@ const RoomsPage: React.FC = () => {
cancelText="取消" cancelText="取消"
disabled={selectedRowKeys.length === 0} disabled={selectedRowKeys.length === 0}
> >
<PermissionButton <Button
permission="room:delete"
danger danger
icon={<InboxOutlined />} icon={<InboxOutlined />}
disabled={selectedRowKeys.length === 0} disabled={selectedRowKeys.length === 0}
loading={batchLoading} loading={batchLoading}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null}
<PermissionButton <PermissionButton
permission="room:create" permission="room:create"
type="primary" type="primary"
@@ -664,6 +676,7 @@ const RoomsPage: React.FC = () => {
> >
宿 宿
</PermissionButton> </PermissionButton>
{hasPermission('room:create') ? (
<Upload <Upload
accept=".xlsx,.xls" accept=".xlsx,.xls"
showUploadList={false} showUploadList={false}
@@ -691,6 +704,7 @@ const RoomsPage: React.FC = () => {
> >
<Button icon={<UploadOutlined />}>Excel</Button> <Button icon={<UploadOutlined />}>Excel</Button>
</Upload> </Upload>
) : null}
<PermissionButton <PermissionButton
permission="room:view" permission="room:view"
icon={<DownloadOutlined />} icon={<DownloadOutlined />}
@@ -727,8 +741,8 @@ const RoomsPage: React.FC = () => {
<Modal <Modal
title={editing ? '编辑宿舍' : '添加宿舍'} title={editing ? '编辑宿舍' : '添加宿舍'}
open={modalOpen} open={modalOpen && canSaveRoom}
onOk={handleSave} onOk={canSaveRoom ? handleSave : undefined}
onCancel={() => { onCancel={() => {
setModalOpen(false); setModalOpen(false);
setEditing(null); setEditing(null);
@@ -854,6 +868,7 @@ const RoomsPage: React.FC = () => {
label: `床位管理 (${beds.length})`, label: `床位管理 (${beds.length})`,
children: ( children: (
<div> <div>
{canEditRooms ? (
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}> <div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button <Button
type="primary" type="primary"
@@ -904,6 +919,7 @@ const RoomsPage: React.FC = () => {
</Button> </Button>
</Popconfirm> </Popconfirm>
</div> </div>
) : null}
<Table <Table
dataSource={beds} dataSource={beds}
rowKey="id" rowKey="id"
@@ -987,20 +1003,19 @@ const RoomsPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
{r.status !== 'occupied' && ( {r.status !== 'occupied' && canEditRooms && (
<Popconfirm <Popconfirm
title="确定归档?" title="确定归档?"
onConfirm={() => handleDeleteBed(r.id)} onConfirm={() => handleDeleteBed(r.id)}
> >
<PermissionButton <Button
permission="room:edit"
size="small" size="small"
type="link" type="link"
danger danger
disabled={drawerRoom?.status === 'archived'} disabled={drawerRoom?.status === 'archived'}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
)} )}
</Space> </Space>
@@ -1016,6 +1031,7 @@ const RoomsPage: React.FC = () => {
label: `柜子管理 (${lockers.length})`, label: `柜子管理 (${lockers.length})`,
children: ( children: (
<div> <div>
{canEditRooms ? (
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}> <div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button <Button
type="primary" type="primary"
@@ -1055,6 +1071,7 @@ const RoomsPage: React.FC = () => {
</Button> </Button>
</Popconfirm> </Popconfirm>
</div> </div>
) : null}
<Table <Table
dataSource={lockers} dataSource={lockers}
rowKey="id" rowKey="id"
@@ -1138,20 +1155,19 @@ const RoomsPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
{r.status !== 'occupied' && ( {r.status !== 'occupied' && canEditRooms && (
<Popconfirm <Popconfirm
title="确定归档?" title="确定归档?"
onConfirm={() => handleDeleteLocker(r.id)} onConfirm={() => handleDeleteLocker(r.id)}
> >
<PermissionButton <Button
permission="room:edit"
size="small" size="small"
type="link" type="link"
danger danger
disabled={drawerRoom?.status === 'archived'} disabled={drawerRoom?.status === 'archived'}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
)} )}
</Space> </Space>
@@ -1168,8 +1184,8 @@ const RoomsPage: React.FC = () => {
<Modal <Modal
title={bedEditing ? '编辑床位' : '添加床位'} title={bedEditing ? '编辑床位' : '添加床位'}
open={bedModalOpen} open={bedModalOpen && canEditRooms}
onOk={handleSaveBed} onOk={canEditRooms ? handleSaveBed : undefined}
onCancel={() => { onCancel={() => {
setBedModalOpen(false); setBedModalOpen(false);
setBedEditing(null); setBedEditing(null);
@@ -1198,8 +1214,8 @@ const RoomsPage: React.FC = () => {
<Modal <Modal
title={lockerEditing ? '编辑柜子' : '添加柜子'} title={lockerEditing ? '编辑柜子' : '添加柜子'}
open={lockerModalOpen} open={lockerModalOpen && canEditRooms}
onOk={handleSaveLocker} onOk={canEditRooms ? handleSaveLocker : undefined}
onCancel={() => { onCancel={() => {
setLockerModalOpen(false); setLockerModalOpen(false);
setLockerEditing(null); setLockerEditing(null);

View File

@@ -38,6 +38,7 @@ import EditableCell from '../../components/EditableCell';
import JinshujuMatchModal from '../../components/JinshujuMatchModal'; import JinshujuMatchModal from '../../components/JinshujuMatchModal';
import { maskIdNumber, maskPhone } from '../../utils/sensitive'; import { maskIdNumber, maskPhone } from '../../utils/sensitive';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const statusMap: Record<string, { text: string; color: string }> = { const statusMap: Record<string, { text: string; color: string }> = {
active: { text: '在读', color: 'green' }, active: { text: '在读', color: 'green' },
@@ -84,11 +85,24 @@ interface StudentFilterLookups {
const StudentsPage: React.FC = () => { const StudentsPage: React.FC = () => {
const { modal } = App.useApp(); 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 [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [organizations, setOrganizations] = useState<any[]>([]); const [organizations, setOrganizations] = useState<any[]>([]);
const [editing, setEditing] = useState<any>(null); const [editing, setEditing] = useState<any>(null);
const canSaveStudent = editing ? canEditStudent : canCreateStudent;
const [searchName, setSearchName] = useState(''); const [searchName, setSearchName] = useState('');
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined); const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
const [filterOrganizationId, setFilterOrganizationId] = useState<number | undefined>(undefined); const [filterOrganizationId, setFilterOrganizationId] = useState<number | undefined>(undefined);
@@ -113,13 +127,40 @@ const StudentsPage: React.FC = () => {
const [jinshujuOpen, setJinshujuOpen] = useState(false); 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) => { const handleViewSensitive = (studentId: number, field: string, value: string) => {
modal.confirm({ if (!logCreateRef.current) return;
sensitiveModalRef.current = modal.confirm({
title: '查看敏感信息', title: '查看敏感信息',
content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`, content: `您即将查看 "${field}" 的完整信息。此操作将被记录。`,
okText: '确认查看', okText: '确认查看',
cancelText: '取消', cancelText: '取消',
onOk: async () => { onOk: async () => {
if (!logCreateRef.current) return;
try { try {
await api.post('/operation-logs/audit', { await api.post('/operation-logs/audit', {
module: '学生管理', module: '学生管理',
@@ -137,6 +178,9 @@ const StudentsPage: React.FC = () => {
message.error('审计日志记录失败,请稍后重试'); message.error('审计日志记录失败,请稍后重试');
} }
}, },
afterClose: () => {
sensitiveModalRef.current = null;
},
}); });
}; };
@@ -189,12 +233,26 @@ const StudentsPage: React.FC = () => {
}, [fetchData]); }, [fetchData]);
useEffect(() => { useEffect(() => {
if (!canLoadOrganizations) {
setOrganizations([]);
setFilterOrganizationId(undefined);
return;
}
if (canViewOrganizations) {
api api
.get('/organizations', { params: { includeArchived: 'false' } }) .get('/organizations', { params: { includeArchived: 'false' } })
.then((res: unknown) => { .then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string }>); setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
}) })
.catch(() => {}); .catch(() => {});
} else {
api
.get('/organizations/options')
.then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string; isHost?: boolean }>);
})
.catch(() => {});
}
api api
.get<StudentFilterLookups>('/students/filter-lookups') .get<StudentFilterLookups>('/students/filter-lookups')
.then((res) => { .then((res) => {
@@ -202,7 +260,7 @@ const StudentsPage: React.FC = () => {
setTeacherOptions(res.teachers || []); setTeacherOptions(res.teachers || []);
}) })
.catch(() => {}); .catch(() => {});
}, []); }, [canLoadOrganizations]);
const handleSave = async () => { const handleSave = async () => {
const values = await form.validateFields(); const values = await form.validateFields();
setSaving(true); setSaving(true);
@@ -417,6 +475,7 @@ const StudentsPage: React.FC = () => {
return ( return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}> <span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span> <span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
{hasPermission('log:create') ? (
<Button <Button
type="link" type="link"
size="small" size="small"
@@ -426,6 +485,7 @@ const StudentsPage: React.FC = () => {
> >
<EyeOutlined style={{ fontSize: 12, color: '#999' }} /> <EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button> </Button>
) : null}
</span> </span>
); );
}, },
@@ -454,6 +514,7 @@ const StudentsPage: React.FC = () => {
return ( return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}> <span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskIdNumber(v)}</span> <span style={{ marginRight: 4 }}>{maskIdNumber(v)}</span>
{hasPermission('log:create') ? (
<Button <Button
type="link" type="link"
size="small" size="small"
@@ -463,6 +524,7 @@ const StudentsPage: React.FC = () => {
> >
<EyeOutlined style={{ fontSize: 12, color: '#999' }} /> <EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button> </Button>
) : null}
</span> </span>
); );
}, },
@@ -506,6 +568,7 @@ const StudentsPage: React.FC = () => {
return ( return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}> <span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span> <span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
{hasPermission('log:create') ? (
<Button <Button
type="link" type="link"
size="small" size="small"
@@ -515,6 +578,7 @@ const StudentsPage: React.FC = () => {
> >
<EyeOutlined style={{ fontSize: 12, color: '#999' }} /> <EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button> </Button>
) : null}
</span> </span>
); );
}, },
@@ -523,7 +587,8 @@ const StudentsPage: React.FC = () => {
title: '所属机构', title: '所属机构',
dataIndex: 'organization', dataIndex: 'organization',
width: 100, width: 100,
render: (organization: { name?: string } | null, record: any) => ( render: (organization: { name?: string } | null, record: any) =>
canChooseOrganization ? (
<EditableCell <EditableCell
value={record.organizationId} value={record.organizationId}
editor="select" editor="select"
@@ -544,6 +609,10 @@ const StudentsPage: React.FC = () => {
'-' '-'
)} )}
</EditableCell> </EditableCell>
) : organization?.name ? (
<Tag color="purple">{organization.name}</Tag>
) : (
'-'
), ),
}, },
{ {
@@ -593,21 +662,18 @@ const StudentsPage: React.FC = () => {
render: (_: any, record: any) => ( render: (_: any, record: any) => (
<Space> <Space>
{record.status === 'archived' ? ( {record.status === 'archived' ? (
canEditStudent ? (
<Popconfirm <Popconfirm
title="确定恢复此学生?恢复后将重新出现在学生列表中。" title="确定恢复此学生?恢复后将重新出现在学生列表中。"
onConfirm={() => handleRestore(record.id)} onConfirm={() => handleRestore(record.id)}
okText="恢复" okText="恢复"
cancelText="取消" cancelText="取消"
> >
<PermissionButton <Button size="small" icon={<UndoOutlined />} type="link">
permission="student:edit"
size="small"
icon={<UndoOutlined />}
type="link"
>
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null
) : ( ) : (
<> <>
<PermissionButton <PermissionButton
@@ -629,27 +695,36 @@ const StudentsPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
{canDeleteStudent ? (
<Popconfirm <Popconfirm
title="归档后不会删除数据,可随时恢复。确定归档?" title="归档后不会删除数据,可随时恢复。确定归档?"
onConfirm={() => handleArchive(record.id)} onConfirm={() => handleArchive(record.id)}
okText="归档" okText="归档"
cancelText="取消" cancelText="取消"
> >
<PermissionButton <Button
permission="student:delete"
size="small" size="small"
icon={<InboxOutlined />} icon={<InboxOutlined />}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null}
</> </>
)} )}
</Space> </Space>
), ),
}, },
], ],
[handleViewSensitive, openDrawer, showArchived, organizations, saveCell], [
handleViewSensitive,
openDrawer,
showArchived,
organizations,
saveCell,
hasPermission,
canChooseOrganization,
],
); );
return ( return (
@@ -679,6 +754,7 @@ const StudentsPage: React.FC = () => {
</Select.Option> </Select.Option>
))} ))}
</Select> </Select>
{canViewOrganizations ? (
<Select <Select
placeholder="所属机构" placeholder="所属机构"
allowClear allowClear
@@ -694,6 +770,7 @@ const StudentsPage: React.FC = () => {
</Select.Option> </Select.Option>
))} ))}
</Select> </Select>
) : null}
<Select <Select
placeholder="所属班级" placeholder="所属班级"
allowClear allowClear
@@ -734,6 +811,7 @@ const StudentsPage: React.FC = () => {
</Button> </Button>
</Space> </Space>
<Space wrap className="responsive-toolbar__group"> <Space wrap className="responsive-toolbar__group">
{canDeleteStudent ? (
<Popconfirm <Popconfirm
title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`} title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`}
onConfirm={handleBatchDelete} onConfirm={handleBatchDelete}
@@ -741,16 +819,16 @@ const StudentsPage: React.FC = () => {
cancelText="取消" cancelText="取消"
disabled={selectedRowKeys.length === 0} disabled={selectedRowKeys.length === 0}
> >
<PermissionButton <Button
permission="student:delete"
danger danger
icon={<InboxOutlined />} icon={<InboxOutlined />}
disabled={selectedRowKeys.length === 0} disabled={selectedRowKeys.length === 0}
loading={batchLoading} loading={batchLoading}
> >
</PermissionButton> </Button>
</Popconfirm> </Popconfirm>
) : null}
<PermissionButton <PermissionButton
permission="student:create" permission="student:create"
type="primary" type="primary"
@@ -765,6 +843,8 @@ const StudentsPage: React.FC = () => {
> >
</PermissionButton> </PermissionButton>
{hasPermission('student:import') ? (
<>
<Upload <Upload
accept=".xlsx,.xls" accept=".xlsx,.xls"
showUploadList={false} showUploadList={false}
@@ -779,13 +859,13 @@ const StudentsPage: React.FC = () => {
> >
<Button icon={<SwapOutlined />}></Button> <Button icon={<SwapOutlined />}></Button>
</Upload> </Upload>
<PermissionButton </>
permission="student:edit" ) : null}
icon={<CloudUploadOutlined />} {canSyncJinshuju ? (
onClick={() => setJinshujuOpen(true)} <Button icon={<CloudUploadOutlined />} onClick={() => setJinshujuOpen(true)}>
>
</PermissionButton> </Button>
) : null}
<PermissionButton <PermissionButton
permission="student:view" permission="student:view"
icon={<DownloadOutlined />} icon={<DownloadOutlined />}
@@ -894,8 +974,8 @@ const StudentsPage: React.FC = () => {
title={editing ? '编辑学生' : '添加学生'} title={editing ? '编辑学生' : '添加学生'}
className="student-form-modal" className="student-form-modal"
width={720} width={720}
open={modalOpen} open={modalOpen && canSaveStudent}
onOk={handleSave} onOk={canSaveStudent ? handleSave : undefined}
onCancel={() => { onCancel={() => {
setModalOpen(false); setModalOpen(false);
setEditing(null); setEditing(null);
@@ -934,6 +1014,7 @@ const StudentsPage: React.FC = () => {
<Form.Item name="emergencyPhone" label="紧急联系人电话"> <Form.Item name="emergencyPhone" label="紧急联系人电话">
<Input /> <Input />
</Form.Item> </Form.Item>
{canChooseOrganization ? (
<Form.Item <Form.Item
name="organizationId" name="organizationId"
label="所属机构" label="所属机构"
@@ -946,11 +1027,14 @@ const StudentsPage: React.FC = () => {
options={organizations.map( options={organizations.map(
(organization: { id: number; name: string; isHost?: boolean }) => ({ (organization: { id: number; name: string; isHost?: boolean }) => ({
value: organization.id, value: organization.id,
label: organization.isHost ? `${organization.name}(本机构)` : organization.name, label: organization.isHost
? `${organization.name}(本机构)`
: organization.name,
}), }),
)} )}
/> />
</Form.Item> </Form.Item>
) : null}
<Form.Item name="supervisor" label="负责人/班主任"> <Form.Item name="supervisor" label="负责人/班主任">
<Input /> <Input />
</Form.Item> </Form.Item>
@@ -968,11 +1052,16 @@ const StudentsPage: React.FC = () => {
</Form> </Form>
</Modal> </Modal>
{canSyncJinshuju ? (
<JinshujuMatchModal <JinshujuMatchModal
open={jinshujuOpen} open={jinshujuOpen}
onClose={() => setJinshujuOpen(false)} onClose={() => setJinshujuOpen(false)}
onApplied={() => { setJinshujuOpen(false); fetchData(); }} onApplied={() => {
setJinshujuOpen(false);
fetchData();
}}
/> />
) : null}
<Drawer <Drawer
title={null} title={null}
open={drawerOpen} open={drawerOpen}

View File

@@ -1,10 +1,12 @@
import React, { useEffect, useState, useCallback, useMemo } from 'react'; 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 { EditOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import api from '../../api'; import api from '../../api';
import { message } from '../../ui/app-message'; import { message } from '../../ui/app-message';
import EditableCell from '../../components/EditableCell'; import EditableCell from '../../components/EditableCell';
import PermissionButton from '../../components/PermissionButton';
import { usePermission } from '../../hooks/usePermission';
interface TeacherRow { interface TeacherRow {
id: number; id: number;
@@ -50,6 +52,8 @@ const ROLE_TYPE_LABELS: Record<string, string> = {
const DEFAULT_PAGE_SIZE = 20; const DEFAULT_PAGE_SIZE = 20;
const TeachersPage: React.FC = () => { const TeachersPage: React.FC = () => {
const { hasPermission } = usePermission();
const canEditTeachers = hasPermission('teacher:edit');
const [data, setData] = useState<TeacherRow[]>([]); const [data, setData] = useState<TeacherRow[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
@@ -190,7 +194,8 @@ const TeachersPage: React.FC = () => {
key: 'actions', key: 'actions',
width: 100, width: 100,
render: (_: unknown, r: TeacherRow) => ( render: (_: unknown, r: TeacherRow) => (
<Button <PermissionButton
permission="teacher:edit"
size="small" size="small"
icon={<EditOutlined />} icon={<EditOutlined />}
onClick={() => { onClick={() => {
@@ -203,11 +208,11 @@ const TeachersPage: React.FC = () => {
}} }}
> >
</Button> </PermissionButton>
), ),
}, },
], ],
[saveProfileCell], [saveProfileCell, form],
); );
return ( return (
@@ -263,8 +268,8 @@ const TeachersPage: React.FC = () => {
/> />
<Modal <Modal
title={`编辑档案 — ${profileModal?.name || ''}`} title={`编辑档案 — ${profileModal?.name || ''}`}
open={!!profileModal} open={!!profileModal && canEditTeachers}
onOk={handleSaveProfile} onOk={canEditTeachers ? handleSaveProfile : undefined}
onCancel={() => setProfileModal(null)} onCancel={() => setProfileModal(null)}
okText="保存" okText="保存"
confirmLoading={saving} confirmLoading={saving}

View 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']);
});
});

View File

@@ -159,7 +159,7 @@ export class OccupanciesController {
} }
@Delete(':id') @Delete(':id')
@RequirePermission('occupancy:view') @RequirePermission('occupancy:delete')
async remove(@Param('id') id: string, @Request() req: any) { async remove(@Param('id') id: string, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req); const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.remove(+id); const result = await this.service.remove(+id);
@@ -177,7 +177,7 @@ export class OccupanciesController {
} }
@Post('batch-delete') @Post('batch-delete')
@RequirePermission('occupancy:view') @RequirePermission('occupancy:delete')
async batchRemove(@Body() body: { ids: number[] }, @Request() req: any) { async batchRemove(@Body() body: { ids: number[] }, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req); const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchRemove(body.ids || []); const result = await this.service.batchRemove(body.ids || []);

View File

@@ -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',
]);
});
});

View File

@@ -25,6 +25,12 @@ export class OrganizationsController {
private logService: OperationLogsService, private logService: OperationLogsService,
) {} ) {}
@Get('options')
@RequirePermission('organization:view', 'student:create', 'student:edit')
findOptions() {
return this.service.findOptions();
}
@Get() @Get()
@RequirePermission('organization:view') @RequirePermission('organization:view')
findAll( findAll(

View File

@@ -27,4 +27,21 @@ describe('OrganizationsService — host organization rules', () => {
await expect(service.remove(1)).rejects.toBeInstanceOf(BadRequestException); await expect(service.remove(1)).rejects.toBeInstanceOf(BadRequestException);
expect(repo.update).not.toHaveBeenCalled(); 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);
});
}); });

View File

@@ -30,6 +30,14 @@ export class OrganizationsService {
return this.repo.find({ where, order: { isHost: 'DESC', name: 'ASC' } }); 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) { async findOne(id: number) {
const organization = await this.repo.findOne({ where: { id } }); const organization = await this.repo.findOne({ where: { id } });
if (!organization) throw new NotFoundException('机构不存在'); if (!organization) throw new NotFoundException('机构不存在');