forked from wangziqi/gongxue-base
Compare commits
31 Commits
codex/xyx
...
200d2e423b
| Author | SHA1 | Date | |
|---|---|---|---|
| 200d2e423b | |||
| 1737563516 | |||
| 6a43f33f7a | |||
| d582d641c0 | |||
| fb9697bd05 | |||
| bc49d1016a | |||
| 8bd445df5a | |||
| fcde6caaaa | |||
| b1f35f9d1a | |||
| 17a5046ea0 | |||
| e45da7f998 | |||
| c75a08affe | |||
| b480070e69 | |||
| 598b4e8acd | |||
| eac336a54a | |||
| ce5fd1c6cb | |||
| 05a936bbc2 | |||
| 3adf4933d8 | |||
| d84f37e98f | |||
| 16b56ffcd5 | |||
| 718c58589f | |||
| aaf49d5580 | |||
| 5cf6aede1e | |||
| 811e7ce826 | |||
| 79fa472b78 | |||
| 029af37f3a | |||
| d572e984d2 | |||
| a93ba657a8 | |||
| 77714642a5 | |||
| e7aa202603 | |||
| 013b3f4afe |
@@ -14,6 +14,7 @@ const RoomsPage = lazy(() => import('./pages/Rooms'));
|
||||
const OccupanciesPage = lazy(() => import('./pages/Occupancies'));
|
||||
const ExpensesPage = lazy(() => import('./pages/Expenses'));
|
||||
const BillsPage = lazy(() => import('./pages/Bills'));
|
||||
const WalletsPage = lazy(() => import('./pages/Wallets'));
|
||||
const RoomVisualPage = lazy(() => import('./pages/RoomVisual'));
|
||||
const OperationLogsPage = lazy(() => import('./pages/OperationLogs'));
|
||||
const UsersPage = lazy(() => import('./pages/Users'));
|
||||
@@ -134,6 +135,14 @@ const App: React.FC = () => {
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="wallets"
|
||||
element={
|
||||
<PermissionRoute permission="wallet:view">
|
||||
<WalletsPage />
|
||||
</PermissionRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="bills"
|
||||
element={
|
||||
|
||||
@@ -73,6 +73,7 @@ const SECTIONS: MenuSection[] = [
|
||||
{ key: '/occupancies', label: '入住管理', icon: 'occupancy', permission: 'occupancy:view' },
|
||||
{ key: '/expenses', label: '费用管理', icon: 'expense', permission: 'expense:view' },
|
||||
{ key: '/bills', label: '账单管理', icon: 'bill', permission: 'bill:view' },
|
||||
{ key: '/wallets', label: '学生余额', icon: 'wallet', permission: 'wallet:view' },
|
||||
{ key: '/deposits', label: '押金管理', icon: 'deposit', permission: 'deposit:view' },
|
||||
],
|
||||
},
|
||||
@@ -111,8 +112,9 @@ export function getRoleDomains(roles: readonly string[], permissions: readonly s
|
||||
normalized.add('academic');
|
||||
}
|
||||
if (
|
||||
permissions.includes('room:view') &&
|
||||
(permissions.includes('occupancy:view') || permissions.includes('expense:view'))
|
||||
(permissions.includes('room:view') &&
|
||||
(permissions.includes('occupancy:view') || permissions.includes('expense:view'))) ||
|
||||
permissions.includes('wallet:view')
|
||||
) {
|
||||
normalized.add('accommodation');
|
||||
}
|
||||
|
||||
@@ -105,6 +105,20 @@ interface AttachmentRecord {
|
||||
fileSize: number;
|
||||
}
|
||||
|
||||
interface AttendanceRecordItem {
|
||||
id: number;
|
||||
attendanceDate: string;
|
||||
session: string;
|
||||
status: string;
|
||||
source?: string;
|
||||
remark?: string | null;
|
||||
punchTime?: string | null;
|
||||
punchDeviceName?: string | null;
|
||||
punchDeviceId?: string | null;
|
||||
schedule?: { subject?: string } | null;
|
||||
class?: { name?: string } | null;
|
||||
}
|
||||
|
||||
interface StudentProfileAggregate {
|
||||
student: StudentInfo;
|
||||
profile: ProfileData | null;
|
||||
@@ -113,6 +127,7 @@ interface StudentProfileAggregate {
|
||||
learningRecords: LearningRecord[];
|
||||
result: ResultData | null;
|
||||
attachments: AttachmentRecord[];
|
||||
attendances: AttendanceRecordItem[];
|
||||
}
|
||||
|
||||
export interface StudentProfileContentProps {
|
||||
@@ -147,6 +162,19 @@ const RECORD_TYPE_OPTIONS = [
|
||||
{ value: 'other', label: '其他' },
|
||||
];
|
||||
|
||||
const STUDENT_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||
active: { text: '在读', color: 'green' },
|
||||
graduated: { text: '已毕业', color: 'blue' },
|
||||
withdrawn: { text: '已退训', color: 'red' },
|
||||
archived: { text: '已归档', color: '#999' },
|
||||
};
|
||||
|
||||
const ENROLLMENT_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||
active: { text: '报读中', color: 'green' },
|
||||
completed: { text: '已结课', color: 'blue' },
|
||||
withdrawn: { text: '已退训', color: 'red' },
|
||||
};
|
||||
|
||||
const COURSE_CATEGORY_OPTIONS = [
|
||||
{ value: 'culture', label: '文化课' },
|
||||
{ value: 'professional', label: '专业课' },
|
||||
@@ -161,6 +189,34 @@ const CLASS_TYPE_OPTIONS = [
|
||||
{ value: 'offline', label: '线下' },
|
||||
];
|
||||
|
||||
const getOptionLabel = (
|
||||
options: Array<{ value: string; label: string }>,
|
||||
value?: string | null,
|
||||
): string => {
|
||||
if (!value) return '-';
|
||||
return options.find((option) => option.value === value)?.label || value;
|
||||
};
|
||||
|
||||
const getCourseCategoryLabel = (value?: string | null): string =>
|
||||
getOptionLabel(COURSE_CATEGORY_OPTIONS, value);
|
||||
|
||||
const getClassTypeLabel = (value?: string | null): string =>
|
||||
getOptionLabel(CLASS_TYPE_OPTIONS, value);
|
||||
|
||||
const getEnrollmentStatus = (value?: string | null): { text: string; color: string } => {
|
||||
if (!value) return { text: '-', color: 'default' };
|
||||
return ENROLLMENT_STATUS_MAP[value] || { text: value, color: 'default' };
|
||||
};
|
||||
|
||||
const getStudentStatus = (value?: string | null): { text: string; color: string } => {
|
||||
if (!value) return { text: '-', color: 'default' };
|
||||
return STUDENT_STATUS_MAP[value] || { text: value, color: 'default' };
|
||||
};
|
||||
|
||||
const formatEnrollmentDisplayName = (enrollment: EnrollmentRecord): string =>
|
||||
enrollment.className ||
|
||||
(enrollment.courseCategory ? getCourseCategoryLabel(enrollment.courseCategory) : String(enrollment.id));
|
||||
|
||||
const ATTACHMENT_CATEGORY_OPTIONS = [
|
||||
{ value: 'id_card', label: '身份证' },
|
||||
{ value: 'transcript', label: '成绩单' },
|
||||
@@ -178,6 +234,58 @@ const formatFileSize = (bytes: number): string => {
|
||||
|
||||
// ---- Tab Components ----
|
||||
|
||||
const ATTENDANCE_STATUS_MAP: Record<string, { text: string; color: string }> = {
|
||||
present: { text: '出勤', color: 'green' },
|
||||
late: { text: '迟到', color: 'orange' },
|
||||
absent: { text: '缺勤', color: 'red' },
|
||||
leave: { text: '请假', color: 'blue' },
|
||||
pending: { text: '待确认', color: 'default' },
|
||||
};
|
||||
|
||||
const SESSION_LABELS: Record<string, string> = {
|
||||
morning_reading: '早自习',
|
||||
morning: '上午',
|
||||
afternoon: '下午',
|
||||
evening_study: '晚自习',
|
||||
night_check: '晚寝',
|
||||
};
|
||||
|
||||
const AttendanceTab: React.FC<{ data: AttendanceRecordItem[] }> = ({ data }) => {
|
||||
const columns: ColumnsType<AttendanceRecordItem> = [
|
||||
{ title: '日期', dataIndex: 'attendanceDate', width: 120 },
|
||||
{ title: '课程', render: (_: unknown, record) => record.schedule?.subject || record.class?.name || '课程考勤' },
|
||||
{ title: '时段', dataIndex: 'session', width: 100, render: (value: string) => SESSION_LABELS[value] || value || '-' },
|
||||
{
|
||||
title: '结果', dataIndex: 'status', width: 90,
|
||||
render: (value: string) => {
|
||||
const meta = ATTENDANCE_STATUS_MAP[value] || { text: value || '-', color: 'default' };
|
||||
return <Tag color={meta.color}>{meta.text}</Tag>;
|
||||
},
|
||||
},
|
||||
{ title: '打卡时间', dataIndex: 'punchTime', width: 170, render: (value?: string | null) => value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-' },
|
||||
{
|
||||
title: '打卡设备',
|
||||
render: (_: unknown, record) => {
|
||||
const name = record.punchDeviceName?.trim();
|
||||
const id = record.punchDeviceId?.trim();
|
||||
if (name && id && name !== id) return `${name}(${id})`;
|
||||
return name || id || (record.source === 'manual' ? '老师手动标记' : '-');
|
||||
},
|
||||
},
|
||||
{ title: '备注', dataIndex: 'remark', render: (value?: string | null) => value || '-' },
|
||||
];
|
||||
|
||||
return data.length > 0 ? (
|
||||
<Table<AttendanceRecordItem>
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
rowKey="id"
|
||||
scroll={{ x: 900 }}
|
||||
pagination={{ defaultPageSize: 15, showSizeChanger: true, pageSizeOptions: [15, 30, 50] }}
|
||||
/>
|
||||
) : <Empty description="暂无出勤记录" />;
|
||||
};
|
||||
|
||||
interface TabProps {
|
||||
studentId: number;
|
||||
onRefresh: () => void;
|
||||
@@ -283,8 +391,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
};
|
||||
|
||||
const columns: ColumnsType<EnrollmentRecord> = [
|
||||
{ title: '课程类别', dataIndex: 'courseCategory', render: (v: string) => v || '-' },
|
||||
{ title: '班型', dataIndex: 'classType', render: (v: string) => v || '-' },
|
||||
{ title: '课程类别', dataIndex: 'courseCategory', render: getCourseCategoryLabel },
|
||||
{ title: '班型', dataIndex: 'classType', render: getClassTypeLabel },
|
||||
{ title: '班级名称', dataIndex: 'className', render: (v: string) => v || '-' },
|
||||
{ title: '班主任', dataIndex: 'headTeacher', render: (v: string) => v || '-' },
|
||||
{ title: '任课教师', dataIndex: 'subjectTeacher', render: (v: string) => v || '-' },
|
||||
@@ -294,12 +402,8 @@ const EnrollmentsTab: React.FC<TabProps & { data: EnrollmentRecord[] }> = ({
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (v: string) => {
|
||||
const colorMap: Record<string, string> = {
|
||||
active: 'green',
|
||||
completed: 'blue',
|
||||
withdrawn: 'red',
|
||||
};
|
||||
return <Tag color={colorMap[v] || 'default'}>{v || '-'}</Tag>;
|
||||
const status = getEnrollmentStatus(v);
|
||||
return <Tag color={status.color}>{status.text}</Tag>;
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -410,7 +514,7 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
|
||||
render: (v: number | undefined) => {
|
||||
if (v === undefined) return '-';
|
||||
const enr = enrollments.find((e) => e.id === v);
|
||||
return enr ? `${enr.className || enr.courseCategory || v}` : String(v);
|
||||
return enr ? formatEnrollmentDisplayName(enr) : String(v);
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -473,7 +577,7 @@ const ExamScoresTab: React.FC<TabProps & { data: ExamScoreRecord[]; enrollments:
|
||||
placeholder="选择关联的报读记录"
|
||||
options={enrollments.map((e) => ({
|
||||
value: e.id,
|
||||
label: `${e.className || e.courseCategory || e.id} (${e.classType})`,
|
||||
label: `${formatEnrollmentDisplayName(e)}(${getClassTypeLabel(e.classType)})`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
@@ -779,7 +883,7 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
|
||||
const tabItems = useMemo(() => {
|
||||
if (!aggregateData) return [];
|
||||
const { profile, enrollments, examScores, learningRecords, result, attachments } = aggregateData;
|
||||
const { profile, enrollments, examScores, learningRecords, result, attachments, attendances } = aggregateData;
|
||||
return [
|
||||
{
|
||||
key: 'profile',
|
||||
@@ -807,8 +911,8 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
},
|
||||
{
|
||||
key: 'attendance',
|
||||
label: '出勤记录',
|
||||
children: <Empty description="暂无出勤记录" />,
|
||||
label: `出勤记录 (${attendances.length})`,
|
||||
children: <AttendanceTab data={attendances} />,
|
||||
},
|
||||
{
|
||||
key: 'learning',
|
||||
@@ -909,7 +1013,10 @@ const StudentProfileContent: React.FC<StudentProfileContentProps> = ({
|
||||
) : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag>{student.status || '-'}</Tag>
|
||||
{(() => {
|
||||
const status = getStudentStatus(student.status);
|
||||
return <Tag color={status.color}>{status.text}</Tag>;
|
||||
})()}
|
||||
</Descriptions.Item>
|
||||
{profile?.targetCollege && (
|
||||
<Descriptions.Item label="目标院校">{profile.targetCollege}</Descriptions.Item>
|
||||
|
||||
@@ -4,7 +4,15 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
min-width: 320px;
|
||||
background: #f5f5f7;
|
||||
}
|
||||
|
||||
body {
|
||||
min-width: 320px;
|
||||
overflow-x: hidden;
|
||||
background: #f5f5f7;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
@@ -15,10 +23,55 @@ body {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
img,
|
||||
svg,
|
||||
canvas {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.app-shell,
|
||||
.app-main,
|
||||
.app-content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
/* Shared responsive toolbar: add these classes to page filter/action rows. */
|
||||
.responsive-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.responsive-toolbar__group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ant-drawer-content-wrapper {
|
||||
max-width: 100vw !important;
|
||||
}
|
||||
|
||||
.ant-pagination {
|
||||
row-gap: 8px;
|
||||
}
|
||||
|
||||
/* === 通用:表格容器横向滚动(防双重滚动条) === */
|
||||
.ant-table-wrapper {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
overscroll-behavior-inline: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* ── 表格单元格省略号截断(按需启用) ──
|
||||
@@ -54,6 +107,65 @@ body {
|
||||
|
||||
/* === 手机 (< 576px) === */
|
||||
@media (max-width: 575px) {
|
||||
.app-header {
|
||||
height: 56px;
|
||||
padding-inline: 8px !important;
|
||||
line-height: 56px;
|
||||
}
|
||||
|
||||
.app-header .ant-btn {
|
||||
width: 40px;
|
||||
min-height: 40px;
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
.app-content {
|
||||
min-height: calc(100dvh - 72px);
|
||||
margin: 8px !important;
|
||||
padding: 12px !important;
|
||||
border-radius: 10px !important;
|
||||
}
|
||||
|
||||
.app-navigation-drawer .ant-drawer-header {
|
||||
padding-inline: 16px;
|
||||
}
|
||||
|
||||
.responsive-toolbar {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.responsive-toolbar__group,
|
||||
.responsive-toolbar > .ant-space {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.responsive-toolbar__group > .ant-space-item,
|
||||
.responsive-toolbar > .ant-space > .ant-space-item {
|
||||
flex: 1 1 140px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.responsive-toolbar .ant-input,
|
||||
.responsive-toolbar .ant-input-affix-wrapper,
|
||||
.responsive-toolbar .ant-input-search,
|
||||
.responsive-toolbar .ant-picker,
|
||||
.responsive-toolbar .ant-select,
|
||||
.responsive-toolbar .ant-upload,
|
||||
.responsive-toolbar .ant-upload-wrapper,
|
||||
.responsive-toolbar .ant-btn {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.ant-btn:not(.ant-btn-sm),
|
||||
.ant-input-affix-wrapper,
|
||||
.ant-input-search-button,
|
||||
.ant-picker,
|
||||
.ant-select-single .ant-select-selector {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.ant-table {
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -65,12 +177,48 @@ body {
|
||||
font-size: 13px;
|
||||
}
|
||||
.ant-modal {
|
||||
max-width: calc(100vw - 24px) !important;
|
||||
margin: 12px auto !important;
|
||||
top: 12px;
|
||||
max-width: calc(100vw - 16px) !important;
|
||||
margin: 0 auto !important;
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
.ant-modal .ant-modal-content {
|
||||
padding: 16px;
|
||||
}
|
||||
.ant-modal .ant-modal-body {
|
||||
max-height: 60vh;
|
||||
max-height: calc(100dvh - 180px);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.ant-modal .ant-modal-footer {
|
||||
display: flex;
|
||||
}
|
||||
.ant-modal .ant-modal-footer .ant-btn {
|
||||
flex: 1;
|
||||
min-height: 40px;
|
||||
}
|
||||
.ant-drawer .ant-drawer-header {
|
||||
padding: 14px 16px;
|
||||
}
|
||||
.ant-drawer .ant-drawer-body {
|
||||
padding: 16px;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.ant-popover,
|
||||
.ant-picker-dropdown {
|
||||
max-width: calc(100vw - 16px);
|
||||
}
|
||||
.ant-pagination {
|
||||
justify-content: center;
|
||||
}
|
||||
.ant-pagination .ant-pagination-options {
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
.ant-alert {
|
||||
padding: 10px 12px;
|
||||
}
|
||||
h1 {
|
||||
font-size: 22px !important;
|
||||
}
|
||||
h2 {
|
||||
font-size: 18px !important;
|
||||
@@ -78,9 +226,8 @@ body {
|
||||
.ant-card {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.ant-space-item .ant-btn {
|
||||
padding: 2px 6px;
|
||||
font-size: 12px;
|
||||
.ant-card .ant-card-body {
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,3 +237,82 @@ body {
|
||||
max-width: calc(100vw - 48px) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.notifications-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.notifications-filter {
|
||||
width: 100%;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.notifications-layout,
|
||||
.notifications-content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.notifications-header {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.notifications-content .ant-list-item {
|
||||
align-items: flex-start;
|
||||
padding: 14px 6px !important;
|
||||
}
|
||||
|
||||
.notifications-content .ant-list-item-meta-avatar {
|
||||
margin-inline-end: 10px;
|
||||
}
|
||||
|
||||
.notifications-content .ant-list-item-meta-title {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
.ant-table-wrapper::before {
|
||||
content: '表格可左右滑动查看';
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
color: #8c8c8c;
|
||||
font-size: 11px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-content {
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.ant-table-wrapper .ant-table-cell-fix-left,
|
||||
.ant-table-wrapper .ant-table-cell-fix-right {
|
||||
box-shadow: 2px 0 5px rgb(0 0 0 / 5%);
|
||||
}
|
||||
}
|
||||
|
||||
.responsive-toolbar--single {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
@media (max-width: 575px) {
|
||||
/* Input.Search is an internal compact group. Keep the text field flexible and
|
||||
the search icon button fixed instead of applying toolbar full-width rules
|
||||
to both children. */
|
||||
.responsive-toolbar .ant-input-search > .ant-input-affix-wrapper {
|
||||
flex: 1 1 auto;
|
||||
width: auto !important;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.responsive-toolbar .ant-input-search > .ant-input-search-btn {
|
||||
flex: 0 0 40px;
|
||||
width: 40px !important;
|
||||
min-width: 40px;
|
||||
padding-inline: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ const iconMap: Record<string, React.ReactNode> = {
|
||||
expense: <DollarOutlined />,
|
||||
bill: <FileTextOutlined />,
|
||||
deposit: <WalletOutlined />,
|
||||
wallet: <WalletOutlined />,
|
||||
classroom: <ReadOutlined />,
|
||||
rental: <FileProtectOutlined />,
|
||||
organization: <TagsOutlined />,
|
||||
@@ -176,13 +177,14 @@ const MainLayout: React.FC = () => {
|
||||
), [selectedKeys, openKeys, menuItems, handleMenuClick]);
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
<Layout className="app-shell" style={{ minHeight: '100vh' }}>
|
||||
{!isMobile && (
|
||||
<Sider
|
||||
trigger={null}
|
||||
collapsible
|
||||
collapsed={isTablet ? true : collapsed}
|
||||
theme="light"
|
||||
className="app-sidebar"
|
||||
style={{ background: '#fff', borderRight: '1px solid #e5e5e7' }}
|
||||
>
|
||||
<div
|
||||
@@ -209,13 +211,15 @@ const MainLayout: React.FC = () => {
|
||||
onClose={() => setDrawerOpen(false)}
|
||||
size={240}
|
||||
styles={{ body: { padding: 0 } }}
|
||||
className="app-navigation-drawer"
|
||||
title="恭学教育基地"
|
||||
>
|
||||
{menuContent}
|
||||
</Drawer>
|
||||
)}
|
||||
<Layout style={{ background: '#f5f5f7' }}>
|
||||
<Layout className="app-main" style={{ background: '#f5f5f7' }}>
|
||||
<Header
|
||||
className="app-header"
|
||||
style={{
|
||||
padding: '0 16px',
|
||||
background: '#fff',
|
||||
@@ -267,8 +271,9 @@ const MainLayout: React.FC = () => {
|
||||
</div>
|
||||
</Header>
|
||||
<Content
|
||||
className="app-content"
|
||||
style={{
|
||||
margin: isMobile ? 12 : isTablet ? 16 : 24,
|
||||
margin: isMobile ? 8 : isTablet ? 16 : 24,
|
||||
padding: isMobile ? 12 : isTablet ? 16 : 24,
|
||||
background: '#fff',
|
||||
borderRadius: 12,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
canPullAttendance,
|
||||
filterLessonAttendanceRecords,
|
||||
getAttendanceExperience,
|
||||
getPunchDisplayInfo,
|
||||
getSchedulePhase,
|
||||
summarizeAttendance,
|
||||
summarizeLessonCheckins,
|
||||
@@ -65,3 +67,55 @@ describe('lesson check-in summary', () => {
|
||||
).toEqual({ total: 4, checkedIn: 2, notCheckedIn: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('lesson attendance filters', () => {
|
||||
const records = [
|
||||
{ id: 1, student: { name: '张三' }, status: 'present' },
|
||||
{ id: 2, student: { name: '李四' }, status: 'late' },
|
||||
{ id: 3, student: { name: '王五' }, status: 'pending' },
|
||||
{ id: 4, student: { name: '赵六' }, status: 'absent' },
|
||||
];
|
||||
|
||||
it('searches students by name and ignores surrounding whitespace', () => {
|
||||
expect(filterLessonAttendanceRecords(records, ' 张 ', 'all').map((item) => item.id)).toEqual([1]);
|
||||
});
|
||||
|
||||
it('groups present and late as checked in', () => {
|
||||
expect(filterLessonAttendanceRecords(records, '', 'checked_in').map((item) => item.id)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('groups pending and absent as not checked in and combines with search', () => {
|
||||
expect(filterLessonAttendanceRecords(records, '王', 'not_checked_in').map((item) => item.id)).toEqual([3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('lesson punch device display', () => {
|
||||
it('labels attendance machine punches with the machine name and id', () => {
|
||||
expect(
|
||||
getPunchDisplayInfo({
|
||||
status: 'present',
|
||||
source: 'dingtalk',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchTime: '2026-07-11T00:55:00.000Z',
|
||||
}),
|
||||
).toEqual({
|
||||
label: '考勤机打卡',
|
||||
machine: true,
|
||||
detail: '东门考勤机(ATM-01)',
|
||||
time: '2026-07-11T00:55:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('distinguishes mobile punches and manual teacher markings', () => {
|
||||
expect(
|
||||
getPunchDisplayInfo({ status: 'present', source: 'dingtalk', punchSource: 'USER' }),
|
||||
).toEqual({ label: '手机打卡', machine: false, detail: undefined, time: undefined });
|
||||
expect(getPunchDisplayInfo({ status: 'present', source: 'manual' })).toEqual({
|
||||
label: '老师手动标记',
|
||||
machine: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -82,3 +82,80 @@ export function summarizeLessonCheckins(
|
||||
notCheckedIn: records.length - checkedIn,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export type LessonAttendanceFilter = 'all' | 'checked_in' | 'not_checked_in';
|
||||
|
||||
export interface LessonAttendanceFilterRecord {
|
||||
student: { name: string };
|
||||
status: string;
|
||||
}
|
||||
|
||||
export function filterLessonAttendanceRecords<T extends LessonAttendanceFilterRecord>(
|
||||
records: readonly T[],
|
||||
keyword: string,
|
||||
filter: LessonAttendanceFilter,
|
||||
): T[] {
|
||||
const normalizedKeyword = keyword.trim().toLocaleLowerCase('zh-CN');
|
||||
return records.filter((record) => {
|
||||
const matchesKeyword =
|
||||
!normalizedKeyword ||
|
||||
record.student.name.toLocaleLowerCase('zh-CN').includes(normalizedKeyword);
|
||||
if (!matchesKeyword || filter === 'all') return matchesKeyword;
|
||||
|
||||
const checkedIn = record.status === 'present' || record.status === 'late';
|
||||
return filter === 'checked_in' ? checkedIn : !checkedIn;
|
||||
});
|
||||
}
|
||||
|
||||
export interface PunchDisplayRecord {
|
||||
status: string;
|
||||
source?: string;
|
||||
punchTime?: string | null;
|
||||
punchSource?: string | null;
|
||||
punchDeviceName?: string | null;
|
||||
punchDeviceId?: string | null;
|
||||
}
|
||||
|
||||
export interface PunchDisplayInfo {
|
||||
label: string;
|
||||
machine: boolean;
|
||||
detail?: string;
|
||||
time?: string;
|
||||
}
|
||||
|
||||
export function getPunchDisplayInfo(record: PunchDisplayRecord): PunchDisplayInfo | null {
|
||||
if (record.status !== 'present' && record.status !== 'late') return null;
|
||||
if (record.source === 'manual') return { label: '老师手动标记', machine: false };
|
||||
|
||||
const source = (record.punchSource || '').trim().toUpperCase();
|
||||
const machine = ['ATM', 'ATTENDANCE_MACHINE', 'MACHINE', 'DEVICE'].some(
|
||||
(value) => source === value || source.includes(value),
|
||||
);
|
||||
const label = machine
|
||||
? '考勤机打卡'
|
||||
: source === 'USER'
|
||||
? '手机打卡'
|
||||
: source.includes('BEACON') || source.includes('BLE')
|
||||
? '蓝牙打卡'
|
||||
: source.includes('WIFI')
|
||||
? 'Wi-Fi 打卡'
|
||||
: source.includes('APPROVE')
|
||||
? '审批补卡'
|
||||
: source
|
||||
? `其他打卡(${record.punchSource})`
|
||||
: '打卡来源未知';
|
||||
const device = record.punchDeviceName?.trim();
|
||||
const deviceId = record.punchDeviceId?.trim();
|
||||
const detail = device
|
||||
? deviceId && deviceId !== device
|
||||
? `${device}(${deviceId})`
|
||||
: device
|
||||
: deviceId || undefined;
|
||||
return {
|
||||
label,
|
||||
machine,
|
||||
detail,
|
||||
time: record.punchTime || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -286,6 +286,32 @@
|
||||
.is-leave { color: #2874c6 !important; background: #edf5ff; }
|
||||
.is-pending { color: #667085 !important; background: #f1f3f6; }
|
||||
|
||||
.lesson-record-filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 0 0 14px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.lesson-record-search {
|
||||
width: 260px;
|
||||
}
|
||||
|
||||
.lesson-record-filter-select {
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
.lesson-record-filter-count {
|
||||
margin-left: auto;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.attendance-status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -414,6 +440,22 @@
|
||||
color: #a1a9b5;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.lesson-record-filters {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.lesson-record-search,
|
||||
.lesson-record-filter-select {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.lesson-record-filter-count {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.attendance-hero,
|
||||
.archive-toolbar {
|
||||
@@ -502,3 +544,25 @@
|
||||
.attendance-marking-actions .ant-btn {
|
||||
min-width: 54px;
|
||||
}
|
||||
|
||||
|
||||
.punch-device-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.punch-device-cell .ant-tag {
|
||||
margin-inline-end: 0;
|
||||
}
|
||||
|
||||
.punch-device-cell strong {
|
||||
color: #1f2937;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.punch-device-cell span {
|
||||
color: #8c8c8c;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@@ -40,10 +40,13 @@ import { usePermission } from '../../hooks/usePermission';
|
||||
import { message } from '../../ui/app-message';
|
||||
import {
|
||||
canPullAttendance,
|
||||
filterLessonAttendanceRecords,
|
||||
getAttendanceExperience,
|
||||
getPunchDisplayInfo,
|
||||
getSchedulePhase,
|
||||
summarizeLessonCheckins,
|
||||
type AttendanceSummary,
|
||||
type LessonAttendanceFilter,
|
||||
type SchedulePhase,
|
||||
} from './attendance-workspace';
|
||||
import './attendance.css';
|
||||
@@ -96,6 +99,10 @@ interface AttendanceRecordItem {
|
||||
class: { id: number; name: string } | null;
|
||||
scheduleId?: number | null;
|
||||
attendanceSessionId?: number | null;
|
||||
punchTime?: string | null;
|
||||
punchSource?: string | null;
|
||||
punchDeviceName?: string | null;
|
||||
punchDeviceId?: string | null;
|
||||
}
|
||||
|
||||
interface AssignedClass {
|
||||
@@ -256,6 +263,8 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
const [lessonRecords, setLessonRecords] = useState<AttendanceRecordItem[]>([]);
|
||||
const [recordLoading, setRecordLoading] = useState(false);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [studentKeyword, setStudentKeyword] = useState('');
|
||||
const [checkinFilter, setCheckinFilter] = useState<LessonAttendanceFilter>('all');
|
||||
|
||||
const loadWorkspace = useCallback(async () => {
|
||||
setLoading(true);
|
||||
@@ -279,6 +288,8 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
|
||||
|
||||
const openAttendance = useCallback(async (schedule: TodaySchedule) => {
|
||||
setStudentKeyword('');
|
||||
setCheckinFilter('all');
|
||||
setSelectedSchedule(schedule);
|
||||
setDrawerOpen(true);
|
||||
setRecordLoading(true);
|
||||
@@ -288,6 +299,7 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
`/attendance-lessons/schedules/${schedule.id}/pull`,
|
||||
{ date: today },
|
||||
);
|
||||
setSelectedSchedule(data.schedule);
|
||||
setLessonSession(data.session);
|
||||
setLessonRecords(data.records);
|
||||
message.success('钉钉打卡已更新;课程截止后系统将自动结算');
|
||||
@@ -328,6 +340,10 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
(item) => getSchedulePhase(item.startTime, item.endTime, now) !== 'ended',
|
||||
);
|
||||
const isAttendanceCompleted = lessonSession?.status === 'completed';
|
||||
const filteredLessonRecords = useMemo(
|
||||
() => filterLessonAttendanceRecords(lessonRecords, studentKeyword, checkinFilter),
|
||||
[lessonRecords, studentKeyword, checkinFilter],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="attendance-page teacher-attendance">
|
||||
@@ -386,7 +402,7 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
)}
|
||||
</Spin>
|
||||
|
||||
<Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} width={820} title={null} className="attendance-drawer">
|
||||
<Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} width={960} title={null} className="attendance-drawer">
|
||||
<div className="lesson-record-header">
|
||||
<span className="attendance-eyebrow">LESSON ATTENDANCE</span>
|
||||
<h2>{selectedSchedule?.subject || '课程考勤'}</h2>
|
||||
@@ -401,12 +417,39 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
<LessonCheckinSummaryStrip records={lessonRecords} />
|
||||
<div className="lesson-record-filters">
|
||||
<Input.Search
|
||||
allowClear
|
||||
value={studentKeyword}
|
||||
placeholder="搜索学生姓名"
|
||||
onChange={(event) => setStudentKeyword(event.target.value)}
|
||||
className="lesson-record-search"
|
||||
/>
|
||||
<Select<LessonAttendanceFilter>
|
||||
value={checkinFilter}
|
||||
onChange={setCheckinFilter}
|
||||
options={[
|
||||
{ value: 'all', label: '全部学生' },
|
||||
{ value: 'checked_in', label: '已打卡' },
|
||||
{ value: 'not_checked_in', label: '未打卡' },
|
||||
]}
|
||||
className="lesson-record-filter-select"
|
||||
/>
|
||||
<span className="lesson-record-filter-count">
|
||||
显示 {filteredLessonRecords.length} / {lessonRecords.length} 人
|
||||
</span>
|
||||
</div>
|
||||
<Table<AttendanceRecordItem>
|
||||
rowKey="id"
|
||||
loading={recordLoading}
|
||||
dataSource={lessonRecords}
|
||||
dataSource={filteredLessonRecords}
|
||||
pagination={false}
|
||||
locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="本节课尚未开始点名" /> }}
|
||||
locale={{
|
||||
emptyText: <Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={lessonRecords.length === 0 ? '本节课尚未开始点名' : '没有符合条件的学生'}
|
||||
/>,
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
title: '学生', dataIndex: ['student', 'name'],
|
||||
@@ -438,6 +481,21 @@ const TeacherAttendanceWorkspace: React.FC = () => {
|
||||
},
|
||||
},
|
||||
{ title: '当前状态', dataIndex: 'status', width: 105, render: (value: string) => <AttendanceStatusTag status={value === 'present' || value === 'late' ? 'present' : 'absent'} /> },
|
||||
{
|
||||
title: '打卡设备',
|
||||
width: 220,
|
||||
render: (_: unknown, record: AttendanceRecordItem) => {
|
||||
const info = getPunchDisplayInfo(record);
|
||||
if (!info) return <span className="muted-text">—</span>;
|
||||
return (
|
||||
<div className="punch-device-cell">
|
||||
<Tag color={info.machine ? 'green' : 'blue'}>{info.label}</Tag>
|
||||
{info.detail && <strong>{info.detail}</strong>}
|
||||
{info.time && <span>{dayjs(info.time).format('HH:mm:ss')}</span>}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ title: '备注', dataIndex: 'remark', render: (value: string | null) => value || <span className="muted-text">—</span> },
|
||||
]}
|
||||
/>
|
||||
@@ -625,6 +683,21 @@ const AdminAttendanceArchive: React.FC<{ canEdit: boolean }> = ({ canEdit }) =>
|
||||
width: 110,
|
||||
render: (value: string) => (value === 'dingtalk' ? '钉钉同步' : value === 'schedule' ? '课程生成' : value === 'lesson' ? '课堂点名' : '人工记录'),
|
||||
},
|
||||
{
|
||||
title: '打卡设备',
|
||||
width: 220,
|
||||
render: (_: unknown, record: AttendanceRecordItem) => {
|
||||
const info = getPunchDisplayInfo(record);
|
||||
if (!info) return <span className="muted-text">—</span>;
|
||||
return (
|
||||
<div className="punch-device-cell">
|
||||
<Tag color={info.machine ? 'green' : 'blue'}>{info.label}</Tag>
|
||||
{info.detail && <strong>{info.detail}</strong>}
|
||||
{info.time && <span>{dayjs(info.time).format('HH:mm:ss')}</span>}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'remark',
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
Popconfirm,
|
||||
Input,
|
||||
Select,
|
||||
Tooltip,
|
||||
Spin,
|
||||
Empty,
|
||||
} from 'antd';
|
||||
@@ -26,12 +25,12 @@ import PermissionButton from '../../components/PermissionButton';
|
||||
import { downloadBlob } from '../../utils/download';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
draft: { text: '草稿', color: 'default' },
|
||||
confirmed: { text: '已确认', color: 'blue' },
|
||||
unpaid: { text: '待支付', color: 'orange' },
|
||||
partially_paid: { text: '部分支付', color: 'gold' },
|
||||
paid: { text: '已支付', color: 'green' },
|
||||
cancelled: { text: '已取消', color: 'default' },
|
||||
};
|
||||
|
||||
const typeMap: Record<string, string> = {
|
||||
@@ -93,8 +92,7 @@ const BillsPage: React.FC = () => {
|
||||
const values = await generateForm.validateFields();
|
||||
try {
|
||||
const res: any = await api.post('/bills/generate', {
|
||||
periodStart: values.period[0].format('YYYY-MM-DD'),
|
||||
periodEnd: values.period[1].format('YYYY-MM-DD'),
|
||||
billingMonth: values.billingMonth.format('YYYY-MM'),
|
||||
});
|
||||
message.success(res.message || '生成成功');
|
||||
setGenerateModal(false);
|
||||
@@ -119,43 +117,29 @@ const BillsPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const updateStatus = async (id: number, status: string) => {
|
||||
try {
|
||||
await api.put(`/bills/${id}/status`, { status });
|
||||
message.success('状态更新成功');
|
||||
fetchData();
|
||||
if (detailModal?.id === id) {
|
||||
setDetailModal({ ...detailModal, status });
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '操作失败');
|
||||
}
|
||||
};
|
||||
|
||||
const batchUpdateStatus = async (status: string) => {
|
||||
if (selectedRows.length === 0) return message.warning('请先选择账单');
|
||||
if (batchLoading) return;
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
await api.put('/bills/batch/status', { ids: selectedRows, status });
|
||||
message.success(`已批量更新 ${selectedRows.length} 条账单`);
|
||||
setSelectedRows([]);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '操作失败');
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
|
||||
const handleCancel = async (id: number) => {
|
||||
let reason = '';
|
||||
Modal.confirm({
|
||||
title: '取消账单并退回已扣余额',
|
||||
content: <Input.TextArea placeholder="请输入取消原因" maxLength={300} onChange={(event) => { reason = event.target.value; }} />,
|
||||
okText: '确认取消', cancelText: '返回',
|
||||
onOk: async () => {
|
||||
if (!reason.trim()) { message.error('请输入取消原因'); throw new Error('reason required'); }
|
||||
await api.post(`/bills/${id}/cancel`, { reason: reason.trim() });
|
||||
message.success('账单已取消,已扣余额已冲正退回');
|
||||
fetchData();
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/bills/${id}`);
|
||||
message.success('账单已删除');
|
||||
message.success('删除成功');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
} catch (error: any) { message.error(error?.message || '删除失败'); }
|
||||
};
|
||||
|
||||
const batchDelete = async () => {
|
||||
@@ -212,31 +196,16 @@ const BillsPage: React.FC = () => {
|
||||
render: (v: number) => <strong>¥{Number(v).toFixed(2)}</strong>,
|
||||
},
|
||||
{
|
||||
title: '可用押金',
|
||||
dataIndex: 'availableDeposit',
|
||||
width: 120,
|
||||
render: (v: number) =>
|
||||
v > 0 ? (
|
||||
<span style={{ color: '#52c41a' }}>¥{Number(v).toFixed(2)}</span>
|
||||
) : (
|
||||
<span style={{ color: '#999' }}>-</span>
|
||||
),
|
||||
title: '已扣余额', dataIndex: 'paidAmount', width: 110,
|
||||
render: (value: number) => <span style={{ color: '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</span>,
|
||||
},
|
||||
{
|
||||
title: '抵扣后应付',
|
||||
dataIndex: 'amountAfterDeposit',
|
||||
width: 130,
|
||||
render: (v: number, r: any) => {
|
||||
const has = Number(r.availableDeposit || 0) > 0;
|
||||
if (!has) return <span style={{ color: '#999' }}>-</span>;
|
||||
const after = Number(v ?? r.totalAmount).toFixed(2);
|
||||
const applied = Number(r.depositApplied || 0).toFixed(2);
|
||||
return (
|
||||
<Tooltip title={`已抵扣押金 ¥${applied}`}>
|
||||
<strong style={{ color: '#fa541c' }}>¥{after}</strong>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
title: '待补缴', dataIndex: 'outstandingAmount', width: 110,
|
||||
render: (value: number) => <strong style={{ color: Number(value) > 0 ? '#cf1322' : '#389e0d' }}>¥{Number(value || 0).toFixed(2)}</strong>,
|
||||
},
|
||||
{
|
||||
title: '钱包余额', dataIndex: 'walletBalance', width: 110,
|
||||
render: (value: number) => `¥${Number(value || 0).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
@@ -263,25 +232,6 @@ const BillsPage: React.FC = () => {
|
||||
>
|
||||
详情
|
||||
</PermissionButton>
|
||||
{record.status === 'draft' && (
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
size="small"
|
||||
onClick={() => updateStatus(record.id, 'confirmed')}
|
||||
>
|
||||
确认
|
||||
</PermissionButton>
|
||||
)}
|
||||
{record.status === 'confirmed' && (
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
size="small"
|
||||
type="primary"
|
||||
onClick={() => updateStatus(record.id, 'paid')}
|
||||
>
|
||||
标记已付
|
||||
</PermissionButton>
|
||||
)}
|
||||
<PermissionButton
|
||||
permission="bill:export-pdf"
|
||||
size="small"
|
||||
@@ -290,33 +240,25 @@ const BillsPage: React.FC = () => {
|
||||
>
|
||||
PDF
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title="确定删除此账单?"
|
||||
onConfirm={() => handleDelete(record.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<PermissionButton permission="bill:delete" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
{record.status !== 'cancelled' && (
|
||||
<PermissionButton permission="bill:delete" size="small" danger onClick={() => handleCancel(record.id)}>
|
||||
取消并冲正
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{Number(record.paidAmount || 0) === 0 && record.status !== 'cancelled' && (
|
||||
<Popconfirm title="确定删除此未支付账单?" onConfirm={() => handleDelete(record.id)} okText="删除" cancelText="取消">
|
||||
<PermissionButton permission="bill:delete" size="small" danger icon={<DeleteOutlined />}>删除</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
], [showDetail, updateStatus, handleDelete, handleExportPdf]);
|
||||
], [showDetail, handleDelete, handleCancel, handleExportPdf]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名或账单周期"
|
||||
allowClear
|
||||
@@ -333,28 +275,14 @@ const BillsPage: React.FC = () => {
|
||||
value={filterStatus}
|
||||
onChange={(v) => setFilterStatus(v)}
|
||||
options={[
|
||||
{ value: 'draft', label: '草稿' },
|
||||
{ value: 'confirmed', label: '已确认' },
|
||||
{ value: 'unpaid', label: '待支付' },
|
||||
{ value: 'partially_paid', label: '部分支付' },
|
||||
{ value: 'paid', label: '已支付' },
|
||||
{ value: 'cancelled', label: '已取消' },
|
||||
]}
|
||||
/>
|
||||
<Select placeholder="费用类型" allowClear style={{ width: 120 }} value={filterExpenseType} onChange={setFilterExpenseType}
|
||||
options={[{value:'water',label:'水费'},{value:'electricity',label:'电费'},{value:'cleaning',label:'保洁费'},{value:'rent',label:'租金'},{value:'other',label:'其他'}]} />
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
onClick={() => batchUpdateStatus('confirmed')}
|
||||
disabled={selectedRows.length === 0}
|
||||
>
|
||||
批量确认
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="bill:confirm"
|
||||
type="primary"
|
||||
onClick={() => batchUpdateStatus('paid')}
|
||||
disabled={selectedRows.length === 0}
|
||||
>
|
||||
批量标记已付
|
||||
</PermissionButton>
|
||||
<Popconfirm
|
||||
title={`确定删除选中的 ${selectedRows.length} 条账单?`}
|
||||
onConfirm={batchDelete}
|
||||
@@ -372,7 +300,7 @@ const BillsPage: React.FC = () => {
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
<Space>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<PermissionButton
|
||||
permission="bill:generate"
|
||||
type="primary"
|
||||
@@ -399,12 +327,7 @@ const BillsPage: React.FC = () => {
|
||||
dataSource={filteredBills}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
pagination={{
|
||||
defaultPageSize: 15,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: [15, 30, 50, 100],
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
}}
|
||||
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 条` }}
|
||||
locale={{ emptyText: <Empty description="暂无数据" /> }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedRows,
|
||||
@@ -422,15 +345,17 @@ const BillsPage: React.FC = () => {
|
||||
>
|
||||
<Form form={generateForm} layout="vertical">
|
||||
<Form.Item
|
||||
name="period"
|
||||
label="账单周期"
|
||||
rules={[{ required: true, message: '请选择账单周期' }]}
|
||||
extra="选择费用对应的时间段,系统将自动计算每个学生的分摊费用"
|
||||
name="billingMonth"
|
||||
label="账单月份"
|
||||
rules={[{ required: true, message: '请选择账单月份' }]}
|
||||
extra="只能选择已结束月份,每个月只能生成一次账单"
|
||||
>
|
||||
<RangePicker
|
||||
<DatePicker
|
||||
style={{ width: '100%' }}
|
||||
placeholder={['开始日期', '结束日期']}
|
||||
format="YYYY-MM-DD"
|
||||
picker="month"
|
||||
placeholder="选择月份"
|
||||
format="YYYY-MM"
|
||||
disabledDate={(current) => !!current && !current.endOf('month').isBefore(dayjs(), 'day')}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
@@ -470,42 +395,11 @@ const BillsPage: React.FC = () => {
|
||||
</strong>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{Number(detailModal.availableDeposit || 0) > 0 && (
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
padding: 12,
|
||||
background: '#f6ffed',
|
||||
border: '1px solid #b7eb8f',
|
||||
borderRadius: 8,
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 13, color: '#666', marginBottom: 6 }}>
|
||||
押金联动(不影响实际押金状态,仅作收款参考)
|
||||
</div>
|
||||
<Space size={24} wrap>
|
||||
<span>
|
||||
当前可用押金:
|
||||
<strong style={{ color: '#52c41a' }}>
|
||||
¥{Number(detailModal.availableDeposit).toFixed(2)}
|
||||
</strong>
|
||||
</span>
|
||||
<span>
|
||||
本账单可抵扣:
|
||||
<strong style={{ color: '#fa8c16' }}>
|
||||
-¥{Number(detailModal.depositApplied || 0).toFixed(2)}
|
||||
</strong>
|
||||
</span>
|
||||
<span>
|
||||
抵扣后实付:
|
||||
<strong style={{ color: '#fa541c', fontSize: 16 }}>
|
||||
¥
|
||||
{Number(detailModal.amountAfterDeposit ?? detailModal.totalAmount).toFixed(2)}
|
||||
</strong>
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
<Descriptions bordered size="small" column={3} style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="已扣余额">¥{Number(detailModal.paidAmount || 0).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="待补缴">¥{Number(detailModal.outstandingAmount || 0).toFixed(2)}</Descriptions.Item>
|
||||
<Descriptions.Item label="当前钱包余额">¥{Number(detailModal.walletBalance || 0).toFixed(2)}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<h4>费用明细</h4>
|
||||
<Table
|
||||
scroll={{ x: 700 }}
|
||||
|
||||
@@ -10,6 +10,7 @@ import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { buildTeacherCandidateOptions, type TeacherCandidateUser } from './teacher-candidate';
|
||||
|
||||
// ---- Types ----
|
||||
|
||||
@@ -39,6 +40,7 @@ interface ClassScheduleItem {
|
||||
weekDay: number;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
attendanceAdvanceMinutes: number;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
subject: string;
|
||||
@@ -83,10 +85,7 @@ interface StudentItem {
|
||||
studentNo?: string;
|
||||
}
|
||||
|
||||
interface UserItem {
|
||||
id: number;
|
||||
username: string;
|
||||
}
|
||||
type UserItem = TeacherCandidateUser;
|
||||
|
||||
// ---- Constants ----
|
||||
|
||||
@@ -353,6 +352,7 @@ const ClassDetailPage: React.FC = () => {
|
||||
{ title: '教室', dataIndex: 'classroomName', render: (v: string | null) => v || '-' },
|
||||
{ title: '星期', dataIndex: 'weekDay', render: (v: number) => WEEK_DAY_MAP[v] || v },
|
||||
{ title: '时间', render: (_: unknown, r: ClassScheduleItem) => `${r.startTime} - ${r.endTime}` },
|
||||
{ title: '签到窗口', render: (_: unknown, r: ClassScheduleItem) => `课前 ${r.attendanceAdvanceMinutes ?? 30} 分钟至下课` },
|
||||
{ title: '日期范围', render: (_: unknown, r: ClassScheduleItem) => `${r.startDate} ~ ${r.endDate}` },
|
||||
{ title: '科目', dataIndex: 'subject' },
|
||||
{ title: '类型', dataIndex: 'scheduleType', render: (v: string) => SCHEDULE_TYPE_MAP[v] || v },
|
||||
@@ -593,16 +593,13 @@ const ClassDetailPage: React.FC = () => {
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
placeholder="选择教师"
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="搜索姓名、用户名、角色或学科"
|
||||
value={teacherUserId}
|
||||
onChange={setTeacherUserId}
|
||||
options={allUsers.map((u) => ({
|
||||
value: u.id,
|
||||
label: u.username,
|
||||
}))}
|
||||
filterOption={(input, option) =>
|
||||
(option?.label as string)?.toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
options={buildTeacherCandidateOptions(allUsers)}
|
||||
notFoundContent="没有可分配的工作人员账号"
|
||||
/>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
|
||||
@@ -154,16 +154,6 @@ const ClassesPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/classes/${id}`);
|
||||
message.success('已删除');
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<ClassItem> = useMemo(() => [
|
||||
{
|
||||
title: '班级名称', dataIndex: 'name', width: 120,
|
||||
@@ -208,11 +198,6 @@ const ClassesPage: React.FC = () => {
|
||||
<PermissionButton permission="class:edit" size="small">归档</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
<Popconfirm title="确认删除?" onConfirm={() => handleDelete(r.id)}>
|
||||
<PermissionButton permission="class:delete" size="small" danger>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -220,7 +205,7 @@ const ClassesPage: React.FC = () => {
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Space style={{ marginBottom: 16 }} wrap>
|
||||
<Space style={{ marginBottom: 16 }} wrap className="responsive-toolbar responsive-toolbar--single">
|
||||
<Input
|
||||
placeholder="搜索名称/编码"
|
||||
prefix={<SearchOutlined />}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildTeacherCandidateLabel,
|
||||
buildTeacherCandidateOptions,
|
||||
isTeacherCandidate,
|
||||
type TeacherCandidateUser,
|
||||
} from './teacher-candidate';
|
||||
|
||||
const baseUser = (overrides: Partial<TeacherCandidateUser> = {}): TeacherCandidateUser => ({
|
||||
id: 1,
|
||||
username: 'teacher',
|
||||
name: '测试老师',
|
||||
isActive: true,
|
||||
isArchived: false,
|
||||
studentStatus: null,
|
||||
roles: [{ code: 'teacher', name: '任课老师' }],
|
||||
profile: { subjects: ['数学', '物理'] },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('class teacher candidates', () => {
|
||||
it('keeps non-teacher staff roles because class duty is selected separately', () => {
|
||||
expect(
|
||||
isTeacherCandidate(baseUser({ roles: [{ code: 'academic', name: '教务管理员' }] })),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps staff-linked accounts so they can serve as head or life teachers', () => {
|
||||
expect(isTeacherCandidate(baseUser({ studentStatus: 'staff' }))).toBe(true);
|
||||
});
|
||||
|
||||
it('excludes active students, disabled, archived, and super-admin accounts', () => {
|
||||
const users = [
|
||||
baseUser({ id: 1, studentStatus: 'active' }),
|
||||
baseUser({ id: 2, isActive: false }),
|
||||
baseUser({ id: 3, isArchived: true }),
|
||||
baseUser({
|
||||
id: 4,
|
||||
roles: [{ code: 'super_admin', name: '超级管理员' }],
|
||||
}),
|
||||
];
|
||||
|
||||
expect(buildTeacherCandidateOptions(users)).toEqual([]);
|
||||
});
|
||||
|
||||
it('shows real name, username, system role, and teaching subjects', () => {
|
||||
expect(buildTeacherCandidateLabel(baseUser())).toBe(
|
||||
'测试老师(teacher) · 任课老师 · 数学/物理',
|
||||
);
|
||||
});
|
||||
});
|
||||
44
apps/admin/src/pages/Classes/teacher-candidate.ts
Normal file
44
apps/admin/src/pages/Classes/teacher-candidate.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
export interface TeacherCandidateRole {
|
||||
code?: string | null;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface TeacherCandidateUser {
|
||||
id: number;
|
||||
username: string;
|
||||
name?: string | null;
|
||||
isActive: boolean;
|
||||
isArchived: boolean;
|
||||
studentStatus?: string | null;
|
||||
roles?: TeacherCandidateRole[];
|
||||
profile?: { subjects?: string[] } | null;
|
||||
}
|
||||
|
||||
const isSuperAdminRole = (role: TeacherCandidateRole) =>
|
||||
role.code === 'super_admin' || role.name === '超级管理员' || role.name === '超管';
|
||||
|
||||
export const isTeacherCandidate = (user: TeacherCandidateUser) => {
|
||||
if (!user.isActive || user.isArchived) return false;
|
||||
if (user.studentStatus && user.studentStatus !== 'staff') return false;
|
||||
return !(user.roles || []).some(isSuperAdminRole);
|
||||
};
|
||||
|
||||
export const buildTeacherCandidateLabel = (user: TeacherCandidateUser) => {
|
||||
const displayName = user.name?.trim();
|
||||
const identity =
|
||||
displayName && displayName !== user.username
|
||||
? `${displayName}(${user.username})`
|
||||
: user.username;
|
||||
const roleNames = [...new Set((user.roles || []).map((role) => role.name).filter(Boolean))];
|
||||
const subjects = [
|
||||
...new Set((user.profile?.subjects || []).map((subject) => subject.trim()).filter(Boolean)),
|
||||
];
|
||||
|
||||
return [identity, roleNames.join('/'), subjects.join('/')].filter(Boolean).join(' · ');
|
||||
};
|
||||
|
||||
export const buildTeacherCandidateOptions = (users: TeacherCandidateUser[]) =>
|
||||
users.filter(isTeacherCandidate).map((user) => ({
|
||||
value: user.id,
|
||||
label: buildTeacherCandidateLabel(user),
|
||||
}));
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildDepositStudentOption } from './deposit-student-option';
|
||||
import { buildDepositStudentOption, buildDepositStudentOptions } from './deposit-student-option';
|
||||
|
||||
describe('deposit student option', () => {
|
||||
it('uses the student number as the non-sensitive identifier', () => {
|
||||
@@ -17,4 +17,13 @@ describe('deposit student option', () => {
|
||||
label: '张三 (#23)',
|
||||
});
|
||||
});
|
||||
|
||||
it('uses lookup rows without requiring a status field', () => {
|
||||
expect(buildDepositStudentOptions([{ id: 23, name: '张三', studentNo: 'S2026001' }])).toEqual([
|
||||
{
|
||||
value: 23,
|
||||
label: '张三 (S2026001)',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,3 +8,6 @@ export const buildDepositStudentOption = (student: DepositStudentLookup) => ({
|
||||
value: student.id,
|
||||
label: `${student.name} (${student.studentNo || `#${student.id}`})`,
|
||||
});
|
||||
|
||||
export const buildDepositStudentOptions = (students: DepositStudentLookup[]) =>
|
||||
students.map(buildDepositStudentOption);
|
||||
|
||||
@@ -19,13 +19,12 @@ import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
import { buildDepositStudentOption } from './deposit-student-option';
|
||||
import { buildDepositStudentOptions } from './deposit-student-option';
|
||||
|
||||
const statusMap: Record<string, { text: string; color: string }> = {
|
||||
paid: { text: '已缴', color: 'green' },
|
||||
paid: { text: '有余额', color: 'green' },
|
||||
refunded: { text: '已全退', color: 'blue' },
|
||||
partial_refund: { text: '部分退还', color: 'orange' },
|
||||
deducted: { text: '已全扣', color: 'red' },
|
||||
depleted: { text: '已扣完', color: 'red' },
|
||||
};
|
||||
|
||||
const installmentStatusMap: Record<string, { text: string; color: string }> = {
|
||||
@@ -86,10 +85,7 @@ const DepositsPage: React.FC = () => {
|
||||
}, [data, searchText, filterStatus]);
|
||||
|
||||
const studentOptions = useMemo(
|
||||
() =>
|
||||
students
|
||||
.filter((s: any) => s.status === 'active')
|
||||
.map(buildDepositStudentOption),
|
||||
() => buildDepositStudentOptions(students),
|
||||
[students],
|
||||
);
|
||||
|
||||
@@ -103,7 +99,7 @@ const DepositsPage: React.FC = () => {
|
||||
paidDate: values.paidDate.format('YYYY-MM-DD'),
|
||||
notes: values.notes,
|
||||
});
|
||||
message.success('押金记录已创建');
|
||||
message.success('押金金额已增加');
|
||||
setCreateModal(false);
|
||||
createForm.resetFields();
|
||||
fetchData();
|
||||
@@ -122,8 +118,6 @@ const DepositsPage: React.FC = () => {
|
||||
const values = await refundForm.validateFields();
|
||||
await api.put(`/deposits/${refundModal.id}/refund`, {
|
||||
refundDate: values.refundDate.format('YYYY-MM-DD'),
|
||||
deductionAmount: values.deductionAmount || 0,
|
||||
deductionReason: values.deductionReason,
|
||||
notes: values.notes,
|
||||
});
|
||||
message.success('退还操作完成');
|
||||
@@ -183,24 +177,13 @@ const DepositsPage: React.FC = () => {
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
|
||||
{ title: '押金金额', dataIndex: 'amount', width: 110, render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '缴纳日期', dataIndex: 'paidDate', width: 110 },
|
||||
{ title: '当前可用押金', dataIndex: 'amount', width: 130, render: (v: number) => `¥${Number(v).toFixed(2)}` },
|
||||
{ title: '最近收取日期', dataIndex: 'paidDate', width: 120 },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (s: string) => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '退还金额',
|
||||
dataIndex: 'refundAmount',
|
||||
render: (v: any) => (v != null ? `¥${Number(v).toFixed(2)}` : '-'),
|
||||
},
|
||||
{
|
||||
title: '扣除金额',
|
||||
dataIndex: 'deductionAmount',
|
||||
render: (v: any) => (v > 0 ? `¥${Number(v).toFixed(2)}` : '-'),
|
||||
},
|
||||
{ title: '扣除原因', dataIndex: 'deductionReason', width: 120, render: (v: any) => v || '-' },
|
||||
{ title: '退还日期', dataIndex: 'refundDate', width: 110, render: (v: any) => v || '-' },
|
||||
{ title: '备注', dataIndex: 'notes', width: 120, render: (v: any) => v || '-' },
|
||||
{
|
||||
@@ -225,7 +208,7 @@ const DepositsPage: React.FC = () => {
|
||||
type="primary"
|
||||
onClick={() => {
|
||||
setRefundModal(record);
|
||||
refundForm.setFieldsValue({ refundDate: dayjs(), deductionAmount: 0 });
|
||||
refundForm.setFieldsValue({ refundDate: dayjs() });
|
||||
}}
|
||||
>
|
||||
退还
|
||||
@@ -288,10 +271,9 @@ const DepositsPage: React.FC = () => {
|
||||
value={filterStatus}
|
||||
onChange={(v) => setFilterStatus(v)}
|
||||
options={[
|
||||
{ value: 'paid', label: '已缴' },
|
||||
{ value: 'paid', label: '有余额' },
|
||||
{ value: 'refunded', label: '已全退' },
|
||||
{ value: 'partial_refund', label: '部分退还' },
|
||||
{ value: 'deducted', label: '已全扣' },
|
||||
{ value: 'depleted', label: '已扣完' },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
@@ -345,11 +327,11 @@ const DepositsPage: React.FC = () => {
|
||||
options={studentOptions}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="amount" label="押金金额(元)" rules={[{ required: true }]}>
|
||||
<Form.Item name="amount" label="本次收取金额(元)" rules={[{ required: true }]}>
|
||||
<InputNumber min={0} precision={2} style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="paidDate" label="缴纳日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择缴纳日期" format="YYYY-MM-DD" />
|
||||
<Form.Item name="paidDate" label="收取日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择收取日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
@@ -368,22 +350,11 @@ const DepositsPage: React.FC = () => {
|
||||
>
|
||||
<Form form={refundForm} layout="vertical">
|
||||
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
||||
押金金额: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
||||
当前可用押金: <strong>¥{Number(refundModal?.amount || 0).toFixed(2)}</strong>
|
||||
</div>
|
||||
<Form.Item name="refundDate" label="退还日期" rules={[{ required: true }]}>
|
||||
<DatePicker style={{ width: '100%' }} placeholder="选择退还日期" format="YYYY-MM-DD" />
|
||||
</Form.Item>
|
||||
<Form.Item name="deductionAmount" label="扣除金额(元)" extra="如无扣除填0">
|
||||
<InputNumber
|
||||
min={0}
|
||||
max={Number(refundModal?.amount || 500)}
|
||||
precision={2}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="deductionReason" label="扣除原因">
|
||||
<Input placeholder="如:房间损坏赔偿" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
@@ -401,8 +372,8 @@ const DepositsPage: React.FC = () => {
|
||||
{detailModal && (
|
||||
<div>
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<p><strong>押金金额:</strong> ¥{Number(detailModal.amount).toFixed(2)}</p>
|
||||
<p><strong>缴纳日期:</strong> {detailModal.paidDate}</p>
|
||||
<p><strong>当前可用押金:</strong> ¥{Number(detailModal.amount).toFixed(2)}</p>
|
||||
<p><strong>最近收取日期:</strong> {detailModal.paidDate}</p>
|
||||
<p>
|
||||
<strong>状态:</strong>{' '}
|
||||
<Tag color={statusMap[detailModal.status]?.color}>
|
||||
|
||||
@@ -46,10 +46,12 @@ const ExpensesPage: React.FC = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [roomModal, setRoomModal] = useState(false);
|
||||
const [personalModal, setPersonalModal] = useState(false);
|
||||
const [utilityModal, setUtilityModal] = useState(false);
|
||||
const [editingRoom, setEditingRoom] = useState<any>(null);
|
||||
const [editingPersonal, setEditingPersonal] = useState<any>(null);
|
||||
const [roomForm] = Form.useForm();
|
||||
const [personalForm] = Form.useForm();
|
||||
const [utilityForm] = Form.useForm();
|
||||
const [roomSearch, setRoomSearch] = useState('');
|
||||
const [roomTypeFilter, setRoomTypeFilter] = useState<string | undefined>(undefined);
|
||||
const [personalSearch, setPersonalSearch] = useState('');
|
||||
@@ -192,6 +194,27 @@ const ExpensesPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleStudentUtility = async () => {
|
||||
const values = await utilityForm.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
const result: any = await api.post('/expenses/student-utility', {
|
||||
studentId: values.studentId,
|
||||
expenseType: values.expenseType,
|
||||
amount: values.amount,
|
||||
periodStart: values.period[0].format('YYYY-MM-DD'),
|
||||
periodEnd: values.period[1].format('YYYY-MM-DD'),
|
||||
description: values.description,
|
||||
});
|
||||
const bill = result.bill;
|
||||
message.success(`账单已生成,已从余额扣除 ¥${Number(bill.paidAmount || 0).toFixed(2)},待补缴 ¥${Number(bill.outstandingAmount || 0).toFixed(2)}`);
|
||||
setUtilityModal(false);
|
||||
utilityForm.resetFields();
|
||||
fetchData();
|
||||
} catch (e: any) { message.error(e?.message || '水电费出账失败'); }
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
|
||||
const handlePersonalExpense = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
@@ -560,6 +583,13 @@ const ExpensesPage: React.FC = () => {
|
||||
批量删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
<PermissionButton
|
||||
permission="expense:create"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => { utilityForm.resetFields(); setUtilityModal(true); }}
|
||||
>
|
||||
添加学生水电费
|
||||
</PermissionButton>
|
||||
<PermissionButton
|
||||
permission="expense:create"
|
||||
type="primary"
|
||||
@@ -639,6 +669,19 @@ const ExpensesPage: React.FC = () => {
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
|
||||
<Modal title="添加学生水电费并立即出账" open={utilityModal} onOk={handleStudentUtility} onCancel={() => setUtilityModal(false)} okText="生成账单并扣余额" confirmLoading={saving}>
|
||||
<Form form={utilityForm} layout="vertical">
|
||||
<Form.Item name="studentId" label="学生" rules={[{ required: true }]}>
|
||||
<Select showSearch optionFilterProp="label" options={students.map((student: any) => ({ value: student.id, label: `${student.name} (${student.studentNo || `#${student.id}`})` }))} />
|
||||
</Form.Item>
|
||||
<Form.Item name="expenseType" label="费用类型" rules={[{ required: true }]}><Select options={[{ value: 'water', label: '水费' }, { value: 'electricity', label: '电费' }]} /></Form.Item>
|
||||
<Form.Item name="amount" label="金额(元)" rules={[{ required: true }]}><InputNumber min={0.01} precision={2} style={{ width: '100%' }} /></Form.Item>
|
||||
<Form.Item name="period" label="账单周期" rules={[{ required: true }]}><RangePicker style={{ width: '100%' }} format="YYYY-MM-DD" /></Form.Item>
|
||||
<Form.Item name="description" label="说明"><Input.TextArea rows={2} maxLength={300} /></Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title={editingPersonal ? '编辑个人费用' : '录入个人附加费'}
|
||||
open={personalModal}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState, useMemo, useCallback } from 'react';
|
||||
import {
|
||||
Card, Form, Input, Button, Space, Spin, Alert, Descriptions, Tag, Divider,
|
||||
Drawer, Tree, Select, TreeSelect, Modal, DatePicker, InputNumber,
|
||||
Drawer, Tree, Select, TreeSelect, Modal, DatePicker,
|
||||
Row, Col, List,
|
||||
} from 'antd';
|
||||
import {
|
||||
@@ -59,7 +59,6 @@ interface ClassItem {
|
||||
classType?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
maxStudents?: number;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
@@ -477,9 +476,6 @@ const IntegrationConfigPage: React.FC = () => {
|
||||
<Form.Item name="endDate" label="结束日期">
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="maxStudents" label="最大人数">
|
||||
<InputNumber min={0} style={{ width: '100%' }} placeholder="0=不限制" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { List, Typography, Menu, Layout, Button, Empty, Spin, Space } from 'antd';
|
||||
import { List, Typography, Menu, Layout, Button, Empty, Spin, Space, Grid, Select } from 'antd';
|
||||
import {
|
||||
BellOutlined,
|
||||
DollarOutlined,
|
||||
@@ -13,6 +13,7 @@ import { message } from '../../ui/app-message';
|
||||
import { formatNotificationText } from '../../utils/notification-display';
|
||||
|
||||
const { Sider, Content } = Layout;
|
||||
const { useBreakpoint } = Grid;
|
||||
|
||||
interface NotificationItem {
|
||||
id: number;
|
||||
@@ -49,6 +50,8 @@ function timeAgo(dateStr: string): string {
|
||||
}
|
||||
|
||||
const NotificationsPage: React.FC = () => {
|
||||
const screens = useBreakpoint();
|
||||
const isMobile = !screens.sm;
|
||||
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
|
||||
const [filter, setFilter] = useState('all');
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -101,27 +104,39 @@ const NotificationsPage: React.FC = () => {
|
||||
? notifications
|
||||
: notifications.filter((n) => n.type === filter);
|
||||
|
||||
const filterItems = [
|
||||
{ key: 'all', icon: <BellOutlined />, label: '全部' },
|
||||
{ key: 'bill_generated', icon: <DollarOutlined />, label: '账单' },
|
||||
{ key: 'check_in', icon: <HomeOutlined />, label: '入住' },
|
||||
{ key: 'class_change', icon: <TeamOutlined />, label: '班级' },
|
||||
{ key: 'announcement', icon: <SettingOutlined />, label: '公告' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100%', background: '#fff' }}>
|
||||
<Sider width={180} style={{ background: '#fff', borderRight: '1px solid #f0f0f0' }}>
|
||||
<Menu
|
||||
mode="inline"
|
||||
selectedKeys={[filter]}
|
||||
onClick={({ key }) => setFilter(key)}
|
||||
items={[
|
||||
{ key: 'all', icon: <BellOutlined />, label: '全部' },
|
||||
{ key: 'bill_generated', icon: <DollarOutlined />, label: '账单' },
|
||||
{ key: 'check_in', icon: <HomeOutlined />, label: '入住' },
|
||||
{ key: 'class_change', icon: <TeamOutlined />, label: '班级' },
|
||||
{ key: 'announcement', icon: <SettingOutlined />, label: '公告' },
|
||||
]}
|
||||
/>
|
||||
</Sider>
|
||||
<Content style={{ padding: 24 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
<Layout className="notifications-layout" style={{ minHeight: '100%', background: '#fff' }}>
|
||||
{!isMobile && (
|
||||
<Sider width={180} style={{ background: '#fff', borderRight: '1px solid #f0f0f0' }}>
|
||||
<Menu
|
||||
mode="inline"
|
||||
selectedKeys={[filter]}
|
||||
onClick={({ key }) => setFilter(key)}
|
||||
items={filterItems}
|
||||
/>
|
||||
</Sider>
|
||||
)}
|
||||
<Content className="notifications-content" style={{ padding: isMobile ? 0 : 24 }}>
|
||||
<div className="notifications-header">
|
||||
<Typography.Title level={4} style={{ margin: 0 }}>通知中心</Typography.Title>
|
||||
<Button onClick={handleMarkAll}>全部已读</Button>
|
||||
</div>
|
||||
{isMobile && (
|
||||
<Select
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
options={filterItems.map((item) => ({ value: item.key, label: item.label }))}
|
||||
className="notifications-filter"
|
||||
/>
|
||||
)}
|
||||
<Spin spinning={loading}>
|
||||
{filtered.length === 0 ? (
|
||||
<Empty description="暂无通知" />
|
||||
@@ -165,7 +180,7 @@ const NotificationsPage: React.FC = () => {
|
||||
</div>
|
||||
}
|
||||
title={
|
||||
<Space>
|
||||
<Space wrap size={[8, 2]}>
|
||||
<Typography.Text
|
||||
strong={!item.isRead}
|
||||
style={{ fontSize: 15 }}
|
||||
|
||||
@@ -40,7 +40,6 @@ const OccupanciesPage: React.FC = () => {
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
const [students, setStudents] = useState<any[]>([]);
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
const [organizations, setOrganizations] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checkInModal, setCheckInModal] = useState(false);
|
||||
const [checkOutModal, setCheckOutModal] = useState<any>(null);
|
||||
@@ -66,14 +65,13 @@ const OccupanciesPage: React.FC = () => {
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [occRes, stuRes, rmRes, tnRes] = (await Promise.allSettled([
|
||||
const [occRes, stuRes, rmRes] = (await Promise.allSettled([
|
||||
api.get('/occupancies', { params: { active: showActive ? 'true' : undefined, dateFrom: dateRange?.[0]?.format('YYYY-MM-DD'), dateTo: dateRange?.[1]?.format('YYYY-MM-DD') } }),
|
||||
api.get('/students/basic-lookups'),
|
||||
api.get('/rooms/overview'),
|
||||
api.get('/organizations'),
|
||||
])) as PromiseSettledResult<any>[];
|
||||
const labels = ['入住数据', '学生列表', '房间列表', '机构列表'];
|
||||
[occRes, stuRes, rmRes, tnRes].forEach((res, i) => {
|
||||
const labels = ['入住数据', '学生列表', '房间列表'];
|
||||
[occRes, stuRes, rmRes].forEach((res, i) => {
|
||||
if (res.status === 'rejected') {
|
||||
message.warning(`${labels[i]}加载失败`);
|
||||
}
|
||||
@@ -81,7 +79,6 @@ const OccupanciesPage: React.FC = () => {
|
||||
setData(occRes.status === 'fulfilled' ? occRes.value : []);
|
||||
setStudents(stuRes.status === 'fulfilled' ? stuRes.value : []);
|
||||
setRooms(rmRes.status === 'fulfilled' ? rmRes.value : []);
|
||||
setOrganizations(tnRes.status === 'fulfilled' ? tnRes.value : []);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
message.error('数据加载异常');
|
||||
@@ -157,7 +154,8 @@ const OccupanciesPage: React.FC = () => {
|
||||
checkInDate: values.checkInDate.format('YYYY-MM-DD'),
|
||||
billingStartDate: values.billingStartDate?.format('YYYY-MM-DD'),
|
||||
stayType: values.stayType,
|
||||
responsibleOrganizationId: values.responsibleOrganizationId,
|
||||
collectDeposit: values.collectDeposit,
|
||||
depositAmount: values.collectDeposit ? values.depositAmount : undefined,
|
||||
notes: values.notes,
|
||||
bedId: values.bedId,
|
||||
lockerId: values.lockerId || undefined,
|
||||
@@ -330,22 +328,14 @@ const OccupanciesPage: React.FC = () => {
|
||||
<div>
|
||||
<Alert
|
||||
title="一站式导入"
|
||||
description="导入入住名单时会自动创建学生和宿舍,无需单独在「学生管理」或「宿舍管理」中手动添加。后续仅需在此页面处理换房/退宿等日常操作即可。"
|
||||
description="导入入住名单时会优先按手机号关联已有学生,所属机构自动取学生档案;未找到学生或宿舍时会自动创建。后续仅需在此页面处理换房/退宿等日常操作即可。"
|
||||
type="info"
|
||||
showIcon
|
||||
closable
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Button type={showActive ? 'primary' : 'default'} onClick={() => setShowActive(true)}>
|
||||
在住记录
|
||||
</Button>
|
||||
@@ -360,14 +350,14 @@ const OccupanciesPage: React.FC = () => {
|
||||
/>
|
||||
<RangePicker value={dateRange} onChange={(dates) => { setDateRange(dates ? [dates[0], dates[1]] : null); }} placeholder={['入住开始', '入住结束']} style={{ width: 240 }} />
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<PermissionButton
|
||||
permission="occupancy:checkin"
|
||||
type="primary"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={() => {
|
||||
checkInForm.resetFields();
|
||||
checkInForm.setFieldsValue({ checkInDate: dayjs() });
|
||||
checkInForm.setFieldsValue({ checkInDate: dayjs(), collectDeposit: true, depositAmount: 500 });
|
||||
setCheckInModal(true);
|
||||
}}
|
||||
>
|
||||
@@ -407,7 +397,7 @@ const OccupanciesPage: React.FC = () => {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Tooltip title="导入时自动创建学生、宿舍和入住记录">
|
||||
<Tooltip title="按手机号关联学生,并自动创建缺失的学生、宿舍和入住记录">
|
||||
<Button type="primary" ghost icon={<UploadOutlined />}>
|
||||
导入入住名单
|
||||
</Button>
|
||||
@@ -598,18 +588,6 @@ const OccupanciesPage: React.FC = () => {
|
||||
placeholder="默认为短租"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="responsibleOrganizationId" label="负责机构">
|
||||
<Select
|
||||
showSearch
|
||||
allowClear
|
||||
optionFilterProp="label"
|
||||
placeholder="默认取学生所属机构"
|
||||
options={organizations.map((t: { id: number; name: string }) => ({
|
||||
value: t.id,
|
||||
label: t.name,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="bedId"
|
||||
label="床位"
|
||||
@@ -630,7 +608,10 @@ const OccupanciesPage: React.FC = () => {
|
||||
空闲 {availableBeds.length} 张床位
|
||||
</div>
|
||||
)}
|
||||
<Form.Item name="lockerId" label="柜子(可选)">
|
||||
<Form.Item
|
||||
name="lockerId"
|
||||
label="柜子(可选)"
|
||||
>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="可选分配柜子"
|
||||
@@ -641,6 +622,32 @@ const OccupanciesPage: React.FC = () => {
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="collectDeposit"
|
||||
label="押金缴纳"
|
||||
valuePropName="checked"
|
||||
extra="开启后,确认入住时同步生成已缴押金记录;已有已缴押金时不会重复创建"
|
||||
>
|
||||
<Switch checkedChildren="已缴" unCheckedChildren="不缴" />
|
||||
</Form.Item>
|
||||
<Form.Item noStyle shouldUpdate={(prev, current) => prev.collectDeposit !== current.collectDeposit}>
|
||||
{({ getFieldValue }) =>
|
||||
getFieldValue('collectDeposit') ? (
|
||||
<Form.Item
|
||||
name="depositAmount"
|
||||
label="押金金额"
|
||||
rules={[{ required: true, message: '请输入押金金额' }]}
|
||||
>
|
||||
<InputNumber
|
||||
min={0.01}
|
||||
precision={2}
|
||||
addonAfter="元"
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
) : null
|
||||
}
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label="备注">
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { Alert, Empty, Form, Input, Modal, Popconfirm, Select, Space, Table, Tag } from 'antd';
|
||||
import { BankOutlined, InboxOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
import { BankOutlined, InboxOutlined, PlusOutlined, UndoOutlined } from '@ant-design/icons';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
@@ -148,35 +148,61 @@ const OrganizationsPage: React.FC = () => {
|
||||
width: 160,
|
||||
render: (_: unknown, record: OrganizationItem) => (
|
||||
<Space>
|
||||
<PermissionButton
|
||||
permission="organization:edit"
|
||||
size="small"
|
||||
onClick={() => openEditor(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{!record.isHost && record.status === 'active' ? (
|
||||
{record.status === 'archived' ? (
|
||||
<Popconfirm
|
||||
title="归档后仍保留历史学生、入住和租赁记录"
|
||||
title="确定恢复此机构?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/organizations/${record.id}`);
|
||||
message.success('机构已归档');
|
||||
await api.put(`/organizations/${record.id}`, { status: 'active' });
|
||||
message.success('机构已恢复');
|
||||
await fetchData();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '归档失败');
|
||||
message.error(error?.message || '恢复失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="organization:delete"
|
||||
permission="organization:edit"
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
type="link"
|
||||
icon={<UndoOutlined />}
|
||||
>
|
||||
归档
|
||||
恢复
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
) : (
|
||||
<>
|
||||
<PermissionButton
|
||||
permission="organization:edit"
|
||||
size="small"
|
||||
onClick={() => openEditor(record)}
|
||||
>
|
||||
编辑
|
||||
</PermissionButton>
|
||||
{!record.isHost ? (
|
||||
<Popconfirm
|
||||
title="归档后仍保留历史学生、入住和租赁记录"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await api.delete(`/organizations/${record.id}`);
|
||||
message.success('机构已归档');
|
||||
await fetchData();
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '归档失败');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PermissionButton
|
||||
permission="organization:delete"
|
||||
size="small"
|
||||
icon={<InboxOutlined />}
|
||||
>
|
||||
归档
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -88,6 +88,7 @@ const RoomsPage: React.FC = () => {
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const [filterBuilding, setFilterBuilding] = useState<string | undefined>(undefined);
|
||||
const [filterStatus, setFilterStatus] = useState<string | undefined>(undefined);
|
||||
const [filterRentalCategory, setFilterRentalCategory] = useState<string | undefined>(undefined);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
@@ -154,8 +155,11 @@ const RoomsPage: React.FC = () => {
|
||||
}
|
||||
if (filterBuilding) result = result.filter((r: Record<string, unknown>) => r.building === filterBuilding);
|
||||
if (filterStatus) result = result.filter((r: Record<string, unknown>) => r.status === filterStatus);
|
||||
if (filterRentalCategory) {
|
||||
result = result.filter((r: Record<string, unknown>) => r.rentalCategory === filterRentalCategory);
|
||||
}
|
||||
return result;
|
||||
}, [data, searchText, filterBuilding, filterStatus]);
|
||||
}, [data, searchText, filterBuilding, filterStatus, filterRentalCategory]);
|
||||
const remainingBedSlots = useMemo(() => {
|
||||
const capacity = Number(drawerRoom?.capacity) || 0;
|
||||
return Math.max(capacity - beds.length, 0);
|
||||
@@ -407,16 +411,8 @@ const RoomsPage: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<h3 style={{ margin: 0 }}>宿舍管理</h3>
|
||||
<Input.Search
|
||||
placeholder="搜索房间号"
|
||||
@@ -434,6 +430,17 @@ const RoomsPage: React.FC = () => {
|
||||
/>
|
||||
<Select placeholder="状态" allowClear style={{ width: 110 }} value={filterStatus} onChange={setFilterStatus}
|
||||
options={[{value:'available',label:'可入住'},{value:'full',label:'已满'},{value:'maintenance',label:'维护中'}]} />
|
||||
<Select
|
||||
placeholder="租赁类型"
|
||||
allowClear
|
||||
style={{ width: 120 }}
|
||||
value={filterRentalCategory}
|
||||
onChange={setFilterRentalCategory}
|
||||
options={[
|
||||
{ value: 'long', label: '长租' },
|
||||
{ value: 'short', label: '短租' },
|
||||
]}
|
||||
/>
|
||||
<Button
|
||||
type={showArchived ? 'primary' : 'default'}
|
||||
onClick={() => setShowArchived(!showArchived)}
|
||||
@@ -443,7 +450,7 @@ const RoomsPage: React.FC = () => {
|
||||
: `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 间宿舍?(有在住人员的会跳过)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
Modal,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
DatePicker,
|
||||
TimePicker,
|
||||
Popconfirm,
|
||||
@@ -53,6 +54,7 @@ interface ClassScheduleItem {
|
||||
weekDay: number;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
attendanceAdvanceMinutes: number;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
subject: string;
|
||||
@@ -351,7 +353,7 @@ const SchedulesPage: React.FC = () => {
|
||||
setEditingSchedule(null);
|
||||
setModalMode('create');
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ classroomId, weekDay });
|
||||
form.setFieldsValue({ classroomId, weekDay, attendanceAdvanceMinutes: 30 });
|
||||
setModalOpen(true);
|
||||
}
|
||||
};
|
||||
@@ -960,9 +962,28 @@ const SchedulesPage: React.FC = () => {
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="attendanceAdvanceMinutes"
|
||||
label="课前签到时间"
|
||||
tooltip="从上课前指定分钟开始,到下课时间结束;期间任意上班或下班打卡都计为出勤"
|
||||
initialValue={30}
|
||||
rules={[{ required: true, message: '请设置课前签到时间' }]}
|
||||
>
|
||||
<InputNumber
|
||||
min={0}
|
||||
max={1440}
|
||||
step={5}
|
||||
addonAfter="分钟"
|
||||
style={{ width: '100%' }}
|
||||
placeholder="例如 30"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
name="timeRange"
|
||||
label="上课时段"
|
||||
tooltip="同一教室的前后两节排课必须至少间隔10分钟"
|
||||
extra="系统按10分钟选择时间,并为相邻排课强制预留至少10分钟。"
|
||||
rules={[{ required: true, message: '请选择时段' }]}
|
||||
>
|
||||
<TimePicker.RangePicker
|
||||
@@ -1008,6 +1029,7 @@ const SchedulesPage: React.FC = () => {
|
||||
weekDay:
|
||||
selectedCell?.weekDay ?? (selectedDate ? selectedDate.day() || 7 : undefined),
|
||||
dateRange: selectedDate ? [selectedDate, selectedDate] : undefined,
|
||||
attendanceAdvanceMinutes: 30,
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -1054,6 +1076,12 @@ const SchedulesPage: React.FC = () => {
|
||||
<strong>时段:</strong>
|
||||
{s.startTime} ~ {s.endTime}
|
||||
</div>
|
||||
{!isMaskedSchedule(s) && (
|
||||
<div>
|
||||
<strong>签到窗口:</strong>
|
||||
课前 {s.attendanceAdvanceMinutes ?? 30} 分钟至下课
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<strong>日期:</strong>
|
||||
{s.startDate} ~ {s.endDate}
|
||||
|
||||
@@ -16,11 +16,13 @@ describe('schedule edit form mapping', () => {
|
||||
startDate: '2026-07-01',
|
||||
endDate: '2026-07-31',
|
||||
notes: '需要投影设备',
|
||||
attendanceAdvanceMinutes: 45,
|
||||
});
|
||||
|
||||
expect(values.classroomId).toBe(1);
|
||||
expect(values.weekDay).toBe(5);
|
||||
expect(values.notes).toBe('需要投影设备');
|
||||
expect(values.attendanceAdvanceMinutes).toBe(45);
|
||||
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',
|
||||
@@ -39,6 +41,7 @@ describe('schedule edit form mapping', () => {
|
||||
timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
|
||||
dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
|
||||
notes: ' 临时调整教室 ',
|
||||
attendanceAdvanceMinutes: 20,
|
||||
}),
|
||||
).toEqual({
|
||||
classId: 1,
|
||||
@@ -51,6 +54,7 @@ describe('schedule edit form mapping', () => {
|
||||
startDate: '2026-08-01',
|
||||
endDate: '2026-08-31',
|
||||
notes: '临时调整教室',
|
||||
attendanceAdvanceMinutes: 20,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -67,6 +71,7 @@ describe('schedule notes normalization', () => {
|
||||
timeRange: [dayjs('2026-01-01 13:30'), dayjs('2026-01-01 17:20')],
|
||||
dateRange: [dayjs('2026-08-01'), dayjs('2026-08-31')],
|
||||
notes: ' ',
|
||||
attendanceAdvanceMinutes: 30,
|
||||
}).notes,
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ export interface ScheduleFormValues {
|
||||
subject: string;
|
||||
teacherId?: number;
|
||||
notes?: string;
|
||||
attendanceAdvanceMinutes: number;
|
||||
timeRange: [Dayjs, Dayjs];
|
||||
dateRange: [Dayjs, Dayjs];
|
||||
}
|
||||
@@ -19,6 +20,7 @@ export interface EditableSchedule {
|
||||
subject: string;
|
||||
teacherId: number | null;
|
||||
notes?: string | null;
|
||||
attendanceAdvanceMinutes?: number | null;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
startDate: string;
|
||||
@@ -32,6 +34,7 @@ export const scheduleToFormValues = (schedule: EditableSchedule): ScheduleFormVa
|
||||
subject: schedule.subject,
|
||||
teacherId: schedule.teacherId ?? undefined,
|
||||
notes: schedule.notes ?? undefined,
|
||||
attendanceAdvanceMinutes: schedule.attendanceAdvanceMinutes ?? 30,
|
||||
timeRange: [dayjs(`2000-01-01 ${schedule.startTime}`), dayjs(`2000-01-01 ${schedule.endTime}`)],
|
||||
dateRange: [dayjs(schedule.startDate), dayjs(schedule.endDate)],
|
||||
});
|
||||
@@ -43,6 +46,7 @@ export const buildSchedulePayload = (values: ScheduleFormValues) => ({
|
||||
subject: values.subject,
|
||||
teacherId: values.teacherId,
|
||||
notes: values.notes?.trim() || undefined,
|
||||
attendanceAdvanceMinutes: values.attendanceAdvanceMinutes,
|
||||
startTime: values.timeRange[0].format('HH:mm'),
|
||||
endTime: values.timeRange[1].format('HH:mm'),
|
||||
startDate: values.dateRange[0].format('YYYY-MM-DD'),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
@@ -62,6 +63,19 @@ interface EnrollmentInfo {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
interface StudentCreateImportResult {
|
||||
message?: string;
|
||||
imported?: number;
|
||||
skipped?: number;
|
||||
}
|
||||
|
||||
interface StudentUpdateImportResult {
|
||||
message?: string;
|
||||
matched?: number;
|
||||
skipped?: number;
|
||||
}
|
||||
|
||||
const StudentsPage: React.FC = () => {
|
||||
const { modal } = App.useApp();
|
||||
const [data, setData] = useState<any[]>([]);
|
||||
@@ -221,20 +235,94 @@ const StudentsPage: React.FC = () => {
|
||||
.catch(() => message.error('下载失败'));
|
||||
};
|
||||
|
||||
const handleMatchImport: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
|
||||
const showCreateImportResult = (result: StudentCreateImportResult) => {
|
||||
const imported = result.imported ?? 0;
|
||||
const skipped = result.skipped ?? 0;
|
||||
|
||||
modal.success({
|
||||
title: '导入完成',
|
||||
okText: '知道了',
|
||||
content: (
|
||||
<div>
|
||||
<Descriptions column={1} size="small">
|
||||
<Descriptions.Item label="成功新增">{imported} 人</Descriptions.Item>
|
||||
<Descriptions.Item label="跳过">{skipped} 人</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<div style={{ marginTop: 12, fontWeight: 600 }}>跳过原因:</div>
|
||||
<ul style={{ marginBottom: 0, paddingLeft: 20 }}>
|
||||
<li>姓名为空</li>
|
||||
<li>已存在同名学生</li>
|
||||
</ul>
|
||||
<div style={{ marginTop: 8, color: '#8c8c8c', fontSize: 12 }}>
|
||||
当前后端只返回统计汇总,暂时无法列出具体哪几行被跳过。
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const showUpdateImportResult = (result: StudentUpdateImportResult) => {
|
||||
const matched = result.matched ?? 0;
|
||||
const skipped = result.skipped ?? 0;
|
||||
|
||||
modal.success({
|
||||
title: '更新完成',
|
||||
okText: '知道了',
|
||||
content: (
|
||||
<div>
|
||||
<Descriptions column={1} size="small">
|
||||
<Descriptions.Item label="成功更新">{matched} 人</Descriptions.Item>
|
||||
<Descriptions.Item label="未匹配">{skipped} 人</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<div style={{ marginTop: 12, fontWeight: 600 }}>匹配规则:</div>
|
||||
<div>手机号优先,身份证号其次</div>
|
||||
<div style={{ marginTop: 8, color: '#8c8c8c', fontSize: 12 }}>
|
||||
当前后端只返回统计汇总,暂时无法列出具体哪几行未匹配。
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const handleCreateStudentsImport: UploadProps['customRequest'] = async ({
|
||||
file,
|
||||
onSuccess,
|
||||
onError,
|
||||
}) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file as File);
|
||||
try {
|
||||
const res = (await api.post('/students/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})) as StudentCreateImportResult;
|
||||
showCreateImportResult(res);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '导入失败');
|
||||
onError?.(e instanceof Error ? e : new Error(err?.message || '导入失败'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateExistingStudentsImport: UploadProps['customRequest'] = async ({
|
||||
file,
|
||||
onSuccess,
|
||||
onError,
|
||||
}) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file as File);
|
||||
try {
|
||||
const res = (await api.post('/students/import-match', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})) as { message: string };
|
||||
message.success(res.message);
|
||||
})) as StudentUpdateImportResult;
|
||||
showUpdateImportResult(res);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '匹配导入失败');
|
||||
onError?.(e instanceof Error ? e : new Error(err?.message || '匹配导入失败'));
|
||||
message.error(err?.message || '更新已有学生资料失败');
|
||||
onError?.(e instanceof Error ? e : new Error(err?.message || '更新已有学生资料失败'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -277,12 +365,12 @@ const StudentsPage: React.FC = () => {
|
||||
render: (v: string, record: any) => {
|
||||
if (!v) return '-';
|
||||
return (
|
||||
<span>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px' }}
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
@@ -305,12 +393,12 @@ const StudentsPage: React.FC = () => {
|
||||
render: (v: string, record: any) => {
|
||||
if (!v) return '-';
|
||||
return (
|
||||
<span>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskIdNumber(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px' }}
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '身份证号', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
@@ -329,12 +417,12 @@ const StudentsPage: React.FC = () => {
|
||||
render: (v: string, record: any) => {
|
||||
if (!v) return '-';
|
||||
return (
|
||||
<span>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ marginRight: 4 }}>{maskPhone(v)}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
style={{ padding: '8px 4px' }}
|
||||
style={{ padding: '8px 4px', flex: 'none' }}
|
||||
onClick={() => handleViewSensitive(record.id, '紧急联系人电话', v)}
|
||||
title="点击查看完整号码"
|
||||
>
|
||||
@@ -441,16 +529,8 @@ const StudentsPage: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<div className="responsive-toolbar">
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Input.Search
|
||||
placeholder="搜索学生姓名"
|
||||
onSearch={setSearchName}
|
||||
@@ -498,7 +578,7 @@ const StudentsPage: React.FC = () => {
|
||||
: `显示已归档${archivedCount > 0 ? ` (${archivedCount})` : ''}`}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Space wrap className="responsive-toolbar__group">
|
||||
<Popconfirm
|
||||
title={`确定批量归档选中的 ${selectedRowKeys.length} 名学生?(数据保留,可恢复)`}
|
||||
onConfirm={handleBatchDelete}
|
||||
@@ -530,29 +610,15 @@ const StudentsPage: React.FC = () => {
|
||||
>
|
||||
添加学生
|
||||
</PermissionButton>
|
||||
<Upload accept=".xlsx,.xls" showUploadList={false} customRequest={handleCreateStudentsImport}>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
<Upload
|
||||
accept=".xlsx,.xls"
|
||||
showUploadList={false}
|
||||
customRequest={async ({ file, onSuccess, onError }: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
try {
|
||||
const res: any = await api.post('/students/import', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
});
|
||||
message.success(res.message);
|
||||
onSuccess?.(res);
|
||||
fetchData();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '导入失败');
|
||||
onError?.(e instanceof Error ? e : new Error(e?.message || '导入失败'));
|
||||
}
|
||||
}}
|
||||
customRequest={handleUpdateExistingStudentsImport}
|
||||
>
|
||||
<Button icon={<UploadOutlined />}>导入Excel</Button>
|
||||
</Upload>
|
||||
<Upload accept=".xlsx,.xls" showUploadList={false} customRequest={handleMatchImport}>
|
||||
<Button icon={<SwapOutlined />}>匹配导入</Button>
|
||||
<Button icon={<SwapOutlined />}>更新已有学生资料</Button>
|
||||
</Upload>
|
||||
<PermissionButton
|
||||
permission="student:view"
|
||||
@@ -570,6 +636,17 @@ const StudentsPage: React.FC = () => {
|
||||
</PermissionButton>
|
||||
</Space>
|
||||
</div>
|
||||
<Alert
|
||||
showIcon
|
||||
type="warning"
|
||||
style={{ marginBottom: 12 }}
|
||||
message={
|
||||
<span>
|
||||
<strong>更新已有学生资料:</strong>先按手机号、再按身份证号匹配;Excel
|
||||
中填写的非空字段会覆盖原资料,未匹配的学生不会新增。请确认姓名、手机号、身份证号、所属机构和联系人等内容无误。
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
|
||||
@@ -181,7 +181,7 @@ const TeachersPage: React.FC = () => {
|
||||
return (
|
||||
<div>
|
||||
<h2 style={{ marginBottom: 16 }}>教师管理</h2>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
<Space style={{ marginBottom: 16 }} wrap className="responsive-toolbar responsive-toolbar--single">
|
||||
<Input.Search
|
||||
placeholder="搜索姓名/用户名"
|
||||
allowClear
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
Tag,
|
||||
Popconfirm,
|
||||
} from 'antd';
|
||||
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined, IdcardOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
import { PlusOutlined, EditOutlined, KeyOutlined, IdcardOutlined, InboxOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
@@ -141,18 +141,6 @@ const UsersPage: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await api.delete(`/rbac/users/${id}`);
|
||||
message.success('已删除');
|
||||
fetchData();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { message?: string };
|
||||
message.error(err?.message || '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const handleResetPwd = (record: any) => {
|
||||
setResetTarget(record);
|
||||
pwdForm.resetFields();
|
||||
@@ -253,13 +241,6 @@ const UsersPage: React.FC = () => {
|
||||
<PermissionButton permission="user:edit" type="link" size="small">归档</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{record.username !== 'admin' && (
|
||||
<Popconfirm title="确认删除?需先归档" onConfirm={() => handleDelete(record.id)}>
|
||||
<PermissionButton permission="user:delete" type="link" size="small" danger icon={<DeleteOutlined />}>
|
||||
删除
|
||||
</PermissionButton>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
|
||||
102
apps/admin/src/pages/Wallets/index.tsx
Normal file
102
apps/admin/src/pages/Wallets/index.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Button, Drawer, Form, Input, InputNumber, Modal, Radio, Space, Switch, Table, Tag } from 'antd';
|
||||
import { HistoryOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import api from '../../api';
|
||||
import PermissionButton from '../../components/PermissionButton';
|
||||
import { message } from '../../ui/app-message';
|
||||
|
||||
interface WalletRow {
|
||||
studentId: number;
|
||||
studentName: string;
|
||||
studentNo?: string;
|
||||
balance: number;
|
||||
outstandingAmount: number;
|
||||
}
|
||||
|
||||
const transactionNames: Record<string, string> = {
|
||||
recharge: '充值', adjustment: '调账', bill_payment: '账单扣款', bill_refund: '账单冲正',
|
||||
};
|
||||
|
||||
const WalletsPage: React.FC = () => {
|
||||
const [rows, setRows] = useState<WalletRow[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [debtOnly, setDebtOnly] = useState(false);
|
||||
const [selected, setSelected] = useState<WalletRow | null>(null);
|
||||
const [transactions, setTransactions] = useState<any[]>([]);
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const fetchRows = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await api.get('/wallets', { params: { keyword: keyword || undefined, debtOnly } });
|
||||
setRows(data as WalletRow[]);
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '加载学生余额失败');
|
||||
} finally { setLoading(false); }
|
||||
}, [keyword, debtOnly]);
|
||||
|
||||
useEffect(() => { void fetchRows(); }, [fetchRows]);
|
||||
|
||||
const openChange = (row: WalletRow) => {
|
||||
setSelected(row);
|
||||
form.setFieldsValue({ type: 'recharge', amount: undefined, description: '' });
|
||||
};
|
||||
|
||||
const submitChange = async () => {
|
||||
if (!selected) return;
|
||||
const values = await form.validateFields();
|
||||
setSaving(true);
|
||||
try {
|
||||
const result: any = await api.post('/wallets/change-balance', { studentId: selected.studentId, ...values });
|
||||
const paid = (result.payments || []).reduce((sum: number, bill: any) => sum + Number(bill.paidAmount || 0), 0);
|
||||
message.success(paid > 0 ? `余额已更新,并自动补扣历史账单` : '余额已更新');
|
||||
setSelected(null);
|
||||
await fetchRows();
|
||||
} catch (error: any) { message.error(error?.message || '余额操作失败'); }
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
|
||||
const showTransactions = async (row: WalletRow) => {
|
||||
setSelected(row); setDrawerOpen(true);
|
||||
try { setTransactions(await api.get('/wallets/transactions', { params: { studentId: row.studentId } }) as any[]); }
|
||||
catch (error: any) { message.error(error?.message || '加载流水失败'); }
|
||||
};
|
||||
|
||||
const columns = useMemo(() => [
|
||||
{ title: '学生', render: (_: unknown, row: WalletRow) => <><strong>{row.studentName}</strong><div style={{ color: '#999' }}>{row.studentNo || `#${row.studentId}`}</div></> },
|
||||
{ title: '可用余额', dataIndex: 'balance', render: (value: number) => <strong style={{ color: Number(value) > 0 ? '#1677ff' : undefined }}>¥{Number(value).toFixed(2)}</strong> },
|
||||
{ title: '未付账单', dataIndex: 'outstandingAmount', render: (value: number) => Number(value) > 0 ? <Tag color="red">¥{Number(value).toFixed(2)}</Tag> : <Tag color="green">无欠费</Tag> },
|
||||
{ title: '操作', render: (_: unknown, row: WalletRow) => <Space><PermissionButton permission="wallet:edit" type="primary" size="small" icon={<PlusOutlined />} onClick={() => openChange(row)}>充值/调账</PermissionButton><Button size="small" icon={<HistoryOutlined />} onClick={() => showTransactions(row)}>流水</Button></Space> },
|
||||
], []);
|
||||
|
||||
return <div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
|
||||
<Space wrap><Input.Search allowClear placeholder="搜索姓名或学号" style={{ width: 240 }} onSearch={setKeyword} onChange={(event) => !event.target.value && setKeyword('')} /><span>仅看欠费</span><Switch checked={debtOnly} onChange={setDebtOnly} /></Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={fetchRows}>刷新</Button>
|
||||
</div>
|
||||
<Table rowKey="studentId" loading={loading} dataSource={rows} columns={columns} pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 人` }} />
|
||||
<Modal title={`${selected?.studentName || ''} - 余额操作`} open={!!selected && !drawerOpen} onCancel={() => setSelected(null)} onOk={submitChange} confirmLoading={saving} okText="确认">
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="type" label="操作类型" rules={[{ required: true }]}><Radio.Group options={[{ label: '充值', value: 'recharge' }, { label: '调账', value: 'adjustment' }]} /></Form.Item>
|
||||
<Form.Item name="amount" label="变动金额" extra="充值填正数;调减余额时填写负数。充值后会按最早账单优先自动补扣。" rules={[{ required: true, message: '请输入金额' }]}><InputNumber precision={2} style={{ width: '100%' }} addonBefore="¥" /></Form.Item>
|
||||
<Form.Item name="description" label="备注"><Input.TextArea maxLength={300} /></Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
<Drawer title={`${selected?.studentName || ''} - 余额流水`} width={680} open={drawerOpen} onClose={() => { setDrawerOpen(false); setSelected(null); }}>
|
||||
<Table rowKey="id" dataSource={transactions} pagination={{ pageSize: 10 }} columns={[
|
||||
{ title: '时间', dataIndex: 'createdAt', render: (value: string) => dayjs(value).format('YYYY-MM-DD HH:mm') },
|
||||
{ title: '类型', dataIndex: 'type', render: (value: string) => transactionNames[value] || value },
|
||||
{ title: '金额', dataIndex: 'amount', render: (value: number) => <span style={{ color: Number(value) >= 0 ? '#389e0d' : '#cf1322' }}>{Number(value) >= 0 ? '+' : ''}¥{Number(value).toFixed(2)}</span> },
|
||||
{ title: '变动后余额', dataIndex: 'balanceAfter', render: (value: number) => `¥${Number(value).toFixed(2)}` },
|
||||
{ title: '关联账单', dataIndex: 'billId', render: (value: number) => value ? `#${value}` : '-' },
|
||||
{ title: '说明', dataIndex: 'description' },
|
||||
]} />
|
||||
</Drawer>
|
||||
</div>;
|
||||
};
|
||||
|
||||
export default WalletsPage;
|
||||
@@ -220,6 +220,6 @@ export const PERMISSION_NODES = [
|
||||
'report:generate',
|
||||
'log:view',
|
||||
'role:view', 'role:add', 'role:update', 'role:delete',
|
||||
'user:view', 'user:add', 'user:update', 'user:delete',
|
||||
'user:view', 'user:add', 'user:update',
|
||||
'dashboard:view',
|
||||
] as const;
|
||||
|
||||
@@ -43,6 +43,8 @@ import {
|
||||
ArchiveAttachment,
|
||||
StudentDingMapping,
|
||||
AiConfig,
|
||||
StudentWallet,
|
||||
WalletTransaction,
|
||||
} from './entities';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { AuthorizationModule } from './authorization';
|
||||
@@ -71,6 +73,7 @@ import { ExpenseTypesModule } from './expense-types/expense-types.module';
|
||||
import { DatabaseMigrationsModule } from './database/database-migrations.module';
|
||||
import { AgentToolsModule } from './agent-tools';
|
||||
import { AiConfigModule } from './ai-config/ai-config.module';
|
||||
import { WalletsModule } from './wallets/wallets.module';
|
||||
|
||||
import {
|
||||
IntegrationConfig,
|
||||
@@ -135,6 +138,8 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
IntegrationConfig,
|
||||
IntegrationConfigDetail,
|
||||
AiConfig,
|
||||
StudentWallet,
|
||||
WalletTransaction,
|
||||
];
|
||||
if (dbType === 'mysql') {
|
||||
return {
|
||||
@@ -168,6 +173,7 @@ import { IntegrationConfigModule } from './integration/config/config.module';
|
||||
DashboardModule,
|
||||
OperationLogsModule,
|
||||
DepositsModule,
|
||||
WalletsModule,
|
||||
ClassroomsModule,
|
||||
AttendanceModule,
|
||||
ClassesModule,
|
||||
|
||||
102
apps/server/src/archive/archive.boundaries.spec.ts
Normal file
102
apps/server/src/archive/archive.boundaries.spec.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { ArchiveService } from './archive.service';
|
||||
|
||||
function createService(repos: Partial<Record<string, Record<string, jest.Mock>>> = {}) {
|
||||
return new ArchiveService(
|
||||
(repos.student ?? {}) as never,
|
||||
(repos.profile ?? {}) as never,
|
||||
(repos.enrollment ?? {}) as never,
|
||||
(repos.exam ?? {}) as never,
|
||||
(repos.learning ?? {}) as never,
|
||||
(repos.result ?? {}) as never,
|
||||
(repos.attachment ?? {}) as never,
|
||||
(repos.attendance ?? {}) as never,
|
||||
{} as never,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ArchiveService — resource and relationship boundaries', () => {
|
||||
it('rejects adding archive records for a missing student', async () => {
|
||||
const student = { findOne: jest.fn().mockResolvedValue(null) };
|
||||
const service = createService({ student });
|
||||
|
||||
await expect(
|
||||
service.addEnrollment(404, { courseCategory: '文化', classType: '冲刺' }),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(
|
||||
service.addLearningRecord(404, {
|
||||
recordDate: '2026-07-14',
|
||||
recordType: '沟通',
|
||||
content: '内容',
|
||||
}),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
|
||||
it('rejects linking an exam score to another student enrollment', async () => {
|
||||
const exam = { create: jest.fn(), save: jest.fn() };
|
||||
const service = createService({
|
||||
student: { findOne: jest.fn().mockResolvedValue({ id: 7 }) },
|
||||
enrollment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
exam,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.addExamScore(7, {
|
||||
examType: '月考',
|
||||
subject: '语文',
|
||||
score: 90,
|
||||
enrollmentId: 99,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(exam.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects moving an existing exam score to another student enrollment', async () => {
|
||||
const exam = {
|
||||
findOne: jest.fn().mockResolvedValue({ id: 3, studentId: 7, enrollmentId: 1 }),
|
||||
save: jest.fn(),
|
||||
};
|
||||
const service = createService({
|
||||
enrollment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
exam,
|
||||
});
|
||||
|
||||
await expect(service.updateExamScore(3, { enrollmentId: 99 })).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
expect(exam.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a missing attachment upload before writing to disk', async () => {
|
||||
const service = createService({ student: { findOne: jest.fn() } });
|
||||
await expect(service.addAttachment(7, undefined as never, 'other')).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects attachment path traversal', async () => {
|
||||
const service = createService({
|
||||
attachment: {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 1,
|
||||
studentId: 7,
|
||||
filePath: '../../etc/passwd',
|
||||
}),
|
||||
},
|
||||
});
|
||||
await expect(service.getAttachmentFile(7, 1)).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('returns not found for update/delete of absent child records', async () => {
|
||||
const service = createService({
|
||||
enrollment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
exam: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
learning: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
attachment: { findOne: jest.fn().mockResolvedValue(null) },
|
||||
});
|
||||
await expect(service.updateEnrollment(1, {})).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.deleteExamScore(1)).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.deleteLearningRecord(1)).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.deleteAttachment(1)).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
Res,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Request as ExpressRequest, Response } from 'express';
|
||||
@@ -47,15 +48,15 @@ export class ArchiveController {
|
||||
|
||||
@Get(':studentId')
|
||||
@RequirePermission('student:view')
|
||||
async getProfile(@Param('studentId') studentId: string, @Request() req: AuthenticatedRequest) {
|
||||
async getProfile(@Param('studentId', ParseIntPipe) studentId: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.getProfile(+studentId);
|
||||
const result = await this.archiveService.getProfile(studentId);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '查看档案',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'archive',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -66,18 +67,18 @@ export class ArchiveController {
|
||||
@Put(':studentId/profile')
|
||||
@RequirePermission('student:edit')
|
||||
async upsertProfile(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: UpsertProfileDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.upsertProfile(+studentId, dto);
|
||||
const result = await this.archiveService.upsertProfile(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '更新档案信息',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'student_profile',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -89,12 +90,12 @@ export class ArchiveController {
|
||||
@Post(':studentId/enrollments')
|
||||
@RequirePermission('student:edit')
|
||||
async addEnrollment(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: CreateEnrollmentDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addEnrollment(+studentId, dto);
|
||||
const result = await this.archiveService.addEnrollment(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -112,18 +113,18 @@ export class ArchiveController {
|
||||
@Put('enrollments/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async updateEnrollment(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateEnrollmentDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.updateEnrollment(+id, dto);
|
||||
const result = await this.archiveService.updateEnrollment(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '编辑报名记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'student_enrollment',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -134,15 +135,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('enrollments/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteEnrollment(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteEnrollment(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteEnrollment(+id);
|
||||
const result = await this.archiveService.deleteEnrollment(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除报名记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'student_enrollment',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -153,12 +154,12 @@ export class ArchiveController {
|
||||
@Post(':studentId/exam-scores')
|
||||
@RequirePermission('student:edit')
|
||||
async addExamScore(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: CreateExamScoreDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addExamScore(+studentId, dto);
|
||||
const result = await this.archiveService.addExamScore(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -176,18 +177,18 @@ export class ArchiveController {
|
||||
@Put('exam-scores/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async updateExamScore(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateExamScoreDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.updateExamScore(+id, dto);
|
||||
const result = await this.archiveService.updateExamScore(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '编辑考试成绩',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'exam_score',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -198,15 +199,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('exam-scores/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteExamScore(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteExamScore(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteExamScore(+id);
|
||||
const result = await this.archiveService.deleteExamScore(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除考试成绩',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'exam_score',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -217,12 +218,12 @@ export class ArchiveController {
|
||||
@Post(':studentId/learning-records')
|
||||
@RequirePermission('student:edit')
|
||||
async addLearningRecord(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: CreateLearningRecordDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addLearningRecord(+studentId, dto);
|
||||
const result = await this.archiveService.addLearningRecord(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -240,18 +241,18 @@ export class ArchiveController {
|
||||
@Put('learning-records/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async updateLearningRecord(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateLearningRecordDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.updateLearningRecord(+id, dto);
|
||||
const result = await this.archiveService.updateLearningRecord(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '编辑学习记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'learning_record',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -262,15 +263,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('learning-records/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteLearningRecord(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteLearningRecord(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteLearningRecord(+id);
|
||||
const result = await this.archiveService.deleteLearningRecord(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除学习记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'learning_record',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -281,18 +282,18 @@ export class ArchiveController {
|
||||
@Put(':studentId/result')
|
||||
@RequirePermission('student:edit')
|
||||
async upsertResult(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Body() dto: UpsertResultDto,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.upsertResult(+studentId, dto);
|
||||
const result = await this.archiveService.upsertResult(studentId, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '更新录取结果',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'result_archive',
|
||||
detail: JSON.stringify(dto),
|
||||
ipAddress,
|
||||
@@ -305,13 +306,13 @@ export class ArchiveController {
|
||||
@RequirePermission('student:edit')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async uploadAttachment(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
@Body('category') category: string,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.addAttachment(+studentId, file, category || 'other');
|
||||
const result = await this.archiveService.addAttachment(studentId, file, category || 'other');
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -329,13 +330,13 @@ export class ArchiveController {
|
||||
@Get(':studentId/attachments/:id')
|
||||
@RequirePermission('student:view')
|
||||
async downloadAttachment(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('id') id: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const { fullPath, fileName, mimeType } = await this.archiveService.getAttachmentFile(
|
||||
+studentId,
|
||||
+id,
|
||||
studentId,
|
||||
id,
|
||||
);
|
||||
res.setHeader('Content-Type', mimeType);
|
||||
res.setHeader('Content-Disposition', `inline; filename="${encodeURIComponent(fileName)}"`);
|
||||
@@ -345,15 +346,15 @@ export class ArchiveController {
|
||||
|
||||
@Delete('attachments/:id')
|
||||
@RequirePermission('student:edit')
|
||||
async deleteAttachment(@Param('id') id: string, @Request() req: AuthenticatedRequest) {
|
||||
async deleteAttachment(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.archiveService.deleteAttachment(+id);
|
||||
const result = await this.archiveService.deleteAttachment(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '学生档案',
|
||||
action: '删除附件',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'archive_attachment',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -364,7 +365,7 @@ export class ArchiveController {
|
||||
@Get(':studentId/report-html')
|
||||
@RequirePermission('student:view')
|
||||
async generateReportHtml(
|
||||
@Param('studentId') studentId: string,
|
||||
@Param('studentId', ParseIntPipe) studentId: number,
|
||||
@Request() req: AuthenticatedRequest,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
@@ -373,12 +374,12 @@ export class ArchiveController {
|
||||
username: req.user?.username,
|
||||
module: 'archive',
|
||||
action: 'generate_report_html',
|
||||
targetId: +studentId,
|
||||
targetId: studentId,
|
||||
targetType: 'student',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
const html = await this.reportService.generateReportHtml(+studentId);
|
||||
const html = await this.reportService.generateReportHtml(studentId);
|
||||
return { html };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ describe('ArchiveService.getProfile', () => {
|
||||
const learningRecordRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const resultRepo = { findOne: jest.fn().mockResolvedValue(result) };
|
||||
const attachmentRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
const attendanceRepo = { find: jest.fn().mockResolvedValue([]) };
|
||||
|
||||
const service = new ArchiveService(
|
||||
studentRepo as never,
|
||||
@@ -26,12 +27,13 @@ describe('ArchiveService.getProfile', () => {
|
||||
learningRecordRepo as never,
|
||||
resultRepo as never,
|
||||
attachmentRepo as never,
|
||||
attendanceRepo as never,
|
||||
{} as never,
|
||||
);
|
||||
|
||||
const response = await service.getProfile(7);
|
||||
|
||||
expect(response).toMatchObject({ student, result });
|
||||
expect(response).toMatchObject({ student, result, attendances: [] });
|
||||
expect(response).not.toHaveProperty('resultArchive');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import { ExamScore } from '../entities/exam-score.entity';
|
||||
import { LearningRecord } from '../entities/learning-record.entity';
|
||||
import { ResultArchive } from '../entities/result-archive.entity';
|
||||
import { ArchiveAttachment } from '../entities/archive-attachment.entity';
|
||||
import { AttendanceRecord } from '../entities/attendance-record.entity';
|
||||
import {
|
||||
UpsertProfileDto,
|
||||
CreateEnrollmentDto,
|
||||
@@ -33,6 +34,7 @@ export class ArchiveService {
|
||||
@InjectRepository(LearningRecord) private learningRecordRepo: Repository<LearningRecord>,
|
||||
@InjectRepository(ResultArchive) private resultRepo: Repository<ResultArchive>,
|
||||
@InjectRepository(ArchiveAttachment) private attachmentRepo: Repository<ArchiveAttachment>,
|
||||
@InjectRepository(AttendanceRecord) private attendanceRepo: Repository<AttendanceRecord>,
|
||||
private readonly notificationsService: NotificationsService,
|
||||
) {}
|
||||
|
||||
@@ -59,15 +61,27 @@ 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,
|
||||
attendances,
|
||||
] = 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' } }),
|
||||
this.attendanceRepo.find({
|
||||
where: { studentId },
|
||||
relations: ['schedule', 'class'],
|
||||
order: { attendanceDate: 'DESC', punchTime: 'DESC' },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
student,
|
||||
@@ -77,6 +91,7 @@ export class ArchiveService {
|
||||
learningRecords,
|
||||
result: resultArchive,
|
||||
attachments,
|
||||
attendances,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -115,9 +130,18 @@ export class ArchiveService {
|
||||
return { message: '已删除' };
|
||||
}
|
||||
|
||||
private async assertEnrollmentBelongsToStudent(studentId: number, enrollmentId?: number) {
|
||||
if (enrollmentId === undefined) return;
|
||||
const enrollment = await this.enrollmentRepo.findOne({
|
||||
where: { id: enrollmentId, studentId },
|
||||
});
|
||||
if (!enrollment) throw new BadRequestException('报名记录不属于该学生');
|
||||
}
|
||||
|
||||
async addExamScore(studentId: number, dto: CreateExamScoreDto) {
|
||||
const student = await this.studentRepo.findOne({ where: { id: studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
await this.assertEnrollmentBelongsToStudent(studentId, dto.enrollmentId);
|
||||
|
||||
const entity = this.examScoreRepo.create({ ...dto, studentId });
|
||||
return this.examScoreRepo.save(entity);
|
||||
@@ -126,6 +150,7 @@ export class ArchiveService {
|
||||
async updateExamScore(id: number, dto: UpdateExamScoreDto) {
|
||||
const entity = await this.examScoreRepo.findOne({ where: { id } });
|
||||
if (!entity) throw new NotFoundException('考试成绩不存在');
|
||||
await this.assertEnrollmentBelongsToStudent(entity.studentId, dto.enrollmentId);
|
||||
Object.assign(entity, dto);
|
||||
return this.examScoreRepo.save(entity);
|
||||
}
|
||||
@@ -173,6 +198,8 @@ export class ArchiveService {
|
||||
}
|
||||
|
||||
async addAttachment(studentId: number, file: Express.Multer.File, category: string) {
|
||||
if (!file?.buffer || !file.originalname) throw new BadRequestException('请选择附件文件');
|
||||
|
||||
const student = await this.studentRepo.findOne({ where: { id: studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { IsOptional, IsString, IsNumber, IsDateString } from 'class-validator';
|
||||
import { IsOptional, IsString, IsNumber, IsDateString, IsNotEmpty, Min } from 'class-validator';
|
||||
|
||||
export class UpsertProfileDto {
|
||||
@IsOptional() @IsString() targetCollege?: string;
|
||||
@@ -11,8 +11,8 @@ export class UpsertProfileDto {
|
||||
}
|
||||
|
||||
export class CreateEnrollmentDto {
|
||||
@IsString() courseCategory: string;
|
||||
@IsString() classType: string;
|
||||
@IsString() @IsNotEmpty() courseCategory: string;
|
||||
@IsString() @IsNotEmpty() classType: string;
|
||||
@IsOptional() @IsString() className?: string;
|
||||
@IsOptional() @IsString() headTeacher?: string;
|
||||
@IsOptional() @IsString() subjectTeacher?: string;
|
||||
@@ -24,12 +24,12 @@ export class CreateEnrollmentDto {
|
||||
export class UpdateEnrollmentDto extends PartialType(CreateEnrollmentDto) {}
|
||||
|
||||
export class CreateExamScoreDto {
|
||||
@IsString() examType: string;
|
||||
@IsString() @IsNotEmpty() examType: string;
|
||||
@IsOptional() @IsString() examName?: string;
|
||||
@IsString() subject: string;
|
||||
@IsNumber() score: number;
|
||||
@IsOptional() @IsNumber() classAvg?: number;
|
||||
@IsOptional() @IsNumber() rank?: number;
|
||||
@IsString() @IsNotEmpty() subject: string;
|
||||
@IsNumber() @Min(0) score: number;
|
||||
@IsOptional() @IsNumber() @Min(0) classAvg?: number;
|
||||
@IsOptional() @IsNumber() @Min(1) rank?: number;
|
||||
@IsOptional() @IsDateString() examDate?: string;
|
||||
@IsOptional() @IsNumber() enrollmentId?: number;
|
||||
}
|
||||
@@ -38,8 +38,8 @@ export class UpdateExamScoreDto extends PartialType(CreateExamScoreDto) {}
|
||||
|
||||
export class CreateLearningRecordDto {
|
||||
@IsDateString() recordDate: string;
|
||||
@IsString() recordType: string;
|
||||
@IsString() content: string;
|
||||
@IsString() @IsNotEmpty() recordType: string;
|
||||
@IsString() @IsNotEmpty() content: string;
|
||||
@IsOptional() @IsString() followUpMethod?: string;
|
||||
@IsOptional() @IsString() nextStep?: string;
|
||||
}
|
||||
@@ -47,8 +47,8 @@ export class CreateLearningRecordDto {
|
||||
export class UpdateLearningRecordDto extends PartialType(CreateLearningRecordDto) {}
|
||||
|
||||
export class UpsertResultDto {
|
||||
@IsOptional() @IsNumber() cultureFinalScore?: number;
|
||||
@IsOptional() @IsNumber() professionalFinalScore?: number;
|
||||
@IsOptional() @IsNumber() @Min(0) cultureFinalScore?: number;
|
||||
@IsOptional() @IsNumber() @Min(0) professionalFinalScore?: number;
|
||||
@IsOptional() @IsString() admissionStatus?: string;
|
||||
@IsOptional() @IsString() admittedCollege?: string;
|
||||
@IsOptional() @IsString() admittedMajor?: string;
|
||||
|
||||
@@ -93,6 +93,31 @@ describe('AttendanceImportService', () => {
|
||||
expect(entity.userName).toBe('张三');
|
||||
});
|
||||
|
||||
it('stores DingTalk punch source and attendance machine metadata', async () => {
|
||||
const entity = await (service as any).mapToEntity({
|
||||
userId: 'ding-1',
|
||||
userName: '张三',
|
||||
workDate: '2026-07-01',
|
||||
timeResult: 'Normal',
|
||||
locationResult: '',
|
||||
planCheckTime: '',
|
||||
actualCheckTime: '2026-07-01T08:00:00.000Z',
|
||||
checkId: 'check-1',
|
||||
checkType: 'OnDuty',
|
||||
sourceType: 'ATM',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
});
|
||||
|
||||
expect(entity).toEqual(
|
||||
expect.objectContaining({
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('fills the student name from the DingTalk mapping when saving an imported record', async () => {
|
||||
dingTalkService.fetchAttendanceResults.mockResolvedValue([
|
||||
{
|
||||
@@ -138,9 +163,19 @@ describe('AttendanceImportService', () => {
|
||||
actualCheckTime: '2026-07-01T08:00:00.000Z',
|
||||
checkId: 'check-1',
|
||||
checkType: 'OnDuty',
|
||||
sourceType: 'ATM',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
},
|
||||
]);
|
||||
dingRawRepo.find.mockResolvedValue([{ dingId: 'check-1' }]);
|
||||
dingRawRepo.find.mockResolvedValue([{
|
||||
dingId: 'check-1',
|
||||
punchSource: null,
|
||||
punchDeviceName: null,
|
||||
punchDeviceId: null,
|
||||
rawData: '',
|
||||
}]);
|
||||
dingRawRepo.save.mockImplementation(async (entities) => entities);
|
||||
attendanceService.autoMatchDingRecords.mockResolvedValue({ matched: 1, total: 1 });
|
||||
|
||||
const result = await service.importFromDingTalk({
|
||||
@@ -150,10 +185,57 @@ describe('AttendanceImportService', () => {
|
||||
autoMatch: true,
|
||||
});
|
||||
|
||||
expect(dingRawRepo.save).toHaveBeenCalledWith(
|
||||
[expect.objectContaining({
|
||||
dingId: 'check-1',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
})],
|
||||
{ chunk: 50 },
|
||||
);
|
||||
expect(attendanceService.autoMatchDingRecords).toHaveBeenCalled();
|
||||
expect(result.matched).toBe(1);
|
||||
});
|
||||
|
||||
it('preserves existing device metadata when a duplicate response omits it', async () => {
|
||||
const existing = {
|
||||
dingId: 'check-keep-device',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
rawData: '{}',
|
||||
};
|
||||
dingTalkService.fetchAttendanceResults.mockResolvedValue([{
|
||||
userId: 'ding-1',
|
||||
userName: '张三',
|
||||
workDate: '2026-07-01',
|
||||
timeResult: 'Normal',
|
||||
locationResult: '',
|
||||
planCheckTime: '',
|
||||
actualCheckTime: '2026-07-01T08:00:00.000Z',
|
||||
checkId: 'check-keep-device',
|
||||
checkType: 'OnDuty',
|
||||
sourceType: '',
|
||||
}]);
|
||||
dingRawRepo.find.mockResolvedValue([existing]);
|
||||
attendanceService.autoMatchDingRecords.mockResolvedValue({ matched: 0, total: 1 });
|
||||
|
||||
await service.importFromDingTalk({
|
||||
startDate: '2026-07-01',
|
||||
endDate: '2026-07-01',
|
||||
userIds: ['ding-1'],
|
||||
autoMatch: true,
|
||||
});
|
||||
|
||||
expect(existing).toEqual(expect.objectContaining({
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
}));
|
||||
expect(dingRawRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('scopes SSE progress events to the importing user', async () => {
|
||||
dingTalkService.fetchAttendanceResults.mockResolvedValue([
|
||||
{
|
||||
|
||||
@@ -104,8 +104,10 @@ export class AttendanceImportService {
|
||||
|
||||
// Stage 2: Parse & deduplicate
|
||||
this.emit('parsing', 0, total, `Parsing ${total} records...`);
|
||||
const existingDingIds = await this.getExistingDingIds(rawResults);
|
||||
const newRecords = rawResults.filter((r) => !existingDingIds.has(r.checkId));
|
||||
const existingByDingId = await this.getExistingRecordsByDingId(rawResults);
|
||||
const newRecords = rawResults.filter((r) => !existingByDingId.has(r.checkId));
|
||||
const duplicateRecords = rawResults.filter((r) => existingByDingId.has(r.checkId));
|
||||
await this.refreshDuplicatePunchMetadata(duplicateRecords, existingByDingId);
|
||||
skipped = rawResults.length - newRecords.length;
|
||||
this.emit('parsing', newRecords.length, total, `${newRecords.length} new records, ${skipped} duplicates skipped`);
|
||||
|
||||
@@ -246,17 +248,45 @@ export class AttendanceImportService {
|
||||
/**
|
||||
* Query which dingIds already exist to skip duplicates.
|
||||
*/
|
||||
private async getExistingDingIds(
|
||||
private async getExistingRecordsByDingId(
|
||||
results: DingTalkAttendanceResult[],
|
||||
): Promise<Set<string>> {
|
||||
): Promise<Map<string, DingAttendanceRaw>> {
|
||||
const dingIds = results.map((r) => r.checkId).filter(Boolean);
|
||||
if (dingIds.length === 0) return new Set();
|
||||
if (dingIds.length === 0) return new Map();
|
||||
|
||||
const existing = await this.dingRawRepo.find({
|
||||
where: { dingId: In(dingIds) },
|
||||
select: ['dingId'],
|
||||
});
|
||||
return new Set(existing.map((e) => e.dingId));
|
||||
return new Map(existing.map((entity) => [entity.dingId, entity]));
|
||||
}
|
||||
|
||||
private async refreshDuplicatePunchMetadata(
|
||||
results: DingTalkAttendanceResult[],
|
||||
existingByDingId: Map<string, DingAttendanceRaw>,
|
||||
): Promise<void> {
|
||||
const changed: DingAttendanceRaw[] = [];
|
||||
for (const result of results) {
|
||||
const entity = existingByDingId.get(result.checkId);
|
||||
if (!entity) continue;
|
||||
const punchSource = result.sourceType || entity.punchSource || null;
|
||||
const punchDeviceName = result.deviceName || entity.punchDeviceName || null;
|
||||
const punchDeviceId = result.deviceId || entity.punchDeviceId || null;
|
||||
if (
|
||||
entity.punchSource === punchSource &&
|
||||
entity.punchDeviceName === punchDeviceName &&
|
||||
entity.punchDeviceId === punchDeviceId
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
entity.punchSource = punchSource;
|
||||
entity.punchDeviceName = punchDeviceName;
|
||||
entity.punchDeviceId = punchDeviceId;
|
||||
entity.rawData = JSON.stringify(result);
|
||||
changed.push(entity);
|
||||
}
|
||||
if (changed.length > 0) {
|
||||
await this.dingRawRepo.save(changed, { chunk: 50 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -271,6 +301,9 @@ export class AttendanceImportService {
|
||||
entity.attendanceType = r.checkType || 'OnDuty';
|
||||
entity.timeResult = r.timeResult;
|
||||
entity.locationResult = r.locationResult || '';
|
||||
entity.punchSource = r.sourceType || null;
|
||||
entity.punchDeviceName = r.deviceName || null;
|
||||
entity.punchDeviceId = r.deviceId || null;
|
||||
|
||||
// Parse check-in/out times
|
||||
if (r.actualCheckTime) {
|
||||
|
||||
@@ -20,6 +20,14 @@ const createService = () => {
|
||||
update: jest.fn().mockResolvedValue({ affected: 1 }),
|
||||
};
|
||||
const attendanceService = {
|
||||
getLessonAttendanceImportDateRange: jest.fn().mockImplementation((targetSchedule, lessonDate: string) => {
|
||||
if (targetSchedule.endTime > targetSchedule.startTime) {
|
||||
return { startDate: lessonDate, endDate: lessonDate };
|
||||
}
|
||||
const next = new Date(`${lessonDate}T00:00:00.000Z`);
|
||||
next.setUTCDate(next.getUTCDate() + 1);
|
||||
return { startDate: lessonDate, endDate: next.toISOString().slice(0, 10) };
|
||||
}),
|
||||
getTeacherClassDingUserIds: jest.fn().mockResolvedValue(['ding-1']),
|
||||
createLessonAttendanceFromDingTalk: jest.fn().mockImplementation(
|
||||
async (_scheduleId: number, lessonDate: string, userId: number, finalize: boolean) => ({
|
||||
@@ -72,6 +80,49 @@ describe('AttendanceSettlementService', () => {
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not settle an in-progress lesson before its end time', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService, importService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([schedule]);
|
||||
sessionRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 90,
|
||||
scheduleId: 2,
|
||||
lessonDate: '2026-07-13',
|
||||
status: 'in_progress',
|
||||
schedule,
|
||||
},
|
||||
]);
|
||||
|
||||
await service.settleEndedLessons(new Date('2026-07-13T09:30:00+08:00'));
|
||||
|
||||
expect(importService.importFromDingTalk).not.toHaveBeenCalled();
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('settles an in-progress lesson when its end time is reached', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([schedule]);
|
||||
sessionRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 90,
|
||||
scheduleId: 2,
|
||||
lessonDate: '2026-07-13',
|
||||
status: 'in_progress',
|
||||
schedule,
|
||||
},
|
||||
]);
|
||||
|
||||
await service.settleEndedLessons(new Date('2026-07-13T10:00:00+08:00'));
|
||||
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).toHaveBeenCalledTimes(1);
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).toHaveBeenCalledWith(
|
||||
2,
|
||||
'2026-07-13',
|
||||
21,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('continues with the next lesson when one settlement fails', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService, importService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([schedule, { ...schedule, id: 3 }]);
|
||||
@@ -155,6 +206,32 @@ describe('AttendanceSettlementService', () => {
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not settle an in-progress overnight lesson before its next-day end time', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService, importService } = createService();
|
||||
const overnightSchedule = {
|
||||
...schedule,
|
||||
id: 4,
|
||||
weekDay: 7,
|
||||
startTime: '22:00',
|
||||
endTime: '01:00',
|
||||
};
|
||||
scheduleRepo.find.mockResolvedValue([]);
|
||||
sessionRepo.find.mockResolvedValue([
|
||||
{
|
||||
id: 91,
|
||||
scheduleId: 4,
|
||||
lessonDate: '2026-07-12',
|
||||
status: 'in_progress',
|
||||
schedule: overnightSchedule,
|
||||
},
|
||||
]);
|
||||
|
||||
await service.settleEndedLessons(new Date('2026-07-13T00:30:00+08:00'));
|
||||
|
||||
expect(importService.importFromDingTalk).not.toHaveBeenCalled();
|
||||
expect(attendanceService.createLessonAttendanceFromDingTalk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('settles an overnight lesson after its next-day end time', async () => {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceService } = createService();
|
||||
scheduleRepo.find.mockResolvedValue([
|
||||
|
||||
@@ -61,7 +61,11 @@ export class AttendanceSettlementService {
|
||||
}
|
||||
}
|
||||
for (const session of sessions) {
|
||||
if (session.status === 'in_progress' && session.schedule) {
|
||||
if (
|
||||
session.status === 'in_progress' &&
|
||||
session.schedule &&
|
||||
this.hasOccurrenceEnded(session.schedule, session.lessonDate, clock)
|
||||
) {
|
||||
candidates.set(`${session.scheduleId}|${session.lessonDate}`, {
|
||||
schedule: session.schedule,
|
||||
lessonDate: session.lessonDate,
|
||||
@@ -110,9 +114,12 @@ export class AttendanceSettlementService {
|
||||
schedule.teacherId,
|
||||
schedule.classId,
|
||||
);
|
||||
const importRange = this.attendanceService.getLessonAttendanceImportDateRange(
|
||||
schedule,
|
||||
lessonDate,
|
||||
);
|
||||
const imported = await this.importService.importFromDingTalk({
|
||||
startDate: lessonDate,
|
||||
endDate: this.isOvernight(schedule) ? this.shiftDate(lessonDate, 1) : lessonDate,
|
||||
...importRange,
|
||||
userIds,
|
||||
autoMatch: true,
|
||||
userId: schedule.teacherId,
|
||||
@@ -160,6 +167,18 @@ export class AttendanceSettlementService {
|
||||
return null;
|
||||
}
|
||||
|
||||
private hasOccurrenceEnded(
|
||||
schedule: ClassSchedule,
|
||||
lessonDate: string,
|
||||
clock: { date: string; minutes: number },
|
||||
): boolean {
|
||||
const occurrenceEndDate = this.isOvernight(schedule)
|
||||
? this.shiftDate(lessonDate, 1)
|
||||
: lessonDate;
|
||||
if (clock.date !== occurrenceEndDate) return clock.date > occurrenceEndDate;
|
||||
return clock.minutes >= this.toMinutes(schedule.endTime);
|
||||
}
|
||||
|
||||
private isOvernight(schedule: ClassSchedule): boolean {
|
||||
return this.toMinutes(schedule.endTime) <= this.toMinutes(schedule.startTime);
|
||||
}
|
||||
|
||||
@@ -162,6 +162,9 @@ describe('AttendanceController — write data scope', () => {
|
||||
assertClassAccess: jest.fn(),
|
||||
getAccessibleClassIds: jest.fn(),
|
||||
getTeacherClassDingUserIds: jest.fn(),
|
||||
getLessonAttendanceImportDateRange: jest.fn().mockImplementation(
|
||||
(_schedule, lessonDate: string) => ({ startDate: lessonDate, endDate: lessonDate }),
|
||||
),
|
||||
batchCreate: jest.fn(),
|
||||
generateFromSchedules: jest.fn(),
|
||||
findAttendanceRecord: jest.fn(),
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Res,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { Observable, filter } from 'rxjs';
|
||||
import type { Request as ExpressRequest, Response } from 'express';
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
QueryDingRawDto,
|
||||
MatchDingRecordDto,
|
||||
AttendanceReportQueryDto,
|
||||
AttendanceAlertsQueryDto,
|
||||
UpdateAttendanceRecordDto,
|
||||
GenerateFromSchedulesDto,
|
||||
LessonAttendanceQueryDto,
|
||||
@@ -93,11 +95,11 @@ export class AttendanceController {
|
||||
@Get('attendance-lessons/schedules/:scheduleId')
|
||||
@RequirePermission('attendance:view')
|
||||
async getLessonAttendance(
|
||||
@Param('scheduleId') scheduleId: string,
|
||||
@Param('scheduleId', ParseIntPipe) scheduleId: number,
|
||||
@Query() query: LessonAttendanceQueryDto,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
const result = await this.service.getLessonAttendance(+scheduleId, query.date);
|
||||
const result = await this.service.getLessonAttendance(scheduleId, query.date);
|
||||
await this.assertClassAccess(req, result.schedule.classId!);
|
||||
return result;
|
||||
}
|
||||
@@ -105,26 +107,29 @@ export class AttendanceController {
|
||||
@Post('attendance-lessons/schedules/:scheduleId/pull')
|
||||
@RequirePermission('attendance:create')
|
||||
async pullLessonAttendance(
|
||||
@Param('scheduleId') scheduleId: string,
|
||||
@Param('scheduleId', ParseIntPipe) scheduleId: number,
|
||||
@Body() dto: StartLessonAttendanceDto,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
const schedule = await this.service.getLessonAttendance(+scheduleId, dto.date);
|
||||
const schedule = await this.service.getLessonAttendance(scheduleId, dto.date);
|
||||
await this.assertClassAccess(req, schedule.schedule.classId!);
|
||||
const importClassIds = await this.service.getTeacherClassDingUserIds(
|
||||
req.user.id,
|
||||
schedule.schedule.classId!,
|
||||
this.canManageAllAttendance(req),
|
||||
);
|
||||
const importRange = this.service.getLessonAttendanceImportDateRange(
|
||||
schedule.schedule,
|
||||
dto.date,
|
||||
);
|
||||
const importResult = await this.importService.importFromDingTalk({
|
||||
startDate: dto.date,
|
||||
endDate: dto.date,
|
||||
...importRange,
|
||||
userIds: importClassIds,
|
||||
autoMatch: true,
|
||||
userId: req.user.id,
|
||||
});
|
||||
const result = await this.service.createLessonAttendanceFromDingTalk(
|
||||
+scheduleId,
|
||||
scheduleId,
|
||||
dto.date,
|
||||
req.user.id,
|
||||
);
|
||||
@@ -143,18 +148,18 @@ export class AttendanceController {
|
||||
@Post('attendance-lessons/:sessionId/complete')
|
||||
@RequirePermission('attendance:create')
|
||||
async completeLessonAttendance(
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Param('sessionId', ParseIntPipe) sessionId: number,
|
||||
@Request() req: { user: RequestUser },
|
||||
) {
|
||||
const session = await this.service.findAttendanceSession(+sessionId);
|
||||
const session = await this.service.findAttendanceSession(sessionId);
|
||||
await this.assertClassAccess(req, session.classId);
|
||||
const result = await this.service.completeLessonAttendance(+sessionId, req.user.id);
|
||||
const result = await this.service.completeLessonAttendance(sessionId, req.user.id);
|
||||
await this.logService.log({
|
||||
userId: req.user.id,
|
||||
username: req.user.username,
|
||||
module: '考勤管理',
|
||||
action: '完成课程点名',
|
||||
targetId: +sessionId,
|
||||
targetId: sessionId,
|
||||
targetType: 'attendanceSession',
|
||||
detail: `班级${session.classId} 日期${session.lessonDate}`,
|
||||
});
|
||||
@@ -278,23 +283,23 @@ export class AttendanceController {
|
||||
@Put('attendance-records/:id')
|
||||
@RequirePermission('attendance:edit', 'attendance:self-edit')
|
||||
async update(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateAttendanceRecordDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const existing = await this.service.findAttendanceRecord(+id);
|
||||
const existing = await this.service.findAttendanceRecord(id);
|
||||
if (existing.classId == null && !this.canManageAllAttendance(req)) {
|
||||
throw new ForbiddenException('无权修改未关联班级的考勤记录');
|
||||
}
|
||||
if (existing.classId != null) await this.assertClassAccess(req, existing.classId);
|
||||
const result = await this.service.update(+id, dto);
|
||||
const result = await this.service.update(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤管理',
|
||||
action: '编辑考勤记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'attendanceRecord',
|
||||
detail: `状态=${result.status}, 备注=${result.remark || ''}`,
|
||||
ipAddress,
|
||||
@@ -306,20 +311,20 @@ export class AttendanceController {
|
||||
// ── Delete a single attendance record ──
|
||||
@Delete('attendance-records/:id')
|
||||
@RequirePermission('attendance:edit', 'attendance:self-edit')
|
||||
async remove(@Param('id') id: string, @Request() req: any) {
|
||||
async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const existing = await this.service.findAttendanceRecord(+id);
|
||||
const existing = await this.service.findAttendanceRecord(id);
|
||||
if (existing.classId == null && !this.canManageAllAttendance(req)) {
|
||||
throw new ForbiddenException('无权删除未关联班级的考勤记录');
|
||||
}
|
||||
if (existing.classId != null) await this.assertClassAccess(req, existing.classId);
|
||||
const result = await this.service.remove(+id);
|
||||
const result = await this.service.remove(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤管理',
|
||||
action: '删除考勤记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'attendanceRecord',
|
||||
detail: `删除考勤记录 ${id}`,
|
||||
ipAddress,
|
||||
@@ -369,18 +374,18 @@ export class AttendanceController {
|
||||
@Post('ding-attendance-raw/:id/match')
|
||||
@RequirePermission('attendance:edit')
|
||||
async matchDingRecord(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: MatchDingRecordDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.matchDingRecord(+id, dto);
|
||||
const result = await this.service.matchDingRecord(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '考勤管理',
|
||||
action: '匹配考勤记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'dingAttendanceRaw',
|
||||
detail: `匹配到学生 ${dto.studentId}`,
|
||||
ipAddress,
|
||||
@@ -458,12 +463,11 @@ export class AttendanceController {
|
||||
@RequirePermission('attendance:view')
|
||||
async getAlerts(
|
||||
@Request() req: { user: RequestUser },
|
||||
@Query('days') days?: string,
|
||||
@Query('threshold') threshold?: string,
|
||||
@Query() query: AttendanceAlertsQueryDto,
|
||||
) {
|
||||
return this.service.getAlerts(
|
||||
days ? +days : 14,
|
||||
threshold ? +threshold : 3,
|
||||
query.days ?? 14,
|
||||
query.threshold ?? 3,
|
||||
await this.getAccessibleClassIds(req),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ const endedSchedule = {
|
||||
subject: '\u6570\u5B66',
|
||||
status: 'active',
|
||||
scheduleType: 'INTERNAL',
|
||||
attendanceAdvanceMinutes: 30,
|
||||
};
|
||||
|
||||
describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
@@ -79,6 +80,9 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
attendanceType: 'OnDuty',
|
||||
timeResult: 'Normal',
|
||||
checkInTime: new Date('2026-07-11T08:55:00+08:00'),
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
},
|
||||
{
|
||||
matchedStudentId: 2,
|
||||
@@ -100,7 +104,15 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
}),
|
||||
);
|
||||
expect(attendanceRepo.save).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ studentId: 1, status: 'present', source: 'dingtalk' }),
|
||||
expect.objectContaining({
|
||||
studentId: 1,
|
||||
status: 'present',
|
||||
source: 'dingtalk',
|
||||
punchSource: 'ATM',
|
||||
punchDeviceName: '东门考勤机',
|
||||
punchDeviceId: 'ATM-01',
|
||||
punchTime: new Date('2026-07-11T08:55:00+08:00'),
|
||||
}),
|
||||
expect.objectContaining({ studentId: 2, status: 'present', source: 'dingtalk' }),
|
||||
expect.objectContaining({ studentId: 3, status: 'pending', source: 'dingtalk' }),
|
||||
expect.objectContaining({ studentId: 4, status: 'pending', source: 'dingtalk' }),
|
||||
@@ -175,6 +187,40 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('counts both OnDuty and OffDuty punches only inside the configured window', async () => {
|
||||
const { service, attendanceRepo, dingRawRepo, scheduleRepo, classStudentRepo, sessionRepo } =
|
||||
createService();
|
||||
scheduleRepo.findOne.mockResolvedValue({ ...endedSchedule, attendanceAdvanceMinutes: 20 });
|
||||
sessionRepo.findOne.mockResolvedValue(null);
|
||||
classStudentRepo.find.mockResolvedValue([
|
||||
{ studentId: 1, student: { id: 1, name: '张三' } },
|
||||
{ studentId: 2, student: { id: 2, name: '李四' } },
|
||||
{ studentId: 3, student: { id: 3, name: '王五' } },
|
||||
]);
|
||||
dingRawRepo.find.mockResolvedValue([
|
||||
{ matchedStudentId: 1, attendanceType: 'OffDuty', checkOutTime: new Date('2026-07-11T08:40:00+08:00') },
|
||||
{ matchedStudentId: 2, attendanceType: 'OffDuty', checkOutTime: new Date('2026-07-11T10:00:00+08:00') },
|
||||
{ matchedStudentId: 3, attendanceType: 'OnDuty', checkInTime: new Date('2026-07-11T08:39:59+08:00') },
|
||||
{ matchedStudentId: 3, attendanceType: 'OffDuty', checkOutTime: new Date('2026-07-11T10:00:01+08:00') },
|
||||
]);
|
||||
|
||||
await service.createLessonAttendanceFromDingTalk(4, '2026-07-11', 21, true);
|
||||
|
||||
expect(attendanceRepo.save).toHaveBeenCalledWith([
|
||||
expect.objectContaining({ studentId: 1, status: 'present' }),
|
||||
expect.objectContaining({ studentId: 2, status: 'present' }),
|
||||
expect.objectContaining({ studentId: 3, status: 'absent' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('expands import dates when the pre-class window crosses midnight', () => {
|
||||
const { service } = createService();
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '00:15', endTime: '01:00', attendanceAdvanceMinutes: 30 },
|
||||
'2026-07-11',
|
||||
)).toEqual({ startDate: '2026-07-10', endDate: '2026-07-11' });
|
||||
});
|
||||
|
||||
it('creates local attendance after the lesson starts', async () => {
|
||||
const { service, attendanceRepo, dingRawRepo, scheduleRepo, classStudentRepo, sessionRepo } =
|
||||
createService();
|
||||
@@ -547,3 +593,38 @@ describe('AttendanceService \u2014 DingTalk course attendance', () => {
|
||||
expect(result.source).toBe('manual');
|
||||
});
|
||||
});
|
||||
|
||||
describe('AttendanceService — attendance window boundaries', () => {
|
||||
it('crosses calendar boundaries only when the window requires it', () => {
|
||||
const { service } = createService();
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '00:30', endTime: '01:30', attendanceAdvanceMinutes: 30 }, '2026-07-13',
|
||||
)).toEqual({ startDate: '2026-07-13', endDate: '2026-07-13' });
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '00:30', endTime: '01:30', attendanceAdvanceMinutes: 31 }, '2026-07-13',
|
||||
)).toEqual({ startDate: '2026-07-12', endDate: '2026-07-13' });
|
||||
expect(service.getLessonAttendanceImportDateRange(
|
||||
{ startTime: '22:00', endTime: '01:00', attendanceAdvanceMinutes: 30 }, '2026-07-13',
|
||||
)).toEqual({ startDate: '2026-07-13', endDate: '2026-07-14' });
|
||||
});
|
||||
|
||||
it('uses Asia/Shanghai time when deciding whether todays lesson has started', async () => {
|
||||
const originalTz = process.env.TZ;
|
||||
process.env.TZ = 'UTC';
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-07-13T01:00:00.000Z'));
|
||||
try {
|
||||
const { service, scheduleRepo, sessionRepo, attendanceRepo } = createService();
|
||||
scheduleRepo.findOne.mockResolvedValue({
|
||||
...endedSchedule, weekDay: 1, startTime: '08:30', endTime: '10:00',
|
||||
startDate: '2026-07-13', endDate: '2026-07-13',
|
||||
});
|
||||
sessionRepo.findOne.mockResolvedValue({ id: 90, status: 'completed' });
|
||||
attendanceRepo.find.mockResolvedValue([]);
|
||||
await expect(service.createLessonAttendanceFromDingTalk(4, '2026-07-13', 21))
|
||||
.resolves.toMatchObject({ records: [] });
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
process.env.TZ = originalTz;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -175,24 +175,45 @@ export class AttendanceService {
|
||||
return { schedule, session, records };
|
||||
}
|
||||
|
||||
private getLessonAttendanceWindow(
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
): { start: number; end: number; dateFrom: string; dateTo: string } {
|
||||
const startMinuteOfDay = this.toMinutes(schedule.startTime);
|
||||
const endMinuteOfDay = this.toMinutes(schedule.endTime);
|
||||
const advanceMinutes = Math.max(0, schedule.attendanceAdvanceMinutes ?? 30);
|
||||
const lessonStart = new Date(`${lessonDate}T${schedule.startTime}:00+08:00`).getTime();
|
||||
let lessonEnd = new Date(`${lessonDate}T${schedule.endTime}:00+08:00`).getTime();
|
||||
const overnight = endMinuteOfDay <= startMinuteOfDay;
|
||||
if (overnight) lessonEnd += 24 * 60 * 60 * 1000;
|
||||
|
||||
return {
|
||||
start: lessonStart - advanceMinutes * 60 * 1000,
|
||||
end: lessonEnd,
|
||||
dateFrom: advanceMinutes > startMinuteOfDay ? this.shiftDate(lessonDate, -1) : lessonDate,
|
||||
dateTo: overnight ? this.shiftDate(lessonDate, 1) : lessonDate,
|
||||
};
|
||||
}
|
||||
|
||||
getLessonAttendanceImportDateRange(
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
): { startDate: string; endDate: string } {
|
||||
const window = this.getLessonAttendanceWindow(schedule, lessonDate);
|
||||
return { startDate: window.dateFrom, endDate: window.dateTo };
|
||||
}
|
||||
|
||||
private selectDingTalkRecordsForLesson(
|
||||
records: DingAttendanceRaw[],
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
startTime: string,
|
||||
endTime: string,
|
||||
): DingAttendanceRaw[] {
|
||||
const [startHour, startMinute] = startTime.split(':').map(Number);
|
||||
const [endHour, endMinute] = endTime.split(':').map(Number);
|
||||
const start = new Date(`${lessonDate}T${startTime}:00+08:00`).getTime();
|
||||
let end = new Date(`${lessonDate}T${endTime}:00+08:00`).getTime();
|
||||
if (endHour * 60 + endMinute <= startHour * 60 + startMinute) end += 24 * 60 * 60 * 1000;
|
||||
const windowStart = start - 3 * 60 * 60 * 1000;
|
||||
const windowEnd = end + 3 * 60 * 60 * 1000;
|
||||
const timed = records.filter((record) => {
|
||||
const window = this.getLessonAttendanceWindow(schedule, lessonDate);
|
||||
return records.filter((record) => {
|
||||
// 上班、下班打卡都有效,按原始记录中实际存在的时间判断。
|
||||
const time = record.checkInTime ?? record.checkOutTime;
|
||||
return time && time.getTime() >= windowStart && time.getTime() <= windowEnd;
|
||||
return time && time.getTime() >= window.start && time.getTime() <= window.end;
|
||||
});
|
||||
return timed.length > 0 ? timed : records.filter((record) => !record.checkInTime && !record.checkOutTime);
|
||||
}
|
||||
|
||||
private mapDingTalkStatus(records: DingAttendanceRaw[], finalize = false): string {
|
||||
@@ -200,6 +221,53 @@ export class AttendanceService {
|
||||
if (hasPunch) return 'present';
|
||||
return finalize ? 'absent' : 'pending';
|
||||
}
|
||||
|
||||
private getLessonPunchMetadata(
|
||||
records: DingAttendanceRaw[],
|
||||
lessonDate: string,
|
||||
startTime: string,
|
||||
): Pick<AttendanceRecord, 'punchTime' | 'punchSource' | 'punchDeviceName' | 'punchDeviceId'> {
|
||||
const punches = records
|
||||
.map((record) => ({ record, time: record.checkInTime ?? record.checkOutTime }))
|
||||
.filter((item): item is { record: DingAttendanceRaw; time: Date } => !!item.time);
|
||||
if (punches.length === 0) {
|
||||
return {
|
||||
punchTime: null,
|
||||
punchSource: null,
|
||||
punchDeviceName: null,
|
||||
punchDeviceId: null,
|
||||
};
|
||||
}
|
||||
|
||||
const lessonStart = new Date(`${lessonDate}T${startTime}:00+08:00`).getTime();
|
||||
punches.sort(
|
||||
(left, right) =>
|
||||
Math.abs(left.time.getTime() - lessonStart) - Math.abs(right.time.getTime() - lessonStart),
|
||||
);
|
||||
const primary = punches[0];
|
||||
const metadataRecord = [...punches]
|
||||
.filter(({ record }) =>
|
||||
!!(record.punchSource || record.punchDeviceName || record.punchDeviceId) ||
|
||||
!['OnDuty', 'OffDuty'].includes(record.attendanceType),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
Math.abs(left.time.getTime() - primary.time.getTime()) -
|
||||
Math.abs(right.time.getTime() - primary.time.getTime()),
|
||||
)[0]?.record;
|
||||
const source =
|
||||
metadataRecord?.punchSource ||
|
||||
(metadataRecord && !['OnDuty', 'OffDuty'].includes(metadataRecord.attendanceType)
|
||||
? metadataRecord.attendanceType
|
||||
: primary.record.punchSource);
|
||||
|
||||
return {
|
||||
punchTime: primary.time,
|
||||
punchSource: source || null,
|
||||
punchDeviceName: metadataRecord?.punchDeviceName || primary.record.punchDeviceName || null,
|
||||
punchDeviceId: metadataRecord?.punchDeviceId || primary.record.punchDeviceId || null,
|
||||
};
|
||||
}
|
||||
async createLessonAttendanceFromDingTalk(
|
||||
scheduleId: number,
|
||||
lessonDate: string,
|
||||
@@ -208,16 +276,13 @@ export class AttendanceService {
|
||||
) {
|
||||
const schedule = await this.getScheduleOccurrence(scheduleId, lessonDate);
|
||||
const now = new Date();
|
||||
const today = [
|
||||
now.getFullYear(),
|
||||
String(now.getMonth() + 1).padStart(2, '0'),
|
||||
String(now.getDate()).padStart(2, '0'),
|
||||
].join('-');
|
||||
const courseClock = this.getCourseClock(now);
|
||||
const today = courseClock.date;
|
||||
if (lessonDate > today) throw new BadRequestException('课程尚未开始,不能拉取考勤');
|
||||
if (lessonDate === today) {
|
||||
const [hour, minute] = schedule.startTime.split(':').map(Number);
|
||||
const startMinute = hour * 60 + minute;
|
||||
const currentMinute = now.getHours() * 60 + now.getMinutes();
|
||||
const currentMinute = courseClock.minutes;
|
||||
if (currentMinute < startMinute) {
|
||||
throw new BadRequestException('课程尚未开始,不能拉取考勤');
|
||||
}
|
||||
@@ -244,7 +309,7 @@ export class AttendanceService {
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
const sessionRepo = manager.getRepository(AttendanceSession);
|
||||
const recordRepo = manager.getRepository(AttendanceRecord);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, lessonDate);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, schedule, lessonDate);
|
||||
const existingRecords = await recordRepo.find({
|
||||
where: { attendanceSessionId: existing.id },
|
||||
order: { studentId: 'ASC' },
|
||||
@@ -265,11 +330,15 @@ export class AttendanceService {
|
||||
|
||||
const raw = this.selectDingTalkRecordsForLesson(
|
||||
rawByStudent.get(record.studentId) ?? [],
|
||||
schedule,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
schedule.endTime,
|
||||
);
|
||||
record.status = this.mapDingTalkStatus(raw, finalize);
|
||||
Object.assign(record, this.getLessonPunchMetadata(
|
||||
raw,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
));
|
||||
record.remark = raw.some((item) => item.checkInTime || item.checkOutTime)
|
||||
? null
|
||||
: finalize
|
||||
@@ -281,9 +350,8 @@ export class AttendanceService {
|
||||
if (existingStudentIds.has(classStudent.studentId)) continue;
|
||||
const raw = this.selectDingTalkRecordsForLesson(
|
||||
rawByStudent.get(classStudent.studentId) ?? [],
|
||||
schedule,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
schedule.endTime,
|
||||
);
|
||||
updatedRecords.push(
|
||||
recordRepo.create({
|
||||
@@ -296,6 +364,11 @@ export class AttendanceService {
|
||||
session: this.mapScheduleTimeToSession(schedule.startTime),
|
||||
status: this.mapDingTalkStatus(raw, finalize),
|
||||
source: 'dingtalk',
|
||||
...this.getLessonPunchMetadata(
|
||||
raw,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
),
|
||||
remark: raw.some((item) => item.checkInTime || item.checkOutTime)
|
||||
? undefined
|
||||
: finalize
|
||||
@@ -320,7 +393,7 @@ export class AttendanceService {
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
const sessionRepo = manager.getRepository(AttendanceSession);
|
||||
const recordRepo = manager.getRepository(AttendanceRecord);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, lessonDate);
|
||||
const rawByStudent = await this.fetchDingTalkRawByStudent(schedule.classId!, schedule, lessonDate);
|
||||
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
where: { classId: schedule.classId!, status: 'active' },
|
||||
@@ -364,9 +437,8 @@ export class AttendanceService {
|
||||
const records = classStudents.map((classStudent) => {
|
||||
const raw = this.selectDingTalkRecordsForLesson(
|
||||
rawByStudent.get(classStudent.studentId) ?? [],
|
||||
schedule,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
schedule.endTime,
|
||||
);
|
||||
return recordRepo.create({
|
||||
studentId: classStudent.studentId,
|
||||
@@ -378,6 +450,11 @@ export class AttendanceService {
|
||||
session: this.mapScheduleTimeToSession(schedule.startTime),
|
||||
status: this.mapDingTalkStatus(raw, finalize),
|
||||
source: 'dingtalk',
|
||||
...this.getLessonPunchMetadata(
|
||||
raw,
|
||||
lessonDate,
|
||||
schedule.startTime,
|
||||
),
|
||||
remark: raw.some((item) => item.checkInTime || item.checkOutTime)
|
||||
? undefined
|
||||
: finalize
|
||||
@@ -398,6 +475,7 @@ export class AttendanceService {
|
||||
|
||||
private async fetchDingTalkRawByStudent(
|
||||
classId: number,
|
||||
schedule: Pick<ClassSchedule, 'startTime' | 'endTime' | 'attendanceAdvanceMinutes'>,
|
||||
lessonDate: string,
|
||||
): Promise<Map<number, DingAttendanceRaw[]>> {
|
||||
const classStudents = await this.classStudentRepo.find({
|
||||
@@ -405,9 +483,10 @@ export class AttendanceService {
|
||||
});
|
||||
if (classStudents.length === 0) return new Map();
|
||||
const studentIds = classStudents.map((cs) => cs.studentId);
|
||||
const window = this.getLessonAttendanceWindow(schedule, lessonDate);
|
||||
const rawRecords = await this.dingRawRepo.find({
|
||||
where: {
|
||||
attendanceDate: lessonDate,
|
||||
attendanceDate: Between(window.dateFrom, window.dateTo),
|
||||
matchedStudentId: In(studentIds),
|
||||
},
|
||||
});
|
||||
@@ -589,6 +668,31 @@ export class AttendanceService {
|
||||
});
|
||||
}
|
||||
|
||||
private toMinutes(time: string): number {
|
||||
const [hour, minute] = time.split(':').map(Number);
|
||||
return hour * 60 + minute;
|
||||
}
|
||||
|
||||
private getCourseClock(date: Date): { date: string; minutes: number } {
|
||||
const parts = Object.fromEntries(
|
||||
new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
||||
}).formatToParts(date).filter((part) => part.type !== 'literal').map((part) => [part.type, part.value]),
|
||||
);
|
||||
return {
|
||||
date: `${parts.year}-${parts.month}-${parts.day}`,
|
||||
minutes: Number(parts.hour) * 60 + Number(parts.minute),
|
||||
};
|
||||
}
|
||||
|
||||
private shiftDate(date: string, days: number): string {
|
||||
const shifted = new Date(`${date}T00:00:00.000Z`);
|
||||
shifted.setUTCDate(shifted.getUTCDate() + days);
|
||||
return shifted.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
private mapScheduleTimeToSession(startTime: string): string {
|
||||
const hour = parseInt(startTime.slice(0, 2), 10);
|
||||
if (hour < 8) return 'morning_reading';
|
||||
@@ -908,6 +1012,10 @@ export class AttendanceService {
|
||||
if (dto.status !== undefined) {
|
||||
record.status = dto.status;
|
||||
record.source = 'manual';
|
||||
record.punchTime = null;
|
||||
record.punchSource = null;
|
||||
record.punchDeviceName = null;
|
||||
record.punchDeviceId = null;
|
||||
}
|
||||
if (dto.remark !== undefined) {
|
||||
record.remark = dto.remark;
|
||||
@@ -933,6 +1041,10 @@ export class AttendanceService {
|
||||
if (dto.status !== undefined) {
|
||||
freshRecord.status = dto.status;
|
||||
freshRecord.source = 'manual';
|
||||
freshRecord.punchTime = null;
|
||||
freshRecord.punchSource = null;
|
||||
freshRecord.punchDeviceName = null;
|
||||
freshRecord.punchDeviceId = null;
|
||||
}
|
||||
if (dto.remark !== undefined) {
|
||||
freshRecord.remark = dto.remark;
|
||||
|
||||
@@ -68,8 +68,10 @@ describe('DingTalkService — attendance records', () => {
|
||||
userId: 'ding-1',
|
||||
workDate: Date.parse('2026-07-12T00:00:00+08:00'),
|
||||
userCheckTime: Date.parse('2026-07-12T21:05:00+08:00'),
|
||||
sourceType: 'USER',
|
||||
sourceType: 'ATM',
|
||||
checkType: 'OnDuty',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
timeResult: 'Normal',
|
||||
},
|
||||
],
|
||||
@@ -83,6 +85,13 @@ describe('DingTalkService — attendance records', () => {
|
||||
});
|
||||
|
||||
expect(record.workDate).toBe('2026-07-12');
|
||||
expect(record).toEqual(
|
||||
expect.objectContaining({
|
||||
checkType: 'OnDuty',
|
||||
sourceType: 'ATM',
|
||||
deviceName: '东门考勤机',
|
||||
deviceId: 'ATM-01',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
IsIn,
|
||||
ValidateNested,
|
||||
IsNotEmpty,
|
||||
ArrayNotEmpty,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
@@ -44,6 +47,7 @@ export class AttendanceRecordItem {
|
||||
|
||||
export class BatchCreateAttendanceDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => AttendanceRecordItem)
|
||||
records: AttendanceRecordItem[];
|
||||
@@ -96,11 +100,14 @@ export class QueryDingRawDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Type(() => Number)
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(200)
|
||||
@Type(() => Number)
|
||||
pageSize?: number;
|
||||
}
|
||||
@@ -139,11 +146,14 @@ export class QueryAttendanceRecordsDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Type(() => Number)
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(200)
|
||||
@Type(() => Number)
|
||||
pageSize?: number;
|
||||
}
|
||||
@@ -165,6 +175,22 @@ export class UpdateAttendanceRecordDto {
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
|
||||
export class AttendanceAlertsQueryDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(365)
|
||||
days?: number;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
threshold?: number;
|
||||
}
|
||||
|
||||
export class AttendanceReportQueryDto {
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService — super admin identity', () => {
|
||||
describe('AuthService — authentication boundaries', () => {
|
||||
it('marks the preset 超管 role as super admin in the JWT payload', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
@@ -22,8 +22,29 @@ describe('AuthService — super admin identity', () => {
|
||||
|
||||
await service.login({ username: 'admin', password: 'secret' }, '127.0.0.1');
|
||||
|
||||
expect(jwtService.sign).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ isSuperAdmin: true }),
|
||||
expect(jwtService.sign).toHaveBeenCalledWith(expect.objectContaining({ isSuperAdmin: true }));
|
||||
});
|
||||
it('rejects an archived user even when the password is valid', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 2,
|
||||
username: 'archived',
|
||||
passwordHash: await bcrypt.hash('secret', 4),
|
||||
isActive: true,
|
||||
isArchived: true,
|
||||
roles: [],
|
||||
}),
|
||||
save: jest.fn(),
|
||||
};
|
||||
const service = new AuthService(
|
||||
userRepo as never,
|
||||
{ sign: jest.fn() } as never,
|
||||
{ getUserPermissions: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.login({ username: 'archived', password: 'secret' }, '192.0.2.10'),
|
||||
).rejects.toThrow('账号已失效');
|
||||
expect(userRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,7 +38,9 @@ export class AuthService {
|
||||
this.recordFailedAttempt(attemptKey);
|
||||
throw new UnauthorizedException('用户名或密码错误');
|
||||
}
|
||||
if (!user.isActive) throw new UnauthorizedException('账号已被禁用,请联系管理员');
|
||||
if (!user.isActive || user.isArchived) {
|
||||
throw new UnauthorizedException('账号已失效,请联系管理员');
|
||||
}
|
||||
const valid = await bcrypt.compare(dto.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
this.recordFailedAttempt(attemptKey);
|
||||
|
||||
@@ -33,6 +33,23 @@ describe('JwtStrategy', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('recognizes the canonical super_admin role code even when the display name changes', async () => {
|
||||
const userRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({
|
||||
id: 1,
|
||||
username: 'admin',
|
||||
isActive: true,
|
||||
isArchived: false,
|
||||
roles: [{ name: '系统管理员', code: 'super_admin', status: 1, permissions: [] }],
|
||||
}),
|
||||
};
|
||||
const strategy = new JwtStrategy(config as never, userRepo as never);
|
||||
|
||||
await expect(strategy.validate({ sub: 1 })).resolves.toEqual(
|
||||
expect.objectContaining({ isSuperAdmin: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ id: 7, isActive: false, isArchived: false, roles: [] }],
|
||||
[{ id: 7, isActive: true, isArchived: true, roles: [] }],
|
||||
|
||||
@@ -47,7 +47,9 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
for (const role of user.roles ?? []) {
|
||||
if (role.status !== 1) continue;
|
||||
roles.push(role.name);
|
||||
if (role.name === '超管' || role.name === 'super_admin') isSuperAdmin = true;
|
||||
if (role.name === '超管' || role.name === 'super_admin' || role.code === 'super_admin') {
|
||||
isSuperAdmin = true;
|
||||
}
|
||||
for (const permission of role.permissions ?? []) permissions.add(permission.code);
|
||||
}
|
||||
|
||||
|
||||
@@ -34,20 +34,6 @@ export class BillsExportService {
|
||||
if (query.status) qb.andWhere('b.status = :status', { status: query.status });
|
||||
const bills = await qb.getMany();
|
||||
|
||||
// 查询涉及学生的"已缴未退"押金,用于导出押金抵扣字段
|
||||
const studentIds = Array.from(new Set(bills.map((b) => b.studentId)));
|
||||
const depMap = new Map<number, number>();
|
||||
if (studentIds.length > 0) {
|
||||
const deposits = await this.depositRepo
|
||||
.createQueryBuilder('d')
|
||||
.where('d.studentId IN (:...ids)', { ids: studentIds })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
.getMany();
|
||||
for (const d of deposits) {
|
||||
depMap.set(d.studentId, (depMap.get(d.studentId) || 0) + Number(d.amount || 0));
|
||||
}
|
||||
}
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = '恭学教育基地管理系统';
|
||||
|
||||
@@ -60,9 +46,8 @@ export class BillsExportService {
|
||||
{ header: '分摊费用', key: 'shared', width: 12 },
|
||||
{ header: '个人费用', key: 'personal', width: 12 },
|
||||
{ header: '总金额', key: 'total', width: 12 },
|
||||
{ header: '可用押金', key: 'deposit', width: 12 },
|
||||
{ header: '押金抵扣', key: 'depositApplied', width: 12 },
|
||||
{ header: '抵扣后应付', key: 'afterDeposit', width: 14 },
|
||||
{ header: '已扣余额', key: 'paidAmount', width: 12 },
|
||||
{ header: '待补缴', key: 'outstandingAmount', width: 12 },
|
||||
{ header: '状态', key: 'status', width: 10 },
|
||||
{ header: '生成时间', key: 'generatedAt', width: 20 },
|
||||
];
|
||||
@@ -71,15 +56,13 @@ export class BillsExportService {
|
||||
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
|
||||
|
||||
const statusMap: Record<string, string> = {
|
||||
draft: '草稿',
|
||||
confirmed: '已确认',
|
||||
unpaid: '待支付',
|
||||
partially_paid: '部分支付',
|
||||
paid: '已结清',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
for (const bill of bills) {
|
||||
const total = Number(bill.totalAmount || 0);
|
||||
const dep = Number((depMap.get(bill.studentId) || 0).toFixed(2));
|
||||
const applied = Number(Math.min(dep, total).toFixed(2));
|
||||
const after = Number(Math.max(0, total - applied).toFixed(2));
|
||||
ws.addRow({
|
||||
id: bill.id,
|
||||
studentName: (bill as any).student?.name || '-',
|
||||
@@ -87,9 +70,8 @@ export class BillsExportService {
|
||||
shared: Number(bill.sharedAmount),
|
||||
personal: Number(bill.personalAmount),
|
||||
total,
|
||||
deposit: dep,
|
||||
depositApplied: applied,
|
||||
afterDeposit: after,
|
||||
paidAmount: Number(bill.paidAmount || 0),
|
||||
outstandingAmount: Number(bill.outstandingAmount || 0),
|
||||
status: statusMap[bill.status] || bill.status,
|
||||
generatedAt: bill.generatedAt ? new Date(bill.generatedAt).toLocaleString('zh-CN') : '',
|
||||
});
|
||||
@@ -147,16 +129,9 @@ export class BillsExportService {
|
||||
return;
|
||||
}
|
||||
|
||||
// 查询该学生的可用押金(已缴未退)
|
||||
const deposits = await this.depositRepo
|
||||
.createQueryBuilder('d')
|
||||
.where('d.studentId = :sid', { sid: bill.studentId })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
.getMany();
|
||||
const availableDeposit = deposits.reduce((s, d) => s + Number(d.amount || 0), 0);
|
||||
const totalAmount = Number(bill.totalAmount || 0);
|
||||
const depositApplied = Math.min(availableDeposit, totalAmount);
|
||||
const amountAfterDeposit = Math.max(0, totalAmount - depositApplied);
|
||||
const paidAmount = Number(bill.paidAmount || 0);
|
||||
const outstandingAmount = Number(bill.outstandingAmount || 0);
|
||||
|
||||
const doc = new PDFDocument({ size: 'A4', margin: 50 });
|
||||
res.setHeader('Content-Type', 'application/pdf');
|
||||
@@ -191,9 +166,10 @@ export class BillsExportService {
|
||||
}
|
||||
|
||||
const statusMap: Record<string, string> = {
|
||||
draft: '草稿',
|
||||
confirmed: '已确认',
|
||||
unpaid: '待支付',
|
||||
partially_paid: '部分支付',
|
||||
paid: '已结清',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
|
||||
// 标题
|
||||
@@ -223,20 +199,8 @@ export class BillsExportService {
|
||||
.fillColor('#007AFF')
|
||||
.text(`应付总额: ¥${totalAmount.toFixed(2)}`);
|
||||
doc.moveDown(0.3);
|
||||
if (availableDeposit > 0) {
|
||||
doc
|
||||
.fontSize(11)
|
||||
.fillColor('#52C41A')
|
||||
.text(`可用押金: ¥${availableDeposit.toFixed(2)}`);
|
||||
doc
|
||||
.fontSize(11)
|
||||
.fillColor('#FA8C16')
|
||||
.text(`押金抵扣: -¥${depositApplied.toFixed(2)}`);
|
||||
doc
|
||||
.fontSize(14)
|
||||
.fillColor('#FF3B30')
|
||||
.text(`抵扣后应付: ¥${amountAfterDeposit.toFixed(2)}`);
|
||||
}
|
||||
doc.fontSize(11).fillColor('#389E0D').text(`已扣余额: ¥${paidAmount.toFixed(2)}`);
|
||||
doc.fontSize(14).fillColor(outstandingAmount > 0 ? '#FF3B30' : '#389E0D').text(`待补缴: ¥${outstandingAmount.toFixed(2)}`);
|
||||
doc.moveDown(1);
|
||||
|
||||
// 明细表格
|
||||
|
||||
77
apps/server/src/bills/bills.boundaries.spec.ts
Normal file
77
apps/server/src/bills/bills.boundaries.spec.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { BillsService } from './bills.service';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
|
||||
function queryBuilder() {
|
||||
return {
|
||||
update: jest.fn().mockReturnThis(),
|
||||
set: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
execute: jest.fn().mockResolvedValue({ affected: 1 }),
|
||||
};
|
||||
}
|
||||
|
||||
function createService(bills: Partial<Bill>[] = []) {
|
||||
const billRepo = {
|
||||
find: jest.fn().mockResolvedValue(bills),
|
||||
findOne: jest.fn().mockResolvedValue(bills[0] ?? null),
|
||||
save: jest.fn(async (value) => value),
|
||||
createQueryBuilder: jest.fn(() => queryBuilder()),
|
||||
};
|
||||
const manager = {
|
||||
delete: jest.fn(),
|
||||
update: jest.fn(),
|
||||
};
|
||||
const dataSource = { transaction: jest.fn(async (callback) => callback(manager)) };
|
||||
const service = new BillsService(
|
||||
billRepo as any,
|
||||
{ delete: jest.fn() } as any,
|
||||
{} as any,
|
||||
{ update: jest.fn() } as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
dataSource as any,
|
||||
{} as any,
|
||||
);
|
||||
return { service, billRepo, dataSource, manager };
|
||||
}
|
||||
|
||||
describe('BillsService state and batch boundaries', () => {
|
||||
it('rejects an empty batch status update', async () => {
|
||||
const { service, billRepo } = createService();
|
||||
await expect(service.batchUpdateStatus([], 'paid')).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(billRepo.find).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a batch status update when some ids do not exist', async () => {
|
||||
const { service, billRepo } = createService([{ id: 1, paidAmount: 0, outstandingAmount: 10 }]);
|
||||
await expect(service.batchUpdateStatus([1, 2], 'unpaid')).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(billRepo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects marking a partially paid bill unpaid', async () => {
|
||||
const { service, billRepo } = createService([{ id: 1, paidAmount: 10, outstandingAmount: 90, status: 'partially_paid' }]);
|
||||
await expect(service.updateStatus(1, { status: 'unpaid' })).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(billRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an empty batch delete', async () => {
|
||||
const { service, dataSource } = createService();
|
||||
await expect(service.batchRemove([])).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(dataSource.transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a batch delete when some ids do not exist', async () => {
|
||||
const { service, dataSource } = createService([{ id: 1, paidAmount: 0, status: 'unpaid' }]);
|
||||
await expect(service.batchRemove([1, 2])).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(dataSource.transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('deletes a bill and its links in one transaction', async () => {
|
||||
const { service, dataSource, manager } = createService([{ id: 1, paidAmount: 0, status: 'unpaid' }]);
|
||||
await expect(service.remove(1)).resolves.toEqual({ message: '账单已删除' });
|
||||
expect(dataSource.transaction).toHaveBeenCalledTimes(1);
|
||||
expect(manager.delete).toHaveBeenCalledTimes(2);
|
||||
expect(manager.update).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Request,
|
||||
Res,
|
||||
Req,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, In } from 'typeorm';
|
||||
@@ -20,7 +21,7 @@ import { NotificationType } from '../entities/notification.entity';
|
||||
import { Student } from '../entities/student.entity';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillsExportService } from './bills-export.service';
|
||||
import { GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
import { CancelBillDto, GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
@@ -49,7 +50,7 @@ export class BillsController {
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '生成账单',
|
||||
detail: `周期 ${dto.periodStart}~${dto.periodEnd}, 生成 ${result.count} 条`,
|
||||
detail: `周期 ${result.periodStart}~${result.periodEnd}, 生成 ${result.count} 条`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
@@ -62,7 +63,7 @@ export class BillsController {
|
||||
recipientIds: [student.userId],
|
||||
type: NotificationType.BILL_GENERATED,
|
||||
title: '新账单',
|
||||
content: `您有一笔新账单,金额: ¥${bill.totalAmount}, 周期: ${dto.periodStart}~${dto.periodEnd}`,
|
||||
content: `您有一笔新账单,金额: ¥${bill.totalAmount}, 周期: ${result.periodStart}~${result.periodEnd}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -75,38 +76,38 @@ export class BillsController {
|
||||
findAll(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('studentId') studentId?: string,
|
||||
@Query('studentId', new ParseIntPipe({ optional: true })) studentId?: number,
|
||||
@Query('status') status?: string,
|
||||
@Query('expenseType') expenseType?: string,
|
||||
) {
|
||||
return this.service.findAll({
|
||||
periodStart, periodEnd,
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
studentId,
|
||||
status, expenseType,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('bill:view')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.service.findOne(+id);
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.service.findOne(id);
|
||||
}
|
||||
|
||||
@Put(':id/status')
|
||||
@RequirePermission('bill:confirm')
|
||||
async updateStatus(
|
||||
@Param('id') id: string,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateBillStatusDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.updateStatus(+id, dto);
|
||||
const result = await this.service.updateStatus(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '确认账单',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -158,17 +159,36 @@ export class BillsController {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post(':id/cancel')
|
||||
@RequirePermission('bill:delete')
|
||||
async cancel(@Param('id', ParseIntPipe) id: number, @Body() dto: CancelBillDto, @Request() req: any) {
|
||||
const result = await this.service.cancel(id, dto, req.user?.id);
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '取消账单并冲正',
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
detail: dto.reason,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('bill:delete')
|
||||
async remove(@Param('id') id: string, @Request() req: any) {
|
||||
async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.remove(+id);
|
||||
const result = await this.service.remove(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '账单管理',
|
||||
action: '删除账单',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -198,7 +218,7 @@ export class BillsController {
|
||||
async exportExcel(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('studentId') studentId?: string,
|
||||
@Query('studentId', new ParseIntPipe({ optional: true })) studentId?: number,
|
||||
@Query('status') status?: string,
|
||||
@Res() res?: Response,
|
||||
@Req() req?: any,
|
||||
@@ -217,7 +237,7 @@ export class BillsController {
|
||||
{
|
||||
periodStart,
|
||||
periodEnd,
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
studentId,
|
||||
status,
|
||||
},
|
||||
res!,
|
||||
@@ -226,18 +246,18 @@ export class BillsController {
|
||||
|
||||
@Get('export/pdf/:id')
|
||||
@RequirePermission('bill:export-pdf')
|
||||
async exportPdf(@Param('id') id: string, @Res() res: Response, @Req() req: any) {
|
||||
async exportPdf(@Param('id', ParseIntPipe) id: number, @Res() res: Response, @Req() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
await this.logService.log({
|
||||
userId: req?.user?.id,
|
||||
username: req?.user?.username,
|
||||
module: '账单管理',
|
||||
action: '导出账单',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'bill',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return this.exportService.exportStudentPdf(+id, res);
|
||||
return this.exportService.exportStudentPdf(id, res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { WalletsModule } from '../wallets/wallets.module';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillItem } from '../entities/bill-item.entity';
|
||||
@@ -7,8 +8,8 @@ import { RoomExpense } from '../entities/room-expense.entity';
|
||||
import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { Student } from '../entities/student.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { BillsService } from './bills.service';
|
||||
import { BillsExportService } from './bills-export.service';
|
||||
import { BillsController } from './bills.controller';
|
||||
@@ -22,10 +23,11 @@ import { BillsController } from './bills.controller';
|
||||
PersonalExpense,
|
||||
Occupancy,
|
||||
Room,
|
||||
Deposit,
|
||||
Student,
|
||||
Deposit,
|
||||
]),
|
||||
NotificationsModule,
|
||||
WalletsModule,
|
||||
],
|
||||
controllers: [BillsController],
|
||||
providers: [BillsService, BillsExportService],
|
||||
|
||||
@@ -9,6 +9,7 @@ import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { WalletsService } from '../wallets/wallets.service';
|
||||
|
||||
type MockRepository<T> = Partial<Record<keyof Repository<T>, jest.Mock>>;
|
||||
|
||||
@@ -56,7 +57,23 @@ describe('BillsService — generateBills', () => {
|
||||
occRepo = mockRepo<Occupancy>();
|
||||
roomRepo = mockRepo<Room>();
|
||||
depositRepo = mockRepo<Deposit>();
|
||||
dataSource = { transaction: jest.fn(), query: jest.fn().mockResolvedValue([]) };
|
||||
let nextBillId = 0;
|
||||
dataSource = {
|
||||
transaction: jest.fn(async (callback) => callback({
|
||||
create: (_entity: unknown, value: unknown) => value,
|
||||
save: jest.fn(async (value: any) => {
|
||||
if ('totalAmount' in value && 'studentId' in value) {
|
||||
const saved = { id: ++nextBillId, ...value };
|
||||
await (billRepo.save as jest.Mock)(saved);
|
||||
return saved;
|
||||
}
|
||||
await (itemRepo.save as jest.Mock)(value);
|
||||
return { id: value.id || 1, ...value };
|
||||
}),
|
||||
createQueryBuilder: jest.fn(() => ({ update: jest.fn().mockReturnThis(), set: jest.fn().mockReturnThis(), where: jest.fn().mockReturnThis(), execute: jest.fn().mockResolvedValue({ affected: 1 }) })),
|
||||
})),
|
||||
query: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
@@ -69,6 +86,7 @@ describe('BillsService — generateBills', () => {
|
||||
{ provide: getRepositoryToken(Room), useValue: roomRepo },
|
||||
{ provide: getRepositoryToken(Deposit), useValue: depositRepo },
|
||||
{ provide: DataSource, useValue: dataSource },
|
||||
{ provide: WalletsService, useValue: { debitBill: jest.fn(async (_manager, bill) => bill), refundBill: jest.fn() } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
@@ -166,6 +184,43 @@ describe('BillsService — generateBills', () => {
|
||||
).toBeCloseTo(300, 0);
|
||||
});
|
||||
|
||||
it('includes room expenses whose periods are inside the generated bill period', async () => {
|
||||
const qb = mockQueryBuilder<RoomExpense>([
|
||||
{
|
||||
id: 1, roomId: 1, expenseType: 'water',
|
||||
amount: '300' as unknown as number, periodStart: '2026-07-01', periodEnd: '2026-07-31',
|
||||
} as RoomExpense,
|
||||
]);
|
||||
(roomExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(qb);
|
||||
|
||||
(occRepo.createQueryBuilder as jest.Mock).mockReturnValue(
|
||||
mockQueryBuilder<Occupancy>([
|
||||
{
|
||||
id: 1, studentId: 10, roomId: 1,
|
||||
billingStartDate: '2026-07-01', billingEndDate: null as unknown as string,
|
||||
stayType: 'short', room: undefined,
|
||||
} as Occupancy,
|
||||
]),
|
||||
);
|
||||
|
||||
(personalExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(
|
||||
mockQueryBuilder<PersonalExpense>([]),
|
||||
);
|
||||
|
||||
const result = await service.generateBills({
|
||||
periodStart: '2026-06-29',
|
||||
periodEnd: '2026-07-31',
|
||||
});
|
||||
|
||||
expect(result.count).toBe(1);
|
||||
expect(qb.where).toHaveBeenCalledWith(
|
||||
'e.periodStart >= :periodStart AND e.periodEnd <= :periodEnd',
|
||||
{ periodStart: '2026-06-29', periodEnd: '2026-07-31' },
|
||||
);
|
||||
const savedCalls = (billRepo.save as jest.Mock).mock.calls as Array<[Record<string, unknown>]>;
|
||||
expect(Number(savedCalls[0][0].sharedAmount)).toBeCloseTo(300, 0);
|
||||
});
|
||||
|
||||
it('mixed → long-term get individual bills, short-term share expenses', async () => {
|
||||
// Room 1: two expenses
|
||||
(roomExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(
|
||||
@@ -489,3 +544,52 @@ describe('BillsService — generateBills', () => {
|
||||
expect(result.count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BillsService — allocation rounding boundary', () => {
|
||||
it('keeps allocated cents equal to the original expense total', async () => {
|
||||
const billRepo = mockRepo<Bill>();
|
||||
const itemRepo = mockRepo<BillItem>();
|
||||
const roomExpRepo = mockRepo<RoomExpense>();
|
||||
const personalExpRepo = mockRepo<PersonalExpense>();
|
||||
const occRepo = mockRepo<Occupancy>();
|
||||
const roomRepo = mockRepo<Room>();
|
||||
let nextBillId = 0;
|
||||
const dataSource = {
|
||||
query: jest.fn().mockResolvedValue([]),
|
||||
transaction: jest.fn(async (callback) => callback({
|
||||
create: (_entity: unknown, value: any) => value,
|
||||
save: jest.fn(async (value: any) => ({ id: value.id || ++nextBillId, ...value })),
|
||||
createQueryBuilder: jest.fn(() => ({
|
||||
update: jest.fn().mockReturnThis(),
|
||||
set: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
execute: jest.fn().mockResolvedValue({ affected: 1 }),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
const service = new BillsService(
|
||||
billRepo as any,
|
||||
itemRepo as any,
|
||||
roomExpRepo as any,
|
||||
personalExpRepo as any,
|
||||
occRepo as any,
|
||||
roomRepo as any,
|
||||
dataSource as any,
|
||||
{ debitBill: jest.fn(async (_manager, bill) => bill) } as any,
|
||||
);
|
||||
(roomExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(mockQueryBuilder<RoomExpense>([
|
||||
{ id: 1, roomId: 1, expenseType: 'water', amount: 100, periodStart: '2026-06-01', periodEnd: '2026-06-30' } as RoomExpense,
|
||||
]));
|
||||
(occRepo.createQueryBuilder as jest.Mock).mockReturnValue(mockQueryBuilder<Occupancy>([
|
||||
{ id: 1, roomId: 1, studentId: 1, stayType: 'short', billingStartDate: '2026-06-01', billingEndDate: '2026-06-01' } as Occupancy,
|
||||
{ id: 2, roomId: 1, studentId: 2, stayType: 'short', billingStartDate: '2026-06-01', billingEndDate: '2026-06-01' } as Occupancy,
|
||||
{ id: 3, roomId: 1, studentId: 3, stayType: 'short', billingStartDate: '2026-06-01', billingEndDate: '2026-06-01' } as Occupancy,
|
||||
]));
|
||||
(personalExpRepo.createQueryBuilder as jest.Mock).mockReturnValue(mockQueryBuilder<PersonalExpense>([]));
|
||||
|
||||
const result = await service.generateBills({ periodStart: '2026-06-01', periodEnd: '2026-06-30' } as any);
|
||||
|
||||
expect(result.bills.map((bill) => Number(bill.totalAmount))).toEqual([33.33, 33.33, 33.34]);
|
||||
expect(result.bills.reduce((sum, bill) => sum + Number(bill.totalAmount), 0)).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, In, DataSource } from 'typeorm';
|
||||
import { Repository, In, DataSource, EntityManager } from 'typeorm';
|
||||
import { Bill } from '../entities/bill.entity';
|
||||
import { BillItem } from '../entities/bill-item.entity';
|
||||
import { RoomExpense } from '../entities/room-expense.entity';
|
||||
import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
import { Occupancy } from '../entities/occupancy.entity';
|
||||
import { Room } from '../entities/room.entity';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
import { GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
import { StudentWallet } from '../entities/student-wallet.entity';
|
||||
import { CancelBillDto, GenerateBillsDto, UpdateBillStatusDto } from './dto/bill.dto';
|
||||
import { WalletsService } from '../wallets/wallets.service';
|
||||
|
||||
|
||||
@Injectable()
|
||||
@@ -20,24 +21,37 @@ export class BillsService {
|
||||
@InjectRepository(PersonalExpense) private personalExpRepo: Repository<PersonalExpense>,
|
||||
@InjectRepository(Occupancy) private occRepo: Repository<Occupancy>,
|
||||
@InjectRepository(Room) private roomRepo: Repository<Room>,
|
||||
@InjectRepository(Deposit) private depositRepo: Repository<Deposit>,
|
||||
private dataSource: DataSource,
|
||||
private walletsService: WalletsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 核心计费引擎:按"人天数"加权分摊
|
||||
*/
|
||||
async generateBills(dto: GenerateBillsDto) {
|
||||
const { periodStart, periodEnd } = dto;
|
||||
const pStart = new Date(periodStart);
|
||||
const pEnd = new Date(periodEnd);
|
||||
const { periodStart, periodEnd } = dto.billingMonth
|
||||
? this.resolveBillingPeriod(dto.billingMonth)
|
||||
: { periodStart: dto.periodStart!, periodEnd: dto.periodEnd! };
|
||||
if (!this.isValidDate(periodStart) || !this.isValidDate(periodEnd) || periodEnd < periodStart) {
|
||||
throw new BadRequestException('账单周期无效,结束日期不能早于开始日期');
|
||||
}
|
||||
const pStart = new Date(`${periodStart}T00:00:00Z`);
|
||||
const pEnd = new Date(`${periodEnd}T00:00:00Z`);
|
||||
|
||||
// 删除该周期已有的草稿账单
|
||||
const existingDrafts = await this.billRepo.find({
|
||||
where: { periodStart, periodEnd, status: 'draft' },
|
||||
});
|
||||
const existingBills = await this.billRepo.find({ where: { periodStart, periodEnd } });
|
||||
if (existingBills.length > 0) {
|
||||
throw new BadRequestException(`${dto.billingMonth || `${periodStart}~${periodEnd}`} 账单已生成,不能重复生成`);
|
||||
}
|
||||
|
||||
const existingDrafts: Bill[] = [];
|
||||
if (existingDrafts.length > 0) {
|
||||
const draftIds = existingDrafts.map((b) => b.id);
|
||||
await this.personalExpRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ billId: null })
|
||||
.where('billId IN (:...ids)', { ids: draftIds })
|
||||
.execute();
|
||||
await this.itemRepo
|
||||
.createQueryBuilder()
|
||||
.delete()
|
||||
@@ -53,7 +67,7 @@ export class BillsService {
|
||||
// 获取所有有费用的宿舍
|
||||
const roomExpenses = await this.roomExpRepo
|
||||
.createQueryBuilder('e')
|
||||
.where('e.periodStart = :periodStart AND e.periodEnd = :periodEnd', {
|
||||
.where('e.periodStart >= :periodStart AND e.periodEnd <= :periodEnd', {
|
||||
periodStart,
|
||||
periodEnd,
|
||||
})
|
||||
@@ -128,11 +142,16 @@ export class BillsService {
|
||||
|
||||
if (totalDays === 0) continue;
|
||||
|
||||
// 对每项费用进行分摊
|
||||
// 对每项费用进行分摊;最后一人承接舍入尾差,保证分摊合计与原费用一致。
|
||||
for (const expense of expenses) {
|
||||
for (const sd of studentDays) {
|
||||
if (sd.days === 0) continue;
|
||||
const amount = Number(((sd.days / totalDays) * Number(expense.amount)).toFixed(2));
|
||||
const eligibleDays = studentDays.filter((sd) => sd.days > 0);
|
||||
const expenseTotal = Number(Number(expense.amount).toFixed(2));
|
||||
let allocated = 0;
|
||||
for (const [index, sd] of eligibleDays.entries()) {
|
||||
const amount = index === eligibleDays.length - 1
|
||||
? Number((expenseTotal - allocated).toFixed(2))
|
||||
: Number(((sd.days / totalDays) * expenseTotal).toFixed(2));
|
||||
allocated = Number((allocated + amount).toFixed(2));
|
||||
if (!studentBillData.has(sd.studentId)) {
|
||||
studentBillData.set(sd.studentId, { shared: 0, items: [] });
|
||||
}
|
||||
@@ -158,6 +177,7 @@ export class BillsService {
|
||||
periodStart,
|
||||
periodEnd,
|
||||
})
|
||||
.andWhere('pe.billId IS NULL')
|
||||
.getMany();
|
||||
|
||||
const personalMap = new Map<number, number>();
|
||||
@@ -177,38 +197,113 @@ export class BillsService {
|
||||
}
|
||||
|
||||
|
||||
// 合并所有涉及的学生
|
||||
// 合并所有涉及的学生,并在同一个事务中生成整批账单,避免中途失败留下半批数据。
|
||||
const allStudentIds = new Set([...studentBillData.keys(), ...personalMap.keys()]);
|
||||
// 生成账单
|
||||
const bills: Bill[] = [];
|
||||
for (const studentId of allStudentIds) {
|
||||
const shared = studentBillData.get(studentId)?.shared || 0;
|
||||
const personal = personalMap.get(studentId) || 0;
|
||||
const total = Number((shared + personal).toFixed(2));
|
||||
|
||||
const bill = this.billRepo.create({
|
||||
studentId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
sharedAmount: Number(shared.toFixed(2)),
|
||||
personalAmount: personal,
|
||||
totalAmount: total,
|
||||
status: 'draft',
|
||||
});
|
||||
const savedBill = await this.billRepo.save(bill);
|
||||
|
||||
// 保存明细
|
||||
const items = [
|
||||
...(studentBillData.get(studentId)?.items || []),
|
||||
...(personalItems.get(studentId) || []),
|
||||
];
|
||||
for (const item of items) {
|
||||
await this.itemRepo.save(this.itemRepo.create({ ...item, billId: savedBill.id }));
|
||||
const bills = await this.dataSource.transaction(async (manager) => {
|
||||
const generated: Bill[] = [];
|
||||
for (const studentId of allStudentIds) {
|
||||
const shared = studentBillData.get(studentId)?.shared || 0;
|
||||
const personal = personalMap.get(studentId) || 0;
|
||||
const total = Number((shared + personal).toFixed(2));
|
||||
let bill = await manager.save(
|
||||
manager.create(Bill, {
|
||||
studentId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
sharedAmount: Number(shared.toFixed(2)),
|
||||
personalAmount: personal,
|
||||
totalAmount: total,
|
||||
source: 'batch',
|
||||
paidAmount: 0,
|
||||
outstandingAmount: total,
|
||||
status: 'unpaid',
|
||||
}),
|
||||
);
|
||||
const items = [
|
||||
...(studentBillData.get(studentId)?.items || []),
|
||||
...(personalItems.get(studentId) || []),
|
||||
];
|
||||
for (const item of items) {
|
||||
await manager.save(manager.create(BillItem, { ...item, billId: bill.id }));
|
||||
}
|
||||
const includedPersonal = personalExps.filter((expense) => expense.studentId === studentId);
|
||||
if (includedPersonal.length) {
|
||||
await manager
|
||||
.createQueryBuilder()
|
||||
.update(PersonalExpense)
|
||||
.set({ billId: bill.id })
|
||||
.where('id IN (:...ids)', { ids: includedPersonal.map((expense) => expense.id) })
|
||||
.execute();
|
||||
}
|
||||
bill = await this.walletsService.debitBill(manager, bill);
|
||||
generated.push(bill);
|
||||
}
|
||||
bills.push(savedBill);
|
||||
}
|
||||
return generated;
|
||||
});
|
||||
|
||||
return { message: `成功生成 ${bills.length} 条账单`, count: bills.length, bills };
|
||||
return { message: `成功生成 ${bills.length} 条账单`, count: bills.length, bills, periodStart, periodEnd };
|
||||
}
|
||||
|
||||
private isValidDate(value: string) {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value || '')) return false;
|
||||
const date = new Date(`${value}T00:00:00Z`);
|
||||
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
|
||||
private resolveBillingPeriod(billingMonth: string) {
|
||||
const matched = /^(\d{4})-(\d{2})$/.exec(billingMonth || '');
|
||||
if (!matched) throw new BadRequestException('账单月份格式错误,请使用 YYYY-MM');
|
||||
const year = Number(matched[1]);
|
||||
const month = Number(matched[2]);
|
||||
if (month < 1 || month > 12) throw new BadRequestException('账单月份格式错误,请使用 YYYY-MM');
|
||||
const targetMonthStart = new Date(year, month - 1, 1);
|
||||
const currentMonthStart = new Date();
|
||||
currentMonthStart.setDate(1);
|
||||
currentMonthStart.setHours(0, 0, 0, 0);
|
||||
if (targetMonthStart >= currentMonthStart) throw new BadRequestException('只能生成已结束月份的账单');
|
||||
const targetMonthEnd = new Date(year, month, 0);
|
||||
const pad = (value: number) => String(value).padStart(2, '0');
|
||||
return { periodStart: `${year}-${pad(month)}-01`, periodEnd: `${year}-${pad(month)}-${pad(targetMonthEnd.getDate())}` };
|
||||
}
|
||||
|
||||
async createImmediatePersonalBill(
|
||||
expense: PersonalExpense,
|
||||
periodStart: string,
|
||||
periodEnd: string,
|
||||
recordedBy?: number,
|
||||
) {
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
let bill = await manager.save(
|
||||
manager.create(Bill, {
|
||||
studentId: expense.studentId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
sharedAmount: 0,
|
||||
personalAmount: Number(expense.amount),
|
||||
totalAmount: Number(expense.amount),
|
||||
source: 'student_utility',
|
||||
paidAmount: 0,
|
||||
outstandingAmount: Number(expense.amount),
|
||||
status: 'unpaid',
|
||||
}),
|
||||
);
|
||||
await manager.save(
|
||||
manager.create(BillItem, {
|
||||
billId: bill.id,
|
||||
roomId: expense.roomId,
|
||||
expenseType: expense.expenseType,
|
||||
description: expense.description || (expense.expenseType === 'water' ? '学生水费' : '学生电费'),
|
||||
days: 0,
|
||||
totalRoomDays: 0,
|
||||
roomTotalAmount: expense.amount,
|
||||
studentAmount: expense.amount,
|
||||
}),
|
||||
);
|
||||
expense.billId = bill.id;
|
||||
await manager.save(expense);
|
||||
bill = await this.walletsService.debitBill(manager, bill, recordedBy);
|
||||
return bill;
|
||||
});
|
||||
}
|
||||
|
||||
async findAll(query?: {
|
||||
@@ -240,70 +335,98 @@ export class BillsService {
|
||||
return withDeposit;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给账单挂上"押金联动"信息:
|
||||
* - availableDeposit: 当前学生处于已缴未退状态(paid)的押金总额
|
||||
* - depositApplied: 本张账单可从押金抵扣的金额(min(押金, 应付总额))
|
||||
* - amountAfterDeposit: 抵扣押金后学生需另外支付的金额
|
||||
*/
|
||||
/** 查询时附加钱包余额和实际支付数据。 */
|
||||
private async attachDepositInfo(bills: Bill[]): Promise<any[]> {
|
||||
if (!bills || bills.length === 0) return bills;
|
||||
const studentIds = Array.from(new Set(bills.map((b) => b.studentId)));
|
||||
if (studentIds.length === 0) return bills;
|
||||
const deposits = await this.depositRepo
|
||||
.createQueryBuilder('d')
|
||||
.where('d.studentId IN (:...ids)', { ids: studentIds })
|
||||
.andWhere('d.status = :status', { status: 'paid' })
|
||||
if (!bills?.length) return bills;
|
||||
const studentIds = Array.from(new Set(bills.map((bill) => bill.studentId)));
|
||||
const wallets = await this.dataSource
|
||||
.getRepository(StudentWallet)
|
||||
.createQueryBuilder('wallet')
|
||||
.where('wallet.studentId IN (:...ids)', { ids: studentIds })
|
||||
.getMany();
|
||||
const depMap = new Map<number, number>();
|
||||
for (const d of deposits) {
|
||||
depMap.set(d.studentId, (depMap.get(d.studentId) || 0) + Number(d.amount || 0));
|
||||
}
|
||||
return bills.map((b) => {
|
||||
const total = Number(b.totalAmount || 0);
|
||||
const available = Number((depMap.get(b.studentId) || 0).toFixed(2));
|
||||
const applied = Number(Math.min(available, total).toFixed(2));
|
||||
const afterDeposit = Number(Math.max(0, total - applied).toFixed(2));
|
||||
return Object.assign({}, b, {
|
||||
availableDeposit: available,
|
||||
depositApplied: applied,
|
||||
amountAfterDeposit: afterDeposit,
|
||||
});
|
||||
});
|
||||
const balanceMap = new Map(wallets.map((wallet: any) => [wallet.studentId, Number(wallet.balance || 0)]));
|
||||
return bills.map((bill) => ({
|
||||
...bill,
|
||||
walletBalance: Number((balanceMap.get(bill.studentId) || 0).toFixed(2)),
|
||||
paidAmount: Number(bill.paidAmount || 0),
|
||||
outstandingAmount: Number(bill.outstandingAmount || 0),
|
||||
}));
|
||||
}
|
||||
|
||||
async updateStatus(id: number, dto: UpdateBillStatusDto) {
|
||||
const bill = await this.billRepo.findOne({ where: { id } });
|
||||
if (!bill) throw new NotFoundException('账单不存在');
|
||||
this.assertStatusMatchesAmounts(bill, dto.status);
|
||||
bill.status = dto.status;
|
||||
return this.billRepo.save(bill);
|
||||
}
|
||||
|
||||
async batchUpdateStatus(ids: number[], status: string) {
|
||||
const uniqueIds = [...new Set(ids || [])];
|
||||
if (uniqueIds.length === 0) throw new BadRequestException('请选择要更新的账单');
|
||||
if (!['unpaid', 'partially_paid', 'paid'].includes(status)) throw new BadRequestException('账单状态无效');
|
||||
const bills = await this.billRepo.find({ where: { id: In(uniqueIds) } });
|
||||
if (bills.length !== uniqueIds.length) throw new NotFoundException('部分账单不存在');
|
||||
for (const bill of bills) this.assertStatusMatchesAmounts(bill, status);
|
||||
await this.billRepo
|
||||
.createQueryBuilder()
|
||||
.update()
|
||||
.set({ status })
|
||||
.where('id IN (:...ids)', { ids })
|
||||
.where('id IN (:...ids)', { ids: uniqueIds })
|
||||
.execute();
|
||||
return { message: `成功更新 ${ids.length} 条账单状态` };
|
||||
return { message: `成功更新 ${uniqueIds.length} 条账单状态` };
|
||||
}
|
||||
|
||||
async cancel(id: number, dto: CancelBillDto, recordedBy?: number) {
|
||||
const reason = dto.reason?.trim();
|
||||
if (!reason) throw new BadRequestException('取消原因不能为空');
|
||||
return this.dataSource.transaction(async (manager) => {
|
||||
const bill = await manager.findOne(Bill, { where: { id } });
|
||||
if (!bill) throw new NotFoundException('账单不存在');
|
||||
if (bill.status === 'cancelled') throw new BadRequestException('账单已经取消');
|
||||
await manager.update(PersonalExpense, { billId: id }, { billId: null });
|
||||
return this.walletsService.refundBill(manager, bill, reason, recordedBy);
|
||||
});
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
const exists = await this.billRepo.findOne({ where: { id } });
|
||||
if (!exists) throw new NotFoundException('账单不存在');
|
||||
await this.itemRepo.delete({ billId: id });
|
||||
await this.billRepo.delete(id);
|
||||
if (Number(exists.paidAmount) > 0 || exists.status === 'cancelled') {
|
||||
throw new BadRequestException('已发生资金流水的账单不能删除,请使用取消账单');
|
||||
}
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await manager.delete(BillItem, { billId: id });
|
||||
await manager.update(PersonalExpense, { billId: id }, { billId: null });
|
||||
await manager.delete(Bill, id);
|
||||
});
|
||||
return { message: '账单已删除' };
|
||||
}
|
||||
|
||||
async batchRemove(ids: number[]) {
|
||||
await this.itemRepo
|
||||
.createQueryBuilder()
|
||||
.delete()
|
||||
.where('billId IN (:...ids)', { ids })
|
||||
.execute();
|
||||
await this.billRepo.createQueryBuilder().delete().where('id IN (:...ids)', { ids }).execute();
|
||||
return { message: `成功删除 ${ids.length} 条账单` };
|
||||
const uniqueIds = [...new Set(ids || [])];
|
||||
if (uniqueIds.length === 0) throw new BadRequestException('请选择要删除的账单');
|
||||
const bills = await this.billRepo.find({ where: { id: In(uniqueIds) } });
|
||||
if (bills.length !== uniqueIds.length) throw new NotFoundException('部分账单不存在');
|
||||
if (bills.some((bill) => Number(bill.paidAmount) > 0 || bill.status === 'cancelled')) {
|
||||
throw new BadRequestException('选中账单包含资金流水,不能批量删除');
|
||||
}
|
||||
await this.dataSource.transaction(async (manager) => {
|
||||
await manager.delete(BillItem, { billId: In(uniqueIds) });
|
||||
await manager.update(PersonalExpense, { billId: In(uniqueIds) }, { billId: null });
|
||||
await manager.delete(Bill, uniqueIds);
|
||||
});
|
||||
return { message: `成功删除 ${uniqueIds.length} 条账单` };
|
||||
}
|
||||
|
||||
private assertStatusMatchesAmounts(bill: Bill, status: string) {
|
||||
const paid = Number(bill.paidAmount || 0);
|
||||
const outstanding = Number(bill.outstandingAmount || 0);
|
||||
const matches = status === 'paid'
|
||||
? outstanding <= 0
|
||||
: status === 'partially_paid'
|
||||
? paid > 0 && outstanding > 0
|
||||
: status === 'unpaid' && paid <= 0 && outstanding > 0;
|
||||
if (!matches) throw new BadRequestException('账单状态必须与实付及未付金额一致');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,35 @@
|
||||
import { IsString, IsOptional } from 'class-validator';
|
||||
import { ArrayNotEmpty, IsArray, IsIn, IsInt, IsNotEmpty, IsOptional, IsString, Matches, MaxLength } from 'class-validator';
|
||||
|
||||
export class GenerateBillsDto {
|
||||
@IsString()
|
||||
periodStart: string; // YYYY-MM-DD
|
||||
@Matches(/^\d{4}-\d{2}$/)
|
||||
billingMonth: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
periodEnd: string; // YYYY-MM-DD
|
||||
periodStart?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
periodEnd?: string;
|
||||
}
|
||||
|
||||
export class UpdateBillStatusDto {
|
||||
@IsString()
|
||||
status: 'draft' | 'confirmed' | 'paid';
|
||||
@IsIn(['unpaid', 'partially_paid', 'paid'])
|
||||
status: 'unpaid' | 'partially_paid' | 'paid';
|
||||
}
|
||||
|
||||
export class CancelBillDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Matches(/\S/)
|
||||
@MaxLength(300)
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export class BatchUpdateBillStatusDto extends UpdateBillStatusDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsInt({ each: true })
|
||||
ids: number[];
|
||||
}
|
||||
|
||||
69
apps/server/src/classes/classes.boundaries.spec.ts
Normal file
69
apps/server/src/classes/classes.boundaries.spec.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { ClassesService } from './classes.service';
|
||||
|
||||
function createService(classRepo: Record<string, jest.Mock>, classTeacherRepo = {}) {
|
||||
return new ClassesService(
|
||||
classRepo as never,
|
||||
{} as never,
|
||||
classTeacherRepo as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ClassesService — archive and teacher boundaries', () => {
|
||||
it('rejects repeated archive and restore operations', async () => {
|
||||
await expect(
|
||||
createService({ findOne: jest.fn().mockResolvedValue({ isArchived: true }) }).archive(1),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
createService({ findOne: jest.fn().mockResolvedValue({ isArchived: false }) }).restore(1),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects assigning a teacher to a missing class', async () => {
|
||||
const classTeacherRepo = { findOne: jest.fn(), create: jest.fn(), save: jest.fn() };
|
||||
await expect(
|
||||
createService({ findOne: jest.fn().mockResolvedValue(null) }, classTeacherRepo).addTeacher(
|
||||
9,
|
||||
{
|
||||
userId: 2,
|
||||
roleType: 'head_teacher',
|
||||
},
|
||||
),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(classTeacherRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects duplicate teacher roles', async () => {
|
||||
const classTeacherRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({ id: 3 }),
|
||||
create: jest.fn(),
|
||||
save: jest.fn(),
|
||||
};
|
||||
await expect(
|
||||
createService(
|
||||
{ findOne: jest.fn().mockResolvedValue({ id: 1 }) },
|
||||
classTeacherRepo,
|
||||
).addTeacher(1, {
|
||||
userId: 2,
|
||||
roleType: 'head_teacher',
|
||||
}),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects removing a teacher or assignment that is not in the class', async () => {
|
||||
const classTeacherRepo = {
|
||||
find: jest.fn().mockResolvedValue([]),
|
||||
findOne: jest.fn().mockResolvedValue(null),
|
||||
delete: jest.fn(),
|
||||
};
|
||||
const service = createService({}, classTeacherRepo);
|
||||
await expect(service.removeTeacher(1, 2)).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(service.removeTeacherAssignment(1, 3)).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(classTeacherRepo.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -41,7 +41,10 @@ describe('ClassesService — teacher data scope', () => {
|
||||
it('clears denormalized teacher ids when the last teacher for that role is removed', async () => {
|
||||
const classRepo = { update: jest.fn() };
|
||||
const classTeacherRepo = {
|
||||
find: jest.fn().mockResolvedValue([]),
|
||||
find: jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce([{ id: 1, classId: 8, userId: 21 }])
|
||||
.mockResolvedValueOnce([]),
|
||||
delete: jest.fn().mockResolvedValue({ affected: 1 }),
|
||||
};
|
||||
const service = new ClassesService(
|
||||
|
||||
@@ -286,6 +286,7 @@ export class ClassesService {
|
||||
async archive(id: number) {
|
||||
const cls = await this.classRepo.findOne({ where: { id } });
|
||||
if (!cls) throw new NotFoundException('班级不存在');
|
||||
if (cls.isArchived) throw new BadRequestException('班级已归档');
|
||||
await this.classRepo.update(id, { isArchived: true });
|
||||
return { success: true };
|
||||
}
|
||||
@@ -294,6 +295,7 @@ export class ClassesService {
|
||||
async restore(id: number) {
|
||||
const cls = await this.classRepo.findOne({ where: { id } });
|
||||
if (!cls) throw new NotFoundException('班级不存在');
|
||||
if (!cls.isArchived) throw new BadRequestException('班级未归档');
|
||||
await this.classRepo.update(id, { isArchived: false });
|
||||
return { success: true };
|
||||
}
|
||||
@@ -392,6 +394,9 @@ export class ClassesService {
|
||||
}
|
||||
|
||||
async addTeacher(classId: number, dto: AddTeacherDto) {
|
||||
const cls = await this.classRepo.findOne({ where: { id: classId } });
|
||||
if (!cls) throw new NotFoundException('班级不存在');
|
||||
|
||||
const existing = await this.classTeacherRepo.findOne({
|
||||
where: { classId, userId: dto.userId, roleType: dto.roleType },
|
||||
});
|
||||
@@ -410,12 +415,18 @@ export class ClassesService {
|
||||
}
|
||||
|
||||
async removeTeacher(classId: number, userId: number) {
|
||||
const assignments = await this.classTeacherRepo.find({ where: { classId, userId } });
|
||||
if (assignments.length === 0) throw new NotFoundException('教师未分配到该班级');
|
||||
await this.classTeacherRepo.delete({ classId, userId });
|
||||
await this.syncClassTeacherIds(classId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async removeTeacherAssignment(classId: number, assignmentId: number) {
|
||||
const assignment = await this.classTeacherRepo.findOne({
|
||||
where: { id: assignmentId, classId },
|
||||
});
|
||||
if (!assignment) throw new NotFoundException('教师角色分配不存在');
|
||||
await this.classTeacherRepo.delete({ id: assignmentId, classId });
|
||||
await this.syncClassTeacherIds(classId);
|
||||
return { success: true };
|
||||
|
||||
@@ -1,43 +1,81 @@
|
||||
import { IsOptional, IsString, IsNotEmpty, IsInt, IsArray, IsDateString, IsEnum, ArrayNotEmpty, ValidateNested } from 'class-validator';
|
||||
import {
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsNotEmpty,
|
||||
IsInt,
|
||||
IsArray,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
ArrayNotEmpty,
|
||||
ValidateNested,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { Type, Transform } from 'class-transformer';
|
||||
import { ClassType, ClassStatus, TeacherRoleType } from '../../entities';
|
||||
|
||||
export class ClassTeacherItemDto {
|
||||
@IsInt()
|
||||
userId: number;
|
||||
|
||||
@IsEnum(TeacherRoleType)
|
||||
roleType: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
subject?: string;
|
||||
}
|
||||
|
||||
export class CreateClassDto {
|
||||
@IsString() @IsNotEmpty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@IsString() @IsNotEmpty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
code: string;
|
||||
|
||||
|
||||
@IsEnum(ClassType) @IsString() @IsNotEmpty()
|
||||
@IsEnum(ClassType)
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
classType: string;
|
||||
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
startDate?: string;
|
||||
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
endDate?: string;
|
||||
|
||||
@IsEnum(ClassStatus) @IsOptional() @IsString()
|
||||
@IsEnum(ClassStatus)
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
headTeacherId?: number;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
lifeTeacherId?: number;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
academicTeacherId?: number;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
maxStudents?: number;
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
|
||||
@IsOptional() @IsArray()
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsInt({ each: true })
|
||||
studentIds?: number[];
|
||||
|
||||
@IsOptional()
|
||||
@@ -46,55 +84,73 @@ export class CreateClassDto {
|
||||
@Type(() => ImportUserItem)
|
||||
users?: ImportUserItem[];
|
||||
|
||||
@IsOptional() @IsArray()
|
||||
teachers?: Array<{ userId: number; roleType: string; subject?: string }>;
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => ClassTeacherItemDto)
|
||||
teachers?: ClassTeacherItemDto[];
|
||||
}
|
||||
|
||||
export class UpdateClassDto {
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
code?: string;
|
||||
|
||||
|
||||
@IsEnum(ClassType) @IsOptional() @IsString()
|
||||
@IsEnum(ClassType)
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
classType?: string;
|
||||
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
startDate?: string;
|
||||
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
endDate?: string;
|
||||
|
||||
@IsEnum(ClassStatus) @IsOptional() @IsString()
|
||||
@IsEnum(ClassStatus)
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
headTeacherId?: number;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
lifeTeacherId?: number;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
academicTeacherId?: number;
|
||||
|
||||
@IsOptional() @IsInt()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
maxStudents?: number;
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export class QueryClassDto {
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
classType?: string;
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -108,7 +164,8 @@ export class QueryClassDto {
|
||||
}
|
||||
|
||||
export class AddStudentsDto {
|
||||
@IsArray() @IsInt({ each: true })
|
||||
@IsArray()
|
||||
@IsInt({ each: true })
|
||||
studentIds: number[];
|
||||
}
|
||||
|
||||
@@ -119,23 +176,28 @@ export class AddTeacherDto {
|
||||
@IsEnum(TeacherRoleType)
|
||||
roleType: string;
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
subject?: string;
|
||||
}
|
||||
|
||||
export class QueryClassScheduleDto {
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
startDate?: string;
|
||||
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
endDate?: string;
|
||||
}
|
||||
|
||||
export class QueryClassAttendanceSummaryDto {
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
startDate?: string;
|
||||
|
||||
@IsOptional() @IsDateString()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
endDate?: string;
|
||||
}
|
||||
export class BatchImportStudentsDto {
|
||||
@@ -147,12 +209,15 @@ export class BatchImportStudentsDto {
|
||||
}
|
||||
|
||||
export class ImportUserItem {
|
||||
@IsString() @IsNotEmpty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
dingUserId: string;
|
||||
|
||||
@IsString() @IsNotEmpty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
name: string;
|
||||
|
||||
@IsOptional() @IsString()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
mobile?: string;
|
||||
}
|
||||
|
||||
42
apps/server/src/classroom-rentals/dto/rental.dto.spec.ts
Normal file
42
apps/server/src/classroom-rentals/dto/rental.dto.spec.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { validate } from 'class-validator';
|
||||
import { CreateRentalDto } from './rental.dto';
|
||||
|
||||
const createRental = (overrides: Partial<CreateRentalDto> = {}) =>
|
||||
Object.assign(new CreateRentalDto(), {
|
||||
classroomId: 1,
|
||||
lesseeOrganizationId: 2,
|
||||
startDate: '2026-08-01',
|
||||
endDate: '2026-08-31',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('classroom rental DTO boundaries', () => {
|
||||
it.each(['2026-02-31', '2026-08-01T00:00:00Z', '2026-8-1'])(
|
||||
'rejects invalid or non-date-only value %s',
|
||||
async (startDate) => {
|
||||
const errors = await validate(createRental({ startDate }));
|
||||
expect(errors.some((error) => error.property === 'startDate')).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['dailyRate', 0],
|
||||
['totalAmount', -1],
|
||||
] as const)('rejects non-positive %s', async (field, value) => {
|
||||
const errors = await validate(createRental({ [field]: value }));
|
||||
expect(errors.some((error) => error.property === field)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts positive amounts and a leap-day date', async () => {
|
||||
await expect(
|
||||
validate(
|
||||
createRental({
|
||||
startDate: '2028-02-29',
|
||||
endDate: '2028-02-29',
|
||||
dailyRate: 0.01,
|
||||
totalAmount: 0.01,
|
||||
}),
|
||||
),
|
||||
).resolves.toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { IsOptional, IsString, IsInt, IsNumber, IsDateString } from 'class-validator';
|
||||
import { IsOptional, IsString, IsInt, IsNumber, IsISO8601, Matches, Min } from 'class-validator';
|
||||
|
||||
export class CreateRentalDto {
|
||||
@IsInt()
|
||||
@@ -11,18 +11,22 @@ export class CreateRentalDto {
|
||||
@IsInt()
|
||||
lesseeOrganizationId: number;
|
||||
|
||||
@IsDateString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
startDate: string;
|
||||
|
||||
@IsDateString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
endDate: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0.01)
|
||||
dailyRate?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0.01)
|
||||
totalAmount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@@ -44,19 +48,23 @@ export class UpdateRentalDto {
|
||||
lesseeOrganizationId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
startDate?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
endDate?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0.01)
|
||||
dailyRate?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0.01)
|
||||
totalAmount?: number;
|
||||
|
||||
@IsOptional()
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
SubjectName,
|
||||
} from '../authorization';
|
||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||
import { DashboardGanttQueryDto, DashboardPeriodQueryDto } from './dto/dashboard-query.dto';
|
||||
|
||||
interface RequestUser {
|
||||
id: number;
|
||||
@@ -43,28 +44,18 @@ export class DashboardController {
|
||||
}
|
||||
|
||||
@Get('gantt')
|
||||
getGanttData(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
@Query('building') building?: string,
|
||||
) {
|
||||
return this.service.getGanttData({ periodStart, periodEnd, building });
|
||||
getGanttData(@Query() query: DashboardGanttQueryDto) {
|
||||
return this.service.getGanttData(query);
|
||||
}
|
||||
|
||||
@Get('expense-stats')
|
||||
getExpenseStats(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
) {
|
||||
return this.service.getExpenseStats(periodStart, periodEnd);
|
||||
getExpenseStats(@Query() query: DashboardPeriodQueryDto) {
|
||||
return this.service.getExpenseStats(query.periodStart, query.periodEnd);
|
||||
}
|
||||
|
||||
@Get('room-ranking')
|
||||
getRoomExpenseRanking(
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
) {
|
||||
return this.service.getRoomExpenseRanking(periodStart, periodEnd);
|
||||
getRoomExpenseRanking(@Query() query: DashboardPeriodQueryDto) {
|
||||
return this.service.getRoomExpenseRanking(query.periodStart, query.periodEnd);
|
||||
}
|
||||
|
||||
@Get('class-attendance-ranking')
|
||||
|
||||
@@ -42,3 +42,45 @@ describe('DashboardService — teacher class scope', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('DashboardService — boundary conditions', () => {
|
||||
it('uses a deny-all predicate instead of an empty SQL IN list', async () => {
|
||||
const qb = createQb();
|
||||
const attendanceRepo = { createQueryBuilder: jest.fn().mockReturnValue(qb) };
|
||||
const service = new DashboardService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{} as never, attendanceRepo as never, {} as never, {} as never, {} as never,
|
||||
{} as never, {} as never,
|
||||
);
|
||||
|
||||
await (service as unknown as {
|
||||
getAttendanceTrend: (today: string, classIds: number[]) => Promise<unknown>;
|
||||
}).getAttendanceTrend('2026-07-14', []);
|
||||
|
||||
expect(qb.andWhere).toHaveBeenCalledWith('1 = 0');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['getGanttData', [{ periodStart: '2026-08-01', periodEnd: '2026-07-31' }]],
|
||||
['getExpenseStats', ['2026-08-01', '2026-07-31']],
|
||||
['getRoomExpenseRanking', ['2026-08-01', '2026-07-31']],
|
||||
] as const)('rejects a reversed period in %s', async (method, args) => {
|
||||
const service = new DashboardService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{} as never,
|
||||
);
|
||||
await expect((service[method] as (...values: never[]) => Promise<unknown>)(...(args as never[])))
|
||||
.rejects.toThrow('结束日期不能早于开始日期');
|
||||
});
|
||||
|
||||
it('uses the China calendar date when the server timezone is behind China', () => {
|
||||
const service = new DashboardService(
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{} as never, {} as never, {} as never, {} as never, {} as never, {} as never,
|
||||
{} as never,
|
||||
);
|
||||
expect((service as unknown as { getChinaDate: (date: Date) => string })
|
||||
.getChinaDate(new Date('2026-07-13T16:30:00.000Z'))).toBe('2026-07-14');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, IsNull, Not, MoreThanOrEqual, In } from 'typeorm';
|
||||
import { Room } from '../entities/room.entity';
|
||||
@@ -40,8 +40,7 @@ export class DashboardService {
|
||||
}
|
||||
|
||||
async getStats(accessibleClassIds?: number[]) {
|
||||
const today = new Date();
|
||||
const todayStr = today.toISOString().slice(0, 10);
|
||||
const todayStr = this.getChinaDate(new Date());
|
||||
const currentMonth = todayStr.slice(0, 7); // YYYY-MM
|
||||
|
||||
const totalRooms = await this.roomRepo.count({ where: { status: Not('archived') } });
|
||||
@@ -180,6 +179,10 @@ export class DashboardService {
|
||||
accessibleClassIds?: number[],
|
||||
) {
|
||||
if (accessibleClassIds) {
|
||||
if (accessibleClassIds.length === 0) {
|
||||
qb.andWhere('1 = 0');
|
||||
return;
|
||||
}
|
||||
qb.andWhere(`${alias}.classId IN (:...accessibleClassIds)`, { accessibleClassIds });
|
||||
}
|
||||
}
|
||||
@@ -260,6 +263,7 @@ export class DashboardService {
|
||||
|
||||
// 甘特图数据:每个宿舍的入住时间线
|
||||
async getGanttData(query?: { periodStart?: string; periodEnd?: string; building?: string }) {
|
||||
this.assertPeriodRange(query?.periodStart, query?.periodEnd);
|
||||
const qb = this.occRepo
|
||||
.createQueryBuilder('o')
|
||||
.leftJoinAndSelect('o.student', 'student')
|
||||
@@ -302,6 +306,7 @@ export class DashboardService {
|
||||
}
|
||||
// 费用统计
|
||||
async getExpenseStats(periodStart?: string, periodEnd?: string) {
|
||||
this.assertPeriodRange(periodStart, periodEnd);
|
||||
const qb = this.expRepo
|
||||
.createQueryBuilder('e')
|
||||
.select('e.expenseType', 'type')
|
||||
@@ -314,6 +319,7 @@ export class DashboardService {
|
||||
|
||||
// 各宿舍费用排行
|
||||
async getRoomExpenseRanking(periodStart?: string, periodEnd?: string) {
|
||||
this.assertPeriodRange(periodStart, periodEnd);
|
||||
const qb = this.expRepo
|
||||
.createQueryBuilder('e')
|
||||
.leftJoin('e.room', 'room')
|
||||
@@ -368,7 +374,7 @@ export class DashboardService {
|
||||
where: { status: 'available' as const },
|
||||
order: { building: 'ASC', name: 'ASC' },
|
||||
});
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const today = this.getChinaDate(new Date());
|
||||
const schedQb = this.scheduleRepo
|
||||
.createQueryBuilder('s')
|
||||
.select('s.classroomId', 'classroomId')
|
||||
@@ -400,12 +406,31 @@ export class DashboardService {
|
||||
}));
|
||||
}
|
||||
|
||||
private assertPeriodRange(periodStart?: string, periodEnd?: string) {
|
||||
if (periodStart && periodEnd && periodStart > periodEnd) {
|
||||
throw new BadRequestException('结束日期不能早于开始日期');
|
||||
}
|
||||
}
|
||||
|
||||
private getChinaDate(date: Date): string {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).formatToParts(date);
|
||||
const values = Object.fromEntries(
|
||||
parts.filter((part) => part.type !== 'literal').map((part) => [part.type, part.value]),
|
||||
);
|
||||
return `${values.year}-${values.month}-${values.day}`;
|
||||
}
|
||||
|
||||
async getClassroomUtilizationStats() {
|
||||
const totalClassrooms = await this.classroomRepo.count({
|
||||
where: { status: 'available' as const },
|
||||
});
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const today = this.getChinaDate(new Date());
|
||||
|
||||
// Count classrooms with active schedules today
|
||||
const schedQb = this.scheduleRepo
|
||||
|
||||
28
apps/server/src/dashboard/dto/dashboard-query.dto.spec.ts
Normal file
28
apps/server/src/dashboard/dto/dashboard-query.dto.spec.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import 'reflect-metadata';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { validate } from 'class-validator';
|
||||
import { DashboardGanttQueryDto, DashboardPeriodQueryDto } from './dashboard-query.dto';
|
||||
|
||||
describe('dashboard query boundaries', () => {
|
||||
it.each(['2026-02-31', '2026-07-13T00:00:00Z', '2026-7-13'])(
|
||||
'rejects invalid or non-date-only value %s',
|
||||
async (periodStart) => {
|
||||
const dto = plainToInstance(DashboardPeriodQueryDto, { periodStart });
|
||||
expect((await validate(dto)).some((error) => error.property === 'periodStart')).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('accepts a valid date range and bounded building name', async () => {
|
||||
const dto = plainToInstance(DashboardGanttQueryDto, {
|
||||
periodStart: '2026-07-01',
|
||||
periodEnd: '2026-07-31',
|
||||
building: 'A座',
|
||||
});
|
||||
expect(await validate(dto)).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects an excessively long building name', async () => {
|
||||
const dto = plainToInstance(DashboardGanttQueryDto, { building: 'A'.repeat(51) });
|
||||
expect((await validate(dto)).some((error) => error.property === 'building')).toBe(true);
|
||||
});
|
||||
});
|
||||
20
apps/server/src/dashboard/dto/dashboard-query.dto.ts
Normal file
20
apps/server/src/dashboard/dto/dashboard-query.dto.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { IsISO8601, IsOptional, IsString, Matches, MaxLength } from 'class-validator';
|
||||
|
||||
export class DashboardPeriodQueryDto {
|
||||
@IsOptional()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
periodStart?: string;
|
||||
|
||||
@IsOptional()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
periodEnd?: string;
|
||||
}
|
||||
|
||||
export class DashboardGanttQueryDto extends DashboardPeriodQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(50)
|
||||
building?: string;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export class DatabaseMigrationsService implements OnApplicationBootstrap {
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
await this.ensureAiConfigTable();
|
||||
await this.ensureCourseAttendanceSchema();
|
||||
await this.ensureStudentWalletSchema();
|
||||
await this.backfillOrganizations();
|
||||
await this.normalizeClassDates();
|
||||
await this.protectAttendanceHistory();
|
||||
@@ -21,6 +22,49 @@ export class DatabaseMigrationsService implements OnApplicationBootstrap {
|
||||
await this.normalizeClassroomStatuses();
|
||||
}
|
||||
|
||||
private async ensureStudentWalletSchema(): Promise<void> {
|
||||
const runner = this.dataSource.createQueryRunner();
|
||||
await runner.connect();
|
||||
try {
|
||||
const isMySQL = this.dataSource.options.type === 'mysql';
|
||||
const pk = isMySQL ? 'INTEGER PRIMARY KEY AUTO_INCREMENT' : 'INTEGER PRIMARY KEY AUTOINCREMENT';
|
||||
await runner.query(`CREATE TABLE IF NOT EXISTS student_wallets (
|
||||
id ${pk}, student_id INTEGER NOT NULL UNIQUE, balance DECIMAL(12,2) NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
await runner.query(`CREATE TABLE IF NOT EXISTS wallet_transactions (
|
||||
id ${pk}, student_id INTEGER NOT NULL, bill_id INTEGER, type VARCHAR(30) NOT NULL,
|
||||
amount DECIMAL(12,2) NOT NULL, balance_after DECIMAL(12,2) NOT NULL,
|
||||
description VARCHAR(300), recorded_by INTEGER,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
const bills = await runner.getTable('bills');
|
||||
if (bills) {
|
||||
const columns = new Set(bills.columns.map((column) => column.name));
|
||||
const additions = [
|
||||
['source', "VARCHAR(30) NOT NULL DEFAULT 'batch'"],
|
||||
['paid_amount', 'DECIMAL(10,2) NOT NULL DEFAULT 0'],
|
||||
['outstanding_amount', 'DECIMAL(10,2) NOT NULL DEFAULT 0'],
|
||||
['cancelled_at', 'DATETIME'],
|
||||
['cancel_reason', 'VARCHAR(300)'],
|
||||
];
|
||||
for (const [name, definition] of additions) {
|
||||
if (!columns.has(name)) await runner.query(`ALTER TABLE bills ADD COLUMN ${name} ${definition}`);
|
||||
}
|
||||
await runner.query("UPDATE bills SET outstanding_amount = total_amount WHERE outstanding_amount = 0 AND status <> 'paid'");
|
||||
await runner.query("UPDATE bills SET paid_amount = total_amount, outstanding_amount = 0 WHERE status = 'paid'");
|
||||
await runner.query("UPDATE bills SET status = 'unpaid' WHERE status IN ('draft', 'confirmed')");
|
||||
}
|
||||
const personalExpenses = await runner.getTable('personal_expenses');
|
||||
if (personalExpenses && !personalExpenses.columns.some((column) => column.name === 'bill_id')) {
|
||||
await runner.query('ALTER TABLE personal_expenses ADD COLUMN bill_id INTEGER');
|
||||
}
|
||||
} finally {
|
||||
await runner.release();
|
||||
}
|
||||
}
|
||||
|
||||
private async removeUnusedClassroomColumns(): Promise<void> {
|
||||
const runner = this.dataSource.createQueryRunner();
|
||||
await runner.connect();
|
||||
@@ -216,7 +260,11 @@ export class DatabaseMigrationsService implements OnApplicationBootstrap {
|
||||
const runner = this.dataSource.createQueryRunner();
|
||||
await runner.connect();
|
||||
try {
|
||||
const tables = await runner.getTables(['attendance_records', 'attendance_sessions']);
|
||||
const tables = await runner.getTables([
|
||||
'class_schedule',
|
||||
'attendance_records',
|
||||
'attendance_sessions',
|
||||
]);
|
||||
const tableNames = new Set(tables.map((table) => table.name));
|
||||
const isMySQL = this.dataSource.options.type === 'mysql';
|
||||
|
||||
@@ -243,6 +291,17 @@ export class DatabaseMigrationsService implements OnApplicationBootstrap {
|
||||
`);
|
||||
}
|
||||
|
||||
if (tableNames.has('class_schedule')) {
|
||||
const scheduleTable = await runner.getTable('class_schedule');
|
||||
const scheduleColumns = new Set(scheduleTable?.columns.map((column) => column.name) ?? []);
|
||||
if (!scheduleColumns.has('attendance_advance_minutes')) {
|
||||
await runner.query(
|
||||
'ALTER TABLE class_schedule ADD COLUMN attendance_advance_minutes INTEGER NOT NULL DEFAULT 30',
|
||||
);
|
||||
this.logger.log('已为排课添加课前签到分钟配置');
|
||||
}
|
||||
}
|
||||
|
||||
const attendanceTable = await runner.getTable('attendance_records');
|
||||
const columnNames = new Set(attendanceTable?.columns.map((column) => column.name) ?? []);
|
||||
if (!columnNames.has('schedule_id')) {
|
||||
|
||||
@@ -209,6 +209,28 @@ describe('DatabaseMigrationsService — course attendance schema', () => {
|
||||
expect(runner.release).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('adds the configurable attendance window to existing schedules', async () => {
|
||||
const runner = mockRunner({
|
||||
getTables: [
|
||||
{ name: 'class_schedule', columns: [{ name: 'id' }] },
|
||||
{ name: 'attendance_records', columns: [{ name: 'id' }] },
|
||||
{ name: 'attendance_sessions', columns: [{ name: 'id' }] },
|
||||
],
|
||||
});
|
||||
runner.getTable.mockImplementation(async (name: string) =>
|
||||
name === 'class_schedule'
|
||||
? { name, columns: [{ name: 'id' }] }
|
||||
: { name, columns: [{ name: 'id' }, { name: 'schedule_id' }, { name: 'attendance_session_id' }] },
|
||||
);
|
||||
await bootstrapCourseAttendance(runner);
|
||||
|
||||
await service.ensureCourseAttendanceSchema();
|
||||
|
||||
expect(runner.query).toHaveBeenCalledWith(
|
||||
expect.stringContaining('ALTER TABLE class_schedule ADD COLUMN attendance_advance_minutes'),
|
||||
);
|
||||
});
|
||||
|
||||
it('creates attendance_sessions with FK RESTRICT constraints when table is missing', async () => {
|
||||
const runner = mockRunner({
|
||||
getTables: [{ name: 'attendance_records', columns: [{ name: 'id' }] }],
|
||||
|
||||
53
apps/server/src/deposits/deposits.boundaries.spec.ts
Normal file
53
apps/server/src/deposits/deposits.boundaries.spec.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { DepositsService } from './deposits.service';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
|
||||
function serviceWith(deposit?: Partial<Deposit>) {
|
||||
const record = deposit ? ({ id: 1, studentId: 2, ...deposit } as Deposit) : null;
|
||||
const repo = {
|
||||
findOne: jest.fn(async (options: any) => options?.where?.studentId ? record : record),
|
||||
create: jest.fn((value) => value),
|
||||
save: jest.fn(async (value) => value),
|
||||
};
|
||||
const installmentRepo = {
|
||||
create: jest.fn((value) => value),
|
||||
save: jest.fn(async (value) => value),
|
||||
};
|
||||
const studentRepo = { findOne: jest.fn().mockResolvedValue({ id: 2 }) };
|
||||
return { service: new DepositsService(repo as any, installmentRepo as any, studentRepo as any), repo, installmentRepo };
|
||||
}
|
||||
|
||||
describe('DepositsService boundaries', () => {
|
||||
it('rejects an installment amount that rounds to zero', async () => {
|
||||
const { service, installmentRepo } = serviceWith({ amount: 500, status: 'paid' });
|
||||
|
||||
await expect(service.addInstallment(1, 0.004, '2026-08-01')).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(installmentRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a repeated full refund', async () => {
|
||||
const { service, repo } = serviceWith({ amount: 0, status: 'refunded' });
|
||||
|
||||
await expect(service.refund(1, { refundDate: '2026-07-14' })).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(repo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rounds cumulative collections and clears stale refund audit fields', async () => {
|
||||
const { service } = serviceWith({
|
||||
amount: 10.01,
|
||||
status: 'refunded',
|
||||
refundDate: '2026-07-01',
|
||||
refundAmount: 5,
|
||||
refundedBy: 9,
|
||||
refundedAt: new Date(),
|
||||
});
|
||||
|
||||
const result = await service.create({ studentId: 2, amount: 0.02, paidDate: '2026-07-14' }, 7);
|
||||
|
||||
expect(result).toMatchObject({ amount: 10.03, status: 'paid', recordedBy: 7 });
|
||||
expect(result.refundDate).toBeNull();
|
||||
expect(result.refundAmount).toBeNull();
|
||||
expect(result.refundedBy).toBeNull();
|
||||
expect(result.refundedAt).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Query,
|
||||
UseGuards,
|
||||
Request,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
@@ -16,7 +17,12 @@ import { Student } from '../entities/student.entity';
|
||||
import { DepositsService } from './deposits.service';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { NotificationType } from '../entities/notification.entity';
|
||||
import { CreateDepositDto, RefundDepositDto } from './dto/deposit.dto';
|
||||
import {
|
||||
CreateDepositDto,
|
||||
CreateDepositInstallmentDto,
|
||||
RefundDepositDto,
|
||||
UpdateDepositInstallmentDto,
|
||||
} from './dto/deposit.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
import { extractRequestInfo } from '../common/request-utils';
|
||||
@@ -40,9 +46,12 @@ export class DepositsController {
|
||||
|
||||
@Get()
|
||||
@RequirePermission('deposit:view')
|
||||
findAll(@Query('studentId') studentId?: string, @Query('status') status?: string) {
|
||||
findAll(
|
||||
@Query('studentId', new ParseIntPipe({ optional: true })) studentId?: number,
|
||||
@Query('status') status?: string,
|
||||
) {
|
||||
return this.service.findAll({
|
||||
studentId: studentId ? +studentId : undefined,
|
||||
studentId,
|
||||
status: status || undefined,
|
||||
});
|
||||
}
|
||||
@@ -55,8 +64,8 @@ export class DepositsController {
|
||||
|
||||
@Get(':id')
|
||||
@RequirePermission('deposit:view')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.service.findOne(+id);
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.service.findOne(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@@ -93,12 +102,12 @@ export class DepositsController {
|
||||
@Post(':id/installments')
|
||||
@RequirePermission('deposit:edit')
|
||||
async addInstallment(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { amount: number; dueDate: string },
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() body: CreateDepositInstallmentDto,
|
||||
@Request() req: { user?: { id: number; username: string }; headers?: Record<string, string> },
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.addInstallment(+id, body.amount, body.dueDate);
|
||||
const result = await this.service.addInstallment(id, body.amount, body.dueDate);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
@@ -116,18 +125,18 @@ export class DepositsController {
|
||||
@Put('installments/:installmentId')
|
||||
@RequirePermission('deposit:edit')
|
||||
async updateInstallment(
|
||||
@Param('installmentId') installmentId: string,
|
||||
@Body() body: { paidDate?: string; status?: string },
|
||||
@Param('installmentId', ParseIntPipe) installmentId: number,
|
||||
@Body() body: UpdateDepositInstallmentDto,
|
||||
@Request() req: { user?: { id: number; username: string }; headers?: Record<string, string> },
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.updateInstallment(+installmentId, body);
|
||||
const result = await this.service.updateInstallment(installmentId, body);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '押金管理',
|
||||
action: '更新分期',
|
||||
targetId: +installmentId,
|
||||
targetId: installmentId,
|
||||
targetType: 'deposit-installment',
|
||||
detail: `更新分期${installmentId}, 状态:${result.status ?? '-'}, 实付日:${result.paidDate ?? '-'}`,
|
||||
ipAddress,
|
||||
@@ -139,17 +148,17 @@ export class DepositsController {
|
||||
@Delete('installments/:installmentId')
|
||||
@RequirePermission('deposit:delete')
|
||||
async deleteInstallment(
|
||||
@Param('installmentId') installmentId: string,
|
||||
@Param('installmentId', ParseIntPipe) installmentId: number,
|
||||
@Request() req: { user?: { id: number; username: string }; headers?: Record<string, string> },
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.deleteInstallment(+installmentId);
|
||||
const result = await this.service.deleteInstallment(installmentId);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '押金管理',
|
||||
action: '删除分期',
|
||||
targetId: +installmentId,
|
||||
targetId: installmentId,
|
||||
targetType: 'deposit-installment',
|
||||
detail: `删除分期${installmentId}`,
|
||||
ipAddress,
|
||||
@@ -160,17 +169,17 @@ export class DepositsController {
|
||||
|
||||
@Put(':id/refund')
|
||||
@RequirePermission('deposit:refund')
|
||||
async refund(@Param('id') id: string, @Body() dto: RefundDepositDto, @Request() req: any) {
|
||||
async refund(@Param('id', ParseIntPipe) id: number, @Body() dto: RefundDepositDto, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.refund(+id, dto, req.user?.id);
|
||||
const result = await this.service.refund(id, dto, req.user?.id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '押金管理',
|
||||
action: '退还押金',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'deposit',
|
||||
detail: `退还¥${result.refundAmount}, 扣除¥${result.deductionAmount}`,
|
||||
detail: `退还全部可用押金 ¥${result.refundAmount}`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
@@ -182,7 +191,7 @@ export class DepositsController {
|
||||
recipientIds: [student.userId],
|
||||
type: 'deposit_refunded',
|
||||
title: '押金已退还',
|
||||
content: `您的押金已退还,退还¥${result.refundAmount},扣除¥${result.deductionAmount}`,
|
||||
content: `您的剩余押金已全部退还,金额: ¥${result.refundAmount}`,
|
||||
});
|
||||
}
|
||||
} catch (_) { /* don't block response */ }
|
||||
@@ -191,15 +200,15 @@ export class DepositsController {
|
||||
|
||||
@Delete(':id')
|
||||
@RequirePermission('deposit:delete')
|
||||
async remove(@Param('id') id: string, @Request() req: any) {
|
||||
async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.remove(+id);
|
||||
const result = await this.service.remove(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '押金管理',
|
||||
action: '删除押金记录',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'deposit',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { DepositsService } from './deposits.service';
|
||||
import { Deposit } from '../entities/deposit.entity';
|
||||
|
||||
describe('DepositsService — direct refund', () => {
|
||||
it('stores the refund result on the main status and renamed audit fields', async () => {
|
||||
it('refunds the full available balance and stores audit fields', async () => {
|
||||
const deposit = {
|
||||
id: 1,
|
||||
amount: 500,
|
||||
@@ -16,20 +16,16 @@ describe('DepositsService — direct refund', () => {
|
||||
|
||||
const result = await service.refund(
|
||||
1,
|
||||
{
|
||||
refundDate: '2026-07-13',
|
||||
deductionAmount: 100,
|
||||
deductionReason: '物品损坏',
|
||||
},
|
||||
{ refundDate: '2026-07-13', notes: '退还剩余押金' },
|
||||
42,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
refundDate: '2026-07-13',
|
||||
refundAmount: 400,
|
||||
deductionAmount: 100,
|
||||
deductionReason: '物品损坏',
|
||||
status: 'partial_refund',
|
||||
amount: 0,
|
||||
refundAmount: 500,
|
||||
notes: '退还剩余押金',
|
||||
status: 'refunded',
|
||||
refundedBy: 42,
|
||||
});
|
||||
expect(result.refundedAt).toBeInstanceOf(Date);
|
||||
|
||||
@@ -7,6 +7,8 @@ import { DepositInstallment } from '../entities/deposit-installment.entity';
|
||||
|
||||
import { CreateDepositDto, RefundDepositDto } from './dto/deposit.dto';
|
||||
|
||||
const money = (value: number | string | null | undefined) => Number(Number(value || 0).toFixed(2));
|
||||
|
||||
@Injectable()
|
||||
export class DepositsService {
|
||||
|
||||
@@ -46,25 +48,50 @@ export class DepositsService {
|
||||
async create(dto: CreateDepositDto, userId?: number) {
|
||||
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
const deposit = this.repo.create({
|
||||
studentId: dto.studentId,
|
||||
amount: dto.amount,
|
||||
paidDate: dto.paidDate,
|
||||
notes: dto.notes,
|
||||
status: 'paid',
|
||||
recordedBy: userId,
|
||||
});
|
||||
const amount = money(dto.amount);
|
||||
if (!Number.isFinite(dto.amount) || Math.abs(dto.amount * 100 - Math.round(dto.amount * 100)) > 1e-8) {
|
||||
throw new BadRequestException('收取金额最多保留两位小数');
|
||||
}
|
||||
if (amount <= 0) throw new BadRequestException('收取金额必须大于0');
|
||||
|
||||
return this.repo.save(deposit);
|
||||
const existing = await this.repo.findOne({ where: { studentId: dto.studentId } });
|
||||
if (existing) {
|
||||
existing.amount = money(Number(existing.amount || 0) + amount);
|
||||
existing.paidDate = dto.paidDate;
|
||||
existing.status = 'paid';
|
||||
existing.recordedBy = userId ?? null;
|
||||
existing.refundDate = null as unknown as string;
|
||||
existing.refundAmount = null as unknown as number;
|
||||
existing.refundedBy = null;
|
||||
existing.refundedAt = null;
|
||||
if (dto.notes) existing.notes = dto.notes;
|
||||
return this.repo.save(existing);
|
||||
}
|
||||
|
||||
return this.repo.save(
|
||||
this.repo.create({
|
||||
studentId: dto.studentId,
|
||||
amount,
|
||||
paidDate: dto.paidDate,
|
||||
notes: dto.notes,
|
||||
status: 'paid',
|
||||
recordedBy: userId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async addInstallment(depositId: number, amount: number, dueDate: string) {
|
||||
const normalizedAmount = money(amount);
|
||||
if (!Number.isFinite(amount) || Math.abs(amount * 100 - Math.round(amount * 100)) > 1e-8) {
|
||||
throw new BadRequestException('分期金额最多保留两位小数');
|
||||
}
|
||||
if (normalizedAmount <= 0) throw new BadRequestException('分期金额必须大于0');
|
||||
const deposit = await this.repo.findOne({ where: { id: depositId } });
|
||||
if (!deposit) throw new NotFoundException('押金记录不存在');
|
||||
|
||||
const installment = this.installmentRepo.create({
|
||||
depositId,
|
||||
amount,
|
||||
amount: normalizedAmount,
|
||||
dueDate,
|
||||
status: 'pending',
|
||||
});
|
||||
@@ -90,18 +117,16 @@ export class DepositsService {
|
||||
async refund(id: number, dto: RefundDepositDto, userId?: number) {
|
||||
const deposit = await this.repo.findOne({ where: { id } });
|
||||
if (!deposit) throw new NotFoundException('押金记录不存在');
|
||||
if (deposit.status !== 'paid') throw new BadRequestException('该押金已处理');
|
||||
if (deposit.status !== 'paid' || Number(deposit.amount) <= 0) {
|
||||
throw new BadRequestException('该学生当前没有可退押金');
|
||||
}
|
||||
|
||||
const deduction = dto.deductionAmount || 0;
|
||||
const refundAmount = Number(deposit.amount) - deduction;
|
||||
if (refundAmount < 0) throw new BadRequestException('扣除金额不能大于押金金额');
|
||||
const refundAmount = money(deposit.amount);
|
||||
|
||||
deposit.refundDate = dto.refundDate;
|
||||
deposit.deductionAmount = deduction;
|
||||
deposit.deductionReason = dto.deductionReason || '';
|
||||
deposit.refundAmount = refundAmount;
|
||||
deposit.status =
|
||||
deduction > 0 ? (refundAmount > 0 ? 'partial_refund' : 'deducted') : 'refunded';
|
||||
deposit.amount = 0;
|
||||
deposit.status = 'refunded';
|
||||
if (dto.notes) deposit.notes = dto.notes;
|
||||
deposit.refundedBy = userId ?? null;
|
||||
deposit.refundedAt = new Date();
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { IsInt, IsNumber, IsString, IsOptional } from 'class-validator';
|
||||
import { IsDateString, IsIn, IsInt, IsNumber, IsString, IsOptional, Min } from 'class-validator';
|
||||
|
||||
export class CreateDepositDto {
|
||||
@IsInt()
|
||||
studentId: number;
|
||||
|
||||
@IsNumber()
|
||||
@IsNumber({ maxDecimalPlaces: 2 })
|
||||
@Min(0.01)
|
||||
amount: number;
|
||||
|
||||
@IsString()
|
||||
@IsDateString()
|
||||
paidDate: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -16,18 +17,29 @@ export class CreateDepositDto {
|
||||
}
|
||||
|
||||
export class RefundDepositDto {
|
||||
@IsString()
|
||||
@IsDateString()
|
||||
refundDate: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
deductionAmount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
deductionReason?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export class CreateDepositInstallmentDto {
|
||||
@IsNumber({ maxDecimalPlaces: 2 })
|
||||
@Min(0.01)
|
||||
amount: number;
|
||||
|
||||
@IsDateString()
|
||||
dueDate: string;
|
||||
}
|
||||
|
||||
export class UpdateDepositInstallmentDto {
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
paidDate?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['pending', 'paid', 'overdue'])
|
||||
status?: string;
|
||||
}
|
||||
|
||||
@@ -67,6 +67,18 @@ export class AttendanceRecord {
|
||||
@Column({ name: 'source', length: 20, default: 'manual' })
|
||||
source: string;
|
||||
|
||||
@Column({ name: 'punch_time', type: 'datetime', nullable: true })
|
||||
punchTime: Date | null;
|
||||
|
||||
@Column({ name: 'punch_source', type: 'varchar', length: 40, nullable: true })
|
||||
punchSource: string | null;
|
||||
|
||||
@Column({ name: 'punch_device_name', type: 'varchar', length: 100, nullable: true })
|
||||
punchDeviceName: string | null;
|
||||
|
||||
@Column({ name: 'punch_device_id', type: 'varchar', length: 100, nullable: true })
|
||||
punchDeviceId: string | null;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
|
||||
@@ -33,9 +33,24 @@ export class Bill {
|
||||
@Column({ name: 'total_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||
totalAmount: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'draft' })
|
||||
@Column({ type: 'varchar', length: 30, default: 'batch' })
|
||||
source: 'batch' | 'student_utility';
|
||||
|
||||
@Column({ name: 'paid_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||
paidAmount: number;
|
||||
|
||||
@Column({ name: 'outstanding_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
|
||||
outstandingAmount: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 20, default: 'unpaid' })
|
||||
status: string;
|
||||
|
||||
@Column({ name: 'cancelled_at', type: 'datetime', nullable: true })
|
||||
cancelledAt: Date | null;
|
||||
|
||||
@Column({ name: 'cancel_reason', type: 'varchar', length: 300, nullable: true })
|
||||
cancelReason: string | null;
|
||||
|
||||
@CreateDateColumn({ name: 'generated_at' })
|
||||
generatedAt: Date;
|
||||
|
||||
|
||||
@@ -45,6 +45,10 @@ export class ClassSchedule {
|
||||
@Column({ name: 'end_time', length: 5 })
|
||||
endTime: string;
|
||||
|
||||
/** 课程开始前允许计入签到的分钟数。 */
|
||||
@Column({ name: 'attendance_advance_minutes', type: 'integer', default: 30 })
|
||||
attendanceAdvanceMinutes: number;
|
||||
|
||||
@Column({ name: 'start_date', type: 'date' })
|
||||
startDate: string;
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ export class Deposit {
|
||||
@Column({ type: 'decimal', precision: 10, scale: 2, default: 500 })
|
||||
amount: number;
|
||||
|
||||
// paid: 已缴 | refunded: 已退 | deducted: 已扣除(部分或全部)
|
||||
// paid: 有可用余额 | refunded: 余额已全部退还 | depleted: 余额已被账单扣完
|
||||
@Column({ type: 'varchar', length: 20, default: 'paid' })
|
||||
status: string;
|
||||
|
||||
@@ -43,8 +43,8 @@ export class Deposit {
|
||||
@Column({ type: 'text', nullable: true })
|
||||
notes: string;
|
||||
|
||||
@Column({ name: 'recorded_by', nullable: true })
|
||||
recordedBy: number;
|
||||
@Column({ name: 'recorded_by', type: 'integer', nullable: true })
|
||||
recordedBy: number | null;
|
||||
|
||||
@Column({ name: 'refunded_by', type: 'integer', nullable: true })
|
||||
refundedBy: number | null;
|
||||
|
||||
@@ -44,6 +44,15 @@ export class DingAttendanceRaw {
|
||||
@Column({ name: 'location_result', length: 20, nullable: true })
|
||||
locationResult: string;
|
||||
|
||||
@Column({ name: 'punch_source', type: 'varchar', length: 40, nullable: true })
|
||||
punchSource: string | null;
|
||||
|
||||
@Column({ name: 'punch_device_name', type: 'varchar', length: 100, nullable: true })
|
||||
punchDeviceName: string | null;
|
||||
|
||||
@Column({ name: 'punch_device_id', type: 'varchar', length: 100, nullable: true })
|
||||
punchDeviceId: string | null;
|
||||
|
||||
@Column({ name: 'match_status', length: 20, default: 'unmatched' })
|
||||
matchStatus: string;
|
||||
|
||||
|
||||
@@ -35,3 +35,6 @@ export { ResultArchive } from './result-archive.entity';
|
||||
export { ArchiveAttachment } from './archive-attachment.entity';
|
||||
export { StudentDingMapping } from './student-ding-mapping.entity';
|
||||
export { AiConfig } from '../ai-config/ai-config.entity';
|
||||
|
||||
export * from './student-wallet.entity';
|
||||
export * from './wallet-transaction.entity';
|
||||
|
||||
@@ -34,6 +34,9 @@ export class PersonalExpense {
|
||||
@Column({ name: 'recorded_by', nullable: true })
|
||||
recordedBy: number;
|
||||
|
||||
@Column({ name: 'bill_id', type: 'integer', nullable: true })
|
||||
billId: number | null;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
|
||||
32
apps/server/src/entities/student-wallet.entity.ts
Normal file
32
apps/server/src/entities/student-wallet.entity.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
JoinColumn,
|
||||
OneToOne,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { Student } from './student.entity';
|
||||
|
||||
@Entity('student_wallets')
|
||||
export class StudentWallet {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'student_id', type: 'integer', unique: true })
|
||||
studentId: number;
|
||||
|
||||
@Column({ type: 'decimal', precision: 12, scale: 2, default: 0 })
|
||||
balance: number;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn({ name: 'updated_at' })
|
||||
updatedAt: Date;
|
||||
|
||||
@OneToOne(() => Student, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'student_id' })
|
||||
student: Student;
|
||||
}
|
||||
32
apps/server/src/entities/wallet-transaction.entity.ts
Normal file
32
apps/server/src/entities/wallet-transaction.entity.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
|
||||
|
||||
@Entity('wallet_transactions')
|
||||
@Index(['studentId', 'createdAt'])
|
||||
export class WalletTransaction {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ name: 'student_id', type: 'integer' })
|
||||
studentId: number;
|
||||
|
||||
@Column({ name: 'bill_id', type: 'integer', nullable: true })
|
||||
billId: number | null;
|
||||
|
||||
@Column({ type: 'varchar', length: 30 })
|
||||
type: 'recharge' | 'adjustment' | 'bill_payment' | 'bill_refund';
|
||||
|
||||
@Column({ type: 'decimal', precision: 12, scale: 2 })
|
||||
amount: number;
|
||||
|
||||
@Column({ name: 'balance_after', type: 'decimal', precision: 12, scale: 2 })
|
||||
balanceAfter: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 300, nullable: true })
|
||||
description: string | null;
|
||||
|
||||
@Column({ name: 'recorded_by', type: 'integer', nullable: true })
|
||||
recordedBy: number | null;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at' })
|
||||
createdAt: Date;
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
import { IsString, IsOptional, IsInt, IsBoolean, IsIn } from 'class-validator';
|
||||
import { IsString, IsOptional, IsInt, IsBoolean, IsIn, IsNotEmpty, Matches, MaxLength, Min } from 'class-validator';
|
||||
|
||||
export class CreateExpenseTypeDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(30)
|
||||
@Matches(/^[a-z][a-z0-9_]*$/)
|
||||
code: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(30)
|
||||
@Matches(/\S/)
|
||||
name: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -13,12 +19,16 @@ export class CreateExpenseTypeDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export class UpdateExpenseTypeDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(30)
|
||||
@Matches(/\S/)
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -27,6 +37,7 @@ export class UpdateExpenseTypeDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
sortOrder?: number;
|
||||
|
||||
@IsOptional()
|
||||
|
||||
68
apps/server/src/expense-types/expense-types.service.spec.ts
Normal file
68
apps/server/src/expense-types/expense-types.service.spec.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import 'reflect-metadata';
|
||||
import { validate } from 'class-validator';
|
||||
import { ConflictException, NotFoundException } from '@nestjs/common';
|
||||
import { CreateExpenseTypeDto, UpdateExpenseTypeDto } from './dto/expense-type.dto';
|
||||
import { ExpenseTypesService } from './expense-types.service';
|
||||
|
||||
describe('ExpenseTypesService boundaries', () => {
|
||||
const createService = () => {
|
||||
const repo = {
|
||||
findOne: jest.fn(),
|
||||
create: jest.fn((value) => value),
|
||||
save: jest.fn(async (value) => ({ id: 1, ...value })),
|
||||
remove: jest.fn(),
|
||||
};
|
||||
return { service: new ExpenseTypesService(repo as never), repo };
|
||||
};
|
||||
|
||||
it('normalizes code and name before duplicate detection and save', async () => {
|
||||
const { service, repo } = createService();
|
||||
repo.findOne.mockResolvedValue(null);
|
||||
await service.create({ code: ' water ', name: ' 水费 ' });
|
||||
expect(repo.findOne).toHaveBeenCalledWith({ where: { code: 'water' } });
|
||||
expect(repo.create).toHaveBeenCalledWith({ code: 'water', name: '水费' });
|
||||
});
|
||||
|
||||
it('rejects a normalized duplicate code', async () => {
|
||||
const { service, repo } = createService();
|
||||
repo.findOne.mockResolvedValue({ id: 1, code: 'water' });
|
||||
await expect(service.create({ code: ' water ', name: '水费' }))
|
||||
.rejects.toBeInstanceOf(ConflictException);
|
||||
});
|
||||
|
||||
it('trims an updated name and preserves omitted fields', async () => {
|
||||
const { service, repo } = createService();
|
||||
repo.findOne.mockResolvedValue({ id: 1, code: 'water', name: '旧名称', enabled: true });
|
||||
await service.update(1, { name: ' 新名称 ' });
|
||||
expect(repo.save).toHaveBeenCalledWith(expect.objectContaining({
|
||||
code: 'water', name: '新名称', enabled: true,
|
||||
}));
|
||||
});
|
||||
|
||||
it('rejects removal of a missing type', async () => {
|
||||
const { service, repo } = createService();
|
||||
repo.findOne.mockResolvedValue(null);
|
||||
await expect(service.remove(999)).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(repo.remove).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('expense type DTO boundaries', () => {
|
||||
it.each(['Water', '1water', 'water-fee', '', 'a'.repeat(31)])('rejects code %j', async (code) => {
|
||||
const dto = Object.assign(new CreateExpenseTypeDto(), { code, name: '水费' });
|
||||
expect((await validate(dto)).some((error) => error.property === 'code')).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['', ' '])('rejects blank name %j and negative sort order', async (name) => {
|
||||
const dto = Object.assign(new CreateExpenseTypeDto(), {
|
||||
code: 'water', name, sortOrder: -1,
|
||||
});
|
||||
const properties = (await validate(dto)).map((error) => error.property);
|
||||
expect(properties).toEqual(expect.arrayContaining(['name', 'sortOrder']));
|
||||
});
|
||||
|
||||
it('accepts zero sort order and boolean enabled update', async () => {
|
||||
const dto = Object.assign(new UpdateExpenseTypeDto(), { sortOrder: 0, enabled: false });
|
||||
expect(await validate(dto)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -52,14 +52,15 @@ export class ExpenseTypesService {
|
||||
}
|
||||
|
||||
async create(dto: CreateExpenseTypeDto): Promise<ExpenseType> {
|
||||
const exists = await this.repo.findOne({ where: { code: dto.code } });
|
||||
const normalized = { ...dto, code: dto.code.trim(), name: dto.name.trim() };
|
||||
const exists = await this.repo.findOne({ where: { code: normalized.code } });
|
||||
if (exists) throw new ConflictException('费用类型代码已存在');
|
||||
return this.repo.save(this.repo.create(dto));
|
||||
return this.repo.save(this.repo.create(normalized));
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateExpenseTypeDto): Promise<ExpenseType> {
|
||||
const t = await this.findOne(id);
|
||||
Object.assign(t, dto);
|
||||
Object.assign(t, dto, dto.name === undefined ? {} : { name: dto.name.trim() });
|
||||
return this.repo.save(t);
|
||||
}
|
||||
|
||||
|
||||
31
apps/server/src/expenses/dto/expense.dto.spec.ts
Normal file
31
apps/server/src/expenses/dto/expense.dto.spec.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'reflect-metadata';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { validate } from 'class-validator';
|
||||
import { BatchRoomExpenseDto } from './expense.dto';
|
||||
|
||||
describe('BatchRoomExpenseDto boundaries', () => {
|
||||
it.each([
|
||||
{ expenses: [] },
|
||||
{ expenses: [{ roomId: 1, expenseType: 'water', amount: 0 }] },
|
||||
{ expenses: [{ roomId: 1, expenseType: 'water', amount: -1 }] },
|
||||
{ expenses: [{ roomId: 1, expenseType: 'water', amount: 1.001 }] },
|
||||
{ periodStart: '2026-02-31' },
|
||||
])('rejects invalid batch payload %#', async (override) => {
|
||||
const dto = plainToInstance(BatchRoomExpenseDto, {
|
||||
periodStart: '2026-07-01',
|
||||
periodEnd: '2026-07-31',
|
||||
expenses: [{ roomId: 1, expenseType: 'water', amount: 10 }],
|
||||
...override,
|
||||
});
|
||||
await expect(validate(dto)).resolves.not.toHaveLength(0);
|
||||
});
|
||||
|
||||
it('accepts a valid batch payload', async () => {
|
||||
const dto = plainToInstance(BatchRoomExpenseDto, {
|
||||
periodStart: '2026-07-01',
|
||||
periodEnd: '2026-07-31',
|
||||
expenses: [{ roomId: 1, expenseType: 'water', amount: 10.25 }],
|
||||
});
|
||||
await expect(validate(dto)).resolves.toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { IsInt, IsString, IsNumber, IsOptional } from 'class-validator';
|
||||
import { ArrayNotEmpty, IsArray, IsDateString, IsIn, IsInt, IsISO8601, IsString, IsNumber, IsOptional, Matches, Min, ValidateNested } from 'class-validator';
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class CreateRoomExpenseDto {
|
||||
@IsInt()
|
||||
@@ -7,13 +9,18 @@ export class CreateRoomExpenseDto {
|
||||
@IsString()
|
||||
expenseType: string;
|
||||
|
||||
@IsNumber()
|
||||
@IsNumber({ maxDecimalPlaces: 2 })
|
||||
@Min(0.01)
|
||||
amount: number;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
@IsDateString()
|
||||
periodStart: string;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
@IsDateString()
|
||||
periodEnd: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -32,10 +39,13 @@ export class CreatePersonalExpenseDto {
|
||||
@IsString()
|
||||
expenseType: string;
|
||||
|
||||
@IsNumber()
|
||||
@IsNumber({ maxDecimalPlaces: 2 })
|
||||
@Min(0.01)
|
||||
amount: number;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
@IsDateString()
|
||||
expenseDate: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -43,12 +53,88 @@ export class CreatePersonalExpenseDto {
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export class BatchRoomExpenseDto {
|
||||
|
||||
export class UpdateRoomExpenseDto extends PartialType(CreateRoomExpenseDto) {}
|
||||
|
||||
export class UpdatePersonalExpenseDto extends PartialType(CreatePersonalExpenseDto) {}
|
||||
|
||||
export class QueryRoomExpenseDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
roomId?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
periodStart?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
periodEnd?: string;
|
||||
}
|
||||
|
||||
export class QueryPersonalExpenseDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
studentId?: number;
|
||||
}
|
||||
|
||||
export class BatchRoomExpenseItemDto {
|
||||
@IsInt()
|
||||
roomId: number;
|
||||
|
||||
@IsString()
|
||||
expenseType: string;
|
||||
|
||||
@IsNumber({ maxDecimalPlaces: 2 })
|
||||
@Min(0.01)
|
||||
amount: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export class BatchRoomExpenseDto {
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
@IsDateString()
|
||||
periodStart: string;
|
||||
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
@IsISO8601({ strict: true })
|
||||
@IsDateString()
|
||||
periodEnd: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => BatchRoomExpenseItemDto)
|
||||
expenses: BatchRoomExpenseItemDto[];
|
||||
}
|
||||
|
||||
|
||||
export class CreateStudentUtilityBillDto {
|
||||
@IsInt()
|
||||
studentId: number;
|
||||
|
||||
@IsIn(['water', 'electricity'])
|
||||
expenseType: 'water' | 'electricity';
|
||||
|
||||
@IsNumber({ maxDecimalPlaces: 2 })
|
||||
@Min(0.01)
|
||||
amount: number;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
periodStart: string;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^\d{4}-\d{2}-\d{2}$/)
|
||||
periodEnd: string;
|
||||
|
||||
expenses: { roomId: number; expenseType: string; amount: number; description?: string }[];
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
}
|
||||
|
||||
107
apps/server/src/expenses/expenses.boundaries.spec.ts
Normal file
107
apps/server/src/expenses/expenses.boundaries.spec.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { ExpensesService } from './expenses.service';
|
||||
import { PersonalExpense } from '../entities/personal-expense.entity';
|
||||
|
||||
const qb = (affected = 1) => ({
|
||||
delete: jest.fn().mockReturnThis(),
|
||||
where: jest.fn().mockReturnThis(),
|
||||
execute: jest.fn().mockResolvedValue({ affected }),
|
||||
});
|
||||
|
||||
function createService(options?: {
|
||||
roomFind?: any[];
|
||||
personalFind?: any[];
|
||||
roomExpense?: any;
|
||||
personalExpense?: any;
|
||||
}) {
|
||||
const roomExpRepo = {
|
||||
create: jest.fn((value) => value),
|
||||
save: jest.fn(async (value) => value),
|
||||
find: jest.fn().mockResolvedValue(options?.roomFind ?? []),
|
||||
findOne: jest.fn().mockResolvedValue(options?.roomExpense ?? null),
|
||||
createQueryBuilder: jest.fn(() => qb()),
|
||||
};
|
||||
const personalExpRepo = {
|
||||
create: jest.fn((value) => value),
|
||||
save: jest.fn(async (value) => value),
|
||||
find: jest.fn().mockResolvedValue(options?.personalFind ?? []),
|
||||
findOne: jest.fn().mockResolvedValue(options?.personalExpense ?? null),
|
||||
createQueryBuilder: jest.fn(() => qb()),
|
||||
delete: jest.fn(),
|
||||
};
|
||||
const roomRepo = {
|
||||
find: jest.fn().mockImplementation(async () => options?.roomFind ?? []),
|
||||
findOne: jest.fn().mockResolvedValue({ id: 1 }),
|
||||
};
|
||||
const studentRepo = { findOne: jest.fn().mockResolvedValue({ id: 1 }) };
|
||||
return {
|
||||
service: new ExpensesService(roomExpRepo as any, personalExpRepo as any, roomRepo as any, studentRepo as any, {} as any),
|
||||
roomExpRepo,
|
||||
personalExpRepo,
|
||||
roomRepo,
|
||||
};
|
||||
}
|
||||
|
||||
describe('ExpensesService boundaries', () => {
|
||||
it('rejects an empty room-expense batch', async () => {
|
||||
const { service, roomExpRepo } = createService();
|
||||
await expect(service.batchCreateRoomExpenses({
|
||||
periodStart: '2026-07-01',
|
||||
periodEnd: '2026-07-31',
|
||||
expenses: [],
|
||||
})).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(roomExpRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a batch when any room does not exist', async () => {
|
||||
const { service, roomExpRepo } = createService({ roomFind: [{ id: 1 }] });
|
||||
await expect(service.batchCreateRoomExpenses({
|
||||
periodStart: '2026-07-01',
|
||||
periodEnd: '2026-07-31',
|
||||
expenses: [
|
||||
{ roomId: 1, expenseType: 'water', amount: 10 },
|
||||
{ roomId: 2, expenseType: 'water', amount: 20 },
|
||||
],
|
||||
})).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(roomExpRepo.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a reversed room-expense period', async () => {
|
||||
const { service } = createService();
|
||||
await expect(service.createRoomExpense({
|
||||
roomId: 1,
|
||||
expenseType: 'water',
|
||||
amount: 10,
|
||||
periodStart: '2026-08-01',
|
||||
periodEnd: '2026-07-31',
|
||||
})).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects a batch delete when only part of the ids exist', async () => {
|
||||
const { service, roomExpRepo } = createService({ roomFind: [{ id: 1 }] });
|
||||
await expect(service.batchDeleteRoomExpenses([1, 2])).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(roomExpRepo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not edit or delete a personal expense already linked to a bill', async () => {
|
||||
const linked = { id: 1, studentId: 1, amount: 20, billId: 9 } as PersonalExpense;
|
||||
const { service, personalExpRepo } = createService({ personalExpense: linked });
|
||||
|
||||
await expect(service.updatePersonalExpense(1, { amount: 30 })).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(service.deletePersonalExpense(1)).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(personalExpRepo.save).not.toHaveBeenCalled();
|
||||
expect(personalExpRepo.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a personal-expense batch delete containing billed records', async () => {
|
||||
const { service, personalExpRepo } = createService({
|
||||
personalFind: [
|
||||
{ id: 1, billId: null },
|
||||
{ id: 2, billId: 9 },
|
||||
],
|
||||
});
|
||||
|
||||
await expect(service.batchDeletePersonalExpenses([1, 2])).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(personalExpRepo.createQueryBuilder).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Res,
|
||||
UseInterceptors,
|
||||
UploadedFile,
|
||||
ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Response } from 'express';
|
||||
@@ -20,6 +21,11 @@ import {
|
||||
CreateRoomExpenseDto,
|
||||
CreatePersonalExpenseDto,
|
||||
BatchRoomExpenseDto,
|
||||
CreateStudentUtilityBillDto,
|
||||
QueryPersonalExpenseDto,
|
||||
QueryRoomExpenseDto,
|
||||
UpdatePersonalExpenseDto,
|
||||
UpdateRoomExpenseDto,
|
||||
} from './dto/expense.dto';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||
@@ -78,6 +84,25 @@ export class ExpensesController {
|
||||
return this.service.getFormLookups();
|
||||
}
|
||||
|
||||
@Post('student-utility')
|
||||
@RequirePermission('expense:create')
|
||||
async createStudentUtilityBill(@Body() dto: CreateStudentUtilityBillDto, @Request() req: any) {
|
||||
const result = await this.service.createStudentUtilityBill(dto, req.user?.id);
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '费用管理',
|
||||
action: '录入学生水电费并出账',
|
||||
targetId: result.bill.id,
|
||||
targetType: 'bill',
|
||||
detail: `学生${dto.studentId} ${dto.expenseType} ¥${dto.amount},自动扣款 ¥${result.bill.paidAmount}`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('room')
|
||||
@RequirePermission('expense:create')
|
||||
async createRoomExpense(@Body() dto: CreateRoomExpenseDto, @Request() req: any) {
|
||||
@@ -116,29 +141,21 @@ export class ExpensesController {
|
||||
|
||||
@Get('room')
|
||||
@RequirePermission('expense:view')
|
||||
findRoomExpenses(
|
||||
@Query('roomId') roomId?: string,
|
||||
@Query('periodStart') periodStart?: string,
|
||||
@Query('periodEnd') periodEnd?: string,
|
||||
) {
|
||||
return this.service.findRoomExpenses({
|
||||
roomId: roomId ? +roomId : undefined,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
});
|
||||
findRoomExpenses(@Query() query: QueryRoomExpenseDto) {
|
||||
return this.service.findRoomExpenses(query);
|
||||
}
|
||||
|
||||
@Delete('room/:id')
|
||||
@RequirePermission('expense:delete')
|
||||
async deleteRoomExpense(@Param('id') id: string, @Request() req: any) {
|
||||
async deleteRoomExpense(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.deleteRoomExpense(+id);
|
||||
const result = await this.service.deleteRoomExpense(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '费用管理',
|
||||
action: '删除费用',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'room_expense',
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -166,18 +183,18 @@ export class ExpensesController {
|
||||
@Put('room/:id')
|
||||
@RequirePermission('expense:edit')
|
||||
async updateRoomExpense(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: CreateRoomExpenseDto,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdateRoomExpenseDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.updateRoomExpense(+id, dto);
|
||||
const result = await this.service.updateRoomExpense(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '费用管理',
|
||||
action: '编辑费用',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
targetType: 'room_expense',
|
||||
detail: `¥${dto.amount} ${dto.expenseType}`,
|
||||
ipAddress,
|
||||
@@ -205,21 +222,21 @@ export class ExpensesController {
|
||||
|
||||
@Get('personal')
|
||||
@RequirePermission('expense:view')
|
||||
findPersonalExpenses(@Query('studentId') studentId?: string) {
|
||||
return this.service.findPersonalExpenses({ studentId: studentId ? +studentId : undefined });
|
||||
findPersonalExpenses(@Query() query: QueryPersonalExpenseDto) {
|
||||
return this.service.findPersonalExpenses(query);
|
||||
}
|
||||
|
||||
@Delete('personal/:id')
|
||||
@RequirePermission('expense:delete')
|
||||
async deletePersonalExpense(@Param('id') id: string, @Request() req: any) {
|
||||
async deletePersonalExpense(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.deletePersonalExpense(+id);
|
||||
const result = await this.service.deletePersonalExpense(id);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '费用管理',
|
||||
action: '删除费用',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
});
|
||||
@@ -246,18 +263,18 @@ export class ExpensesController {
|
||||
@Put('personal/:id')
|
||||
@RequirePermission('expense:edit')
|
||||
async updatePersonalExpense(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: CreatePersonalExpenseDto,
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() dto: UpdatePersonalExpenseDto,
|
||||
@Request() req: any,
|
||||
) {
|
||||
const { ipAddress, userAgent } = extractRequestInfo(req);
|
||||
const result = await this.service.updatePersonalExpense(+id, dto);
|
||||
const result = await this.service.updatePersonalExpense(id, dto);
|
||||
await this.logService.log({
|
||||
userId: req.user?.id,
|
||||
username: req.user?.username,
|
||||
module: '费用管理',
|
||||
action: '编辑费用',
|
||||
targetId: +id,
|
||||
targetId: id,
|
||||
detail: `¥${dto.amount} ${dto.expenseType}`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
|
||||
@@ -7,11 +7,13 @@ import { Student } from '../entities/student.entity';
|
||||
import { ExpensesService } from './expenses.service';
|
||||
import { ExpensesController } from './expenses.controller';
|
||||
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
|
||||
import { BillsModule } from '../bills/bills.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([RoomExpense, PersonalExpense, Room, Student]),
|
||||
OperationLogsModule,
|
||||
BillsModule,
|
||||
],
|
||||
controllers: [ExpensesController],
|
||||
providers: [ExpensesService],
|
||||
|
||||
@@ -9,8 +9,10 @@ import {
|
||||
CreateRoomExpenseDto,
|
||||
CreatePersonalExpenseDto,
|
||||
BatchRoomExpenseDto,
|
||||
CreateStudentUtilityBillDto,
|
||||
} from './dto/expense.dto';
|
||||
import { RoomsService } from '../rooms/rooms.service';
|
||||
import { BillsService } from '../bills/bills.service';
|
||||
|
||||
|
||||
@Injectable()
|
||||
@@ -20,6 +22,7 @@ export class ExpensesService {
|
||||
@InjectRepository(PersonalExpense) private personalExpRepo: Repository<PersonalExpense>,
|
||||
@InjectRepository(Room) private roomRepo: Repository<Room>,
|
||||
@InjectRepository(Student) private studentRepo: Repository<Student>,
|
||||
private billsService: BillsService,
|
||||
) {}
|
||||
|
||||
async getFormLookups() {
|
||||
@@ -39,6 +42,8 @@ export class ExpensesService {
|
||||
|
||||
// 宿舍费用
|
||||
async createRoomExpense(dto: CreateRoomExpenseDto, userId?: number) {
|
||||
this.assertValidPeriod(dto.periodStart, dto.periodEnd);
|
||||
this.assertPositiveAmount(dto.amount);
|
||||
const room = await this.roomRepo.findOne({ where: { id: dto.roomId } });
|
||||
if (!room) throw new NotFoundException('宿舍不存在');
|
||||
const entity = this.roomExpRepo.create({ ...dto, recordedBy: userId });
|
||||
@@ -46,6 +51,12 @@ export class ExpensesService {
|
||||
}
|
||||
|
||||
async batchCreateRoomExpenses(dto: BatchRoomExpenseDto, userId?: number) {
|
||||
this.assertValidPeriod(dto.periodStart, dto.periodEnd);
|
||||
if (!dto.expenses?.length) throw new BadRequestException('请至少填写一条费用');
|
||||
dto.expenses.forEach((expense) => this.assertPositiveAmount(expense.amount));
|
||||
const roomIds = [...new Set(dto.expenses.map((expense) => expense.roomId))];
|
||||
const existingRooms = await this.roomRepo.find({ where: { id: In(roomIds) }, select: ['id'] });
|
||||
if (existingRooms.length !== roomIds.length) throw new NotFoundException('部分宿舍不存在');
|
||||
const entities = dto.expenses.map((e) => {
|
||||
const entity = this.roomExpRepo.create({
|
||||
roomId: e.roomId,
|
||||
@@ -80,11 +91,14 @@ export class ExpensesService {
|
||||
}
|
||||
|
||||
async batchDeleteRoomExpenses(ids: number[]) {
|
||||
if (!ids || ids.length === 0) throw new BadRequestException('请选择要删除的记录');
|
||||
const uniqueIds = [...new Set(ids || [])];
|
||||
if (uniqueIds.length === 0) throw new BadRequestException('请选择要删除的记录');
|
||||
const existing = await this.roomExpRepo.find({ where: { id: In(uniqueIds) }, select: ['id'] });
|
||||
if (existing.length !== uniqueIds.length) throw new NotFoundException('部分费用记录不存在');
|
||||
const result = await this.roomExpRepo
|
||||
.createQueryBuilder()
|
||||
.delete()
|
||||
.where('id IN (:...ids)', { ids })
|
||||
.where('id IN (:...ids)', { ids: uniqueIds })
|
||||
.execute();
|
||||
return { message: '批量删除成功', deleted: result.affected || 0 };
|
||||
}
|
||||
@@ -92,12 +106,65 @@ export class ExpensesService {
|
||||
async updateRoomExpense(id: number, dto: Partial<CreateRoomExpenseDto>) {
|
||||
const e = await this.roomExpRepo.findOne({ where: { id } });
|
||||
if (!e) throw new NotFoundException('费用记录不存在');
|
||||
const periodStart = dto.periodStart ?? e.periodStart;
|
||||
const periodEnd = dto.periodEnd ?? e.periodEnd;
|
||||
this.assertValidPeriod(periodStart, periodEnd);
|
||||
if (dto.amount !== undefined) this.assertPositiveAmount(dto.amount);
|
||||
if (dto.roomId !== undefined && dto.roomId !== e.roomId) {
|
||||
const room = await this.roomRepo.findOne({ where: { id: dto.roomId } });
|
||||
if (!room) throw new NotFoundException('宿舍不存在');
|
||||
}
|
||||
Object.assign(e, dto);
|
||||
return this.roomExpRepo.save(e);
|
||||
}
|
||||
|
||||
private assertPositiveAmount(amount: number) {
|
||||
if (!Number.isFinite(amount) || Math.abs(amount * 100 - Math.round(amount * 100)) > 1e-8) {
|
||||
throw new BadRequestException('费用金额最多保留两位小数');
|
||||
}
|
||||
if (amount <= 0) throw new BadRequestException('费用金额必须大于0');
|
||||
}
|
||||
|
||||
private assertValidPeriod(periodStart: string, periodEnd: string) {
|
||||
if (!this.isValidDate(periodStart) || !this.isValidDate(periodEnd) || periodEnd < periodStart) {
|
||||
throw new BadRequestException('账期无效,结束日期不能早于开始日期');
|
||||
}
|
||||
}
|
||||
|
||||
private isValidDate(value: string) {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value || '')) return false;
|
||||
const date = new Date(`${value}T00:00:00Z`);
|
||||
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
|
||||
async createStudentUtilityBill(dto: CreateStudentUtilityBillDto, userId?: number) {
|
||||
this.assertValidPeriod(dto.periodStart, dto.periodEnd);
|
||||
this.assertPositiveAmount(dto.amount);
|
||||
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
const expense = await this.personalExpRepo.save(
|
||||
this.personalExpRepo.create({
|
||||
studentId: dto.studentId,
|
||||
expenseType: dto.expenseType,
|
||||
amount: dto.amount,
|
||||
expenseDate: dto.periodEnd,
|
||||
description: dto.description || (dto.expenseType === 'water' ? '学生水费' : '学生电费'),
|
||||
recordedBy: userId,
|
||||
billId: null,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
const bill = await this.billsService.createImmediatePersonalBill(expense, dto.periodStart, dto.periodEnd, userId);
|
||||
return { expense, bill };
|
||||
} catch (error) {
|
||||
await this.personalExpRepo.delete(expense.id);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 个人附加费
|
||||
async createPersonalExpense(dto: CreatePersonalExpenseDto, userId?: number) {
|
||||
this.assertPositiveAmount(dto.amount);
|
||||
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
const entity = this.personalExpRepo.create({ ...dto, recordedBy: userId });
|
||||
@@ -117,16 +184,23 @@ export class ExpensesService {
|
||||
async deletePersonalExpense(id: number) {
|
||||
const e = await this.personalExpRepo.findOne({ where: { id } });
|
||||
if (!e) throw new NotFoundException('费用记录不存在');
|
||||
if (e.billId) throw new BadRequestException('已计入账单的个人费用不能删除,请先取消账单');
|
||||
await this.personalExpRepo.delete(id);
|
||||
return { message: '删除成功' };
|
||||
}
|
||||
|
||||
async batchDeletePersonalExpenses(ids: number[]) {
|
||||
if (!ids || ids.length === 0) throw new BadRequestException('请选择要删除的记录');
|
||||
const uniqueIds = [...new Set(ids || [])];
|
||||
if (uniqueIds.length === 0) throw new BadRequestException('请选择要删除的记录');
|
||||
const existing = await this.personalExpRepo.find({ where: { id: In(uniqueIds) } });
|
||||
if (existing.length !== uniqueIds.length) throw new NotFoundException('部分费用记录不存在');
|
||||
if (existing.some((expense) => expense.billId)) {
|
||||
throw new BadRequestException('选中记录包含已计入账单的个人费用');
|
||||
}
|
||||
const result = await this.personalExpRepo
|
||||
.createQueryBuilder()
|
||||
.delete()
|
||||
.where('id IN (:...ids)', { ids })
|
||||
.where('id IN (:...ids)', { ids: uniqueIds })
|
||||
.execute();
|
||||
return { message: '批量删除成功', deleted: result.affected || 0 };
|
||||
}
|
||||
@@ -134,6 +208,12 @@ export class ExpensesService {
|
||||
async updatePersonalExpense(id: number, dto: Partial<CreatePersonalExpenseDto>) {
|
||||
const e = await this.personalExpRepo.findOne({ where: { id } });
|
||||
if (!e) throw new NotFoundException('费用记录不存在');
|
||||
if (e.billId) throw new BadRequestException('已计入账单的个人费用不能修改,请先取消账单');
|
||||
if (dto.amount !== undefined) this.assertPositiveAmount(dto.amount);
|
||||
if (dto.studentId !== undefined && dto.studentId !== e.studentId) {
|
||||
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });
|
||||
if (!student) throw new NotFoundException('学生不存在');
|
||||
}
|
||||
Object.assign(e, dto);
|
||||
return this.personalExpRepo.save(e);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ describe('IntegrationConfigService.testConnection', () => {
|
||||
}),
|
||||
};
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: jest.fn().mockResolvedValue({ accessToken: 'token' }),
|
||||
}) as never;
|
||||
|
||||
@@ -47,3 +48,52 @@ describe('IntegrationConfigService.testConnection', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('IntegrationConfigService security boundaries', () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('masks AppSecret without mutating the parsed source object', async () => {
|
||||
const content = JSON.stringify({
|
||||
config: { corpId: 'corp', agentId: 'agent', appSecret: 'top-secret' },
|
||||
});
|
||||
const configRepo = {
|
||||
findOne: jest.fn().mockResolvedValue({ id: 1, type: 'THIRD' }),
|
||||
};
|
||||
const detailRepo = {
|
||||
find: jest.fn().mockResolvedValue([{ type: 'DINGTALK_SYNC', enable: true, content }]),
|
||||
};
|
||||
const service = new IntegrationConfigService(configRepo as never, detailRepo as never);
|
||||
|
||||
await expect(service.getThirdConfig()).resolves.toEqual([
|
||||
{
|
||||
type: 'DINGTALK',
|
||||
verify: true,
|
||||
config: { corpId: 'corp', agentId: 'agent' },
|
||||
},
|
||||
]);
|
||||
expect(JSON.parse(content).config.appSecret).toBe('top-secret');
|
||||
});
|
||||
|
||||
it('treats a non-2xx DingTalk token response as a failed connection even if it contains a token field', async () => {
|
||||
const configRepo = { findOne: jest.fn() };
|
||||
const detailRepo = { findOne: jest.fn() };
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
json: jest.fn().mockResolvedValue({ accessToken: 'must-not-be-used' }),
|
||||
}) as never;
|
||||
const service = new IntegrationConfigService(configRepo as never, detailRepo as never);
|
||||
|
||||
await expect(
|
||||
service.testConnection('DINGTALK' as never, {
|
||||
corpId: 'corp',
|
||||
agentId: 'agent',
|
||||
appSecret: 'secret',
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -205,13 +205,21 @@ export class IntegrationConfigService {
|
||||
|
||||
/** 调钉钉新版接口拿 access_token */
|
||||
private async fetchDingTalkToken(appKey: string, appSecret: string): Promise<string | null> {
|
||||
const res = await fetch('https://api.dingtalk.com/v1.0/oauth2/accessToken', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ appKey, appSecret }),
|
||||
});
|
||||
const body = (await res.json()) as { accessToken?: string; expireIn?: number };
|
||||
return body.accessToken || null;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 10_000);
|
||||
try {
|
||||
const res = await fetch('https://api.dingtalk.com/v1.0/oauth2/accessToken', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ appKey, appSecret }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const body = (await res.json()) as { accessToken?: string; expireIn?: number };
|
||||
return body.accessToken || null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析并脱敏:删掉 appSecret 后返回 config 对象 */
|
||||
@@ -219,9 +227,10 @@ export class IntegrationConfigService {
|
||||
if (!content) return {};
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
const cfg = parsed.config || parsed;
|
||||
if (cfg.appSecret) delete cfg.appSecret;
|
||||
return cfg;
|
||||
const source = parsed.config || parsed;
|
||||
if (!source || typeof source !== 'object' || Array.isArray(source)) return {};
|
||||
const { appSecret: _appSecret, ...masked } = source as Record<string, unknown>;
|
||||
return masked;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -174,3 +174,41 @@ describe('DingTalkService — attendance machine only group', () => {
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
describe('DingTalkService — department user pagination boundaries', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
global.fetch = undefined as unknown as typeof fetch;
|
||||
});
|
||||
|
||||
it('stops when DingTalk says there is another page but omits the next cursor', async () => {
|
||||
const service = new DingTalkService({} as never, {} as never);
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
json: jest.fn().mockResolvedValue({
|
||||
errcode: 0,
|
||||
errmsg: 'ok',
|
||||
result: {
|
||||
list: [{ userid: 'u1', name: 'Alice', mobile: '', dept_id_list: [1] }],
|
||||
has_more: true,
|
||||
},
|
||||
}),
|
||||
}) as jest.MockedFunction<typeof fetch>;
|
||||
|
||||
await expect((service as any).getDeptUsers('token', 1)).resolves.toHaveLength(1);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stops when the next cursor repeats the current cursor', async () => {
|
||||
const service = new DingTalkService({} as never, {} as never);
|
||||
global.fetch = jest.fn().mockResolvedValue({
|
||||
json: jest.fn().mockResolvedValue({
|
||||
errcode: 0,
|
||||
errmsg: 'ok',
|
||||
result: { list: [], has_more: true, next_cursor: 0 },
|
||||
}),
|
||||
}) as jest.MockedFunction<typeof fetch>;
|
||||
|
||||
await expect((service as any).getDeptUsers('token', 1)).resolves.toEqual([]);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -51,6 +51,11 @@ export interface DingTalkAttendanceResult {
|
||||
actualCheckTime: string;
|
||||
checkId: string;
|
||||
checkType: string;
|
||||
/** 钉钉返回的打卡来源,例如 ATM / USER / BEACON。 */
|
||||
sourceType: string;
|
||||
/** 部分钉钉租户会额外返回考勤机名称或编号。 */
|
||||
deviceName?: string;
|
||||
deviceId?: string;
|
||||
}
|
||||
|
||||
// ── 组织架构 API 类型 ──
|
||||
@@ -274,8 +279,13 @@ export class DingTalkService {
|
||||
if (body.errcode === 0 && body.result) {
|
||||
all.push(...body.result.list);
|
||||
hasMore = body.result.has_more;
|
||||
if (hasMore && body.result.next_cursor !== undefined) {
|
||||
cursor = body.result.next_cursor;
|
||||
if (hasMore) {
|
||||
if (body.result.next_cursor === undefined || body.result.next_cursor === cursor) {
|
||||
this.logger.error(`获取部门 ${deptId} 用户失败: 分页游标未前进`);
|
||||
hasMore = false;
|
||||
} else {
|
||||
cursor = body.result.next_cursor;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hasMore = false;
|
||||
@@ -505,6 +515,8 @@ export class DingTalkService {
|
||||
checkType?: string; timeResult?: string;
|
||||
locationResult?: string; locationMethod?: string;
|
||||
userAddress?: string; userLongitude?: number; userLatitude?: number;
|
||||
deviceName?: string; deviceId?: string | number;
|
||||
attendanceMachineName?: string; attendanceMachineId?: string | number;
|
||||
}>;
|
||||
};
|
||||
if (data.errcode !== 0) throw new Error(`钉钉考勤获取失败: ${data.errmsg}`);
|
||||
@@ -520,7 +532,10 @@ export class DingTalkService {
|
||||
planCheckTime: '',
|
||||
actualCheckTime: new Date(r.userCheckTime).toISOString(),
|
||||
checkId: String(r.id),
|
||||
checkType: r.checkType ?? r.sourceType ?? '',
|
||||
checkType: r.checkType ?? '',
|
||||
sourceType: r.sourceType ?? '',
|
||||
deviceName: r.deviceName ?? r.attendanceMachineName,
|
||||
deviceId: String(r.deviceId ?? r.attendanceMachineId ?? '') || undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'reflect-metadata';
|
||||
import { plainToInstance } from 'class-transformer';
|
||||
import { validate } from 'class-validator';
|
||||
import { NotificationQueryDto } from './notification.dto';
|
||||
import { CreateNotificationDto, NotificationQueryDto } from './notification.dto';
|
||||
|
||||
describe('NotificationQueryDto', () => {
|
||||
it('converts numeric query-string values before integer validation', async () => {
|
||||
@@ -15,3 +15,21 @@ describe('NotificationQueryDto', () => {
|
||||
expect(dto.limit).toBe(20);
|
||||
});
|
||||
});
|
||||
|
||||
describe('notification DTO boundaries', () => {
|
||||
it('rejects an empty recipient set', async () => {
|
||||
const dto = plainToInstance(CreateNotificationDto, {
|
||||
recipientIds: [],
|
||||
type: 'test',
|
||||
title: '标题',
|
||||
});
|
||||
await expect(validate(dto)).resolves.toEqual(expect.arrayContaining([expect.any(Object)]));
|
||||
});
|
||||
|
||||
it('rejects non-positive cursors and page sizes outside 1-100', async () => {
|
||||
for (const value of [{ after: '0' }, { limit: '0' }, { limit: '101' }]) {
|
||||
const dto = plainToInstance(NotificationQueryDto, value);
|
||||
expect(await validate(dto)).not.toEqual([]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
import { IsString, IsNotEmpty, IsOptional, IsArray, IsInt } from 'class-validator';
|
||||
import {
|
||||
ArrayNotEmpty,
|
||||
IsString,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsArray,
|
||||
IsInt,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class CreateNotificationDto {
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsInt({ each: true })
|
||||
recipientIds: number[];
|
||||
|
||||
@@ -27,10 +37,13 @@ export class NotificationQueryDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
after?: number;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(100)
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user