fix: align permission-gated UI actions

This commit is contained in:
2026-07-23 11:32:13 +08:00
parent adf738288f
commit c98d37307e
28 changed files with 1340 additions and 718 deletions

View File

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

View File

@@ -0,0 +1,67 @@
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('fails closed after profile refresh failure', async () => {
writePermissions(['student:edit']);
beginPermissionVerification();
clearPermissions('ready');
expect(readPermissionState()).toEqual({ permissions: [], status: 'ready' });
await renderPermissionButton();
expect(container?.textContent).not.toContain('编辑学生');
expect(localStorage.getItem('permissions')).toBeNull();
});
});

View File

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

View File

@@ -1,11 +1,14 @@
import React from 'react';
import { Navigate } from 'react-router-dom';
import { Result } from 'antd';
import { Result, Spin } from 'antd';
import { usePermission } from '../hooks/usePermission';
import { findRoleAwareLandingPath } from '../auth/menu-policy';
const DefaultRoute: React.FC = () => {
const { permissions } = usePermission();
const { permissions, permissionsReady } = usePermission();
if (!permissionsReady) {
return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;
}
const roles = (() => {
try {
return JSON.parse(localStorage.getItem('user') || '{}').roles || [];

View File

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

View File

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

View File

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

View File

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

View File

@@ -31,7 +31,11 @@ import {
} from '@ant-design/icons';
import { usePermission } from '../hooks/usePermission';
import api from '../api';
import { writePermissions } from '../auth/permission-store';
import {
beginPermissionVerification,
clearPermissions,
writePermissions,
} from '../auth/permission-store';
import NotificationBell from '../components/NotificationBell';
import RouteDock from '../components/RouteDock';
import { buildMenu, type AppMenuItem } from '../auth/menu-policy';
@@ -82,6 +86,7 @@ const MainLayout: React.FC = () => {
useEffect(() => {
let cancelled = false;
beginPermissionVerification();
api
.get<{ id: number; username: string; permissions: string[]; roles?: string[] }>(
'/auth/profile',
@@ -95,6 +100,7 @@ const MainLayout: React.FC = () => {
setUser(nextUser);
})
.catch(() => {
if (!cancelled) clearPermissions('ready');
// The API interceptor handles expired/invalid sessions.
});
return () => {
@@ -116,7 +122,7 @@ const MainLayout: React.FC = () => {
const handleLogout = useCallback(() => {
localStorage.removeItem('token');
localStorage.removeItem('user');
localStorage.removeItem('permissions');
clearPermissions();
navigate('/login');
}, [navigate]);

View File

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

View File

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

View File

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

View File

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

View File

@@ -25,6 +25,7 @@ import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const statusMap: Record<string, { text: string; color: string }> = {
available: { text: '可用', color: 'green' },
@@ -48,6 +49,7 @@ const typeColor: Record<string, string> = {
};
const ClassroomsPage: React.FC = () => {
const { hasPermission } = usePermission();
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
@@ -402,27 +404,29 @@ const ClassroomsPage: React.FC = () => {
>
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
try {
const res: any = await api.post('/classrooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
message.success(res.message);
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
{hasPermission('classroom:create') ? (
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
try {
const res: any = await api.post('/classrooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
message.success(res.message);
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
) : null}
<PermissionButton
permission="classroom:view"
icon={<DownloadOutlined />}

View File

@@ -8,6 +8,7 @@ import EditableCell from '../../components/EditableCell';
import { useViewSensitive } from '../../hooks/useViewSensitive';
import { maskPhone } from '../../utils/sensitive';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
import type { ExamItem } from './types';
import './style.css';
@@ -21,12 +22,29 @@ interface ScoreRow {
rank: number | null;
}
interface ExamDetail extends ExamItem { scores: ScoreRow[] }
interface ExamDetail extends ExamItem {
scores: ScoreRow[];
}
const PhoneCell: React.FC<{ row: ScoreRow }> = ({ row }) => {
const reveal = useViewSensitive(row.studentId, '考试管理');
const { hasPermission } = usePermission();
if (!row.phone) return <>-</>;
return <Space size={4}><span>{maskPhone(row.phone)}</span><Tooltip title="查看完整手机号"><Button type="text" size="small" icon={<EyeOutlined />} onClick={() => reveal('手机号', row.phone)} /></Tooltip></Space>;
return (
<Space size={4}>
<span>{maskPhone(row.phone)}</span>
{hasPermission('log:create') ? (
<Tooltip title="查看完整手机号">
<Button
type="text"
size="small"
icon={<EyeOutlined />}
onClick={() => reveal('手机号', row.phone)}
/>
</Tooltip>
) : null}
</Space>
);
};
const ExamDetailPage: React.FC = () => {
@@ -37,12 +55,18 @@ const ExamDetailPage: React.FC = () => {
const load = useCallback(async () => {
setLoading(true);
try { setDetail(await api.get<ExamDetail>(`/exams/${id}`)); }
catch (error) { message.error((error as { message?: string })?.message || '加载考试失败'); }
finally { setLoading(false); }
try {
setDetail(await api.get<ExamDetail>(`/exams/${id}`));
} catch (error) {
message.error((error as { message?: string })?.message || '加载考试失败');
} finally {
setLoading(false);
}
}, [id]);
useEffect(() => { void load(); }, [load]);
useEffect(() => {
void load();
}, [load]);
const saveScore = async (row: ScoreRow, value: number | undefined) => {
await api.put(`/exams/${id}/scores/${row.id}`, { score: value ?? null });
message.success('成绩已保存');
@@ -52,7 +76,11 @@ const ExamDetailPage: React.FC = () => {
const columns = useMemo<ColumnsType<ScoreRow>>(() => {
if (!detail) return [];
const fixed = [
{ title: '手机号*', width: 155, render: (_: unknown, row: ScoreRow) => <PhoneCell row={row} /> },
{
title: '手机号*',
width: 155,
render: (_: unknown, row: ScoreRow) => <PhoneCell row={row} />,
},
{ title: '姓名', dataIndex: 'name', width: 100 },
{ title: '考试类型*', width: 110, render: () => detail.examType },
{ title: '考试名称', width: 170, render: () => detail.examName },
@@ -60,32 +88,84 @@ const ExamDetailPage: React.FC = () => {
];
return [
...fixed,
{ title: '成绩*', dataIndex: 'score', width: 100, render: (value: number | null, row: ScoreRow) => <EditableCell<number | undefined> value={value ?? undefined} editor="money" min={0} max={999.99} permission="exam:view" onSave={(next) => saveScore(row, next)}>{value ?? '-'}</EditableCell> },
{ title: '班级均分', dataIndex: 'classAvg', width: 110, render: (value: number | null) => value ?? '-' },
{ title: '排名', dataIndex: 'rank', width: 80, render: (value: number | null) => value ?? '-' },
{
title: '成绩*',
dataIndex: 'score',
width: 100,
render: (value: number | null, row: ScoreRow) => (
<EditableCell<number | undefined>
value={value ?? undefined}
editor="money"
min={0}
max={999.99}
permission="exam:view"
onSave={(next) => saveScore(row, next)}
>
{value ?? '-'}
</EditableCell>
),
},
{
title: '班级均分',
dataIndex: 'classAvg',
width: 110,
render: (value: number | null) => value ?? '-',
},
{
title: '排名',
dataIndex: 'rank',
width: 80,
render: (value: number | null) => value ?? '-',
},
{ title: '考试日期', width: 110, render: () => detail.examDate },
{ title: '关联报读(班级名)', width: 180, render: () => detail.className },
];
}, [detail]);
if (loading && !detail) return <div className="exam-detail-loading"><Spin size="large" /></div>;
if (loading && !detail)
return (
<div className="exam-detail-loading">
<Spin size="large" />
</div>
);
if (!detail) return <Empty description="考试不存在或无权访问" />;
const average = detail.scores.find((row) => row.classAvg !== null)?.classAvg ?? null;
return (
<div className="exam-detail-page">
<div className="exam-detail-header"><Space><Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/exams')}></Button><h2>{detail.examName}</h2></Space></div>
<div className="exam-detail-header">
<Space>
<Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/exams')}>
</Button>
<h2>{detail.examName}</h2>
</Space>
</div>
<Card className="exam-summary">
<Descriptions column={{ xs: 1, sm: 2, lg: 5 }}>
<Descriptions.Item label="考试类型">{detail.examType}</Descriptions.Item>
<Descriptions.Item label="科目">{detail.subject}</Descriptions.Item>
<Descriptions.Item label="考试班级">{detail.className}</Descriptions.Item>
<Descriptions.Item label="考试日期">{detail.examDate}</Descriptions.Item>
<Descriptions.Item label="录入进度">{detail.enteredScores}/{detail.totalStudents} {average ?? '-'}</Descriptions.Item>
<Descriptions.Item label="录入进度">
{detail.enteredScores}/{detail.totalStudents} {average ?? '-'}
</Descriptions.Item>
</Descriptions>
</Card>
<Card title="成绩表">
<Table<ScoreRow> columns={columns} dataSource={detail.scores} rowKey="id" loading={loading} scroll={{ x: 1310 }} pagination={{ defaultPageSize: 30, showSizeChanger: true, pageSizeOptions: [30, 50, 100] }} locale={{ emptyText: <Empty description="暂无学生名单" /> }} />
<Table<ScoreRow>
columns={columns}
dataSource={detail.scores}
rowKey="id"
loading={loading}
scroll={{ x: 1310 }}
pagination={{
defaultPageSize: 30,
showSizeChanger: true,
pageSizeOptions: [30, 50, 100],
}}
locale={{ emptyText: <Empty description="暂无学生名单" /> }}
/>
</Card>
</div>
);

View File

@@ -29,6 +29,7 @@ import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { downloadBlob } from '../../utils/download';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const { RangePicker } = DatePicker;
@@ -38,6 +39,7 @@ const isFormValidationError = (error: unknown) =>
Array.isArray((error as { errorFields?: unknown }).errorFields);
const ExpensesPage: React.FC = () => {
const { hasPermission } = usePermission();
const [roomExpenses, setRoomExpenses] = useState<any[]>([]);
const [personalExpenses, setPersonalExpenses] = useState<any[]>([]);
const [rooms, setRooms] = useState<any[]>([]);
@@ -574,33 +576,35 @@ const ExpensesPage: React.FC = () => {
onChange={(v) => setRoomTypeFilter(v)}
options={typeOptions}
/>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
try {
const res: any = await api.post('/expenses/utility/import', formData);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
{hasPermission('expense:create') ? (
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
try {
const res: any = await api.post('/expenses/utility/import', formData);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
) : null}
<PermissionButton
permission="expense:view"
icon={<DownloadOutlined />}
@@ -697,27 +701,29 @@ const ExpensesPage: React.FC = () => {
onChange={(v) => setPersonalTypeFilter(v)}
options={personalTypeOptions}
/>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
try {
const formData = new FormData();
formData.append('file', file);
const res: any = await api.post('/expenses/personal/import', formData);
message.success(res.message || '导入完成');
if (res.errors?.length)
res.errors.forEach((e: string) => message.warning(e));
fetchData();
onSuccess?.(res);
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}></Button>
</Upload>
{hasPermission('expense:create') ? (
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
try {
const formData = new FormData();
formData.append('file', file);
const res: any = await api.post('/expenses/personal/import', formData);
message.success(res.message || '导入完成');
if (res.errors?.length)
res.errors.forEach((e: string) => message.warning(e));
fetchData();
onSuccess?.(res);
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Button icon={<UploadOutlined />}></Button>
</Upload>
) : null}
<PermissionButton
permission="expense:view"
icon={<DownloadOutlined />}

View File

@@ -111,7 +111,8 @@ interface DeleteAttendanceGroupsResponse {
}
const IntegrationConfigPage: React.FC = () => {
const { hasAllPermissions } = usePermission();
const { hasPermission, hasAllPermissions } = usePermission();
const canCreateClass = hasPermission('class:create');
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
@@ -458,12 +459,14 @@ const IntegrationConfigPage: React.FC = () => {
>
</Button>
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
>
</Button>
{canCreateClass ? (
<Button
disabled={checkedKeys.filter((k) => String(k).startsWith('user-')).length === 0}
onClick={() => setClassModalOpen(true)}
>
</Button>
) : null}
</Space>
}
>
@@ -485,9 +488,11 @@ const IntegrationConfigPage: React.FC = () => {
title="班级列表"
size="small"
extra={
<Button size="small" onClick={() => setClassModalOpen(true)}>
+
</Button>
canCreateClass ? (
<Button size="small" onClick={() => setClassModalOpen(true)}>
+
</Button>
) : null
}
>
<List
@@ -514,45 +519,47 @@ const IntegrationConfigPage: React.FC = () => {
</Row>
{/* Create class Modal */}
<Modal
title="创建班级"
open={classModalOpen}
onOk={handleCreateClass}
onCancel={() => {
setClassModalOpen(false);
classForm.resetFields();
}}
confirmLoading={importing}
destroyOnClose
>
<Form form={classForm} layout="vertical">
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
<Input placeholder="如 CS2024-01" />
</Form.Item>
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
<Select
options={[
{ value: 'culture', label: '文化课' },
{ value: 'professional', label: '专业课' },
{ value: 'bootcamp', label: '集训营' },
{ value: 'sprint', label: '冲刺班' },
]}
/>
</Form.Item>
<Form.Item name="startDate" label="开班日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="endDate" label="结束日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
{canCreateClass ? (
<Modal
title="创建班级"
open={classModalOpen}
onOk={handleCreateClass}
onCancel={() => {
setClassModalOpen(false);
classForm.resetFields();
}}
confirmLoading={importing}
destroyOnClose
>
<Form form={classForm} layout="vertical">
<Form.Item name="name" label="班级名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="code" label="班级编码" rules={[{ required: true }]}>
<Input placeholder="如 CS2024-01" />
</Form.Item>
<Form.Item name="classType" label="班型" rules={[{ required: true }]}>
<Select
options={[
{ value: 'culture', label: '文化课' },
{ value: 'professional', label: '专业课' },
{ value: 'bootcamp', label: '集训营' },
{ value: 'sprint', label: '冲刺班' },
]}
/>
</Form.Item>
<Form.Item name="startDate" label="开班日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="endDate" label="结束日期">
<DatePicker style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="notes" label="备注">
<Input.TextArea rows={2} />
</Form.Item>
</Form>
</Modal>
) : null}
</Drawer>
)}
<Modal

View File

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

View File

@@ -33,10 +33,13 @@ import { maskPhone, maskIdNumber } from '../../utils/sensitive';
import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message';
import { buildCheckInPayload, buildTransferPayload } from './occupancy-form';
import { usePermission } from '../../hooks/usePermission';
const { RangePicker } = DatePicker;
const OccupanciesPage: React.FC = () => {
const { hasPermission } = usePermission();
const canCheckIn = hasPermission('occupancy:checkin');
const [data, setData] = useState<any[]>([]);
const [students, setStudents] = useState<any[]>([]);
const [rooms, setRooms] = useState<any[]>([]);
@@ -93,7 +96,12 @@ const OccupanciesPage: React.FC = () => {
[data, selectedRowKeys],
);
const latestSelectedCheckInDate = useMemo(
() => selectedBatchRecords.map((item) => item.checkInDate).filter(Boolean).sort().at(-1),
() =>
selectedBatchRecords
.map((item) => item.checkInDate)
.filter(Boolean)
.sort()
.at(-1),
[selectedBatchRecords],
);
const latestSelectedBillingStartDate = useMemo(
@@ -106,7 +114,8 @@ const OccupanciesPage: React.FC = () => {
[selectedBatchRecords],
);
const dateNotBefore = (start: string | Dayjs | null | undefined, messageText: string) =>
const dateNotBefore =
(start: string | Dayjs | null | undefined, messageText: string) =>
(_: unknown, value?: Dayjs | null) => {
if (!value || !start) return Promise.resolve();
const startDate = dayjs.isDayjs(start) ? start : dayjs(start);
@@ -457,46 +466,77 @@ const OccupanciesPage: React.FC = () => {
>
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
const params = new URLSearchParams();
if (autoDeposit) {
params.set('autoDeposit', 'true');
params.set('depositAmount', String(depositAmount));
}
try {
const res: any = await api.post(
`/occupancies/import?${params.toString()}`,
formData,
{ headers: { 'Content-Type': 'multipart/form-data' } },
);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
<Button type="primary" ghost icon={<UploadOutlined />}>
</Button>
</Tooltip>
</Upload>
{canCheckIn ? (
<>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async ({ file, onSuccess, onError }: any) => {
const formData = new FormData();
formData.append('file', file);
const params = new URLSearchParams();
if (autoDeposit) {
params.set('autoDeposit', 'true');
params.set('depositAmount', String(depositAmount));
}
try {
const res: any = await api.post(
`/occupancies/import?${params.toString()}`,
formData,
{ headers: { 'Content-Type': 'multipart/form-data' } },
);
if (res.errors?.length > 0) {
Modal.warning({
title: res.message,
content: res.errors.join('\n'),
width: 500,
});
} else {
message.success(res.message);
}
onSuccess?.(res);
fetchData();
} catch (e: any) {
message.error(e?.message || '导入失败');
onError?.(e);
}
}}
>
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
<Button type="primary" ghost icon={<UploadOutlined />}>
</Button>
</Tooltip>
</Upload>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
{autoDeposit && (
<Space.Compact>
<InputNumber
size="small"
min={0}
value={depositAmount}
onChange={(v) => setDepositAmount(v || 500)}
style={{ width: 60 }}
/>
<span
style={{
padding: '0 8px',
display: 'flex',
alignItems: 'center',
border: '1px solid #d9d9d9',
backgroundColor: '#fafafa',
fontSize: 12,
}}
>
</span>
</Space.Compact>
)}
</span>
</>
) : null}
<PermissionButton
permission="occupancy:view"
icon={<DownloadOutlined />}
@@ -521,33 +561,6 @@ const OccupanciesPage: React.FC = () => {
>
</PermissionButton>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<Switch size="small" checked={autoDeposit} onChange={setAutoDeposit} />
{autoDeposit && (
<Space.Compact>
<InputNumber
size="small"
min={0}
value={depositAmount}
onChange={(v) => setDepositAmount(v || 500)}
style={{ width: 60 }}
/>
<span
style={{
padding: '0 8px',
display: 'flex',
alignItems: 'center',
border: '1px solid #d9d9d9',
backgroundColor: '#fafafa',
fontSize: 12,
}}
>
</span>
</Space.Compact>
)}
</span>
</Space>
</div>
{selectedRowKeys.length > 0 && (
@@ -642,7 +655,11 @@ const OccupanciesPage: React.FC = () => {
.filter((s: any) => s.status === 'active')
.map((s: any) => {
const activeOccupancy = activeOccupancyByStudentId.get(s.id);
const identifier = s.idNumber ? maskIdNumber(s.idNumber) : s.phone ? maskPhone(s.phone) : '';
const identifier = s.idNumber
? maskIdNumber(s.idNumber)
: s.phone
? maskPhone(s.phone)
: '';
return {
value: s.id,
label: `${s.name} (${identifier})${activeOccupancy ? ` · 已入住${activeOccupancy.room?.roomNumber ? ` ${activeOccupancy.room.roomNumber}` : ''}` : ''}`,
@@ -668,18 +685,25 @@ const OccupanciesPage: React.FC = () => {
}))}
/>
</Form.Item>
<Form.Item name="checkInDate" label="入住日期" rules={[{ required: true, message: '请选择入住日期' }]}>
<Form.Item
name="checkInDate"
label="入住日期"
rules={[{ required: true, message: '请选择入住日期' }]}
>
<DatePicker style={{ width: '100%' }} placeholder="选择入住日期" format="YYYY-MM-DD" />
</Form.Item>
<Form.Item
name="billingStartDate"
label="计费起始日"
dependencies={["checkInDate"]}
dependencies={['checkInDate']}
extra="默认与入住日期相同,可调整(如学生要求从次日开始计费)"
rules={[
{ required: true, message: '请选择计费起始日' },
({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('checkInDate'), '计费起始日不能早于入住日期'),
validator: dateNotBefore(
getFieldValue('checkInDate'),
'计费起始日不能早于入住日期',
),
}),
]}
>
@@ -689,7 +713,11 @@ const OccupanciesPage: React.FC = () => {
format="YYYY-MM-DD"
/>
</Form.Item>
<Form.Item name="stayType" label="入住类型" rules={[{ required: true, message: '请选择入住类型' }]}>
<Form.Item
name="stayType"
label="入住类型"
rules={[{ required: true, message: '请选择入住类型' }]}
>
<Select
options={[
{ value: 'short', label: '短租' },
@@ -714,7 +742,9 @@ const OccupanciesPage: React.FC = () => {
<Select
placeholder={selectedCheckInRoomId ? '请选择床位' : '请先选择房间'}
loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0}
disabled={
!selectedCheckInRoomId || availableResourcesLoading || availableBeds.length === 0
}
options={availableBeds.map((b) => ({
value: b.id,
label: b.bedNumber,
@@ -732,7 +762,9 @@ const OccupanciesPage: React.FC = () => {
allowClear
placeholder="可选分配柜子"
loading={availableResourcesLoading}
disabled={!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0}
disabled={
!selectedCheckInRoomId || availableResourcesLoading || availableLockers.length === 0
}
options={availableLockers.map((l) => ({
value: l.id,
label: l.lockerNumber,
@@ -792,12 +824,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item
name="billingEndDate"
label="计费截止日"
dependencies={["checkOutDate"]}
dependencies={['checkOutDate']}
extra="默认与退宿日期相同"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(
checkOutModal?.billingStartDate || checkOutModal?.checkInDate || getFieldValue('checkOutDate'),
checkOutModal?.billingStartDate ||
checkOutModal?.checkInDate ||
getFieldValue('checkOutDate'),
'计费截止日不能早于计费起始日',
),
}),
@@ -948,7 +982,11 @@ const OccupanciesPage: React.FC = () => {
<Select
placeholder={selectedTransferRoomId ? '请选择目标床位' : '请先选择目标宿舍'}
loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableBeds.length === 0}
disabled={
!selectedTransferRoomId ||
transferResourcesLoading ||
transferAvailableBeds.length === 0
}
options={transferAvailableBeds.map((bed) => ({
value: bed.id,
label: bed.bedNumber,
@@ -966,7 +1004,11 @@ const OccupanciesPage: React.FC = () => {
allowClear
placeholder="可选分配目标宿舍柜子"
loading={transferResourcesLoading}
disabled={!selectedTransferRoomId || transferResourcesLoading || transferAvailableLockers.length === 0}
disabled={
!selectedTransferRoomId ||
transferResourcesLoading ||
transferAvailableLockers.length === 0
}
options={transferAvailableLockers.map((locker) => ({
value: locker.id,
label: locker.lockerNumber,
@@ -979,7 +1021,9 @@ const OccupanciesPage: React.FC = () => {
label="换房日期"
rules={[
{ required: true, message: '请选择换房日期' },
{ validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期') },
{
validator: dateNotBefore(transferModal?.checkInDate, '换房日期不能早于原入住日期'),
},
]}
>
<DatePicker style={{ width: '100%' }} placeholder="选择换房日期" format="YYYY-MM-DD" />
@@ -987,12 +1031,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item
name="oldBillingEndDate"
label="旧房计费截止日"
dependencies={["transferDate"]}
dependencies={['transferDate']}
extra="默认为换房当天"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(
transferModal?.billingStartDate || transferModal?.checkInDate || getFieldValue('transferDate'),
transferModal?.billingStartDate ||
transferModal?.checkInDate ||
getFieldValue('transferDate'),
'旧房计费截止日不能早于计费起始日',
),
}),
@@ -1007,11 +1053,14 @@ const OccupanciesPage: React.FC = () => {
<Form.Item
name="newBillingStartDate"
label="新房计费起始日"
dependencies={["transferDate"]}
dependencies={['transferDate']}
extra="默认为换房次日"
rules={[
({ getFieldValue }) => ({
validator: dateNotBefore(getFieldValue('transferDate'), '新房计费起始日不能早于换房日期'),
validator: dateNotBefore(
getFieldValue('transferDate'),
'新房计费起始日不能早于换房日期',
),
}),
]}
>

View File

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

View File

@@ -31,6 +31,7 @@ import { downloadBlob } from '../../utils/download';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const statusMap: Record<string, { text: string; color: string }> = {
available: { text: '可入住', color: 'green' },
@@ -84,6 +85,8 @@ function parseRoomNumber(input: string) {
}
const RoomsPage: React.FC = () => {
const { hasPermission } = usePermission();
const canEditRooms = hasPermission('room:edit');
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
@@ -664,33 +667,35 @@ const RoomsPage: React.FC = () => {
>
宿
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async (options: UploadRequestOption<{ message?: string }>) => {
const { file, onSuccess, onError } = options;
if (typeof file === 'string') {
message.error('不支持字符串文件');
return;
}
try {
const formData = new FormData();
formData.append('file', file);
const res = await api.post<{ message?: string }>('/rooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
message.success(res.message || '导入成功');
onSuccess?.(res);
fetchData();
} catch (e: unknown) {
const err = e as { message?: string };
message.error(err?.message || '导入失败');
onError?.(e as UploadRequestError);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
{hasPermission('room:create') ? (
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={async (options: UploadRequestOption<{ message?: string }>) => {
const { file, onSuccess, onError } = options;
if (typeof file === 'string') {
message.error('不支持字符串文件');
return;
}
try {
const formData = new FormData();
formData.append('file', file);
const res = await api.post<{ message?: string }>('/rooms/import', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
message.success(res.message || '导入成功');
onSuccess?.(res);
fetchData();
} catch (e: unknown) {
const err = e as { message?: string };
message.error(err?.message || '导入失败');
onError?.(e as UploadRequestError);
}
}}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
) : null}
<PermissionButton
permission="room:view"
icon={<DownloadOutlined />}
@@ -854,56 +859,58 @@ const RoomsPage: React.FC = () => {
label: `床位管理 (${beds.length})`,
children: (
<div>
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
onClick={() => {
setBedEditing(null);
bedForm.resetFields();
setBedModalOpen(true);
}}
>
</Button>
<Popconfirm
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
description={
remainingBedSlots > 0 ? (
<InputNumber
min={1}
max={remainingBedSlots}
defaultValue={defaultBatchBedCount}
id="batch-bed-count"
style={{ width: 80 }}
/>
) : (
'如需增加床位,请先调整宿舍额定人数'
)
}
onConfirm={() => {
const input = document.getElementById(
'batch-bed-count',
) as HTMLInputElement;
handleBatchBeds(
input
? parseInt(input.value) || defaultBatchBedCount
: defaultBatchBedCount,
);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
{canEditRooms ? (
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
onClick={() => {
setBedEditing(null);
bedForm.resetFields();
setBedModalOpen(true);
}}
>
</Button>
<Popconfirm
title={remainingBedSlots > 0 ? '批量生成床位' : '床位已达到额定人数'}
description={
remainingBedSlots > 0 ? (
<InputNumber
min={1}
max={remainingBedSlots}
defaultValue={defaultBatchBedCount}
id="batch-bed-count"
style={{ width: 80 }}
/>
) : (
'如需增加床位,请先调整宿舍额定人数'
)
}
onConfirm={() => {
const input = document.getElementById(
'batch-bed-count',
) as HTMLInputElement;
handleBatchBeds(
input
? parseInt(input.value) || defaultBatchBedCount
: defaultBatchBedCount,
);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
</Button>
</Popconfirm>
</div>
<Button
size="small"
disabled={drawerRoom?.status === 'archived' || remainingBedSlots === 0}
>
</Button>
</Popconfirm>
</div>
) : null}
<Table
dataSource={beds}
rowKey="id"
@@ -1016,45 +1023,47 @@ const RoomsPage: React.FC = () => {
label: `柜子管理 (${lockers.length})`,
children: (
<div>
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived'}
onClick={() => {
setLockerEditing(null);
lockerForm.resetFields();
setLockerModalOpen(true);
}}
>
</Button>
<Popconfirm
title="批量生成柜子"
description={
<InputNumber
min={1}
max={20}
defaultValue={4}
id="batch-locker-count"
style={{ width: 80 }}
/>
}
onConfirm={() => {
const input = document.getElementById(
'batch-locker-count',
) as HTMLInputElement;
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived'}
>
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
{canEditRooms ? (
<div style={{ marginBottom: 12, display: 'flex', gap: 8 }}>
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
disabled={drawerRoom?.status === 'archived'}
onClick={() => {
setLockerEditing(null);
lockerForm.resetFields();
setLockerModalOpen(true);
}}
>
</Button>
</Popconfirm>
</div>
<Popconfirm
title="批量生成柜子"
description={
<InputNumber
min={1}
max={20}
defaultValue={4}
id="batch-locker-count"
style={{ width: 80 }}
/>
}
onConfirm={() => {
const input = document.getElementById(
'batch-locker-count',
) as HTMLInputElement;
handleBatchLockers(input ? parseInt(input.value) || 4 : 4);
}}
okText="生成"
disabled={drawerRoom?.status === 'archived'}
>
<Button size="small" disabled={drawerRoom?.status === 'archived'}>
</Button>
</Popconfirm>
</div>
) : null}
<Table
dataSource={lockers}
rowKey="id"
@@ -1168,8 +1177,8 @@ const RoomsPage: React.FC = () => {
<Modal
title={bedEditing ? '编辑床位' : '添加床位'}
open={bedModalOpen}
onOk={handleSaveBed}
open={bedModalOpen && canEditRooms}
onOk={canEditRooms ? handleSaveBed : undefined}
onCancel={() => {
setBedModalOpen(false);
setBedEditing(null);
@@ -1198,8 +1207,8 @@ const RoomsPage: React.FC = () => {
<Modal
title={lockerEditing ? '编辑柜子' : '添加柜子'}
open={lockerModalOpen}
onOk={handleSaveLocker}
open={lockerModalOpen && canEditRooms}
onOk={canEditRooms ? handleSaveLocker : undefined}
onCancel={() => {
setLockerModalOpen(false);
setLockerEditing(null);

View File

@@ -38,6 +38,7 @@ import EditableCell from '../../components/EditableCell';
import JinshujuMatchModal from '../../components/JinshujuMatchModal';
import { maskIdNumber, maskPhone } from '../../utils/sensitive';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
const statusMap: Record<string, { text: string; color: string }> = {
active: { text: '在读', color: 'green' },
@@ -84,6 +85,10 @@ interface StudentFilterLookups {
const StudentsPage: React.FC = () => {
const { modal } = App.useApp();
const { hasPermission, hasAnyPermission } = usePermission();
const canViewOrganizations = hasPermission('organization:view');
const canChooseOrganization =
canViewOrganizations && hasAnyPermission('student:create', 'student:edit');
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
@@ -189,12 +194,17 @@ const StudentsPage: React.FC = () => {
}, [fetchData]);
useEffect(() => {
api
.get('/organizations', { params: { includeArchived: 'false' } })
.then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string }>);
})
.catch(() => {});
if (canViewOrganizations) {
api
.get('/organizations', { params: { includeArchived: 'false' } })
.then((res: unknown) => {
setOrganizations(res as Array<{ id: number; name: string }>);
})
.catch(() => {});
} else {
setOrganizations([]);
setFilterOrganizationId(undefined);
}
api
.get<StudentFilterLookups>('/students/filter-lookups')
.then((res) => {
@@ -202,7 +212,7 @@ const StudentsPage: React.FC = () => {
setTeacherOptions(res.teachers || []);
})
.catch(() => {});
}, []);
}, [canViewOrganizations]);
const handleSave = async () => {
const values = await form.validateFields();
setSaving(true);
@@ -417,15 +427,17 @@ const StudentsPage: React.FC = () => {
return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
{hasPermission('log:create') ? (
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
) : null}
</span>
);
},
@@ -454,15 +466,17 @@ const StudentsPage: React.FC = () => {
return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskIdNumber(v)}</span>
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
{hasPermission('log:create') ? (
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
) : null}
</span>
);
},
@@ -506,15 +520,17 @@ const StudentsPage: React.FC = () => {
return (
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
{hasPermission('log:create') ? (
<Button
type="link"
size="small"
style={{ padding: '8px 4px', flex: 'none' }}
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
title="点击查看完整号码"
>
<EyeOutlined style={{ fontSize: 12, color: '#999' }} />
</Button>
) : null}
</span>
);
},
@@ -523,28 +539,33 @@ const StudentsPage: React.FC = () => {
title: '所属机构',
dataIndex: 'organization',
width: 100,
render: (organization: { name?: string } | null, record: any) => (
<EditableCell
value={record.organizationId}
editor="select"
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
permission="student:edit"
disabled={record.status === 'archived'}
required
onSave={(next) => saveCell(record, 'organizationId', next)}
>
{organization?.name ? (
<Tag
color="purple"
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
>
{organization.name}
</Tag>
) : (
'-'
)}
</EditableCell>
),
render: (organization: { name?: string } | null, record: any) =>
canChooseOrganization ? (
<EditableCell
value={record.organizationId}
editor="select"
options={organizations.map((item) => ({ value: item.id, label: item.name }))}
permission="student:edit"
disabled={record.status === 'archived'}
required
onSave={(next) => saveCell(record, 'organizationId', next)}
>
{organization?.name ? (
<Tag
color="purple"
style={{ maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis' }}
>
{organization.name}
</Tag>
) : (
'-'
)}
</EditableCell>
) : organization?.name ? (
<Tag color="purple">{organization.name}</Tag>
) : (
'-'
),
},
{
title: '负责人',
@@ -649,7 +670,15 @@ const StudentsPage: React.FC = () => {
),
},
],
[handleViewSensitive, openDrawer, showArchived, organizations, saveCell],
[
handleViewSensitive,
openDrawer,
showArchived,
organizations,
saveCell,
hasPermission,
canChooseOrganization,
],
);
return (
@@ -679,21 +708,23 @@ const StudentsPage: React.FC = () => {
</Select.Option>
))}
</Select>
<Select
placeholder="所属机构"
allowClear
style={{ width: 140 }}
value={filterOrganizationId}
onChange={(v) => {
setFilterOrganizationId(v);
}}
>
{organizations.map((t: { id: number; name: string }) => (
<Select.Option key={t.id} value={t.id}>
{t.name}
</Select.Option>
))}
</Select>
{canViewOrganizations ? (
<Select
placeholder="所属机构"
allowClear
style={{ width: 140 }}
value={filterOrganizationId}
onChange={(v) => {
setFilterOrganizationId(v);
}}
>
{organizations.map((t: { id: number; name: string }) => (
<Select.Option key={t.id} value={t.id}>
{t.name}
</Select.Option>
))}
</Select>
) : null}
<Select
placeholder="所属班级"
allowClear
@@ -765,22 +796,26 @@ const StudentsPage: React.FC = () => {
>
</PermissionButton>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleCreateStudentsImport}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleUpdateExistingStudentsImport}
>
<Button icon={<SwapOutlined />}></Button>
</Upload>
{hasPermission('student:import') ? (
<>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleCreateStudentsImport}
>
<Button icon={<UploadOutlined />}>Excel</Button>
</Upload>
<Upload
accept=".xlsx,.xls"
showUploadList={false}
customRequest={handleUpdateExistingStudentsImport}
>
<Button icon={<SwapOutlined />}></Button>
</Upload>
</>
) : null}
<PermissionButton
permission="student:edit"
permission="sync:read"
icon={<CloudUploadOutlined />}
onClick={() => setJinshujuOpen(true)}
>
@@ -934,23 +969,27 @@ const StudentsPage: React.FC = () => {
<Form.Item name="emergencyPhone" label="紧急联系人电话">
<Input />
</Form.Item>
<Form.Item
name="organizationId"
label="所属机构"
rules={[{ required: true, message: '请选择所属机构' }]}
>
<Select
showSearch
optionFilterProp="label"
placeholder="选择所属机构"
options={organizations.map(
(organization: { id: number; name: string; isHost?: boolean }) => ({
value: organization.id,
label: organization.isHost ? `${organization.name}(本机构)` : organization.name,
}),
)}
/>
</Form.Item>
{canChooseOrganization ? (
<Form.Item
name="organizationId"
label="所属机构"
rules={[{ required: true, message: '请选择所属机构' }]}
>
<Select
showSearch
optionFilterProp="label"
placeholder="选择所属机构"
options={organizations.map(
(organization: { id: number; name: string; isHost?: boolean }) => ({
value: organization.id,
label: organization.isHost
? `${organization.name}(本机构)`
: organization.name,
}),
)}
/>
</Form.Item>
) : null}
<Form.Item name="supervisor" label="负责人/班主任">
<Input />
</Form.Item>
@@ -968,11 +1007,16 @@ const StudentsPage: React.FC = () => {
</Form>
</Modal>
<JinshujuMatchModal
open={jinshujuOpen}
onClose={() => setJinshujuOpen(false)}
onApplied={() => { setJinshujuOpen(false); fetchData(); }}
/>
{hasPermission('sync:read') ? (
<JinshujuMatchModal
open={jinshujuOpen}
onClose={() => setJinshujuOpen(false)}
onApplied={() => {
setJinshujuOpen(false);
fetchData();
}}
/>
) : null}
<Drawer
title={null}
open={drawerOpen}

View File

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

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

View File

@@ -33,8 +33,9 @@ export class CreateStudentDto {
@IsString()
emergencyPhone?: string;
@IsOptional()
@IsInt()
organizationId: number;
organizationId?: number;
@IsOptional()
@IsString()

View File

@@ -43,6 +43,21 @@ describe('StudentsService — archive lifecycle boundaries', () => {
expect(repo.save).not.toHaveBeenCalled();
});
it('defaults a new student to the active host organization when none is supplied', async () => {
const repo = {
create: jest.fn((value) => value),
save: jest.fn(async (value) => ({ ...value, id: 1 })),
};
const organizationRepo = {
findOne: jest.fn().mockResolvedValue({ id: 7, isHost: true, status: 'active' }),
};
await expect(createService(repo, organizationRepo).create({ name: '张三' })).resolves.toEqual(
expect.objectContaining({ organizationId: 7 }),
);
expect(repo.create).toHaveBeenCalledWith(expect.objectContaining({ organizationId: 7 }));
});
it('returns not found for a missing student', async () => {
const repo = { findOne: jest.fn().mockResolvedValue(null) };
await expect(createService(repo).findOne(404)).rejects.toBeInstanceOf(NotFoundException);
@@ -50,11 +65,13 @@ describe('StudentsService — archive lifecycle boundaries', () => {
it('builds export archive maps from profile and result rows', async () => {
const profileRepo = {
find: jest.fn().mockResolvedValue([{
studentId: 1,
targetCollege: '北京大学',
collegeSchool: '北京职业技术学院',
}]),
find: jest.fn().mockResolvedValue([
{
studentId: 1,
targetCollege: '北京大学',
collegeSchool: '北京职业技术学院',
},
]),
};
const resultRepo = {
find: jest.fn().mockResolvedValue([{ studentId: 1, admissionStatus: 'pending' }]),

View File

@@ -164,8 +164,9 @@ export class StudentsService {
}
async create(dto: CreateStudentDto) {
await this.assertActiveOrganization(dto.organizationId);
return this.repo.save(this.repo.create(dto));
const organizationId = dto.organizationId || (await this.getHostOrganizationId());
await this.assertActiveOrganization(organizationId);
return this.repo.save(this.repo.create({ ...dto, organizationId }));
}
async update(id: number, dto: UpdateStudentDto) {
@@ -314,7 +315,9 @@ export class StudentsService {
};
}
private normalizeImportData(importData: StudentWorkbookImport | StudentImportRow[]): StudentWorkbookImport {
private normalizeImportData(
importData: StudentWorkbookImport | StudentImportRow[],
): StudentWorkbookImport {
if (Array.isArray(importData)) {
return { students: importData, enrollments: [], examScores: [], learningRecords: [] };
}
@@ -370,18 +373,24 @@ export class StudentsService {
if (!phone) return imported;
const enrollmentByClassName = new Map<string, StudentEnrollment>();
for (const enrollmentRow of data.enrollments.filter((item) => this.normalizePhone(item.phone) === phone)) {
for (const enrollmentRow of data.enrollments.filter(
(item) => this.normalizePhone(item.phone) === phone,
)) {
const enrollment = await this.upsertEnrollmentFromImport(studentId, enrollmentRow);
if (!enrollment) continue;
if (enrollment.className) enrollmentByClassName.set(enrollment.className, enrollment);
imported++;
}
for (const examRow of data.examScores.filter((item) => this.normalizePhone(item.phone) === phone)) {
for (const examRow of data.examScores.filter(
(item) => this.normalizePhone(item.phone) === phone,
)) {
if (await this.upsertExamScoreFromImport(studentId, examRow, enrollmentByClassName)) {
imported++;
}
}
for (const learningRow of data.learningRecords.filter((item) => this.normalizePhone(item.phone) === phone)) {
for (const learningRow of data.learningRecords.filter(
(item) => this.normalizePhone(item.phone) === phone,
)) {
if (await this.upsertLearningRecordFromImport(studentId, learningRow)) {
imported++;
}
@@ -390,7 +399,9 @@ export class StudentsService {
}
private async upsertProfileFromImport(studentId: number, row: StudentImportRow) {
const entity = (await this.profileRepo.findOne({ where: { studentId } })) || this.profileRepo.create({ studentId });
const entity =
(await this.profileRepo.findOne({ where: { studentId } })) ||
this.profileRepo.create({ studentId });
if (row.targetCollege?.trim()) entity.targetCollege = row.targetCollege.trim();
if (row.targetMajor?.trim()) entity.targetMajor = row.targetMajor.trim();
if (row.collegeSchool?.trim()) entity.collegeSchool = row.collegeSchool.trim();
@@ -403,9 +414,12 @@ export class StudentsService {
}
private async upsertResultFromImport(studentId: number, row: StudentImportRow) {
const entity = (await this.resultRepo.findOne({ where: { studentId } })) || this.resultRepo.create({ studentId });
const entity =
(await this.resultRepo.findOne({ where: { studentId } })) ||
this.resultRepo.create({ studentId });
if (row.cultureFinalScore !== undefined) entity.cultureFinalScore = row.cultureFinalScore;
if (row.professionalFinalScore !== undefined) entity.professionalFinalScore = row.professionalFinalScore;
if (row.professionalFinalScore !== undefined)
entity.professionalFinalScore = row.professionalFinalScore;
if (row.admissionStatus?.trim()) entity.admissionStatus = row.admissionStatus.trim();
if (row.admittedCollege?.trim()) entity.admittedCollege = row.admittedCollege.trim();
if (row.admittedMajor?.trim()) entity.admittedMajor = row.admittedMajor.trim();
@@ -623,10 +637,9 @@ export class StudentsService {
// ---- Filters ----
if (query?.keyword) {
qb.andWhere(
'(student.name LIKE :keyword OR student.studentNo LIKE :keyword)',
{ keyword: `%${query.keyword}%` },
);
qb.andWhere('(student.name LIKE :keyword OR student.studentNo LIKE :keyword)', {
keyword: `%${query.keyword}%`,
});
}
if (query?.organizationId) {
qb.andWhere('student.organizationId = :orgId', { orgId: query.organizationId });