feat: add student wallet utility billing

This commit is contained in:
2026-07-14 20:39:32 +08:00
parent b480070e69
commit c75a08affe
29 changed files with 986 additions and 548 deletions

View File

@@ -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={

View File

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

View File

@@ -51,6 +51,7 @@ const iconMap: Record<string, React.ReactNode> = {
expense: <DollarOutlined />,
bill: <FileTextOutlined />,
deposit: <WalletOutlined />,
wallet: <WalletOutlined />,
classroom: <ReadOutlined />,
rental: <FileProtectOutlined />,
organization: <TagsOutlined />,

View File

@@ -10,7 +10,6 @@ import {
Popconfirm,
Input,
Select,
Tooltip,
Spin,
Empty,
} from 'antd';
@@ -26,174 +25,23 @@ import PermissionButton from '../../components/PermissionButton';
import { downloadBlob } from '../../utils/download';
import { message } from '../../ui/app-message';
const statusMap: Record<string, { text: string; color: string }> = {
draft: { text: '草稿', color: 'default' },
unpaid: { text: '待支付', color: 'orange' },
partially_paid: { text: '部分支付', color: 'gold' },
paid: { text: '已支付', color: 'green' },
cancelled: { text: '已取消', color: 'default' },
};
const typeMap: Record<string, string> = {
water: '水费',
electricity: '电费',
cleaning: '保洁费',
rent: '租金',
damage: '损坏赔偿',
penalty: '罚款',
other: '其他',
};
const escapeHtml = (value: unknown) =>
String(value ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
const money = (value: unknown) => `¥${Number(value || 0).toFixed(2)}`;
const buildBillPrintHtml = (bill: any) => {
const studentName = bill.student?.name || '-';
const status = statusMap[bill.status]?.text || bill.status || '-';
const generatedAt = bill.generatedAt
? dayjs(bill.generatedAt).format('YYYY-MM-DD HH:mm')
: dayjs().format('YYYY-MM-DD HH:mm');
const hasDeposit = Number(bill.availableDeposit || 0) > 0;
const depositDeducted = Number(bill.depositDeductedAmount || 0);
const items = bill.items || [];
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>账单_${escapeHtml(studentName)}_${escapeHtml(bill.id)}</title>
<style>
@page { size: A4; margin: 0; }
* { box-sizing: border-box; }
body {
margin: 0;
color: #000;
background: #f5f5f5;
font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", Arial, sans-serif;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.page {
width: 210mm;
min-height: 297mm;
margin: 0 auto;
padding: 50px;
background: #fff;
}
h1 { margin: 0; text-align: center; font-size: 20px; line-height: 1.35; font-weight: 700; }
.generated-time { margin-top: 8px; text-align: center; color: #666; font-size: 10px; }
.basic-info { margin-top: 24px; font-size: 12px; line-height: 1.8; }
.section-title { margin: 16px 0 6px; font-size: 14px; font-weight: 700; text-decoration: underline; }
.amount-summary { font-size: 12px; line-height: 1.75; }
.total { color: #007aff; font-size: 14px; font-weight: 700; }
.deposit { color: #52c41a; font-size: 11px; }
.deposit-deducted { color: #fa8c16; font-size: 11px; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; margin-top: 8px; }
th, td { padding: 5px 6px; border-bottom: 1px solid #ccc; font-size: 9px; line-height: 1.45; text-align: left; vertical-align: top; word-break: break-word; }
th { color: #333; font-weight: 700; }
td.amount, th.amount { text-align: right; white-space: nowrap; }
.footer { margin-top: 34px; text-align: center; color: #999; font-size: 8px; }
.print-actions {
position: fixed;
right: 18px;
top: 18px;
display: flex;
gap: 8px;
}
.print-actions button {
height: 32px;
padding: 0 12px;
border: 1px solid #1f6feb;
border-radius: 4px;
background: #1f6feb;
color: #fff;
cursor: pointer;
}
@media print {
body { background: #fff; }
.page { margin: 0; }
.print-actions { display: none; }
}
</style>
</head>
<body>
<div class="print-actions">
<button onclick="window.print()">打印 / 另存为 PDF</button>
</div>
<main class="page">
<h1>恭学教育基地水电费账单</h1>
<div class="generated-time">生成时间: ${escapeHtml(generatedAt)}</div>
<div class="basic-info">
<div>学生姓名: ${escapeHtml(studentName)}</div>
<div>计费周期: ${escapeHtml(bill.periodStart)} ~ ${escapeHtml(bill.periodEnd)}</div>
<div>账单状态: ${escapeHtml(status)}</div>
</div>
<section>
<div class="section-title">费用汇总</div>
<div class="amount-summary">
<div>分摊费用: ${escapeHtml(money(bill.sharedAmount))}</div>
<div>个人费用: ${escapeHtml(money(bill.personalAmount))}</div>
<div class="total">应付总额: ${escapeHtml(money(bill.totalAmount))}</div>
${
hasDeposit || depositDeducted > 0
? `<div class="deposit">可用押金: ${escapeHtml(money(bill.availableDeposit))}</div>
${depositDeducted > 0 ? `<div class="deposit-deducted">已扣押金: -${escapeHtml(money(depositDeducted))}</div>` : ''}`
: ''
}
</div>
</section>
<section>
<div class="section-title">费用明细</div>
<table>
<thead>
<tr>
<th style="width: 22%;">费用类型</th>
<th>说明</th>
<th style="width: 11%;">天数</th>
<th style="width: 12%;">总人天</th>
<th class="amount" style="width: 16%;">金额(元)</th>
</tr>
</thead>
<tbody>
${
items.length
? items
.map(
(item: any) => `<tr>
<td>${escapeHtml(typeMap[item.expenseType] || item.expenseType || '-')}</td>
<td>${escapeHtml(item.description || '-')}</td>
<td>${escapeHtml(item.days || 0)}</td>
<td>${escapeHtml(item.totalRoomDays || 0)}</td>
<td class="amount">${escapeHtml(Number(item.studentAmount || 0).toFixed(2))}</td>
</tr>`,
)
.join('')
: '<tr><td colspan="5" style="text-align:center; color:#999;">暂无费用明细</td></tr>'
}
</tbody>
</table>
</section>
<div class="footer">
本账单由恭学教育基地管理系统自动生成
</div>
</main>
<script>
window.addEventListener('load', () => {
setTimeout(() => window.print(), 250);
});
</script>
</body>
</html>`;
};
const BillsPage: React.FC = () => {
const [bills, setBills] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
@@ -239,34 +87,19 @@ const BillsPage: React.FC = () => {
});
}, [bills, searchText, filterStatus]);
const selectedBillRows = useMemo(
() => bills.filter((bill: any) => selectedRows.includes(bill.id)),
[bills, selectedRows],
);
const canBatchConfirm =
selectedBillRows.length > 0
&& selectedBillRows.every((bill: any) => bill.status === 'draft' && bill.depositSufficient);
const canBatchDelete =
selectedBillRows.length > 0 && selectedBillRows.every((bill: any) => bill.status !== 'paid');
const handleGenerate = async () => {
if (saving) return;
setSaving(true);
const values = await generateForm.validateFields();
try {
const values = await generateForm.validateFields();
setSaving(true);
const res: any = await api.post('/bills/generate', {
billingMonth: values.billingMonth.format('YYYY-MM'),
});
message.success(res.message || '生成成功');
setGenerateModal(false);
generateForm.resetFields();
void fetchData();
fetchData();
} catch (e: any) {
// Ant Design 的表单校验失败会 reject字段本身已展示错误无需再弹“生成失败”。
if (!e?.errorFields) {
message.error(e?.message || '生成失败');
}
message.error(e?.message || '生成失败');
} finally {
setSaving(false);
}
@@ -284,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) {
void showDetail(id);
}
} 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 () => {
@@ -346,24 +165,11 @@ const BillsPage: React.FC = () => {
);
};
const handleExportPdf = useCallback(async (billId: number) => {
const printWindow = window.open('', '_blank');
if (!printWindow) {
message.error('无法打开打印窗口,请允许浏览器弹窗后重试');
return;
}
printWindow.document.write('<!doctype html><title>账单加载中</title><body>账单加载中...</body>');
try {
const bill = await api.get(`/bills/${billId}`);
printWindow.document.open();
printWindow.document.write(buildBillPrintHtml(bill));
printWindow.document.close();
} catch (e: any) {
printWindow.close();
message.error(e?.message || '账单数据加载失败');
}
}, []);
const handleExportPdf = (billId: number) => {
downloadBlob(`/bills/export/pdf/${billId}`, `账单_${billId}.pdf`).catch(() =>
message.error('导出失败'),
);
};
const columns = useMemo(() => [
{ title: '学生', width: 120, render: (_: any, r: any) => r.student?.name || '-' },
@@ -390,26 +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: 'depositDeductedAmount',
width: 120,
render: (v: number) =>
Number(v || 0) > 0 ? (
<span style={{ color: '#fa8c16' }}>¥{Number(v).toFixed(2)}</span>
) : (
<span style={{ color: '#999' }}>-</span>
),
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: '状态',
@@ -436,25 +232,6 @@ const BillsPage: React.FC = () => {
>
</PermissionButton>
{record.status === 'draft' && (
<Tooltip
title={
record.depositSufficient
? '确认后将自动从该学生押金余额中扣除账单金额'
: '押金不足,请先到押金管理收取押金'
}
>
<PermissionButton
permission="bill:confirm"
size="small"
type="primary"
disabled={!record.depositSufficient}
onClick={() => updateStatus(record.id, 'paid')}
>
</PermissionButton>
</Tooltip>
)}
<PermissionButton
permission="bill:export-pdf"
size="small"
@@ -463,26 +240,20 @@ const BillsPage: React.FC = () => {
>
PDF
</PermissionButton>
<Popconfirm
title="确定删除此账单?"
onConfirm={() => handleDelete(record.id)}
okText="删除"
cancelText="取消"
>
<PermissionButton
permission="bill:delete"
size="small"
danger
disabled={record.status === 'paid'}
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>
@@ -512,31 +283,25 @@ const BillsPage: React.FC = () => {
value={filterStatus}
onChange={(v) => setFilterStatus(v)}
options={[
{ value: 'draft', 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"
type="primary"
onClick={() => batchUpdateStatus('paid')}
disabled={!canBatchConfirm}
>
</PermissionButton>
<Popconfirm
title={`确定删除选中的 ${selectedRows.length} 条账单?`}
onConfirm={batchDelete}
okText="删除"
cancelText="取消"
disabled={!canBatchDelete}
disabled={selectedRows.length === 0}
>
<PermissionButton
permission="bill:delete"
danger
disabled={!canBatchDelete}
disabled={selectedRows.length === 0}
icon={<DeleteOutlined />}
>
@@ -570,12 +335,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,
@@ -603,9 +363,7 @@ const BillsPage: React.FC = () => {
picker="month"
placeholder="选择月份"
format="YYYY-MM"
disabledDate={(current) =>
!!current && !current.endOf('month').isBefore(dayjs(), 'day')
}
disabledDate={(current) => !!current && !current.endOf('month').isBefore(dayjs(), 'day')}
/>
</Form.Item>
</Form>
@@ -645,37 +403,11 @@ const BillsPage: React.FC = () => {
</strong>
</Descriptions.Item>
</Descriptions>
{(Number(detailModal.availableDeposit || 0) > 0
|| Number(detailModal.depositDeductedAmount || 0) > 0
|| detailModal.status === 'draft') && (
<div
style={{
marginBottom: 16,
padding: 12,
background: detailModal.depositSufficient || detailModal.status === 'paid' ? '#f6ffed' : '#fff2f0',
border: `1px solid ${detailModal.depositSufficient || detailModal.status === 'paid' ? '#b7eb8f' : '#ffccc7'}`,
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.depositDeductedAmount || 0).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 }}

View File

@@ -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}

View 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;

View File

@@ -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,

View File

@@ -5,7 +5,7 @@ import { Bill } from '../entities/bill.entity';
import { BillItem } from '../entities/bill-item.entity';
import { Deposit } from '../entities/deposit.entity';
import * as ExcelJS from 'exceljs';
import PDFDocument from 'pdfkit';
import * as PDFDocument from 'pdfkit';
import { Response } from 'express';
@Injectable()
@@ -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,8 +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: 'depositDeducted', width: 12 },
{ header: '已扣余额', key: 'paidAmount', width: 12 },
{ header: '待补缴', key: 'outstandingAmount', width: 12 },
{ header: '状态', key: 'status', width: 10 },
{ header: '生成时间', key: 'generatedAt', width: 20 },
];
@@ -70,12 +56,13 @@ export class BillsExportService {
ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };
const statusMap: Record<string, string> = {
draft: '草稿',
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));
ws.addRow({
id: bill.id,
studentName: (bill as any).student?.name || '-',
@@ -83,8 +70,8 @@ export class BillsExportService {
shared: Number(bill.sharedAmount),
personal: Number(bill.personalAmount),
total,
deposit: dep,
depositDeducted: Number(bill.depositDeductedAmount || 0),
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') : '',
});
@@ -142,15 +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 depositDeducted = Number(bill.depositDeductedAmount || 0);
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');
@@ -185,8 +166,10 @@ export class BillsExportService {
}
const statusMap: Record<string, string> = {
draft: '草稿',
unpaid: '待支付',
partially_paid: '部分支付',
paid: '已结清',
cancelled: '已取消',
};
// 标题
@@ -216,18 +199,8 @@ export class BillsExportService {
.fillColor('#007AFF')
.text(`应付总额: ¥${totalAmount.toFixed(2)}`);
doc.moveDown(0.3);
if (availableDeposit > 0 || depositDeducted > 0) {
doc
.fontSize(11)
.fillColor('#52C41A')
.text(`可用押金: ¥${availableDeposit.toFixed(2)}`);
if (depositDeducted > 0) {
doc
.fontSize(11)
.fillColor('#FA8C16')
.text(`已扣押金: -¥${depositDeducted.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);
// 明细表格

View File

@@ -7,7 +7,6 @@ import {
Param,
Body,
Query,
ParseIntPipe,
UseGuards,
Request,
Res,
@@ -21,11 +20,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 {
BatchUpdateBillStatusDto,
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';
@@ -93,22 +88,54 @@ export class BillsController {
@Get(':id')
@RequirePermission('bill:view')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.service.findOne(id);
findOne(@Param('id') id: string) {
return this.service.findOne(+id);
}
@Put(':id/status')
@RequirePermission('bill:confirm')
async updateStatus(
@Param('id') id: string,
@Body() dto: UpdateBillStatusDto,
@Request() req: any,
) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.updateStatus(+id, dto);
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账单管理',
action: '确认账单',
targetId: +id,
targetType: 'bill',
ipAddress,
userAgent,
});
// Send bill_paid notification
try {
const student = await this.studentRepo.findOne({ where: { id: result.studentId } });
if (student?.userId) {
void this.notificationsService.create({
recipientIds: [student.userId],
type: NotificationType.BILL_PAID,
title: '账单已确认',
content: `账单 #${result.id} 已确认收款,金额: ¥${result.totalAmount}`,
});
}
} catch (_) { /* don't block response */ }
return result;
}
// Static routes must be declared before /:id/status, otherwise "batch" is
// treated as an id and converted to NaN by the parameterized route.
@Put('batch/status')
@RequirePermission('bill:confirm')
async batchUpdateStatus(@Body() body: BatchUpdateBillStatusDto, @Request() req: any) {
async batchUpdateStatus(@Body() body: { ids: number[]; status: string }, @Request() req: any) {
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.batchUpdateStatus(body.ids, body.status);
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账单管理',
action: '确认账单并扣押金',
action: '确认账单',
detail: `IDs: ${body.ids.join(',')}`,
ipAddress,
userAgent,
@@ -131,51 +158,36 @@ export class BillsController {
return result;
}
@Put(':id/status')
@RequirePermission('bill:confirm')
async updateStatus(
@Param('id', ParseIntPipe) id: number,
@Body() dto: UpdateBillStatusDto,
@Request() req: any,
) {
@Post(':id/cancel')
@RequirePermission('bill:delete')
async cancel(@Param('id') id: string, @Body() dto: CancelBillDto, @Request() req: any) {
const result = await this.service.cancel(+id, dto, req.user?.id);
const { ipAddress, userAgent } = extractRequestInfo(req);
const result = await this.service.updateStatus(id, dto);
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '账单管理',
action: '确认账单并扣押金',
targetId: id,
action: '取消账单并冲正',
targetId: +id,
targetType: 'bill',
detail: dto.reason,
ipAddress,
userAgent,
});
// Send bill_paid notification
try {
const student = await this.studentRepo.findOne({ where: { id: result.studentId } });
if (student?.userId) {
void this.notificationsService.create({
recipientIds: [student.userId],
type: NotificationType.BILL_PAID,
title: '账单已确认',
content: `账单 #${result.id} 已确认收款,金额: ¥${result.totalAmount}`,
});
}
} catch (_) { /* don't block response */ }
return result;
}
@Delete(':id')
@RequirePermission('bill:delete')
async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
async remove(@Param('id') id: string, @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,
@@ -233,18 +245,18 @@ export class BillsController {
@Get('export/pdf/:id')
@RequirePermission('bill:export-pdf')
async exportPdf(@Param('id', ParseIntPipe) id: number, @Res() res: Response, @Req() req: any) {
async exportPdf(@Param('id') id: string, @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);
}
}

View File

@@ -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,7 +8,6 @@ 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 { BillsService } from './bills.service';
import { BillsExportService } from './bills-export.service';
@@ -22,10 +22,10 @@ import { BillsController } from './bills.controller';
PersonalExpense,
Occupancy,
Room,
Deposit,
Student,
]),
NotificationsModule,
WalletsModule,
],
controllers: [BillsController],
providers: [BillsService, BillsExportService],

View File

@@ -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();

View File

@@ -7,8 +7,9 @@ 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,26 +21,47 @@ 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 } = this.resolveBillingPeriod(dto.billingMonth);
const { periodStart, periodEnd } = dto.billingMonth
? this.resolveBillingPeriod(dto.billingMonth)
: { periodStart: dto.periodStart!, periodEnd: dto.periodEnd! };
const pStart = new Date(periodStart);
const pEnd = new Date(periodEnd);
const existingBills = await this.billRepo.find({
where: { periodStart, periodEnd },
});
const existingBills = await this.billRepo.find({ where: { periodStart, periodEnd } });
if (existingBills.length > 0) {
throw new BadRequestException(`${dto.billingMonth} 账单已生成,不能重复生成`);
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()
.where('billId IN (:...ids)', { ids: draftIds })
.execute();
await this.billRepo
.createQueryBuilder()
.delete()
.where('id IN (:...ids)', { ids: draftIds })
.execute();
}
// 获取所有有费用的宿舍
const roomExpenses = await this.roomExpRepo
.createQueryBuilder('e')
.where('e.periodStart >= :periodStart AND e.periodEnd <= :periodEnd', {
@@ -147,6 +169,7 @@ export class BillsService {
periodStart,
periodEnd,
})
.andWhere('pe.billId IS NULL')
.getMany();
const personalMap = new Map<number, number>();
@@ -175,63 +198,100 @@ export class BillsService {
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.dataSource.transaction(async (manager) => {
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);
return bill;
});
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 }));
}
bills.push(savedBill);
}
return {
message: `成功生成 ${dto.billingMonth}${bills.length} 条账单`,
count: bills.length,
periodStart,
periodEnd,
bills,
};
return { message: `成功生成 ${bills.length} 条账单`, count: bills.length, bills, periodStart, periodEnd };
}
private resolveBillingPeriod(billingMonth: string) {
const matched = /^(\d{4})-(\d{2})$/.exec(billingMonth || '');
if (!matched) {
throw new BadRequestException('账单月份格式错误,请使用 YYYY-MM');
}
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');
}
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('只能生成已结束月份的账单');
}
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())}`,
};
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?: {
@@ -263,107 +323,80 @@ export class BillsService {
return withDeposit;
}
/**
* 给账单挂上"押金联动"信息:
* - availableDeposit: 学生当前实时可用押金余额,生成账单时不会冻结
* - depositSufficient: 草稿账单是否已有足够余额可确认
* - depositDeductedAmount: 已确认账单实际扣除的押金金额
*/
/** 查询时附加钱包余额和实际支付数据。 */
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 })
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));
return Object.assign({}, b, {
availableDeposit: available,
depositSufficient: available >= total,
depositDeductedAmount: Number(b.depositDeductedAmount || 0),
});
});
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) {
if (dto.status !== 'paid') {
throw new BadRequestException('账单只能通过确认支付完成扣款');
const bill = await this.billRepo.findOne({ where: { id } });
if (!bill) throw new NotFoundException('账单不存在');
if (dto.status === 'paid' && Number(bill.outstandingAmount) > 0) {
throw new BadRequestException('存在未付金额,不能直接标记为已支付');
}
return this.dataSource.transaction((manager) => this.payBill(manager, id));
bill.status = dto.status;
return this.billRepo.save(bill);
}
async batchUpdateStatus(ids: number[], status: string) {
if (status !== 'paid') {
throw new BadRequestException('账单只能通过确认支付完成扣款');
const bills = await this.billRepo.find({ where: { id: In(ids) } });
if (status === 'paid' && bills.some((bill) => Number(bill.outstandingAmount) > 0)) {
throw new BadRequestException('选中账单存在未付金额,不能直接标记为已支付');
}
const uniqueIds = Array.from(new Set(ids));
await this.dataSource.transaction(async (manager) => {
for (const id of uniqueIds) await this.payBill(manager, id);
});
return { message: `成功确认 ${uniqueIds.length} 条账单并扣除押金` };
await this.billRepo
.createQueryBuilder()
.update()
.set({ status })
.where('id IN (:...ids)', { ids })
.execute();
return { message: `成功更新 ${ids.length} 条账单状态` };
}
private async payBill(manager: EntityManager, id: number) {
const billRepo = manager.getRepository(Bill);
const depositRepo = manager.getRepository(Deposit);
const lock = this.supportsPessimisticLocks()
? ({ mode: 'pessimistic_write' } as const)
: undefined;
const bill = await billRepo.findOne({ where: { id }, ...(lock ? { lock } : {}) });
if (!bill) throw new NotFoundException(`账单 ${id} 不存在`);
if (bill.status === 'paid') return bill;
if (bill.status !== 'draft') throw new BadRequestException(`账单 ${id} 当前状态无法确认支付`);
const deposit = await depositRepo.findOne({
where: { studentId: bill.studentId },
...(lock ? { lock } : {}),
async cancel(id: number, dto: CancelBillDto, recordedBy?: number) {
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, dto.reason, recordedBy);
});
const available = Number(deposit?.amount || 0);
const required = Number(bill.totalAmount || 0);
if (!deposit || available < required) {
throw new BadRequestException(
`账单 ${id} 押金不足:需 ¥${required.toFixed(2)},当前可用 ¥${available.toFixed(2)},请先到押金管理收取押金`,
);
}
deposit.amount = Number((available - required).toFixed(2));
deposit.status = deposit.amount > 0 ? 'paid' : 'depleted';
bill.depositDeductedAmount = required;
bill.status = 'paid';
await depositRepo.save(deposit);
return billRepo.save(bill);
}
private supportsPessimisticLocks() {
return ['mysql', 'mariadb', 'postgres', 'cockroachdb', 'mssql', 'oracle'].includes(
String(this.dataSource.options.type),
);
}
async remove(id: number) {
const exists = await this.billRepo.findOne({ where: { id } });
if (!exists) throw new NotFoundException('账单不存在');
if (exists.status === 'paid') throw new BadRequestException('已支付账单不能删除');
if (Number(exists.paidAmount) > 0 || exists.status === 'cancelled') {
throw new BadRequestException('已发生资金流水的账单不能删除,请使用取消账单');
}
await this.itemRepo.delete({ billId: id });
await this.personalExpRepo.update({ billId: id }, { billId: null });
await this.billRepo.delete(id);
return { message: '账单已删除' };
}
async batchRemove(ids: number[]) {
const bills = await this.billRepo.find({ where: { id: In(ids) } });
if (bills.some((bill) => bill.status === 'paid')) {
throw new BadRequestException('已支付账单不能删除');
if (bills.some((bill) => Number(bill.paidAmount) > 0 || bill.status === 'cancelled')) {
throw new BadRequestException('选中账单包含资金流水,不能批量删除');
}
await this.itemRepo
await this.itemRepo.createQueryBuilder().delete().where('billId IN (:...ids)', { ids }).execute();
await this.personalExpRepo
.createQueryBuilder()
.delete()
.update()
.set({ billId: null })
.where('billId IN (:...ids)', { ids })
.execute();
await this.billRepo.createQueryBuilder().delete().where('id IN (:...ids)', { ids }).execute();

View File

@@ -1,22 +1,28 @@
import { ArrayNotEmpty, IsArray, IsIn, IsInt, IsOptional, IsString, Matches } from 'class-validator';
import { ArrayNotEmpty, IsArray, IsIn, IsInt, IsOptional, IsString, Matches, MaxLength } from 'class-validator';
export class GenerateBillsDto {
@IsString()
@Matches(/^\d{4}-\d{2}$/)
billingMonth: string; // YYYY-MM
billingMonth: string;
@IsOptional()
@IsString()
periodStart?: string; // deprecated, derived from billingMonth
periodStart?: string;
@IsOptional()
@IsString()
periodEnd?: string; // deprecated, derived from billingMonth
periodEnd?: string;
}
export class UpdateBillStatusDto {
@IsIn(['paid'])
status: 'paid';
@IsIn(['unpaid', 'partially_paid', 'paid'])
status: 'unpaid' | 'partially_paid' | 'paid';
}
export class CancelBillDto {
@IsString()
@MaxLength(300)
reason: string;
}
export class BatchUpdateBillStatusDto extends UpdateBillStatusDto {

View File

@@ -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();

View File

@@ -33,12 +33,24 @@ export class Bill {
@Column({ name: 'total_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
totalAmount: number;
@Column({ name: 'deposit_deducted_amount', type: 'decimal', precision: 10, scale: 2, default: 0 })
depositDeductedAmount: number;
@Column({ type: 'varchar', length: 30, default: 'batch' })
source: 'batch' | 'student_utility';
@Column({ type: 'varchar', length: 20, default: 'draft' })
@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;

View File

@@ -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';

View File

@@ -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;

View 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;
}

View 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;
}

View File

@@ -1,4 +1,4 @@
import { IsInt, IsString, IsNumber, IsOptional } from 'class-validator';
import { IsIn, IsInt, IsString, IsNumber, IsOptional, Matches, Min } from 'class-validator';
export class CreateRoomExpenseDto {
@IsInt()
@@ -52,3 +52,28 @@ export class BatchRoomExpenseDto {
expenses: { roomId: number; expenseType: string; amount: number; description?: string }[];
}
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;
@IsOptional()
@IsString()
description?: string;
}

View File

@@ -20,6 +20,7 @@ import {
CreateRoomExpenseDto,
CreatePersonalExpenseDto,
BatchRoomExpenseDto,
CreateStudentUtilityBillDto,
} from './dto/expense.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
@@ -78,6 +79,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) {

View File

@@ -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],

View File

@@ -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() {
@@ -96,6 +99,30 @@ export class ExpensesService {
return this.roomExpRepo.save(e);
}
async createStudentUtilityBill(dto: CreateStudentUtilityBillDto, userId?: number) {
if (dto.periodEnd < dto.periodStart) throw new BadRequestException('账期结束日期不能早于开始日期');
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) {
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });

View File

@@ -51,6 +51,8 @@ const PRESET_PERMISSIONS: Array<{ code: string; name: string; group: string }> =
{ code: 'deposit:edit', name: '编辑押金', group: 'deposit' },
{ code: 'deposit:delete', name: '删除押金', group: 'deposit' },
{ code: 'deposit:refund', name: '直接退还押金', group: 'deposit' },
{ code: 'wallet:view', name: '查看学生余额', group: 'wallet' },
{ code: 'wallet:edit', name: '充值和调账', group: 'wallet' },
{ code: 'classroom:view', name: '查看教室', group: 'classroom' },
{ code: 'classroom:create', name: '新增教室', group: 'classroom' },
{ code: 'classroom:edit', name: '编辑教室', group: 'classroom' },
@@ -176,6 +178,7 @@ export const PRESET_ROLES: Array<{
'expense',
'bill',
'deposit',
'wallet',
'dashboard',
'notification',
'profile',

View File

@@ -0,0 +1,18 @@
import { IsIn, IsInt, IsNumber, IsOptional, IsString, MaxLength, NotEquals } from 'class-validator';
export class ChangeWalletBalanceDto {
@IsInt()
studentId: number;
@IsNumber({ maxDecimalPlaces: 2 })
@NotEquals(0)
amount: number;
@IsIn(['recharge', 'adjustment'])
type: 'recharge' | 'adjustment';
@IsOptional()
@IsString()
@MaxLength(300)
description?: string;
}

View File

@@ -0,0 +1,44 @@
import { Body, Controller, Get, Post, Query, Request, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RequirePermission } from '../auth/decorators/permission.decorator';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import { ChangeWalletBalanceDto } from './dto/wallet.dto';
import { WalletsService } from './wallets.service';
@UseGuards(JwtAuthGuard)
@Controller('wallets')
export class WalletsController {
constructor(private service: WalletsService, private logService: OperationLogsService) {}
@Get()
@RequirePermission('wallet:view')
findAll(@Query('keyword') keyword?: string, @Query('debtOnly') debtOnly?: string) {
return this.service.findAll({ keyword, debtOnly: debtOnly === 'true' });
}
@Get('transactions')
@RequirePermission('wallet:view')
findTransactions(@Query('studentId') studentId: string) {
return this.service.findTransactions(Number(studentId));
}
@Post('change-balance')
@RequirePermission('wallet:edit')
async changeBalance(@Body() dto: ChangeWalletBalanceDto, @Request() req: any) {
const result = await this.service.changeBalance(dto, req.user?.id);
const { ipAddress, userAgent } = extractRequestInfo(req);
await this.logService.log({
userId: req.user?.id,
username: req.user?.username,
module: '学生余额',
action: dto.type === 'recharge' ? '余额充值' : '余额调账',
targetId: dto.studentId,
targetType: 'student_wallet',
detail: `金额 ¥${dto.amount}${dto.description ? `${dto.description}` : ''}`,
ipAddress,
userAgent,
});
return result;
}
}

View File

@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Bill } from '../entities/bill.entity';
import { Student } from '../entities/student.entity';
import { StudentWallet } from '../entities/student-wallet.entity';
import { WalletTransaction } from '../entities/wallet-transaction.entity';
import { OperationLogsModule } from '../operation-logs/operation-logs.module';
import { WalletsController } from './wallets.controller';
import { WalletsService } from './wallets.service';
@Module({
imports: [TypeOrmModule.forFeature([StudentWallet, WalletTransaction, Student, Bill]), OperationLogsModule],
controllers: [WalletsController],
providers: [WalletsService],
exports: [WalletsService],
})
export class WalletsModule {}

View File

@@ -0,0 +1,52 @@
import { BadRequestException } from '@nestjs/common';
import { WalletsService } from './wallets.service';
import { Bill } from '../entities/bill.entity';
const manager = (walletBalance: number) => {
const wallet = { id: 1, studentId: 10, balance: walletBalance };
const saved: any[] = [];
return {
wallet,
saved,
value: {
findOne: jest.fn(async () => wallet),
findOneByOrFail: jest.fn(async () => wallet),
save: jest.fn(async (value: any) => { saved.push(value); return value; }),
create: jest.fn((_entity: unknown, value: unknown) => value),
createQueryBuilder: jest.fn(),
},
};
};
describe('WalletsService payment rules', () => {
const service = new WalletsService({} as any, {} as any, {} as any, {} as any);
it('partially pays a bill when balance is insufficient', async () => {
const ctx = manager(40);
const bill = { id: 9, studentId: 10, totalAmount: 100, paidAmount: 0, outstandingAmount: 100, status: 'unpaid' } as Bill;
const result = await service.debitBill(ctx.value as any, bill, 1);
expect(result.status).toBe('partially_paid');
expect(Number(result.paidAmount)).toBe(40);
expect(Number(result.outstandingAmount)).toBe(60);
expect(Number(ctx.wallet.balance)).toBe(0);
expect(ctx.saved.some((row) => row.type === 'bill_payment' && Number(row.amount) === -40)).toBe(true);
});
it('marks a bill paid when balance covers it', async () => {
const ctx = manager(120);
const bill = { id: 9, studentId: 10, totalAmount: 100, paidAmount: 0, outstandingAmount: 100, status: 'unpaid' } as Bill;
const result = await service.debitBill(ctx.value as any, bill);
expect(result.status).toBe('paid');
expect(Number(result.outstandingAmount)).toBe(0);
expect(Number(ctx.wallet.balance)).toBe(20);
});
it('refunds paid amount and cancels the bill', async () => {
const ctx = manager(10);
const bill = { id: 9, studentId: 10, totalAmount: 100, paidAmount: 40, outstandingAmount: 60, status: 'partially_paid' } as Bill;
const result = await service.refundBill(ctx.value as any, bill, '录入错误', 1);
expect(result.status).toBe('cancelled');
expect(Number(ctx.wallet.balance)).toBe(50);
expect(ctx.saved.some((row) => row.type === 'bill_refund' && Number(row.amount) === 40)).toBe(true);
});
});

View File

@@ -0,0 +1,167 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, EntityManager, Repository } from 'typeorm';
import { Bill } from '../entities/bill.entity';
import { Student } from '../entities/student.entity';
import { StudentWallet } from '../entities/student-wallet.entity';
import { WalletTransaction } from '../entities/wallet-transaction.entity';
import { In } from 'typeorm';
import { ChangeWalletBalanceDto } from './dto/wallet.dto';
const money = (value: number | string | null | undefined) => Number(Number(value || 0).toFixed(2));
@Injectable()
export class WalletsService {
constructor(
@InjectRepository(StudentWallet) private walletRepo: Repository<StudentWallet>,
@InjectRepository(WalletTransaction) private transactionRepo: Repository<WalletTransaction>,
@InjectRepository(Student) private studentRepo: Repository<Student>,
private dataSource: DataSource,
) {}
async findAll(query?: { keyword?: string; debtOnly?: boolean }) {
const students = await this.studentRepo
.createQueryBuilder('student')
.where('student.status = :status', { status: 'active' })
.andWhere(
query?.keyword
? '(student.name LIKE :keyword OR student.studentNo LIKE :keyword)'
: '1 = 1',
query?.keyword ? { keyword: `%${query.keyword}%` } : {},
)
.orderBy('student.name', 'ASC')
.getMany();
if (!students.length) return [];
const ids = students.map((student) => student.id);
const wallets = await this.walletRepo.find({ where: { studentId: In(ids) } });
const bills = await this.dataSource.getRepository(Bill)
.createQueryBuilder('bill')
.select('bill.studentId', 'studentId')
.addSelect('SUM(bill.outstandingAmount)', 'outstandingAmount')
.where('bill.studentId IN (:...ids)', { ids })
.andWhere('bill.status IN (:...statuses)', { statuses: ['unpaid', 'partially_paid'] })
.groupBy('bill.studentId')
.getRawMany<{ studentId: number; outstandingAmount: string }>();
const walletMap = new Map(wallets.map((wallet) => [wallet.studentId, wallet]));
const debtMap = new Map(bills.map((bill) => [Number(bill.studentId), money(bill.outstandingAmount)]));
return students
.map((student) => ({
studentId: student.id,
studentName: student.name,
studentNo: student.studentNo,
balance: money(walletMap.get(student.id)?.balance),
outstandingAmount: debtMap.get(student.id) || 0,
}))
.filter((row) => !query?.debtOnly || row.outstandingAmount > 0);
}
async findTransactions(studentId: number) {
return this.transactionRepo.find({ where: { studentId }, order: { createdAt: 'DESC' } });
}
async changeBalance(dto: ChangeWalletBalanceDto, recordedBy?: number) {
if (dto.type === 'recharge' && dto.amount <= 0) throw new BadRequestException('充值金额必须大于 0');
const student = await this.studentRepo.findOne({ where: { id: dto.studentId } });
if (!student) throw new NotFoundException('学生不存在');
return this.dataSource.transaction(async (manager) => {
const wallet = await this.getOrCreateWallet(manager, dto.studentId);
const nextBalance = money(Number(wallet.balance) + dto.amount);
if (nextBalance < 0) throw new BadRequestException('调账后余额不能小于 0');
wallet.balance = nextBalance;
await manager.save(wallet);
await manager.save(
manager.create(WalletTransaction, {
studentId: dto.studentId,
billId: null,
type: dto.type,
amount: money(dto.amount),
balanceAfter: nextBalance,
description: dto.description || (dto.type === 'recharge' ? '财务充值' : '余额调账'),
recordedBy: recordedBy || null,
}),
);
const payments = dto.amount > 0 ? await this.settleOutstandingBills(manager, dto.studentId, recordedBy) : [];
const finalWallet = await manager.findOneByOrFail(StudentWallet, { studentId: dto.studentId });
return { wallet: finalWallet, payments };
});
}
async debitBill(manager: EntityManager, bill: Bill, recordedBy?: number) {
if (bill.status === 'cancelled' || money(bill.outstandingAmount) <= 0) return bill;
const wallet = await this.getOrCreateWallet(manager, bill.studentId);
const amount = money(Math.min(Number(wallet.balance), Number(bill.outstandingAmount)));
if (amount <= 0) {
bill.status = money(bill.paidAmount) > 0 ? 'partially_paid' : 'unpaid';
return manager.save(bill);
}
wallet.balance = money(Number(wallet.balance) - amount);
bill.paidAmount = money(Number(bill.paidAmount) + amount);
bill.outstandingAmount = money(Number(bill.totalAmount) - Number(bill.paidAmount));
bill.status = bill.outstandingAmount <= 0 ? 'paid' : 'partially_paid';
await manager.save(wallet);
await manager.save(bill);
await manager.save(
manager.create(WalletTransaction, {
studentId: bill.studentId,
billId: bill.id,
type: 'bill_payment',
amount: -amount,
balanceAfter: wallet.balance,
description: `账单 #${bill.id} 自动扣款`,
recordedBy: recordedBy || null,
}),
);
return bill;
}
async refundBill(manager: EntityManager, bill: Bill, reason: string, recordedBy?: number) {
const paid = money(bill.paidAmount);
if (paid > 0) {
const wallet = await this.getOrCreateWallet(manager, bill.studentId);
wallet.balance = money(Number(wallet.balance) + paid);
await manager.save(wallet);
await manager.save(
manager.create(WalletTransaction, {
studentId: bill.studentId,
billId: bill.id,
type: 'bill_refund',
amount: paid,
balanceAfter: wallet.balance,
description: `取消账单 #${bill.id} 冲正:${reason}`,
recordedBy: recordedBy || null,
}),
);
}
bill.status = 'cancelled';
bill.paidAmount = 0;
bill.outstandingAmount = 0;
bill.cancelledAt = new Date();
bill.cancelReason = reason;
return manager.save(bill);
}
private async settleOutstandingBills(manager: EntityManager, studentId: number, recordedBy?: number) {
const bills = await manager
.createQueryBuilder(Bill, 'bill')
.where('bill.studentId = :studentId', { studentId })
.andWhere('bill.status IN (:...statuses)', { statuses: ['unpaid', 'partially_paid'] })
.andWhere('bill.outstandingAmount > 0')
.orderBy('bill.periodStart', 'ASC')
.addOrderBy('bill.id', 'ASC')
.getMany();
const settled: Bill[] = [];
for (const bill of bills) {
const wallet = await manager.findOne(StudentWallet, { where: { studentId } });
if (!wallet || money(wallet.balance) <= 0) break;
settled.push(await this.debitBill(manager, bill, recordedBy));
}
return settled;
}
private async getOrCreateWallet(manager: EntityManager, studentId: number) {
let wallet = await manager.findOne(StudentWallet, { where: { studentId } });
if (!wallet) wallet = await manager.save(manager.create(StudentWallet, { studentId, balance: 0 }));
return wallet;
}
}