feat: support batch wallet balance changes
This commit is contained in:
@@ -27,7 +27,10 @@ const WalletsPage: React.FC = () => {
|
|||||||
const [transactions, setTransactions] = useState<any[]>([]);
|
const [transactions, setTransactions] = useState<any[]>([]);
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
|
const [batchForm] = Form.useForm();
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
|
||||||
|
const [batchModalOpen, setBatchModalOpen] = useState(false);
|
||||||
|
|
||||||
const fetchRows = useCallback(async () => {
|
const fetchRows = useCallback(async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -46,6 +49,11 @@ const WalletsPage: React.FC = () => {
|
|||||||
form.setFieldsValue({ type: 'recharge', amount: undefined, description: '' });
|
form.setFieldsValue({ type: 'recharge', amount: undefined, description: '' });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openBatchChange = () => {
|
||||||
|
batchForm.setFieldsValue({ type: 'recharge', amount: undefined, description: '' });
|
||||||
|
setBatchModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
const submitChange = async () => {
|
const submitChange = async () => {
|
||||||
if (!selected) return;
|
if (!selected) return;
|
||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
@@ -60,6 +68,30 @@ const WalletsPage: React.FC = () => {
|
|||||||
finally { setSaving(false); }
|
finally { setSaving(false); }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const submitBatchChange = async () => {
|
||||||
|
const values = await batchForm.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const result: any = await api.post('/wallets/batch-change-balance', {
|
||||||
|
studentIds: selectedRowKeys,
|
||||||
|
...values,
|
||||||
|
});
|
||||||
|
const paid = (result.results || []).reduce((sum: number, item: any) => {
|
||||||
|
return sum + (item.payments || []).reduce((paymentSum: number, bill: any) => paymentSum + Number(bill.paidAmount || 0), 0);
|
||||||
|
}, 0);
|
||||||
|
message.success(
|
||||||
|
paid > 0
|
||||||
|
? `已批量更新 ${selectedRowKeys.length} 名学生余额,并自动补扣历史账单`
|
||||||
|
: `已批量更新 ${selectedRowKeys.length} 名学生余额`,
|
||||||
|
);
|
||||||
|
setBatchModalOpen(false);
|
||||||
|
setSelectedRowKeys([]);
|
||||||
|
batchForm.resetFields();
|
||||||
|
await fetchRows();
|
||||||
|
} catch (error: any) { message.error(error?.message || '批量余额操作失败'); }
|
||||||
|
finally { setSaving(false); }
|
||||||
|
};
|
||||||
|
|
||||||
const showTransactions = async (row: WalletRow) => {
|
const showTransactions = async (row: WalletRow) => {
|
||||||
setSelected(row); setDrawerOpen(true);
|
setSelected(row); setDrawerOpen(true);
|
||||||
try { setTransactions(await api.get('/wallets/transactions', { params: { studentId: row.studentId } }) as any[]); }
|
try { setTransactions(await api.get('/wallets/transactions', { params: { studentId: row.studentId } }) as any[]); }
|
||||||
@@ -76,9 +108,19 @@ const WalletsPage: React.FC = () => {
|
|||||||
return <div>
|
return <div>
|
||||||
<div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
|
<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>
|
<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>
|
<Space wrap>
|
||||||
|
<PermissionButton permission="wallet:edit" type="primary" icon={<PlusOutlined />} disabled={selectedRowKeys.length === 0} onClick={openBatchChange}>批量充值/调账</PermissionButton>
|
||||||
|
<Button icon={<ReloadOutlined />} onClick={fetchRows}>刷新</Button>
|
||||||
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
<Table rowKey="studentId" loading={loading} dataSource={rows} columns={columns} pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 人` }} />
|
<Table
|
||||||
|
rowKey="studentId"
|
||||||
|
loading={loading}
|
||||||
|
dataSource={rows}
|
||||||
|
columns={columns}
|
||||||
|
rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
|
||||||
|
pagination={{ pageSize: 15, showTotal: (total) => `共 ${total} 人` }}
|
||||||
|
/>
|
||||||
<Modal title={`${selected?.studentName || ''} - 余额操作`} open={!!selected && !drawerOpen} onCancel={() => setSelected(null)} onOk={submitChange} confirmLoading={saving} okText="确认">
|
<Modal title={`${selected?.studentName || ''} - 余额操作`} open={!!selected && !drawerOpen} onCancel={() => setSelected(null)} onOk={submitChange} confirmLoading={saving} okText="确认">
|
||||||
<Form form={form} layout="vertical">
|
<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="type" label="操作类型" rules={[{ required: true }]}><Radio.Group options={[{ label: '充值', value: 'recharge' }, { label: '调账', value: 'adjustment' }]} /></Form.Item>
|
||||||
@@ -86,6 +128,27 @@ const WalletsPage: React.FC = () => {
|
|||||||
<Form.Item name="description" label="备注"><Input.TextArea maxLength={300} /></Form.Item>
|
<Form.Item name="description" label="备注"><Input.TextArea maxLength={300} /></Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
<Modal
|
||||||
|
title={`批量余额操作(${selectedRowKeys.length} 人)`}
|
||||||
|
open={batchModalOpen}
|
||||||
|
onCancel={() => setBatchModalOpen(false)}
|
||||||
|
onOk={submitBatchChange}
|
||||||
|
confirmLoading={saving}
|
||||||
|
okText="确认批量修改"
|
||||||
|
>
|
||||||
|
<Form form={batchForm} layout="vertical">
|
||||||
|
<div style={{ marginBottom: 16, padding: 12, background: '#f5f5f5', borderRadius: 8 }}>
|
||||||
|
已选择 <strong>{selectedRowKeys.length}</strong> 名学生,将按相同金额批量修改水电费余额。
|
||||||
|
</div>
|
||||||
|
<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); }}>
|
<Drawer title={`${selected?.studentName || ''} - 余额流水`} width={680} open={drawerOpen} onClose={() => { setDrawerOpen(false); setSelected(null); }}>
|
||||||
<Table rowKey="id" dataSource={transactions} pagination={{ pageSize: 10 }} columns={[
|
<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: 'createdAt', render: (value: string) => dayjs(value).format('YYYY-MM-DD HH:mm') },
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { IsIn, IsInt, IsNumber, IsOptional, IsString, MaxLength, NotEquals } from 'class-validator';
|
import { Type } from 'class-transformer';
|
||||||
|
import { ArrayNotEmpty, IsArray, IsIn, IsInt, IsNumber, IsOptional, IsString, MaxLength, NotEquals } from 'class-validator';
|
||||||
|
|
||||||
export class ChangeWalletBalanceDto {
|
export class ChangeWalletBalanceDto {
|
||||||
@IsInt()
|
@IsInt()
|
||||||
@@ -16,3 +17,24 @@ export class ChangeWalletBalanceDto {
|
|||||||
@MaxLength(300)
|
@MaxLength(300)
|
||||||
description?: string;
|
description?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export class BatchChangeWalletBalanceDto {
|
||||||
|
@IsArray()
|
||||||
|
@ArrayNotEmpty()
|
||||||
|
@IsInt({ each: true })
|
||||||
|
@Type(() => Number)
|
||||||
|
studentIds: number[];
|
||||||
|
|
||||||
|
@IsNumber({ maxDecimalPlaces: 2 })
|
||||||
|
@NotEquals(0)
|
||||||
|
amount: number;
|
||||||
|
|
||||||
|
@IsIn(['recharge', 'adjustment'])
|
||||||
|
type: 'recharge' | 'adjustment';
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(300)
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
|||||||
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
import { RequirePermission } from '../auth/decorators/permission.decorator';
|
||||||
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
import { OperationLogsService } from '../operation-logs/operation-logs.service';
|
||||||
import { extractRequestInfo } from '../common/request-utils';
|
import { extractRequestInfo } from '../common/request-utils';
|
||||||
import { ChangeWalletBalanceDto } from './dto/wallet.dto';
|
import { BatchChangeWalletBalanceDto, ChangeWalletBalanceDto } from './dto/wallet.dto';
|
||||||
import { WalletsService } from './wallets.service';
|
import { WalletsService } from './wallets.service';
|
||||||
|
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
@@ -41,4 +41,24 @@ export class WalletsController {
|
|||||||
});
|
});
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Post('batch-change-balance')
|
||||||
|
@RequirePermission('wallet:edit')
|
||||||
|
async batchChangeBalance(@Body() dto: BatchChangeWalletBalanceDto, @Request() req: any) {
|
||||||
|
const result = await this.service.batchChangeBalance(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: undefined,
|
||||||
|
targetType: 'student_wallet',
|
||||||
|
detail: `学生${result.count}人,金额 ¥${dto.amount}${dto.description ? `,${dto.description}` : ''}`,
|
||||||
|
ipAddress,
|
||||||
|
userAgent,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { Student } from '../entities/student.entity';
|
|||||||
import { StudentWallet } from '../entities/student-wallet.entity';
|
import { StudentWallet } from '../entities/student-wallet.entity';
|
||||||
import { WalletTransaction } from '../entities/wallet-transaction.entity';
|
import { WalletTransaction } from '../entities/wallet-transaction.entity';
|
||||||
import { In } from 'typeorm';
|
import { In } from 'typeorm';
|
||||||
import { ChangeWalletBalanceDto } from './dto/wallet.dto';
|
import { BatchChangeWalletBalanceDto, ChangeWalletBalanceDto } from './dto/wallet.dto';
|
||||||
|
|
||||||
const money = (value: number | string | null | undefined) => Number(Number(value || 0).toFixed(2));
|
const money = (value: number | string | null | undefined) => Number(Number(value || 0).toFixed(2));
|
||||||
|
|
||||||
@@ -92,6 +92,20 @@ export class WalletsService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async batchChangeBalance(dto: BatchChangeWalletBalanceDto, recordedBy?: number) {
|
||||||
|
const uniqueStudentIds = Array.from(new Set(dto.studentIds));
|
||||||
|
const results: Awaited<ReturnType<WalletsService['changeBalance']>>[] = [];
|
||||||
|
for (const studentId of uniqueStudentIds) {
|
||||||
|
results.push(await this.changeBalance({
|
||||||
|
studentId,
|
||||||
|
amount: dto.amount,
|
||||||
|
type: dto.type,
|
||||||
|
description: dto.description,
|
||||||
|
}, recordedBy));
|
||||||
|
}
|
||||||
|
return { count: uniqueStudentIds.length, results };
|
||||||
|
}
|
||||||
|
|
||||||
async debitBill(manager: EntityManager, bill: Bill, recordedBy?: number) {
|
async debitBill(manager: EntityManager, bill: Bill, recordedBy?: number) {
|
||||||
if (bill.status === 'cancelled') return bill;
|
if (bill.status === 'cancelled') return bill;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user