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