diff --git a/apps/admin/src/pages/Classes/detail.tsx b/apps/admin/src/pages/Classes/detail.tsx
index 435b46b..d2fbaa7 100644
--- a/apps/admin/src/pages/Classes/detail.tsx
+++ b/apps/admin/src/pages/Classes/detail.tsx
@@ -19,6 +19,7 @@ interface ClassStudent {
studentName: string;
studentNo: string;
joinDate: string;
+ leaveDate: string | null;
status: string;
}
@@ -305,6 +306,7 @@ const ClassDetailPage: React.FC = () => {
{ title: '姓名', dataIndex: 'studentName' },
{ title: '学号', dataIndex: 'studentNo' },
{ title: '加入日期', dataIndex: 'joinDate' },
+ { title: '离班日期', dataIndex: 'leaveDate', render: (v: string | null) => v || '-' },
{
title: '状态',
dataIndex: 'status',
@@ -316,11 +318,12 @@ const ClassDetailPage: React.FC = () => {
},
{
title: '操作',
- render: (_: unknown, r: ClassStudent) => (
- handleRemoveStudent(r.studentId)}>
- 移除
-
- ),
+ render: (_: unknown, r: ClassStudent) =>
+ r.status === 'active' ? (
+ handleRemoveStudent(r.studentId)}>
+ 移除
+
+ ) : null,
},
];
diff --git a/apps/admin/src/pages/ClassroomRentals/index.tsx b/apps/admin/src/pages/ClassroomRentals/index.tsx
index 08d7451..5892fad 100644
--- a/apps/admin/src/pages/ClassroomRentals/index.tsx
+++ b/apps/admin/src/pages/ClassroomRentals/index.tsx
@@ -15,7 +15,7 @@ import {
Tooltip,
Empty,
} from 'antd';
-import { PlusOutlined, UploadOutlined, DeleteOutlined, FileTextOutlined } from '@ant-design/icons';
+import { PlusOutlined, UploadOutlined, DeleteOutlined, FileTextOutlined, StopOutlined, CheckOutlined } from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import api from '../../api';
import { downloadBlob } from '../../utils/download';
@@ -39,6 +39,7 @@ const ClassroomRentalsPage: React.FC = () => {
const [editing, setEditing] = useState(null);
const [form] = Form.useForm();
const [filterMonth, setFilterMonth] = useState(null);
+ const [filterStatus, setFilterStatus] = useState();
const [searchText, setSearchText] = useState('');
const [saving, setSaving] = useState(false);
const [unavailableDates, setUnavailableDates] = useState>(new Set());
@@ -48,20 +49,22 @@ const ClassroomRentalsPage: React.FC = () => {
const selectedClassroomId = Form.useWatch('classroomId', form);
const filteredData = useMemo(() => {
- if (!searchText) return data;
- const s = searchText.toLowerCase();
return data.filter((r: any) => {
+ if (filterStatus && r.effectiveStatus !== filterStatus) return false;
+ if (!searchText) return true;
+ const s = searchText.toLowerCase();
const matchClassroom = r.classroom?.name?.toLowerCase().includes(s);
const matchOrganization = r.lesseeOrganization?.name?.toLowerCase().includes(s);
return matchClassroom || matchOrganization;
});
- }, [data, searchText]);
+ }, [data, searchText, filterStatus]);
const fetchData = async () => {
setLoading(true);
try {
const params: any = {};
if (filterMonth) params.month = filterMonth.format('YYYY-MM');
+ params.includeEnded = true;
const res: any = await api.get('/classroom-rentals', { params });
setData(res);
} catch (e: any) {
@@ -215,6 +218,16 @@ const ClassroomRentalsPage: React.FC = () => {
}
};
+ const handleRentalAction = async (id: number, action: 'cancel' | 'end') => {
+ try {
+ await api.put(`/classroom-rentals/${id}/${action}`);
+ message.success(action === 'cancel' ? '租赁已取消' : '租赁已结束');
+ fetchData();
+ } catch (e: any) {
+ message.error(e?.message || '操作失败');
+ }
+ };
+
const handleDownloadContract = async (id: number, filename?: string) => {
try {
await downloadBlob(`/classroom-rentals/${id}/contract`, filename || `contract-${id}.pdf`);
@@ -308,6 +321,19 @@ const ClassroomRentalsPage: React.FC = () => {
width: 100,
render: (v: any) => (v ? `¥${v}` : '-'),
},
+ {
+ title: '状态',
+ dataIndex: 'effectiveStatus',
+ width: 90,
+ render: (status: string) => {
+ const config: Record = {
+ active: { text: '进行中', color: 'green' },
+ ended: { text: '已结束', color: 'default' },
+ cancelled: { text: '已取消', color: 'red' },
+ };
+ return {config[status]?.text || status};
+ },
+ },
{
title: '合同',
width: 120,
@@ -364,21 +390,30 @@ const ClassroomRentalsPage: React.FC = () => {
width: 150,
render: (_: any, record: any) => (
- openEdit(record)}
- >
- 编辑
-
- handleDelete(record.id)}
- >
-
- 删除
-
-
+ {record.effectiveStatus === 'active' && (
+ <>
+ openEdit(record)}>
+ 编辑
+
+ handleRentalAction(record.id, 'cancel')}>
+ }>
+ 取消
+
+
+ {!dayjs(record.startDate).isAfter(dayjs(), 'day') && (
+ handleRentalAction(record.id, 'end')}>
+ }>
+ 结束
+
+
+ )}
+ >
+ )}
+ {record.effectiveStatus !== 'active' && (
+ handleDelete(record.id)}>
+ 删除
+
+ )}
),
},
@@ -415,6 +450,18 @@ const ClassroomRentalsPage: React.FC = () => {
allowClear
format="YYYY-MM"
/>
+
{
optionFilterProp="label"
placeholder="选择教室"
onChange={handleClassroomChange}
- options={classrooms.map((c) => ({
+ options={classrooms.filter((c) => c.status === 'available').map((c) => ({
value: c.id,
label: `${c.building ? c.building + ' · ' : ''}${c.name}(${c.roomType})`,
}))}
diff --git a/apps/admin/src/pages/Classrooms/index.tsx b/apps/admin/src/pages/Classrooms/index.tsx
index e3e9fe8..360e52f 100644
--- a/apps/admin/src/pages/Classrooms/index.tsx
+++ b/apps/admin/src/pages/Classrooms/index.tsx
@@ -61,7 +61,7 @@ const ClassroomsPage: React.FC = () => {
const filteredData = useMemo(() => {
let result = data;
if (searchText) { const s = searchText.toLowerCase(); result = result.filter((d: Record) => (typeof d.name === 'string' && d.name.toLowerCase().includes(s)) || (typeof d.building === 'string' && d.building.toLowerCase().includes(s))); }
- if (filterStatus) result = result.filter((d: Record) => d.status === filterStatus);
+ if (filterStatus) result = result.filter((d: Record) => d.effectiveStatus === filterStatus);
return result;
}, [data, searchText, filterStatus]);
@@ -157,11 +157,11 @@ const ClassroomsPage: React.FC = () => {
{
title: '状态', width: 100,
dataIndex: 'status',
- render: (s: string, record: { currentUsage?: CurrentUsage | null }) => {
- const effectiveStatus = record.currentUsage ? 'in_use' : s;
+ render: (_s: string, record: { effectiveStatus?: string; status: string; currentUsage?: CurrentUsage | null }) => {
+ const effectiveStatus = record.effectiveStatus || record.status;
return (
- {statusMap[effectiveStatus]?.text || s}
+ {statusMap[effectiveStatus]?.text || effectiveStatus}
);
},
@@ -228,7 +228,7 @@ const ClassroomsPage: React.FC = () => {
if (!e.target.value) setSearchText('');
}}
/>
-
+
- {record.status === 'paid' && !record.refundStatus && (
+ {record.status === 'paid' && (
<>
{
{statusMap[detailModal.status]?.text || detailModal.status}
- {detailModal.refundStatus && (
-
- 退款状态:{' '}
-
- {refundStatusMap[detailModal.refundStatus]?.text || detailModal.refundStatus}
-
-
- )}
{detailModal.notes && 备注: {detailModal.notes}
}
diff --git a/apps/admin/src/pages/IntegrationConfig/index.tsx b/apps/admin/src/pages/IntegrationConfig/index.tsx
index e553f6f..7226466 100644
--- a/apps/admin/src/pages/IntegrationConfig/index.tsx
+++ b/apps/admin/src/pages/IntegrationConfig/index.tsx
@@ -1,7 +1,7 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
- Card, Form, Input, Button, Space, Spin, Switch, Alert, Descriptions, Tag,
- Tabs, Drawer, Tree, Select, TreeSelect, Modal, DatePicker, InputNumber,
+ Card, Form, Input, Button, Space, Spin, Alert, Descriptions, Tag, Divider,
+ Drawer, Tree, Select, TreeSelect, Modal, DatePicker, InputNumber,
Row, Col, List,
} from 'antd';
import {
@@ -15,12 +15,15 @@ import api from '../../api';
import { message } from '../../ui/app-message';
import { usePermission } from '../../hooks/usePermission';
import PermissionButton from '../../components/PermissionButton';
+import {
+ buildDingTalkConfigPayload,
+ isAppSecretRequired,
+ type DingTalkConfigFormValues,
+} from './integration-config-form';
interface DingTalkConfig {
agentId: string;
- appSecret: string;
corpId: string;
- startEnable: boolean;
}
interface DingOrgTreeNodeExt {
@@ -94,9 +97,9 @@ const IntegrationConfigPage: React.FC = () => {
const [testing, setTesting] = useState(false);
const [config, setConfig] = useState(null);
const [verified, setVerified] = useState(null);
- const [form] = Form.useForm();
+ const [form] = Form.useForm();
- // ── Sync Users Tab ──
+ // ── Manual organization sync ──
const [syncRootDeptId, setSyncRootDeptId] = useState(undefined);
const [orgTree, setOrgTree] = useState([]);
const [drawerOpen, setDrawerOpen] = useState(false);
@@ -137,9 +140,10 @@ const IntegrationConfigPage: React.FC = () => {
const handleSave = async () => {
const values = await form.validateFields();
+ const payload = buildDingTalkConfigPayload(values);
setSaving(true);
try {
- await api.post('/integration/config', { type: 'DINGTALK', config: values });
+ await api.post('/integration/config', { type: 'DINGTALK', config: payload });
message.success('配置已保存');
await fetchConfig();
} catch (e: unknown) {
@@ -152,11 +156,12 @@ const IntegrationConfigPage: React.FC = () => {
const handleTest = async () => {
const values = await form.validateFields();
+ const payload = buildDingTalkConfigPayload(values);
setTesting(true);
try {
const res = await api.post<{ success: boolean; message: string }>('/integration/config/test', {
type: 'DINGTALK',
- config: values,
+ config: payload,
});
setVerified(res.success);
message.success(res.message);
@@ -345,12 +350,8 @@ const IntegrationConfigPage: React.FC = () => {
}
};
- const syncTabItems = config && hasAllPermissions('sync:read', 'class:view', 'class:edit')
- ? [
- {
- key: 'sync-users',
- label: '同步用户',
- children: (
+ const syncPanel = config && hasAllPermissions('sync:read', 'class:view', 'class:edit')
+ ? (
- ),
- },
- ]
- : [];
-
- const tabItems = [
- {
- key: 'config',
- label: '配置',
- children: (
-
- {config && (
-
- {config.corpId || '-'}
- {config.agentId || '-'}
-
-
- {config.startEnable ? '已启用' : '未启用'}
-
-
-
- )}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- } loading={saving} onClick={handleSave}>
- 保存配置
-
- } loading={testing} onClick={handleTest}>
- 测试连接
-
-
-
-
- ),
- },
- ...syncTabItems,
- ];
+ )
+ : null;
return (
-
- {verified === true && } color="success">已连接}
- {verified === false && } color="error">未连接}
-
- }>
-
+
+ {verified === true && (
+ } color="success">
+ 已连接
+
+ )}
+ {verified === false && (
+ } color="error">
+ 未连接
+
+ )}
+
+ }
+ >
+
+ {config && (
+
+ {config.corpId || '-'}
+ {config.agentId || '-'}
+ 手动触发
+
+ )}
+
+
+
+
+
+
+
+
+
+
+
+
+
+ }
+ loading={saving}
+ onClick={handleSave}
+ >
+ 保存配置
+
+ } loading={testing} onClick={handleTest}>
+ 测试连接
+
+
+
+
+ {syncPanel && (
+ <>
+ 组织用户导入
+ {syncPanel}
+ >
+ )}
+
);
};
diff --git a/apps/admin/src/pages/IntegrationConfig/integration-config-form.integration.test.ts b/apps/admin/src/pages/IntegrationConfig/integration-config-form.integration.test.ts
new file mode 100644
index 0000000..5219ac7
--- /dev/null
+++ b/apps/admin/src/pages/IntegrationConfig/integration-config-form.integration.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildDingTalkConfigPayload,
+ isAppSecretRequired,
+} from './integration-config-form';
+
+describe('DingTalk integration config form', () => {
+ it('requires AppSecret only for the first configuration', () => {
+ expect(isAppSecretRequired(false)).toBe(true);
+ expect(isAppSecretRequired(true)).toBe(false);
+ });
+
+ it('builds a manual-sync config without the retired startEnable flag', () => {
+ expect(
+ buildDingTalkConfigPayload({
+ corpId: 'ding-corp',
+ agentId: 'app-key',
+ appSecret: '',
+ }),
+ ).toEqual({
+ corpId: 'ding-corp',
+ agentId: 'app-key',
+ appSecret: undefined,
+ });
+ });
+});
diff --git a/apps/admin/src/pages/IntegrationConfig/integration-config-form.ts b/apps/admin/src/pages/IntegrationConfig/integration-config-form.ts
new file mode 100644
index 0000000..4e18c1a
--- /dev/null
+++ b/apps/admin/src/pages/IntegrationConfig/integration-config-form.ts
@@ -0,0 +1,13 @@
+export interface DingTalkConfigFormValues {
+ agentId: string;
+ appSecret?: string;
+ corpId: string;
+}
+
+export const isAppSecretRequired = (hasSavedConfig: boolean) => !hasSavedConfig;
+
+export const buildDingTalkConfigPayload = (values: DingTalkConfigFormValues) => ({
+ corpId: values.corpId.trim(),
+ agentId: values.agentId.trim(),
+ appSecret: values.appSecret?.trim() || undefined,
+});
diff --git a/apps/admin/src/pages/Occupancies/index.tsx b/apps/admin/src/pages/Occupancies/index.tsx
index 5344a0e..6ea930e 100644
--- a/apps/admin/src/pages/Occupancies/index.tsx
+++ b/apps/admin/src/pages/Occupancies/index.tsx
@@ -32,6 +32,7 @@ import { downloadBlob } from '../../utils/download';
import { maskPhone, maskIdNumber } from '../../utils/sensitive';
import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message';
+import { buildTransferPayload } from './occupancy-form';
const { RangePicker } = DatePicker;
@@ -59,6 +60,8 @@ const OccupanciesPage: React.FC = () => {
const [batchCheckOutForm] = Form.useForm();
const [availableBeds, setAvailableBeds] = useState([]);
const [availableLockers, setAvailableLockers] = useState([]);
+ const [transferAvailableBeds, setTransferAvailableBeds] = useState([]);
+ const [transferAvailableLockers, setTransferAvailableLockers] = useState([]);
const fetchData = useCallback(async () => {
setLoading(true);
@@ -110,6 +113,30 @@ const OccupanciesPage: React.FC = () => {
} catch (e) { console.error(e); }
};
+ const handleTransferRoomChange = async (roomId: number) => {
+ transferForm.setFieldValue('newBedId', undefined);
+ transferForm.setFieldValue('newLockerId', undefined);
+ if (!roomId) {
+ setTransferAvailableBeds([]);
+ setTransferAvailableLockers([]);
+ return;
+ }
+ try {
+ const [beds, lockers] = await Promise.all([
+ api.get(`/rooms/${roomId}/beds/available`),
+ api.get(`/rooms/${roomId}/lockers/available`),
+ ]);
+ setTransferAvailableBeds(beds);
+ setTransferAvailableLockers(lockers);
+ if (beds.length === 1) transferForm.setFieldValue('newBedId', beds[0].id);
+ } catch (e) {
+ console.error(e);
+ setTransferAvailableBeds([]);
+ setTransferAvailableLockers([]);
+ message.error('目标宿舍床位和柜子加载失败');
+ }
+ };
+
const filteredData = useMemo(() => {
if (!searchText) return data;
const keyword = searchText.toLowerCase();
@@ -170,13 +197,10 @@ const OccupanciesPage: React.FC = () => {
const values = await transferForm.validateFields();
setSaving(true);
try {
- await api.put(`/occupancies/${transferModal.id}/transfer`, {
- newRoomId: values.newRoomId,
- transferDate: values.transferDate.format('YYYY-MM-DD'),
- oldBillingEndDate: values.oldBillingEndDate?.format('YYYY-MM-DD'),
- newBillingStartDate: values.newBillingStartDate?.format('YYYY-MM-DD'),
- reason: values.reason,
- });
+ await api.put(
+ `/occupancies/${transferModal.id}/transfer`,
+ buildTransferPayload(values),
+ );
message.success('换房成功');
setTransferModal(null);
transferForm.resetFields();
@@ -261,6 +285,9 @@ const OccupanciesPage: React.FC = () => {
size="small"
icon={}
onClick={() => {
+ setTransferAvailableBeds([]);
+ setTransferAvailableLockers([]);
+ transferForm.resetFields();
setTransferModal(record);
transferForm.setFieldsValue({ transferDate: dayjs() });
}}
@@ -708,7 +735,12 @@ const OccupanciesPage: React.FC = () => {
title={`换房 - ${transferModal?.student?.name}`}
open={!!transferModal}
onOk={handleTransfer}
- onCancel={() => setTransferModal(null)}
+ onCancel={() => {
+ setTransferModal(null);
+ transferForm.resetFields();
+ setTransferAvailableBeds([]);
+ setTransferAvailableLockers([]);
+ }}
okText="确认换房"
confirmLoading={saving}
width={500}
@@ -719,6 +751,7 @@ const OccupanciesPage: React.FC = () => {
showSearch
optionFilterProp="label"
placeholder="选择目标宿舍"
+ onChange={handleTransferRoomChange}
options={rooms
.filter((r: any) => r.id !== transferModal?.roomId)
.map((r: any) => ({
@@ -728,6 +761,38 @@ const OccupanciesPage: React.FC = () => {
}))}
/>
+
+
+ {transferAvailableBeds.length > 0 && (
+
+ 空闲 {transferAvailableBeds.length} 张床位
+
+ )}
+
+
diff --git a/apps/admin/src/pages/Occupancies/occupancy-form.integration.test.ts b/apps/admin/src/pages/Occupancies/occupancy-form.integration.test.ts
new file mode 100644
index 0000000..4bd4b2a
--- /dev/null
+++ b/apps/admin/src/pages/Occupancies/occupancy-form.integration.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import dayjs from 'dayjs';
+import { buildTransferPayload } from './occupancy-form';
+
+describe('occupancy transfer form', () => {
+ it('submits the target room resources with the transfer dates', () => {
+ expect(
+ buildTransferPayload({
+ newRoomId: 5,
+ newBedId: 12,
+ newLockerId: 18,
+ transferDate: dayjs('2026-07-13'),
+ oldBillingEndDate: dayjs('2026-07-13'),
+ newBillingStartDate: dayjs('2026-07-14'),
+ reason: '调整宿舍',
+ }),
+ ).toEqual({
+ newRoomId: 5,
+ newBedId: 12,
+ newLockerId: 18,
+ transferDate: '2026-07-13',
+ oldBillingEndDate: '2026-07-13',
+ newBillingStartDate: '2026-07-14',
+ reason: '调整宿舍',
+ });
+ });
+});
diff --git a/apps/admin/src/pages/Occupancies/occupancy-form.ts b/apps/admin/src/pages/Occupancies/occupancy-form.ts
new file mode 100644
index 0000000..e25171b
--- /dev/null
+++ b/apps/admin/src/pages/Occupancies/occupancy-form.ts
@@ -0,0 +1,21 @@
+import type { Dayjs } from 'dayjs';
+
+export interface TransferFormValues {
+ newRoomId: number;
+ newBedId: number;
+ newLockerId?: number;
+ transferDate: Dayjs;
+ oldBillingEndDate?: Dayjs;
+ newBillingStartDate?: Dayjs;
+ reason?: string;
+}
+
+export const buildTransferPayload = (values: TransferFormValues) => ({
+ newRoomId: values.newRoomId,
+ newBedId: values.newBedId,
+ newLockerId: values.newLockerId || undefined,
+ transferDate: values.transferDate.format('YYYY-MM-DD'),
+ oldBillingEndDate: values.oldBillingEndDate?.format('YYYY-MM-DD'),
+ newBillingStartDate: values.newBillingStartDate?.format('YYYY-MM-DD'),
+ reason: values.reason,
+});
diff --git a/apps/admin/src/pages/Rooms/index.tsx b/apps/admin/src/pages/Rooms/index.tsx
index 8afe184..b7ba609 100644
--- a/apps/admin/src/pages/Rooms/index.tsx
+++ b/apps/admin/src/pages/Rooms/index.tsx
@@ -159,13 +159,14 @@ const RoomsPage: React.FC = () => {
const handleSave = async () => {
const values = await form.validateFields();
+ const payload = values;
setSaving(true);
try {
if (editing) {
- await api.put(`/rooms/${editing.id}`, values);
+ await api.put(`/rooms/${editing.id}`, payload);
message.success('更新成功');
} else {
- await api.post('/rooms', values);
+ await api.post('/rooms', payload);
message.success('创建成功');
}
setModalOpen(false);
@@ -337,12 +338,6 @@ const RoomsPage: React.FC = () => {
/>
),
},
- {
- title: '性别',
- dataIndex: 'gender',
- width: 80,
- render: (v: any) => (v ? {v} : '-'),
- },
{
title: '状态',
dataIndex: 'status',
diff --git a/apps/admin/src/pages/Schedules/index.tsx b/apps/admin/src/pages/Schedules/index.tsx
index 42547cf..c37e756 100644
--- a/apps/admin/src/pages/Schedules/index.tsx
+++ b/apps/admin/src/pages/Schedules/index.tsx
@@ -947,6 +947,19 @@ const SchedulesPage: React.FC = () => {
/>
+
+
+
+
{
endTime: '18:00',
startDate: '2026-07-01',
endDate: '2026-07-31',
+ notes: '需要投影设备',
});
expect(values.classroomId).toBe(1);
expect(values.weekDay).toBe(5);
+ expect(values.notes).toBe('需要投影设备');
expect(values.timeRange.map((item) => item.format('HH:mm'))).toEqual(['14:00', '18:00']);
expect(values.dateRange.map((item) => item.format('YYYY-MM-DD'))).toEqual([
'2026-07-01',
@@ -36,6 +38,7 @@ describe('schedule edit form mapping', () => {
teacherId: 4,
timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
+ notes: ' 临时调整教室 ',
}),
).toEqual({
classId: 1,
@@ -47,6 +50,24 @@ describe('schedule edit form mapping', () => {
endTime: '17:20',
startDate: '2026-08-01',
endDate: '2026-08-31',
+ notes: '临时调整教室',
});
});
});
+
+
+describe('schedule notes normalization', () => {
+ it('omits whitespace-only notes from the payload', () => {
+ expect(
+ buildSchedulePayload({
+ classId: 1,
+ classroomId: 2,
+ weekDay: 6,
+ subject: '作文',
+ timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
+ dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
+ notes: ' ',
+ }).notes,
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/admin/src/pages/Schedules/schedule-form.ts b/apps/admin/src/pages/Schedules/schedule-form.ts
index 42d1d7f..dc4560c 100644
--- a/apps/admin/src/pages/Schedules/schedule-form.ts
+++ b/apps/admin/src/pages/Schedules/schedule-form.ts
@@ -6,6 +6,7 @@ export interface ScheduleFormValues {
weekDay: number;
subject: string;
teacherId?: number;
+ notes?: string;
timeRange: [Dayjs, Dayjs];
dateRange: [Dayjs, Dayjs];
}
@@ -17,6 +18,7 @@ export interface EditableSchedule {
weekDay: number;
subject: string;
teacherId: number | null;
+ notes?: string | null;
startTime: string;
endTime: string;
startDate: string;
@@ -29,6 +31,7 @@ export const scheduleToFormValues = (schedule: EditableSchedule): ScheduleFormVa
weekDay: schedule.weekDay,
subject: schedule.subject,
teacherId: schedule.teacherId ?? undefined,
+ notes: schedule.notes ?? undefined,
timeRange: [dayjs(`2000-01-01 ${schedule.startTime}`), dayjs(`2000-01-01 ${schedule.endTime}`)],
dateRange: [dayjs(schedule.startDate), dayjs(schedule.endDate)],
});
@@ -39,6 +42,7 @@ export const buildSchedulePayload = (values: ScheduleFormValues) => ({
weekDay: values.weekDay,
subject: values.subject,
teacherId: values.teacherId,
+ notes: values.notes?.trim() || undefined,
startTime: values.timeRange[0].format('HH:mm'),
endTime: values.timeRange[1].format('HH:mm'),
startDate: values.dateRange[0].format('YYYY-MM-DD'),
diff --git a/apps/admin/src/pages/Users/index.tsx b/apps/admin/src/pages/Users/index.tsx
index 739285f..b6684d1 100644
--- a/apps/admin/src/pages/Users/index.tsx
+++ b/apps/admin/src/pages/Users/index.tsx
@@ -15,6 +15,10 @@ import dayjs from 'dayjs';
import api from '../../api';
import PermissionButton from '../../components/PermissionButton';
import { message } from '../../ui/app-message';
+import {
+ userProfileResponseToFormValues,
+ type UserProfileResponse,
+} from './user-profile-form';
const UsersPage: React.FC = () => {
const [data, setData] = useState([]);
@@ -36,8 +40,8 @@ const UsersPage: React.FC = () => {
const handleOpenProfile = async (record: any) => {
setProfileUser(record);
try {
- const res: any = await api.get(`/rbac/users/${record.id}/profile`);
- profileForm.setFieldsValue(res);
+ const res = await api.get(`/rbac/users/${record.id}/profile`);
+ profileForm.setFieldsValue(userProfileResponseToFormValues(res));
} catch {
profileForm.setFieldsValue({});
}
diff --git a/apps/admin/src/pages/Users/user-profile-form.integration.test.ts b/apps/admin/src/pages/Users/user-profile-form.integration.test.ts
new file mode 100644
index 0000000..9455a8d
--- /dev/null
+++ b/apps/admin/src/pages/Users/user-profile-form.integration.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { userProfileResponseToFormValues } from './user-profile-form';
+
+describe('user profile form mapping', () => {
+ it('unwraps the nested profile returned by the user profile endpoint', () => {
+ expect(
+ userProfileResponseToFormValues({
+ id: 9,
+ username: 'teacher01',
+ name: '测试教师',
+ profile: {
+ joinedAt: '2026-07-01',
+ qualifications: '教师资格证',
+ subjects: ['语文', '历史'],
+ },
+ }),
+ ).toEqual({
+ joinedAt: '2026-07-01',
+ qualifications: '教师资格证',
+ subjects: ['语文', '历史'],
+ });
+ });
+
+ it('returns empty form values when the user has no profile', () => {
+ expect(userProfileResponseToFormValues({ profile: null })).toEqual({});
+ });
+});
diff --git a/apps/admin/src/pages/Users/user-profile-form.ts b/apps/admin/src/pages/Users/user-profile-form.ts
new file mode 100644
index 0000000..8a60032
--- /dev/null
+++ b/apps/admin/src/pages/Users/user-profile-form.ts
@@ -0,0 +1,16 @@
+export interface UserProfileFormValues {
+ joinedAt?: string;
+ qualifications?: string;
+ subjects?: string[];
+}
+
+export interface UserProfileResponse {
+ id?: number;
+ username?: string;
+ name?: string;
+ profile?: UserProfileFormValues | null;
+}
+
+export const userProfileResponseToFormValues = (
+ response: UserProfileResponse,
+): UserProfileFormValues => response.profile || {};
diff --git a/apps/server/package.json b/apps/server/package.json
index 095d893..b909f7c 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -28,6 +28,7 @@
"@nestjs/core": "^11.0.1",
"@nestjs/event-emitter": "^3.1.0",
"@nestjs/jwt": "^11.0.2",
+ "@nestjs/mapped-types": "^2.1.1",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.1.19",
"@nestjs/schedule": "^6.1.3",
diff --git a/apps/server/src/archive/archive-report.service.spec.ts b/apps/server/src/archive/archive-report.service.spec.ts
new file mode 100644
index 0000000..457b337
--- /dev/null
+++ b/apps/server/src/archive/archive-report.service.spec.ts
@@ -0,0 +1,31 @@
+import { ArchiveReportService } from './archive-report.service';
+
+describe('ArchiveReportService retired profile fields', () => {
+ it('does not render the retired campus field in a student report', async () => {
+ const service = new ArchiveReportService(
+ { findOne: jest.fn().mockResolvedValue({ campusLocation: '旧校区', grade: '高三' }) } as never,
+ { find: jest.fn().mockResolvedValue([]) } as never,
+ { find: jest.fn().mockResolvedValue([]) } as never,
+ { find: jest.fn().mockResolvedValue([]) } as never,
+ { findOne: jest.fn().mockResolvedValue(null) } as never,
+ { find: jest.fn().mockResolvedValue([]) } as never,
+ {
+ findOne: jest.fn().mockResolvedValue({
+ id: 1,
+ name: '测试学生',
+ gender: '男',
+ phone: '',
+ ethnicity: '',
+ emergencyContact: '',
+ emergencyPhone: '',
+ }),
+ } as never,
+ );
+
+ const html = await service.generateReportHtml(1);
+
+ expect(html).not.toContain('旧校区');
+ expect(html).not.toContain('校区');
+ expect(html).toContain('高三');
+ });
+});
diff --git a/apps/server/src/archive/archive-report.service.ts b/apps/server/src/archive/archive-report.service.ts
index 5e58672..036af73 100644
--- a/apps/server/src/archive/archive-report.service.ts
+++ b/apps/server/src/archive/archive-report.service.ts
@@ -308,7 +308,6 @@ ${this.buildLearningAndResult(learnings, result, now)}
民族${this.esc(student.ethnicity || '-')}
紧急联系人${this.esc(student.emergencyContact || '-')}
紧急电话${this.esc(student.emergencyPhone || '-')}
- 校区${this.esc(profile?.campusLocation || '-')}
年级${this.esc(profile?.grade || '-')}
`;
diff --git a/apps/server/src/archive/archive.controller.ts b/apps/server/src/archive/archive.controller.ts
index 86642bc..3c626af 100644
--- a/apps/server/src/archive/archive.controller.ts
+++ b/apps/server/src/archive/archive.controller.ts
@@ -20,8 +20,11 @@ import { ArchiveService } from './archive.service';
import {
UpsertProfileDto,
CreateEnrollmentDto,
+ UpdateEnrollmentDto,
CreateExamScoreDto,
+ UpdateExamScoreDto,
CreateLearningRecordDto,
+ UpdateLearningRecordDto,
UpsertResultDto,
} from './dto/archive.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
@@ -110,7 +113,7 @@ export class ArchiveController {
@RequirePermission('student:edit')
async updateEnrollment(
@Param('id') id: string,
- @Body() dto: Partial,
+ @Body() dto: UpdateEnrollmentDto,
@Request() req: AuthenticatedRequest,
) {
const { ipAddress, userAgent } = extractRequestInfo(req);
@@ -174,7 +177,7 @@ export class ArchiveController {
@RequirePermission('student:edit')
async updateExamScore(
@Param('id') id: string,
- @Body() dto: Partial,
+ @Body() dto: UpdateExamScoreDto,
@Request() req: AuthenticatedRequest,
) {
const { ipAddress, userAgent } = extractRequestInfo(req);
@@ -238,7 +241,7 @@ export class ArchiveController {
@RequirePermission('student:edit')
async updateLearningRecord(
@Param('id') id: string,
- @Body() dto: Partial,
+ @Body() dto: UpdateLearningRecordDto,
@Request() req: AuthenticatedRequest,
) {
const { ipAddress, userAgent } = extractRequestInfo(req);
@@ -330,12 +333,12 @@ export class ArchiveController {
@Param('id') id: string,
@Res() res: Response,
) {
- const { fullPath, fileName, mimeType } = await this.archiveService.getAttachmentFile(+studentId, +id);
- res.setHeader('Content-Type', mimeType);
- res.setHeader(
- 'Content-Disposition',
- `inline; filename="${encodeURIComponent(fileName)}"`,
+ const { fullPath, fileName, mimeType } = await this.archiveService.getAttachmentFile(
+ +studentId,
+ +id,
);
+ res.setHeader('Content-Type', mimeType);
+ res.setHeader('Content-Disposition', `inline; filename="${encodeURIComponent(fileName)}"`);
const stream = fs.createReadStream(fullPath);
stream.pipe(res);
}
@@ -358,7 +361,6 @@ export class ArchiveController {
return result;
}
-
@Get(':studentId/report-html')
@RequirePermission('student:view')
async generateReportHtml(
diff --git a/apps/server/src/archive/archive.service.spec.ts b/apps/server/src/archive/archive.service.spec.ts
new file mode 100644
index 0000000..4fe9957
--- /dev/null
+++ b/apps/server/src/archive/archive.service.spec.ts
@@ -0,0 +1,37 @@
+import { ArchiveService } from './archive.service';
+
+describe('ArchiveService.getProfile', () => {
+ it('returns the admission archive under the public result field', async () => {
+ const student = { id: 7, name: '测试学生' };
+ const result = {
+ id: 3,
+ studentId: 7,
+ cultureFinalScore: 450,
+ admittedCollege: '测试学院',
+ };
+
+ const studentRepo = { findOne: jest.fn().mockResolvedValue(student) };
+ const profileRepo = { findOne: jest.fn().mockResolvedValue(null) };
+ const enrollmentRepo = { find: jest.fn().mockResolvedValue([]) };
+ const examScoreRepo = { find: jest.fn().mockResolvedValue([]) };
+ const learningRecordRepo = { find: jest.fn().mockResolvedValue([]) };
+ const resultRepo = { findOne: jest.fn().mockResolvedValue(result) };
+ const attachmentRepo = { find: jest.fn().mockResolvedValue([]) };
+
+ const service = new ArchiveService(
+ studentRepo as never,
+ profileRepo as never,
+ enrollmentRepo as never,
+ examScoreRepo as never,
+ learningRecordRepo as never,
+ resultRepo as never,
+ attachmentRepo as never,
+ {} as never,
+ );
+
+ const response = await service.getProfile(7);
+
+ expect(response).toMatchObject({ student, result });
+ expect(response).not.toHaveProperty('resultArchive');
+ });
+});
diff --git a/apps/server/src/archive/archive.service.ts b/apps/server/src/archive/archive.service.ts
index 93a98f3..d5c17e5 100644
--- a/apps/server/src/archive/archive.service.ts
+++ b/apps/server/src/archive/archive.service.ts
@@ -15,8 +15,11 @@ import { ArchiveAttachment } from '../entities/archive-attachment.entity';
import {
UpsertProfileDto,
CreateEnrollmentDto,
+ UpdateEnrollmentDto,
CreateExamScoreDto,
+ UpdateExamScoreDto,
CreateLearningRecordDto,
+ UpdateLearningRecordDto,
UpsertResultDto,
} from './dto/archive.dto';
@@ -44,7 +47,9 @@ export class ArchiveService {
? path.resolve(process.cwd(), normalizedPath)
: path.resolve(this.uploadDir, normalizedPath);
const allowedRoots = [this.uploadDir, path.resolve(process.cwd(), 'uploads', 'archive')];
- if (!allowedRoots.some((root) => fullPath === root || fullPath.startsWith(`${root}${path.sep}`))) {
+ if (
+ !allowedRoots.some((root) => fullPath === root || fullPath.startsWith(`${root}${path.sep}`))
+ ) {
throw new BadRequestException('路径非法');
}
return fullPath;
@@ -54,21 +59,15 @@ export class ArchiveService {
const student = await this.studentRepo.findOne({ where: { id: studentId } });
if (!student) throw new NotFoundException('学生不存在');
- const [
- profileRaw,
- enrollments,
- examScores,
- learningRecords,
- resultArchive,
- attachments,
- ] = await Promise.all([
- this.profileRepo.findOne({ where: { studentId } }),
- this.enrollmentRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } }),
- this.examScoreRepo.find({ where: { studentId }, order: { examDate: 'DESC' } }),
- this.learningRecordRepo.find({ where: { studentId }, order: { recordDate: 'DESC' } }),
- this.resultRepo.findOne({ where: { studentId } }),
- this.attachmentRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } }),
- ]);
+ const [profileRaw, enrollments, examScores, learningRecords, resultArchive, attachments] =
+ await Promise.all([
+ this.profileRepo.findOne({ where: { studentId } }),
+ this.enrollmentRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } }),
+ this.examScoreRepo.find({ where: { studentId }, order: { examDate: 'DESC' } }),
+ this.learningRecordRepo.find({ where: { studentId }, order: { recordDate: 'DESC' } }),
+ this.resultRepo.findOne({ where: { studentId } }),
+ this.attachmentRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } }),
+ ]);
return {
student,
@@ -76,7 +75,7 @@ export class ArchiveService {
enrollments,
examScores,
learningRecords,
- resultArchive,
+ result: resultArchive,
attachments,
};
}
@@ -102,7 +101,7 @@ export class ArchiveService {
return this.enrollmentRepo.save(entity);
}
- async updateEnrollment(id: number, dto: Partial) {
+ async updateEnrollment(id: number, dto: UpdateEnrollmentDto) {
const entity = await this.enrollmentRepo.findOne({ where: { id } });
if (!entity) throw new NotFoundException('报名记录不存在');
Object.assign(entity, dto);
@@ -124,7 +123,7 @@ export class ArchiveService {
return this.examScoreRepo.save(entity);
}
- async updateExamScore(id: number, dto: Partial) {
+ async updateExamScore(id: number, dto: UpdateExamScoreDto) {
const entity = await this.examScoreRepo.findOne({ where: { id } });
if (!entity) throw new NotFoundException('考试成绩不存在');
Object.assign(entity, dto);
@@ -146,7 +145,7 @@ export class ArchiveService {
return this.learningRecordRepo.save(entity);
}
- async updateLearningRecord(id: number, dto: Partial) {
+ async updateLearningRecord(id: number, dto: UpdateLearningRecordDto) {
const entity = await this.learningRecordRepo.findOne({ where: { id } });
if (!entity) throw new NotFoundException('学习记录不存在');
Object.assign(entity, dto);
@@ -225,4 +224,3 @@ export class ArchiveService {
return { message: '已删除' };
}
}
-
diff --git a/apps/server/src/archive/dto/archive.dto.spec.ts b/apps/server/src/archive/dto/archive.dto.spec.ts
new file mode 100644
index 0000000..6a47aab
--- /dev/null
+++ b/apps/server/src/archive/dto/archive.dto.spec.ts
@@ -0,0 +1,57 @@
+import 'reflect-metadata';
+import { ValidationPipe } from '@nestjs/common';
+import { plainToInstance } from 'class-transformer';
+import { validate } from 'class-validator';
+import {
+ UpdateEnrollmentDto,
+ UpdateExamScoreDto,
+ UpdateLearningRecordDto,
+ UpsertProfileDto,
+} from './archive.dto';
+
+const pipe = new ValidationPipe({ transform: true, whitelist: true });
+
+async function transform(metatype: new () => T, value: unknown) {
+ return pipe.transform(value, { type: 'body', metatype });
+}
+
+describe('UpsertProfileDto retired fields', () => {
+ it('removes the retired campusLocation field under whitelist validation', async () => {
+ const dto = plainToInstance(UpsertProfileDto, {
+ grade: '高三',
+ campusLocation: '旧校区',
+ });
+
+ await validate(dto, { whitelist: true });
+
+ expect(dto).toMatchObject({ grade: '高三' });
+ expect(dto).not.toHaveProperty('campusLocation');
+ });
+});
+
+describe('archive update DTOs', () => {
+ it('allows partial enrollment updates and strips unknown fields', async () => {
+ await expect(
+ transform(UpdateEnrollmentDto, { className: '新班级', ignored: 'value' }),
+ ).resolves.toEqual(expect.objectContaining({ className: '新班级' }));
+ const result = await transform(UpdateEnrollmentDto, {
+ className: '新班级',
+ ignored: 'value',
+ });
+ expect(result).not.toHaveProperty('ignored');
+ });
+
+ it('retains create DTO validation rules for exam scores', async () => {
+ await expect(transform(UpdateExamScoreDto, { score: '90' })).rejects.toThrow();
+ await expect(transform(UpdateExamScoreDto, { score: 90 })).resolves.toMatchObject({
+ score: 90,
+ });
+ });
+
+ it('retains create DTO date validation for learning records', async () => {
+ await expect(
+ transform(UpdateLearningRecordDto, { recordDate: 'not-a-date' }),
+ ).rejects.toThrow();
+ await expect(transform(UpdateLearningRecordDto, {})).resolves.toEqual({});
+ });
+});
diff --git a/apps/server/src/archive/dto/archive.dto.ts b/apps/server/src/archive/dto/archive.dto.ts
index 404cb77..85fef07 100644
--- a/apps/server/src/archive/dto/archive.dto.ts
+++ b/apps/server/src/archive/dto/archive.dto.ts
@@ -1,3 +1,4 @@
+import { PartialType } from '@nestjs/mapped-types';
import { IsOptional, IsString, IsNumber, IsDateString } from 'class-validator';
export class UpsertProfileDto {
@@ -5,7 +6,6 @@ export class UpsertProfileDto {
@IsOptional() @IsString() targetMajor?: string;
@IsOptional() @IsString() subjectDirection?: string;
@IsOptional() @IsString() grade?: string;
- @IsOptional() @IsString() campusLocation?: string;
@IsOptional() @IsDateString() profileDate?: string;
@IsOptional() @IsString() notes?: string;
}
@@ -21,6 +21,8 @@ export class CreateEnrollmentDto {
@IsOptional() @IsString() status?: string;
}
+export class UpdateEnrollmentDto extends PartialType(CreateEnrollmentDto) {}
+
export class CreateExamScoreDto {
@IsString() examType: string;
@IsOptional() @IsString() examName?: string;
@@ -32,6 +34,8 @@ export class CreateExamScoreDto {
@IsOptional() @IsNumber() enrollmentId?: number;
}
+export class UpdateExamScoreDto extends PartialType(CreateExamScoreDto) {}
+
export class CreateLearningRecordDto {
@IsDateString() recordDate: string;
@IsString() recordType: string;
@@ -40,6 +44,8 @@ export class CreateLearningRecordDto {
@IsOptional() @IsString() nextStep?: string;
}
+export class UpdateLearningRecordDto extends PartialType(CreateLearningRecordDto) {}
+
export class UpsertResultDto {
@IsOptional() @IsNumber() cultureFinalScore?: number;
@IsOptional() @IsNumber() professionalFinalScore?: number;
diff --git a/apps/server/src/classes/classes.batch-import-membership.spec.ts b/apps/server/src/classes/classes.batch-import-membership.spec.ts
new file mode 100644
index 0000000..fea8627
--- /dev/null
+++ b/apps/server/src/classes/classes.batch-import-membership.spec.ts
@@ -0,0 +1,47 @@
+import { ClassesService } from './classes.service';
+import { ClassStudent } from '../entities';
+
+describe('ClassesService — DingTalk class import membership lifecycle', () => {
+ it('reactivates left memberships and skips active memberships', async () => {
+ const left = {
+ classId: 3,
+ studentId: 8,
+ status: 'left',
+ joinDate: '2026-01-01',
+ leaveDate: '2026-02-01',
+ } as ClassStudent;
+ const active = { classId: 3, studentId: 9, status: 'active' } as ClassStudent;
+ const classStudentRepo = {
+ find: jest.fn().mockResolvedValue([left, active]),
+ create: jest.fn().mockImplementation((value: Partial) => value),
+ save: jest.fn().mockImplementation(async (value: ClassStudent[]) => value),
+ };
+ const service = new ClassesService(
+ { findOne: jest.fn().mockResolvedValue({ id: 3 }) } as never,
+ classStudentRepo as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ { create: jest.fn(), save: jest.fn() } as never,
+ {
+ find: jest.fn().mockResolvedValue([
+ { dingUserId: 'd8', studentId: 8 },
+ { dingUserId: 'd9', studentId: 9 },
+ ]),
+ create: jest.fn(),
+ save: jest.fn(),
+ } as never,
+ );
+
+ const result = await service.batchImportStudents(3, [
+ { dingUserId: 'd8', name: '学生8' },
+ { dingUserId: 'd9', name: '学生9' },
+ ]);
+
+ expect(result).toEqual({ imported: 1, skipped: 1 });
+ expect(left).toMatchObject({ status: 'active', leaveDate: null });
+ expect(left.joinDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ expect(classStudentRepo.save).toHaveBeenCalledWith([left]);
+ });
+});
diff --git a/apps/server/src/classes/classes.membership.spec.ts b/apps/server/src/classes/classes.membership.spec.ts
new file mode 100644
index 0000000..9dc2167
--- /dev/null
+++ b/apps/server/src/classes/classes.membership.spec.ts
@@ -0,0 +1,95 @@
+import { BadRequestException, NotFoundException } from '@nestjs/common';
+import { ClassesService } from './classes.service';
+import { ClassStudent } from '../entities';
+
+function createService(
+ classStudentRepo: Record,
+ classRepo: Record = { findOne: jest.fn().mockResolvedValue({ id: 3 }) },
+ studentRepo: Record = {
+ find: jest.fn().mockResolvedValue([{ id: 8 }, { id: 9 }, { id: 10 }]),
+ },
+) {
+ return new ClassesService(
+ classRepo as never,
+ classStudentRepo as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ studentRepo as never,
+ {} as never,
+ );
+}
+
+describe('ClassesService — student membership lifecycle', () => {
+ it('marks an active membership as left instead of deleting it', async () => {
+ const membership = {
+ classId: 3,
+ studentId: 8,
+ status: 'active',
+ leaveDate: null,
+ } as ClassStudent;
+ const repo = {
+ findOne: jest.fn().mockResolvedValue(membership),
+ save: jest.fn().mockImplementation(async (value: ClassStudent) => value),
+ };
+ const service = createService(repo);
+
+ await service.removeStudent(3, 8);
+
+ expect(membership.status).toBe('left');
+ expect(membership.leaveDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ expect(repo.save).toHaveBeenCalledWith(membership);
+ });
+
+ it('rejects removing an already-left membership', async () => {
+ const repo = {
+ findOne: jest.fn().mockResolvedValue({ status: 'left' }),
+ save: jest.fn(),
+ };
+ const service = createService(repo);
+
+ await expect(service.removeStudent(3, 8)).rejects.toBeInstanceOf(BadRequestException);
+ expect(repo.save).not.toHaveBeenCalled();
+ });
+
+ it('rejects removing a student without a membership', async () => {
+ const repo = {
+ findOne: jest.fn().mockResolvedValue(null),
+ save: jest.fn(),
+ };
+ const service = createService(repo);
+
+ await expect(service.removeStudent(3, 8)).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('reactivates left memberships, creates new ones, and skips active ones', async () => {
+ const left = {
+ id: 1,
+ classId: 3,
+ studentId: 8,
+ status: 'left',
+ joinDate: '2026-01-01',
+ leaveDate: '2026-02-01',
+ } as ClassStudent;
+ const active = { id: 2, classId: 3, studentId: 9, status: 'active' } as ClassStudent;
+ const repo = {
+ find: jest.fn().mockResolvedValue([left, active]),
+ create: jest.fn().mockImplementation((value: Partial) => value),
+ save: jest.fn().mockImplementation(async (value: ClassStudent[]) => value),
+ };
+ const service = createService(repo);
+
+ const result = await service.addStudents(3, [8, 9, 10, 10]);
+
+ expect(result).toEqual({ added: 2, skipped: 1 });
+ expect(left).toMatchObject({ status: 'active', leaveDate: null });
+ expect(left.joinDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ expect(repo.create).toHaveBeenCalledWith(
+ expect.objectContaining({ classId: 3, studentId: 10, status: 'active' }),
+ );
+ expect(repo.save).toHaveBeenCalledWith(
+ expect.arrayContaining([left, expect.objectContaining({ studentId: 10 })]),
+ );
+ });
+});
diff --git a/apps/server/src/classes/classes.service.ts b/apps/server/src/classes/classes.service.ts
index d61a45f..36451a6 100644
--- a/apps/server/src/classes/classes.service.ts
+++ b/apps/server/src/classes/classes.service.ts
@@ -227,34 +227,45 @@ export class ClassesService {
}
// 3. Fetch existing class-student links in one query
- const allStudentIds = Array.from(dingToStudentId.values());
- const alreadyInClass = new Set();
- if (allStudentIds.length > 0) {
- const existingClassStudents = await this.classStudentRepo.find({
- where: { classId, studentId: In(allStudentIds) },
- });
- for (const cs of existingClassStudents) {
- alreadyInClass.add(cs.studentId);
+ const allStudentIds = Array.from(new Set(dingToStudentId.values()));
+ const existingClassStudents =
+ allStudentIds.length > 0
+ ? await this.classStudentRepo.find({
+ where: { classId, studentId: In(allStudentIds) },
+ })
+ : [];
+ const existingByStudentId = new Map(
+ existingClassStudents.map((classStudent) => [classStudent.studentId, classStudent]),
+ );
+ const today = new Date().toISOString().slice(0, 10);
+ let skipped = 0;
+ const memberships = allStudentIds.flatMap((studentId) => {
+ const existing = existingByStudentId.get(studentId);
+ if (existing?.status === 'active') {
+ skipped++;
+ return [];
}
- }
-
- // 4. Batch insert new class-student records
- const newClassStudents = allStudentIds
- .filter((sid) => !alreadyInClass.has(sid))
- .map((studentId) =>
+ if (existing) {
+ existing.status = 'active';
+ existing.joinDate = today;
+ existing.leaveDate = null;
+ return [existing];
+ }
+ return [
this.classStudentRepo.create({
classId,
studentId,
status: 'active',
- joinDate: new Date().toISOString().slice(0, 10),
+ joinDate: today,
}),
- );
+ ];
+ });
- if (newClassStudents.length > 0) {
- await this.classStudentRepo.save(newClassStudents);
+ if (memberships.length > 0) {
+ await this.classStudentRepo.save(memberships);
}
- return { imported: newClassStudents.length, skipped: alreadyInClass.size };
+ return { imported: memberships.length, skipped };
}
async update(id: number, dto: UpdateClassDto) {
const cls = await this.classRepo.findOne({ where: { id } });
@@ -315,26 +326,61 @@ export class ClassesService {
}
async addStudents(classId: number, studentIds: number[]) {
+ const uniqueStudentIds = [...new Set(studentIds)];
+ if (uniqueStudentIds.length === 0) return { added: 0, skipped: 0 };
+
+ const cls = await this.classRepo.findOne({ where: { id: classId } });
+ if (!cls) throw new NotFoundException('班级不存在');
+
+ const students = await this.studentRepo.find({ where: { id: In(uniqueStudentIds) } });
+ if (students.length !== uniqueStudentIds.length) {
+ throw new NotFoundException('部分学生不存在');
+ }
+
const existing = await this.classStudentRepo.find({
- where: { classId, studentId: In(studentIds) },
+ where: { classId, studentId: In(uniqueStudentIds) },
});
- const existingIds = new Set(existing.map((e) => e.studentId));
- const newIds = studentIds.filter((id) => !existingIds.has(id));
-
- const entries = newIds.map((sid) =>
- this.classStudentRepo.create({
- classId,
- studentId: sid,
- joinDate: new Date().toISOString().split('T')[0],
- }),
+ const existingByStudentId = new Map(
+ existing.map((classStudent) => [classStudent.studentId, classStudent]),
);
- if (entries.length) await this.classStudentRepo.save(entries);
+ const today = new Date().toISOString().split('T')[0];
+ let skipped = 0;
+ const memberships = uniqueStudentIds.flatMap((studentId) => {
+ const current = existingByStudentId.get(studentId);
+ if (current?.status === 'active') {
+ skipped++;
+ return [];
+ }
+ if (current) {
+ current.status = 'active';
+ current.joinDate = today;
+ current.leaveDate = null;
+ return [current];
+ }
+ return [
+ this.classStudentRepo.create({
+ classId,
+ studentId,
+ status: 'active',
+ joinDate: today,
+ }),
+ ];
+ });
+ if (memberships.length) await this.classStudentRepo.save(memberships);
- return { added: entries.length, skipped: studentIds.length - entries.length };
+ return { added: memberships.length, skipped };
}
async removeStudent(classId: number, studentId: number) {
- await this.classStudentRepo.delete({ classId, studentId });
+ const membership = await this.classStudentRepo.findOne({
+ where: { classId, studentId },
+ });
+ if (!membership) throw new NotFoundException('学生不在该班级');
+ if (membership.status !== 'active') throw new BadRequestException('学生已离班');
+
+ membership.status = 'left';
+ membership.leaveDate = new Date().toISOString().split('T')[0];
+ await this.classStudentRepo.save(membership);
return { success: true };
}
diff --git a/apps/server/src/classroom-rentals/classroom-rentals.controller.ts b/apps/server/src/classroom-rentals/classroom-rentals.controller.ts
index f1dfc23..4577ec8 100644
--- a/apps/server/src/classroom-rentals/classroom-rentals.controller.ts
+++ b/apps/server/src/classroom-rentals/classroom-rentals.controller.ts
@@ -137,6 +137,42 @@ export class ClassroomRentalsController {
return result;
}
+ @Put(':id/cancel')
+ @RequirePermission('rental:edit')
+ async cancel(@Param('id') id: string, @Request() req: any) {
+ const { ipAddress, userAgent } = extractRequestInfo(req);
+ const result = await this.service.cancel(+id);
+ await this.logService.log({
+ userId: req.user?.id,
+ username: req.user?.username,
+ module: '教室租赁',
+ action: '取消租赁',
+ targetId: +id,
+ targetType: 'classroom-rental',
+ ipAddress,
+ userAgent,
+ });
+ return result;
+ }
+
+ @Put(':id/end')
+ @RequirePermission('rental:edit')
+ async end(@Param('id') id: string, @Request() req: any) {
+ const { ipAddress, userAgent } = extractRequestInfo(req);
+ const result = await this.service.end(+id);
+ await this.logService.log({
+ userId: req.user?.id,
+ username: req.user?.username,
+ module: '教室租赁',
+ action: '结束租赁',
+ targetId: +id,
+ targetType: 'classroom-rental',
+ ipAddress,
+ userAgent,
+ });
+ return result;
+ }
+
@Delete(':id')
@RequirePermission('rental:delete')
async remove(@Param('id') id: string, @Request() req: any) {
diff --git a/apps/server/src/classroom-rentals/classroom-rentals.service.spec.ts b/apps/server/src/classroom-rentals/classroom-rentals.service.spec.ts
index b3e4886..e5058bc 100644
--- a/apps/server/src/classroom-rentals/classroom-rentals.service.spec.ts
+++ b/apps/server/src/classroom-rentals/classroom-rentals.service.spec.ts
@@ -243,7 +243,7 @@ describe('ClassroomRentalsService — rental schedule sync', () => {
startDate: '2026-03-01',
endDate: '2026-03-31',
};
- const classroom = { id: 1, departmentId: 10 } as Classroom;
+ const classroom = { id: 1, status: 'available' } as Classroom;
const hostOrganization = {
id: 1,
name: 'Host',
@@ -315,8 +315,8 @@ describe('ClassroomRentalsService — rental schedule sync', () => {
id: 1,
classroomId: 1,
lesseeOrganizationId: 2,
- startDate: '2026-03-01',
- endDate: '2026-03-31',
+ startDate: '2026-07-01',
+ endDate: '2099-03-31',
status: 'active',
notes: '',
lesseeOrganization: { id: 2, name: 'Organization A' } as Organization,
@@ -324,8 +324,8 @@ describe('ClassroomRentalsService — rental schedule sync', () => {
} as ClassroomRental;
const updatedRental = {
...existingRental,
- startDate: '2026-04-01',
- endDate: '2026-04-30',
+ startDate: '2026-08-01',
+ endDate: '2099-04-30',
};
const existingSchedule = {
id: 50,
@@ -339,12 +339,12 @@ describe('ClassroomRentalsService — rental schedule sync', () => {
scheduleRepo.createQueryBuilder.mockReturnValue(mockQueryBuilder([]));
scheduleRepo.findOne.mockResolvedValue(existingSchedule);
- const dto: UpdateRentalDto = { startDate: '2026-04-01', endDate: '2026-04-30' };
+ const dto: UpdateRentalDto = { startDate: '2026-08-01', endDate: '2099-04-30' };
await service.update(1, dto);
expect(rentalRepo.update).toHaveBeenCalledWith(
1,
- expect.objectContaining({ startDate: '2026-04-01', endDate: '2026-04-30' }),
+ expect.objectContaining({ startDate: '2026-08-01', endDate: '2099-04-30' }),
);
expect(scheduleRepo.update).toHaveBeenCalledWith(
50,
@@ -352,8 +352,8 @@ describe('ClassroomRentalsService — rental schedule sync', () => {
scheduleType: 'RENTAL',
rentalId: 1,
classroomId: 1,
- startDate: '2026-04-01',
- endDate: '2026-04-30',
+ startDate: '2026-08-01',
+ endDate: '2099-04-30',
status: 'active',
subject: 'Organization A 租赁',
}),
@@ -362,27 +362,59 @@ describe('ClassroomRentalsService — rental schedule sync', () => {
expect(scheduleRepo.delete).not.toHaveBeenCalled();
});
- it('deletes the RENTAL schedule row when status changes to cancelled', async () => {
+ it('deletes the RENTAL schedule row when the rental is cancelled', async () => {
const rental = {
id: 1,
classroomId: 1,
lesseeOrganizationId: 2,
- startDate: '2026-03-01',
- endDate: '2026-03-31',
+ startDate: '2026-07-01',
+ endDate: '2099-03-31',
status: 'active',
lesseeOrganization: { id: 2, name: 'Organization A' } as Organization,
} as ClassroomRental;
- const cancelledRental = { ...rental, status: 'cancelled' };
+ const cancelledRental = { ...rental, status: 'cancelled' } as ClassroomRental;
rentalRepo.findOne.mockResolvedValueOnce(rental).mockResolvedValueOnce(cancelledRental);
- await service.update(1, { status: 'cancelled' });
+ await service.cancel(1);
expect(rentalRepo.update).toHaveBeenCalledWith(1, { status: 'cancelled' });
expect(scheduleRepo.delete).toHaveBeenCalledWith({ rentalId: 1, scheduleType: 'RENTAL' });
- expect(scheduleRepo.findOne).not.toHaveBeenCalled();
- expect(scheduleRepo.update).not.toHaveBeenCalled();
- expect(scheduleRepo.create).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('lifecycle actions', () => {
+ it('ends an active rental and shortens a future end date', async () => {
+ const rental = {
+ id: 1,
+ classroomId: 1,
+ startDate: '2026-07-01',
+ endDate: '2099-12-31',
+ status: 'active',
+ lesseeOrganization: { name: 'Organization A' },
+ } as ClassroomRental;
+ const ended = { ...rental, status: 'ended', endDate: '2026-07-13' } as ClassroomRental;
+ rentalRepo.findOne.mockResolvedValueOnce(rental).mockResolvedValueOnce(ended);
+ scheduleRepo.findOne.mockResolvedValue({ id: 50 } as ClassSchedule);
+
+ await service.end(1);
+
+ expect(rentalRepo.update).toHaveBeenCalledWith(
+ 1,
+ expect.objectContaining({ status: 'ended' }),
+ );
+ expect(scheduleRepo.update).toHaveBeenCalled();
+ });
+
+ it('rejects ending a future rental', async () => {
+ rentalRepo.findOne.mockResolvedValue({
+ id: 1,
+ startDate: '2099-01-01',
+ endDate: '2099-12-31',
+ status: 'active',
+ } as ClassroomRental);
+
+ await expect(service.end(1)).rejects.toThrow('租赁尚未开始');
});
});
@@ -394,7 +426,7 @@ describe('ClassroomRentalsService — rental schedule sync', () => {
lesseeOrganizationId: 2,
startDate: '2026-03-01',
endDate: '2026-03-31',
- status: 'active',
+ status: 'cancelled',
lesseeOrganization: { id: 2, name: 'Organization A' } as Organization,
} as ClassroomRental;
@@ -419,7 +451,7 @@ describe('ClassroomRentalsService — organization roles', () => {
createQueryBuilder: jest.fn().mockReturnValue(mockQueryBuilder([])),
} as any;
const classroomRepo = {
- findOne: jest.fn().mockResolvedValue({ id: 1, departmentId: 10 }),
+ findOne: jest.fn().mockResolvedValue({ id: 1, status: 'available' }),
} as any;
const organizationRepo = {
findOne: jest
diff --git a/apps/server/src/classroom-rentals/classroom-rentals.service.ts b/apps/server/src/classroom-rentals/classroom-rentals.service.ts
index 54be700..70024cf 100644
--- a/apps/server/src/classroom-rentals/classroom-rentals.service.ts
+++ b/apps/server/src/classroom-rentals/classroom-rentals.service.ts
@@ -6,8 +6,8 @@ import {
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Not, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
-import { ClassroomRental } from '../entities/classroom-rental.entity';
-import { Classroom } from '../entities/classroom.entity';
+import { ClassroomRental, ClassroomRentalStatus } from '../entities/classroom-rental.entity';
+import { Classroom, ClassroomStatus } from '../entities/classroom.entity';
import { Organization } from '../entities/organization.entity';
import { ClassSchedule } from '../entities/class-schedule.entity';
import { CreateRentalDto, UpdateRentalDto } from './dto/rental.dto';
@@ -70,8 +70,11 @@ export class ClassroomRentalsService {
const last = `${y}-${String(m).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
qb.andWhere('r.startDate <= :last AND r.endDate >= :first', { first, last });
}
- if (!query?.includeEnded) qb.andWhere('r.status != :cancelled', { cancelled: 'cancelled' });
- return qb.getMany();
+ if (!query?.includeEnded) {
+ qb.andWhere('r.status = :active', { active: ClassroomRentalStatus.ACTIVE });
+ }
+ const rentals = await qb.getMany();
+ return rentals.map((rental) => this.withEffectiveStatus(rental));
}
async findOne(id: number) {
@@ -80,7 +83,7 @@ export class ClassroomRentalsService {
relations: ['classroom', 'lessorOrganization', 'lesseeOrganization'],
});
if (!rental) throw new NotFoundException('租赁订单不存在');
- return rental;
+ return this.withEffectiveStatus(rental);
}
async getUnavailableDates(classroomId: number, year: number, month: number, excludeId?: number) {
@@ -93,7 +96,7 @@ export class ClassroomRentalsService {
where: {
...(excludeId ? { id: Not(excludeId) } : {}),
classroomId,
- status: Not('cancelled'),
+ status: ClassroomRentalStatus.ACTIVE,
startDate: LessThanOrEqual(monthEnd),
endDate: MoreThanOrEqual(monthStart),
},
@@ -101,7 +104,7 @@ export class ClassroomRentalsService {
this.scheduleRepo.find({
where: {
classroomId,
- status: 'active',
+ status: ClassroomRentalStatus.ACTIVE,
scheduleType: 'INTERNAL',
startDate: LessThanOrEqual(monthEnd),
endDate: MoreThanOrEqual(monthStart),
@@ -133,7 +136,7 @@ export class ClassroomRentalsService {
.createQueryBuilder('r')
.leftJoinAndSelect('r.lesseeOrganization', 'lesseeOrganization')
.where('r.classroomId = :cid', { cid: classroomId })
- .andWhere('r.status != :cancelled', { cancelled: 'cancelled' })
+ .andWhere('r.status = :active', { active: ClassroomRentalStatus.ACTIVE })
.andWhere('r.startDate <= :end', { end: endDate })
.andWhere('r.endDate >= :start', { start: startDate });
if (excludeId) qb.andWhere('r.id != :excludeId', { excludeId });
@@ -222,6 +225,9 @@ export class ClassroomRentalsService {
if (dto.startDate > dto.endDate) throw new BadRequestException('起始日期不能晚于结束日期');
const classroom = await this.classroomRepo.findOne({ where: { id: dto.classroomId } });
if (!classroom) throw new NotFoundException('教室不存在');
+ if (classroom.status !== ClassroomStatus.AVAILABLE) {
+ throw new BadRequestException('仅可用教室可以创建租赁');
+ }
const lessorOrganization = dto.lessorOrganizationId
? await this.organizationRepo.findOne({
where: { id: dto.lessorOrganizationId, status: 'active' },
@@ -253,7 +259,7 @@ export class ClassroomRentalsService {
lessorOrganizationId: lessorOrganization.id,
lesseeOrganizationId: lesseeOrganization.id,
createdBy: userId,
- status: 'active',
+ status: ClassroomRentalStatus.ACTIVE,
});
const saved = await this.repo.save(rental);
await this.syncScheduleFromRental(saved, lesseeOrganization.name);
@@ -262,11 +268,21 @@ export class ClassroomRentalsService {
async update(id: number, dto: UpdateRentalDto) {
const rental = await this.findOne(id);
+ if (rental.effectiveStatus !== ClassroomRentalStatus.ACTIVE) {
+ throw new BadRequestException('已结束或已取消的租赁不能编辑');
+ }
// 若修改了教室/日期,重新冲突检查
const newClassroomId = dto.classroomId ?? rental.classroomId;
const newStart = dto.startDate ?? rental.startDate;
const newEnd = dto.endDate ?? rental.endDate;
if (newStart > newEnd) throw new BadRequestException('起始日期不能晚于结束日期');
+ if (dto.classroomId && dto.classroomId !== rental.classroomId) {
+ const classroom = await this.classroomRepo.findOne({ where: { id: dto.classroomId } });
+ if (!classroom) throw new NotFoundException('教室不存在');
+ if (classroom.status !== ClassroomStatus.AVAILABLE) {
+ throw new BadRequestException('仅可用教室可以承接租赁');
+ }
+ }
if (dto.classroomId || dto.startDate || dto.endDate) {
const conflicts = await this.findConflicts(newClassroomId, newStart, newEnd, id);
if (conflicts.length > 0) {
@@ -300,16 +316,46 @@ export class ClassroomRentalsService {
}
await this.repo.update(id, dto);
const updated = await this.findOne(id);
- if (dto.status === 'cancelled') {
- await this.scheduleRepo.delete({ rentalId: id, scheduleType: 'RENTAL' });
- } else {
- await this.syncScheduleFromRental(updated);
- }
+ await this.syncScheduleFromRental(updated);
return updated;
}
+ async cancel(id: number) {
+ const rental = await this.findOne(id);
+ if (rental.effectiveStatus !== ClassroomRentalStatus.ACTIVE) {
+ throw new BadRequestException('仅有效租赁可以取消');
+ }
+ await this.repo.update(id, { status: ClassroomRentalStatus.CANCELLED });
+ await this.scheduleRepo.delete({ rentalId: id, scheduleType: 'RENTAL' });
+ return this.findOne(id);
+ }
+
+ async end(id: number) {
+ const rental = await this.findOne(id);
+ if (rental.effectiveStatus !== ClassroomRentalStatus.ACTIVE) {
+ throw new BadRequestException('仅有效租赁可以结束');
+ }
+ const today = new Intl.DateTimeFormat('en-CA', {
+ timeZone: 'Asia/Shanghai',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).format(new Date());
+ if (rental.startDate > today) throw new BadRequestException('租赁尚未开始,不能结束');
+ await this.repo.update(id, {
+ status: ClassroomRentalStatus.ENDED,
+ endDate: rental.endDate > today ? today : rental.endDate,
+ });
+ const ended = await this.findOne(id);
+ await this.syncScheduleFromRental(ended);
+ return ended;
+ }
+
async remove(id: number) {
const rental = await this.findOne(id);
+ if (rental.effectiveStatus === ClassroomRentalStatus.ACTIVE) {
+ throw new BadRequestException('进行中的租赁请先取消或结束');
+ }
// 同步删除对应排课记录
await this.scheduleRepo.delete({ rentalId: id, scheduleType: 'RENTAL' });
// 同时删除合同文件
@@ -327,6 +373,20 @@ export class ClassroomRentalsService {
return { message: '删除成功' };
}
+ private withEffectiveStatus(rental: ClassroomRental) {
+ const today = new Intl.DateTimeFormat('en-CA', {
+ timeZone: 'Asia/Shanghai',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ }).format(new Date());
+ const effectiveStatus =
+ rental.status === ClassroomRentalStatus.ACTIVE && rental.endDate < today
+ ? ClassroomRentalStatus.ENDED
+ : rental.status;
+ return Object.assign(rental, { effectiveStatus });
+ }
+
/**
* 同步租赁订单到 class_schedules(schedule_type = 'RENTAL')
*/
@@ -348,7 +408,7 @@ export class ClassroomRentalsService {
teacherId: null,
scheduleType: 'RENTAL',
rentalId: rental.id,
- status: 'active',
+ status: rental.status === ClassroomRentalStatus.CANCELLED ? 'cancelled' : 'active',
notes: rental.notes,
};
if (schedule) {
@@ -437,14 +497,16 @@ export class ClassroomRentalsService {
const last = `${year}-${String(month).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
const classrooms = await this.classroomRepo.find({
- where: { status: Not('archived') },
+ where: { status: Not(ClassroomStatus.ARCHIVED) },
order: { building: 'ASC', name: 'ASC' },
});
const rentals = await this.repo
.createQueryBuilder('r')
.leftJoinAndSelect('r.lesseeOrganization', 'lesseeOrganization')
.leftJoinAndSelect('r.classroom', 'classroom')
- .where('r.status != :cancelled', { cancelled: 'cancelled' })
+ .where('r.status IN (:...statuses)', {
+ statuses: [ClassroomRentalStatus.ACTIVE, ClassroomRentalStatus.ENDED],
+ })
.andWhere('r.startDate <= :last AND r.endDate >= :first', { first, last })
.getMany();
diff --git a/apps/server/src/classroom-rentals/dto/rental.dto.ts b/apps/server/src/classroom-rentals/dto/rental.dto.ts
index 92b34f4..573c4fd 100644
--- a/apps/server/src/classroom-rentals/dto/rental.dto.ts
+++ b/apps/server/src/classroom-rentals/dto/rental.dto.ts
@@ -1,4 +1,4 @@
-import { IsOptional, IsString, IsInt, IsNumber, IsEnum, IsDateString } from 'class-validator';
+import { IsOptional, IsString, IsInt, IsNumber, IsDateString } from 'class-validator';
export class CreateRentalDto {
@IsInt()
@@ -62,8 +62,4 @@ export class UpdateRentalDto {
@IsOptional()
@IsString()
notes?: string;
-
- @IsOptional()
- @IsEnum(['active', 'ended', 'cancelled'])
- status?: string;
}
diff --git a/apps/server/src/classrooms/classrooms.service.ts b/apps/server/src/classrooms/classrooms.service.ts
index c379914..61ca5f8 100644
--- a/apps/server/src/classrooms/classrooms.service.ts
+++ b/apps/server/src/classrooms/classrooms.service.ts
@@ -1,14 +1,13 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { Repository, Not } from 'typeorm';
-import { Classroom } from '../entities/classroom.entity';
-import { ClassroomRental } from '../entities/classroom-rental.entity';
+import { Repository, Not, MoreThanOrEqual } from 'typeorm';
+import { Classroom, ClassroomStatus } from '../entities/classroom.entity';
+import { ClassroomRental, ClassroomRentalStatus } from '../entities/classroom-rental.entity';
import { ClassSchedule } from '../entities/class-schedule.entity';
import { CreateClassroomDto, UpdateClassroomDto } from './dto/classroom.dto';
@Injectable()
export class ClassroomsService {
-
constructor(
@InjectRepository(Classroom) private repo: Repository,
@InjectRepository(ClassroomRental) private rentalRepo: Repository,
@@ -21,49 +20,148 @@ export class ClassroomsService {
if (query?.roomType) where.roomType = query.roomType;
if (!query?.includeArchived) where.status = Not('archived');
const list = await this.repo.find({ where, order: { building: 'ASC', name: 'ASC' } });
- const usageMap = await this.getCurrentUsageForClassrooms(list.map((c) => c.id));
- return list.map((c) => ({ ...c, currentUsage: usageMap.get(c.id) ?? null }));
+ const usageMap = await this.getUsageForClassrooms(list.map((c) => c.id));
+ return list.map((classroom) => this.withEffectiveStatus(classroom, usageMap.get(classroom.id)));
}
async findOne(id: number) {
const cls = await this.repo.findOne({ where: { id } });
if (!cls) throw new NotFoundException('教室不存在');
- const usageMap = await this.getCurrentUsageForClassrooms([id]);
- return { ...cls, currentUsage: usageMap.get(id) ?? null };
+ const usageMap = await this.getUsageForClassrooms([id]);
+ return this.withEffectiveStatus(cls, usageMap.get(id));
}
async create(dto: CreateClassroomDto) {
const exists = await this.repo.findOne({ where: { name: dto.name } });
if (exists) throw new BadRequestException(`教室 ${dto.name} 已存在`);
- return this.repo.save(this.repo.create(dto));
+ return this.repo.save(this.repo.create({ ...dto, status: ClassroomStatus.AVAILABLE }));
}
async update(id: number, dto: UpdateClassroomDto) {
- await this.findOne(id);
+ const classroom = await this.repo.findOne({ where: { id } });
+ if (!classroom) throw new NotFoundException('教室不存在');
+ if (dto.status === ClassroomStatus.MAINTENANCE && classroom.status !== dto.status) {
+ await this.assertNoActiveAllocations(id);
+ }
await this.repo.update(id, dto);
return this.repo.findOne({ where: { id } });
}
async remove(id: number) {
- await this.findOne(id);
- await this.repo.update(id, { status: 'archived' });
+ const classroom = await this.repo.findOne({ where: { id } });
+ if (!classroom) throw new NotFoundException('教室不存在');
+ await this.assertNoActiveAllocations(id);
+ await this.repo.update(id, { status: ClassroomStatus.ARCHIVED });
return { message: '已归档' };
}
async restore(id: number) {
- await this.findOne(id);
- await this.repo.update(id, { status: 'reserved' });
+ const classroom = await this.repo.findOne({ where: { id } });
+ if (!classroom) throw new NotFoundException('教室不存在');
+ await this.repo.update(id, { status: ClassroomStatus.AVAILABLE });
return this.repo.findOne({ where: { id } });
}
- private async getCurrentUsageForClassrooms(classroomIds: number[]): Promise