feat: 实现订单日报系统

- 创建订单日报系统,支持每天8:01自动生成前一天(早8点到当天早8点)的日报
- 新建两个数据库表:t_daily_report_config(配置表)和 t_daily_report_history(历史表)
- 原表 t_equipment_charge_order 只读取不修改,严格遵守用户要求
- 支持按企业ID或用户ID拆分日报,用户ID会提示是企业用户还是普通用户
- 用户可自定义选择报表字段,所有字段使用中文显示
- 实现配置管理、日报生成、历史查看的完整功能
- 代码检查全部通过,静态检查无错误

Coze-Commit-Type: user
Coze-User-ID: 3722323274763196
Coze-Conversation-ID: 9894087
This commit is contained in:
user9994793890
2026-07-07 16:14:42 +08:00
parent b6a1b77054
commit ba91796dc1
21 changed files with 2734 additions and 253 deletions

View File

@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
// PUT - 更新配置
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const body = await request.json();
const { config_name, split_type, selected_fields, is_active } = body;
const { id: configId } = await params;
// 构建更新字段
const updateFields: string[] = [];
const updateValues: any[] = [];
if (config_name) {
updateFields.push('config_name = ?');
updateValues.push(config_name);
}
if (split_type) {
updateFields.push('split_type = ?');
updateValues.push(split_type);
}
if (selected_fields) {
updateFields.push('selected_fields = ?');
updateValues.push(JSON.stringify(selected_fields));
}
if (is_active !== undefined) {
updateFields.push('is_active = ?');
updateValues.push(is_active);
}
if (updateFields.length === 0) {
return NextResponse.json({
success: false,
message: '没有要更新的字段'
}, { status: 400 });
}
updateValues.push(configId);
await pool.execute(
`UPDATE t_daily_report_config SET ${updateFields.join(', ')} WHERE id = ?`,
updateValues
);
return NextResponse.json({
success: true,
message: '配置更新成功'
});
} catch (error) {
return NextResponse.json({
success: false,
message: '更新配置失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}
// DELETE - 删除配置(设置为禁用)
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id: configId } = await params;
await pool.execute(
'UPDATE t_daily_report_config SET is_active = 0 WHERE id = ?',
[configId]
);
return NextResponse.json({
success: true,
message: '配置已禁用'
});
} catch (error) {
return NextResponse.json({
success: false,
message: '禁用配置失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { getAllFields } from '@/lib/field-mapping';
// GET - 获取所有配置
export async function GET() {
try {
const [configs] = await pool.execute<any[]>(
'SELECT * FROM t_daily_report_config WHERE is_active = 1 ORDER BY create_time DESC'
);
return NextResponse.json({
success: true,
data: configs,
availableFields: getAllFields()
});
} catch (error) {
return NextResponse.json({
success: false,
message: '获取配置失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}
// POST - 创建新配置
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { config_name, split_type, selected_fields } = body;
// 验证必填字段
if (!config_name || !split_type || !selected_fields || selected_fields.length === 0) {
return NextResponse.json({
success: false,
message: '缺少必填字段'
}, { status: 400 });
}
// 验证拆分方式
if (split_type !== 'company_id' && split_type !== 'user_id') {
return NextResponse.json({
success: false,
message: '拆分方式必须是 company_id 或 user_id'
}, { status: 400 });
}
// 插入配置
const [result] = await pool.execute(
`INSERT INTO t_daily_report_config (config_name, split_type, selected_fields)
VALUES (?, ?, ?)`,
[config_name, split_type, JSON.stringify(selected_fields)]
);
return NextResponse.json({
success: true,
message: '配置创建成功',
data: result
});
} catch (error) {
return NextResponse.json({
success: false,
message: '创建配置失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
// GET - 获取企业列表或用户列表
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const type = searchParams.get('type'); // 'company' 或 'user'
if (type === 'company') {
// 获取企业列表(根据company_id分组,并统计订单数量)
const [companies] = await pool.execute(`
SELECT
company_id,
COUNT(*) as order_count,
SUM(actual_pay_amount) as total_amount
FROM t_equipment_charge_order
WHERE state = 3 AND company_id IS NOT NULL
GROUP BY company_id
ORDER BY order_count DESC
`);
return NextResponse.json({
success: true,
data: companies,
type: '企业'
});
} else if (type === 'user') {
// 获取用户列表(根据user_id分组,区分企业用户和普通用户)
const [users] = await pool.execute(`
SELECT
user_id,
order_type,
COUNT(*) as order_count,
SUM(actual_pay_amount) as total_amount,
CASE
WHEN order_type = 3 THEN '企业用户'
WHEN order_type = 1 THEN '普通用户'
ELSE '其他类型'
END as user_type_label
FROM t_equipment_charge_order
WHERE state = 3
GROUP BY user_id, order_type
ORDER BY order_count DESC
`);
return NextResponse.json({
success: true,
data: users,
type: '用户'
});
} else {
return NextResponse.json({
success: false,
message: '类型参数必须为 company 或 user'
}, { status: 400 });
}
} catch (error) {
return NextResponse.json({
success: false,
message: '获取数据失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,22 @@
import { NextResponse } from 'next/server';
import { initDatabaseTables } from '@/lib/init-tables';
export async function POST() {
try {
await initDatabaseTables();
return NextResponse.json({
success: true,
message: '数据库表初始化成功',
createdTables: [
't_daily_report_config - 日报字段配置表',
't_daily_report_history - 日报生成历史表'
]
});
} catch (error) {
return NextResponse.json({
success: false,
message: '数据库表初始化失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from 'next/server';
import { generateDailyReport, generateBatchReports } from '@/lib/report-generator';
// POST - 生成日报
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { split_type, split_value, selected_fields, report_date, config_id } = body;
// 如果提供了config_id,则批量生成所有企业/用户的日报
if (config_id) {
const results = await generateBatchReports(config_id);
return NextResponse.json({
success: true,
message: '批量日报生成完成',
data: results
});
}
// 否则生成单个企业/用户的日报
if (!split_type || !split_value || !selected_fields || selected_fields.length === 0) {
return NextResponse.json({
success: false,
message: '缺少必填字段'
}, { status: 400 });
}
const result = await generateDailyReport(split_type, split_value, selected_fields, report_date);
return NextResponse.json({
success: result.success,
message: result.success ? '日报生成成功' : result.error,
data: result
});
} catch (error) {
return NextResponse.json({
success: false,
message: '生成日报失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
// GET - 获取日报历史记录
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1');
const pageSize = parseInt(searchParams.get('pageSize') || '20');
const splitType = searchParams.get('splitType');
const reportDate = searchParams.get('reportDate');
// 构建查询条件
let whereClause = 'WHERE 1=1';
const queryParams: any[] = [];
if (splitType) {
whereClause += ' AND split_type = ?';
queryParams.push(splitType);
}
if (reportDate) {
whereClause += ' AND report_date = ?';
queryParams.push(reportDate);
}
// 查询总数
const [countResult] = await pool.execute(
`SELECT COUNT(*) as total FROM t_daily_report_history ${whereClause}`,
queryParams
);
const total = (countResult as any[])[0].total;
// 查询数据
const offset = (page - 1) * pageSize;
queryParams.push(offset, pageSize);
const [history] = await pool.execute(
`SELECT * FROM t_daily_report_history ${whereClause}
ORDER BY create_time DESC
LIMIT ?, ?`,
queryParams
);
return NextResponse.json({
success: true,
data: history,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize)
}
});
} catch (error) {
return NextResponse.json({
success: false,
message: '获取历史记录失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}

View File

@@ -0,0 +1,25 @@
import { NextResponse } from 'next/server';
import { testConnection } from '@/lib/db';
export async function GET() {
try {
const isConnected = await testConnection();
if (isConnected) {
return NextResponse.json({
success: true,
message: '数据库连接成功'
});
} else {
return NextResponse.json({
success: false,
message: '数据库连接失败'
}, { status: 500 });
}
} catch (error) {
return NextResponse.json({
success: false,
message: '数据库连接失败',
error: error instanceof Error ? error.message : '未知错误'
}, { status: 500 });
}
}

View File

@@ -1,35 +1,566 @@
import type { Metadata } from 'next';
import Image from 'next/image';
'use client';
export const metadata: Metadata = {
title: '扣子编程 - AI 开发伙伴',
description: '扣子编程,你的 AI 开发伙伴已就位',
};
import { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { toast } from '@/hooks/use-toast';
import { Toaster } from '@/components/ui/toaster';
export default function Home() {
const [configs, setConfigs] = useState<any[]>([]);
const [availableFields, setAvailableFields] = useState<any[]>([]);
const [companies, setCompanies] = useState<any[]>([]);
const [users, setUsers] = useState<any[]>([]);
const [history, setHistory] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
// 配置表单
const [configName, setConfigName] = useState('');
const [splitType, setSplitType] = useState('company_id');
const [selectedFields, setSelectedFields] = useState<string[]>([]);
// 日报生成表单
const [reportSplitType, setReportSplitType] = useState('company_id');
const [reportSplitValue, setReportSplitValue] = useState('');
const [reportSelectedFields, setReportSelectedFields] = useState<string[]>([]);
const [reportDate, setReportDate] = useState('');
// 历史查询
const [historyPage, setHistoryPage] = useState(1);
const [historyTotal, setHistoryTotal] = useState(0);
useEffect(() => {
loadData();
}, []);
useEffect(() => {
if (splitType === 'company_id') {
loadCompanies();
} else {
loadUsers();
}
}, [splitType]);
useEffect(() => {
if (reportSplitType === 'company_id') {
loadCompanies();
} else {
loadUsers();
}
}, [reportSplitType]);
const loadData = async () => {
try {
// 加载配置和字段
const configRes = await fetch('/api/config');
const configData = await configRes.json();
if (configData.success) {
setConfigs(configData.data);
setAvailableFields(configData.availableFields);
}
// 加载历史
loadHistory();
} catch (error) {
console.error('加载数据失败:', error);
}
};
const loadCompanies = async () => {
try {
const res = await fetch('/api/entities?type=company');
const data = await res.json();
if (data.success) {
setCompanies(data.data);
}
} catch (error) {
console.error('加载企业列表失败:', error);
}
};
const loadUsers = async () => {
try {
const res = await fetch('/api/entities?type=user');
const data = await res.json();
if (data.success) {
setUsers(data.data);
}
} catch (error) {
console.error('加载用户列表失败:', error);
}
};
const loadHistory = async (page = 1) => {
try {
const res = await fetch(`/api/report/history?page=${page}&pageSize=10`);
const data = await res.json();
if (data.success) {
setHistory(data.data);
setHistoryTotal(data.pagination.total);
setHistoryPage(page);
}
} catch (error) {
console.error('加载历史记录失败:', error);
}
};
const handleCreateConfig = async () => {
if (!configName || selectedFields.length === 0) {
toast({
title: '错误',
description: '请填写配置名称并选择至少一个字段',
variant: 'destructive'
});
return;
}
setLoading(true);
try {
const res = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
config_name: configName,
split_type: splitType,
selected_fields: selectedFields
})
});
const data = await res.json();
if (data.success) {
toast({
title: '成功',
description: '配置创建成功'
});
loadData();
setConfigName('');
setSelectedFields([]);
} else {
toast({
title: '错误',
description: data.message,
variant: 'destructive'
});
}
} catch (error) {
toast({
title: '错误',
description: '创建配置失败',
variant: 'destructive'
});
}
setLoading(false);
};
const handleGenerateReport = async () => {
if (!reportSplitValue || reportSelectedFields.length === 0) {
toast({
title: '错误',
description: '请选择企业/用户并选择至少一个字段',
variant: 'destructive'
});
return;
}
setLoading(true);
try {
const res = await fetch('/api/report/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
split_type: reportSplitType,
split_value: reportSplitValue,
selected_fields: reportSelectedFields,
report_date: reportDate
})
});
const data = await res.json();
if (data.success) {
toast({
title: '成功',
description: `日报生成成功,共 ${data.data.totalOrders} 条订单,总金额 ${data.data.totalAmount} 元`
});
loadHistory();
} else {
toast({
title: '错误',
description: data.message,
variant: 'destructive'
});
}
} catch (error) {
toast({
title: '错误',
description: '生成日报失败',
variant: 'destructive'
});
}
setLoading(false);
};
const handleDeleteConfig = async (id: string) => {
setLoading(true);
try {
const res = await fetch(`/api/config/${id}`, {
method: 'DELETE'
});
const data = await res.json();
if (data.success) {
toast({
title: '成功',
description: '配置已禁用'
});
loadData();
} else {
toast({
title: '错误',
description: data.message,
variant: 'destructive'
});
}
} catch (error) {
toast({
title: '错误',
description: '禁用配置失败',
variant: 'destructive'
});
}
setLoading(false);
};
const handleFieldChange = (field: string, checked: boolean, type: 'config' | 'report') => {
if (type === 'config') {
if (checked) {
setSelectedFields([...selectedFields, field]);
} else {
setSelectedFields(selectedFields.filter(f => f !== field));
}
} else {
if (checked) {
setReportSelectedFields([...reportSelectedFields, field]);
} else {
setReportSelectedFields(reportSelectedFields.filter(f => f !== field));
}
}
};
return (
<div className="flex h-full items-center justify-center bg-background text-foreground transition-colors duration-300 dark:bg-background dark:text-foreground overflow-hidden min-h-screen">
{/* 主容器 */}
<main className="flex w-full h-full max-w-3xl flex-col items-center justify-center px-16 py-32 sm:items-center">
<div className="flex flex-col items-center justify-between gap-4">
<Image
src="https://lf-coze-web-cdn.coze.cn/obj/eden-cn/lm-lgvj/ljhwZthlaukjlkulzlp/coze-coding/icon/coze-coding.gif"
alt="扣子编程 Logo"
width={156}
height={130}
/>
<div>
<div className="flex flex-col items-center gap-2 text-center sm:items-center sm:text-center">
<h1 className="max-w-xl text-base font-semibold leading-tight tracking-tight text-foreground dark:text-foreground">
应用开发中
</h1>
<p className="max-w-2xl text-sm leading-8 text-muted-foreground dark:text-muted-foreground">
请稍后,页面即将呈现
</p>
<div className="min-h-screen bg-gray-50 p-8">
<div className="max-w-7xl mx-auto">
<Card className="mb-6">
<CardHeader>
<CardTitle className="text-2xl">订单日报系统</CardTitle>
<CardDescription>
每天早8点自动生成前一天的订单日报(早8点到当天早8点)
</CardDescription>
</CardHeader>
</Card>
<Tabs defaultValue="config" className="space-y-4">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="config">配置管理</TabsTrigger>
<TabsTrigger value="generate">日报生成</TabsTrigger>
<TabsTrigger value="history">历史记录</TabsTrigger>
</TabsList>
<TabsContent value="config">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 创建配置 */}
<Card>
<CardHeader>
<CardTitle>创建新配置</CardTitle>
<CardDescription>配置日报的字段和拆分方式</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label htmlFor="configName">配置名称</Label>
<Input
id="configName"
value={configName}
onChange={(e) => setConfigName(e.target.value)}
placeholder="例如:企业日报配置"
/>
</div>
<div>
<Label htmlFor="splitType">拆分方式</Label>
<Select value={splitType} onValueChange={setSplitType}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="company_id">按企业ID拆分</SelectItem>
<SelectItem value="user_id">按用户ID拆分</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label>选择字段(已选 {selectedFields.length} 个)</Label>
<div className="grid grid-cols-2 md:grid-cols-3 gap-2 mt-2 h-[300px] overflow-y-auto border rounded p-2">
{availableFields.map((field) => (
<div key={field.field} className="flex items-center space-x-2">
<Checkbox
id={`config-${field.field}`}
checked={selectedFields.includes(field.field)}
onCheckedChange={(checked) =>
handleFieldChange(field.field, checked as boolean, 'config')
}
/>
<Label htmlFor={`config-${field.field}`} className="text-sm">
{field.label}
</Label>
</div>
))}
</div>
</div>
<Button
onClick={handleCreateConfig}
disabled={loading}
className="w-full"
>
{loading ? '创建中...' : '创建配置'}
</Button>
</CardContent>
</Card>
{/* 配置列表 */}
<Card>
<CardHeader>
<CardTitle>现有配置</CardTitle>
<CardDescription>查看和管理已创建的配置</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>配置名称</TableHead>
<TableHead>拆分方式</TableHead>
<TableHead>字段数量</TableHead>
<TableHead>操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{configs.map((config) => (
<TableRow key={config.id}>
<TableCell>{config.config_name}</TableCell>
<TableCell>
<Badge variant={config.split_type === 'company_id' ? 'default' : 'secondary'}>
{config.split_type === 'company_id' ? '企业' : '用户'}
</Badge>
</TableCell>
<TableCell>
{JSON.parse(config.selected_fields).length} 个
</TableCell>
<TableCell>
<Button
variant="destructive"
size="sm"
onClick={() => handleDeleteConfig(config.id)}
disabled={loading}
>
禁用
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
</div>
</div>
</main>
</TabsContent>
<TabsContent value="generate">
<Card>
<CardHeader>
<CardTitle>手动生成日报</CardTitle>
<CardDescription>
选择企业/用户和字段,手动生成指定日期的日报
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<Label htmlFor="reportSplitType">拆分方式</Label>
<Select value={reportSplitType} onValueChange={setReportSplitType}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="company_id">按企业ID</SelectItem>
<SelectItem value="user_id">按用户ID</SelectItem>
</SelectContent>
</Select>
{reportSplitType === 'user_id' && (
<p className="text-sm text-muted-foreground mt-1">
注意:用户ID可能对应企业用户或普通用户
</p>
)}
</div>
<div>
<Label htmlFor="reportSplitValue">
{reportSplitType === 'company_id' ? '企业ID' : '用户ID'}
</Label>
<Select value={reportSplitValue} onValueChange={setReportSplitValue}>
<SelectTrigger>
<SelectValue placeholder="请选择" />
</SelectTrigger>
<SelectContent>
{reportSplitType === 'company_id'
? companies.map((company) => (
<SelectItem key={company.company_id} value={String(company.company_id)}>
企业ID: {company.company_id} ({company.order_count} 单)
</SelectItem>
))
: users.map((user) => (
<SelectItem key={`${user.user_id}-${user.order_type}`} value={String(user.user_id)}>
用户ID: {user.user_id} ({user.user_type_label}, {user.order_count} 单)
</SelectItem>
))
}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="reportDate">报表日期(可选,默认昨天)</Label>
<Input
id="reportDate"
type="date"
value={reportDate}
onChange={(e) => setReportDate(e.target.value)}
/>
</div>
</div>
<div>
<Label>选择字段(已选 {reportSelectedFields.length} 个)</Label>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2 mt-2 h-[300px] overflow-y-auto border rounded p-2">
{availableFields.map((field) => (
<div key={field.field} className="flex items-center space-x-2">
<Checkbox
id={`report-${field.field}`}
checked={reportSelectedFields.includes(field.field)}
onCheckedChange={(checked) =>
handleFieldChange(field.field, checked as boolean, 'report')
}
/>
<Label htmlFor={`report-${field.field}`} className="text-sm">
{field.label}
</Label>
</div>
))}
</div>
</div>
<Button
onClick={handleGenerateReport}
disabled={loading}
className="w-full"
size="lg"
>
{loading ? '生成中...' : '生成日报'}
</Button>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="history">
<Card>
<CardHeader>
<CardTitle>日报历史记录</CardTitle>
<CardDescription>查看已生成的日报历史</CardDescription>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>报表日期</TableHead>
<TableHead>拆分方式</TableHead>
<TableHead>拆分值</TableHead>
<TableHead>订单数</TableHead>
<TableHead>总金额</TableHead>
<TableHead>状态</TableHead>
<TableHead>生成时间</TableHead>
<TableHead>操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{history.map((record) => (
<TableRow key={record.id}>
<TableCell>{record.report_date}</TableCell>
<TableCell>
<Badge variant={record.split_type === 'company_id' ? 'default' : 'secondary'}>
{record.split_type === 'company_id' ? '企业' : '用户'}
</Badge>
</TableCell>
<TableCell>{record.split_value}</TableCell>
<TableCell>{record.total_orders}</TableCell>
<TableCell>¥{record.total_amount}</TableCell>
<TableCell>
<Badge variant={record.status === 1 ? 'default' : 'destructive'}>
{record.status === 1 ? '成功' : '失败'}
</Badge>
</TableCell>
<TableCell>
{new Date(record.create_time).toLocaleString()}
</TableCell>
<TableCell>
{record.file_path && (
<Button
variant="outline"
size="sm"
onClick={() => window.open(record.file_path, '_blank')}
>
下载
</Button>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{historyTotal > 10 && (
<div className="flex justify-center gap-2 mt-4">
<Button
variant="outline"
disabled={historyPage === 1}
onClick={() => loadHistory(historyPage - 1)}
>
上一页
</Button>
<span className="flex items-center">
第 {historyPage} 页,共 {Math.ceil(historyTotal / 10)} 页
</span>
<Button
variant="outline"
disabled={historyPage >= Math.ceil(historyTotal / 10)}
onClick={() => loadHistory(historyPage + 1)}
>
下一页
</Button>
</div>
)}
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
<Toaster />
</div>
);
}
}

127
src/components/ui/toast.tsx Normal file
View File

@@ -0,0 +1,127 @@
import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}

View File

@@ -0,0 +1,33 @@
import { useToast } from "@/hooks/use-toast"
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

186
src/hooks/use-toast.ts Normal file
View File

@@ -0,0 +1,186 @@
import * as React from "react"
import type { ToastActionElement, ToastProps } from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_TIMEOUT = 5000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_VALUE
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_TIMEOUT)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open: boolean) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

31
src/lib/db.ts Normal file
View File

@@ -0,0 +1,31 @@
import mysql from 'mysql2/promise';
// 数据库配置
const dbConfig = {
host: 'haoslm2.xicp.net',
user: 'root',
password: 'DsideaL147258369',
database: 'yltcharge',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
};
// 创建连接池
const pool = mysql.createPool(dbConfig);
// 导出连接池
export default pool;
// 测试连接
export async function testConnection(): Promise<boolean> {
try {
const connection = await pool.getConnection();
console.log('数据库连接成功');
connection.release();
return true;
} catch (error) {
console.error('数据库连接失败:', error);
return false;
}
}

157
src/lib/field-mapping.ts Normal file
View File

@@ -0,0 +1,157 @@
// 字段定义:数据库字段名 -> 中文显示名
export const FIELD_MAPPING: Record<string, string> = {
'id': 'ID',
'user_id': '用户ID',
'company_id': '企业ID',
'station_id': '充电站ID',
'equipment_id': '充电桩ID',
'connector_id': '充电枪ID',
'user_card_no': '用户充电卡号',
'state': '订单状态',
'operate_state': '订单操作状态',
'order_no': '订单号',
'platform_order_no': '平台订单号',
'platform_sale_type': '平台转售模式',
'platform_driver_id': '平台用户ID',
'platform_phone': '平台用户手机号',
'charging_amt': '预充金额',
'order_type': '订单类型',
'order_time': '订单时间',
'charge_begin_time': '充电开始时间',
'charge_end_time': '充电结束时间',
'charge_begin_degree': '充电开始度数',
'charge_end_degree': '充电结束度数',
'charge_degree': '充电度数',
'charge_ah': '充电电量',
'charge_times_degree': '充电分时度数',
'charge_begin_soc': '充电开始SOC',
'charge_end_soc': '充电结束SOC',
'charge_cur_soc': '充电当前SOC',
'charge_duration': '充电时长',
'charge_settle_type': '充电结算类型',
'charge_unit_price': '电费单价',
'charge_unit_cost': '电费成本单价',
'charge_unit_service_fee': '服务费单价',
'receivable_electric_fee': '应收电费',
'receivable_service_fee': '应收服务费',
'receivable_total_fee': '应收总金额',
'charge_elecfee_amount': '电费(实收电费)',
'charge_elecfee_cost_amount': '电费成本',
'charge_service_amount': '服务费(实收服务费)',
'actual_pay_amount': '实际支付金额',
'pay_order_no': '支付订单号',
'pay_amount': '本次订单付款金额',
'pay_method': '支付方式',
'pay_status': '支付状态',
'pay_time': '支付时间',
'user_coupon_id': '用户优惠券ID',
'coupon_name': '优惠券名称',
'coupon_type': '优惠券类型',
'coupon_amount': '优惠券总金额',
'elecfee_coupon_amount': '电费优惠券金额',
'servicefee_coupon_amount': '服务费优惠券金额',
'invoice_id': '发票ID',
'invoice_fee': '可以开票金额',
'ticket_status': '开票状态',
'activity_electric_fee': '活动优惠电费',
'activity_service_fee': '活动优惠服务费',
'charge_plate_no': '车牌号',
'charge_vin': '车辆VIN码',
'charge_strategy': '充电策略',
'charge_strategy_param': '充电策略参数',
'operator_id': '运营商ID',
'operator_income': '运营商收入金额',
'plat_service_fee': '平台服务费',
'charge_discount_type': '充电优惠类型',
'settle_electric_fee': '结算电费',
'settle_service_fee': '结算服务费',
'settle_fee': '结算总费用',
'settle_method': '结算方式',
'settle_coupon_amount': '结算优惠金额',
'settle_coupon_electric_fee': '结算电费金额',
'settle_coupon_service_fee': '结算服务费',
'settle_status': '是否开启结算',
'cancel_type': '取消类型',
'cancel_code': '取消编码',
'cancel_msg': '取消原因',
'cancel_time': '取消时间',
'finish_type': '结束类型',
'finish_code': '结束编码',
'finish_msg': '结束原因',
'finish_time': '订单结束时间',
'boot_mode': '启动方式',
'settlement_type': '结算类型',
'is_parking_coupon': '领取停车券状态',
'control_source': '渠道',
'exception_flag': '订单异常标志',
'exception_msg': '订单异常描述',
'report_time': '订单上报时间',
'com_service_fee': '企业服务费',
'com_electric_fee': '企业电费',
'com_total_fee': '企业费用',
'com_charge_discount_type': '企业结算折扣方式',
'com_charge_discount': '优惠折扣',
'has_shallow_report': '有无浅检报告',
'has_deep_report': '有无深检报告',
'is_exception': '是否为异常订单',
'shallow_report_is_received': '是否已领取浅检报告',
'create_time': '创建时间',
'update_time': '更新时间',
'charge_market_id': '充电市场ID',
'coupon_total_amount': '总优惠金额',
'coupon_service_total_amount': '总优惠服务费',
'coupon_elecfee_total_amount': '总优惠电费',
'activity_name': '活动名称',
'activity_total_fee': '活动优惠总金额',
'company_activity_id': '企业活动ID',
'company_activity_name': '企业活动名称',
'company_activity_total_fee': '企业优惠总金额',
'company_activity_service_fee': '企业优惠服务费',
'company_activity_electric_fee': '企业优惠电费',
'subsidy_degree': '补贴度数',
'subsidy_fee': '补贴金额',
'special_channel_order_source': '特殊渠道订单来源'
};
// 获取所有可用字段
export function getAllFields(): Array<{ field: string; label: string }> {
return Object.entries(FIELD_MAPPING).map(([field, label]) => ({
field,
label
}));
}
// 订单状态映射
export const STATE_MAPPING: Record<number, string> = {
0: '创建中',
1: '准备充电中',
2: '充电中',
3: '完成',
4: '取消',
5: '挂起',
6: '需要手动补单',
7: '结算中'
};
// 订单类型映射
export const ORDER_TYPE_MAPPING: Record<number, string> = {
1: '普通用户订单',
3: '企业用户订单',
4: '第三方平台订单'
};
// 支付方式映射
export const PAY_METHOD_MAPPING: Record<number, string> = {
0: '余额支付',
1: '支付宝',
2: '微信小程序',
3: '微信APP支付'
};
// 支付状态映射
export const PAY_STATUS_MAPPING: Record<number, string> = {
0: '未支付',
1: '待支付',
2: '已支付',
3: '支付失败'
};

55
src/lib/init-tables.ts Normal file
View File

@@ -0,0 +1,55 @@
import pool from './db';
// 创建配置表和历史表的SQL语句
const createTablesSQL = `
-- 日报配置表(用户字段选择配置)
CREATE TABLE IF NOT EXISTS t_daily_report_config (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '配置ID',
config_name VARCHAR(100) NOT NULL COMMENT '配置名称',
split_type VARCHAR(20) NOT NULL COMMENT '拆分方式:company_id 或 user_id',
selected_fields JSON NOT NULL COMMENT '用户选择的字段列表(JSON数组)',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_active TINYINT DEFAULT 1 COMMENT '是否启用:0禁用 1启用'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='日报字段配置表';
-- 日报生成历史记录表
CREATE TABLE IF NOT EXISTS t_daily_report_history (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '记录ID',
report_date DATE NOT NULL COMMENT '报表日期',
start_time DATETIME NOT NULL COMMENT '报表开始时间',
end_time DATETIME NOT NULL COMMENT '报表结束时间',
split_type VARCHAR(20) NOT NULL COMMENT '拆分方式:company_id 或 user_id',
split_value VARCHAR(100) NOT NULL COMMENT '拆分值(企业ID或用户ID)',
config_id BIGINT COMMENT '使用的配置ID',
total_orders INT DEFAULT 0 COMMENT '订单总数',
total_amount DECIMAL(15,2) DEFAULT 0 COMMENT '总金额',
file_path VARCHAR(500) COMMENT '生成的文件路径',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '生成时间',
status TINYINT DEFAULT 1 COMMENT '状态:0失败 1成功'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='日报生成历史表';
`;
// 初始化数据库表
export async function initDatabaseTables(): Promise<void> {
try {
const connection = await pool.getConnection();
// 执行创建表的SQL
const statements = createTablesSQL.split(';').filter(stmt => stmt.trim());
for (const statement of statements) {
if (statement.trim()) {
await connection.execute(statement);
}
}
connection.release();
console.log('数据库表初始化成功');
console.log('创建了以下表:');
console.log('1. t_daily_report_config - 日报字段配置表');
console.log('2. t_daily_report_history - 日报生成历史表');
} catch (error) {
console.error('数据库表初始化失败:', error);
throw error;
}
}

254
src/lib/report-generator.ts Normal file
View File

@@ -0,0 +1,254 @@
import pool from '@/lib/db';
import { FIELD_MAPPING, STATE_MAPPING, ORDER_TYPE_MAPPING, PAY_METHOD_MAPPING, PAY_STATUS_MAPPING } from '@/lib/field-mapping';
import * as XLSX from 'xlsx';
import { writeFileSync, mkdirSync } from 'fs';
import path from 'path';
// 日报生成配置
interface ReportConfig {
config_id: number;
split_type: string; // 'company_id' 或 'user_id'
selected_fields: string[]; // 用户选择的字段
}
// 日报生成结果
interface ReportResult {
success: boolean;
reportDate: string;
startTime: string;
endTime: string;
splitType: string;
splitValue: string;
totalOrders: number;
totalAmount: number;
filePath?: string;
error?: string;
}
// 生成日报
export async function generateDailyReport(
splitType: string,
splitValue: string,
selectedFields: string[],
reportDate?: string // 可选的报表日期,默认为昨天
): Promise<ReportResult> {
try {
// 计算时间范围:前一天早8点到当天早8点
const targetDate = reportDate ? new Date(reportDate) : new Date();
targetDate.setDate(targetDate.getDate() - 1); // 昨天
const startTime = new Date(targetDate);
startTime.setHours(8, 0, 0, 0);
const endTime = new Date(targetDate);
endTime.setDate(endTime.getDate() + 1);
endTime.setHours(8, 0, 0, 0);
// 查询订单数据
const queryField = splitType === 'company_id' ? 'company_id' : 'user_id';
const fieldList = selectedFields.join(', ');
const [orders] = await pool.execute<any[]>(
`SELECT ${fieldList} FROM t_equipment_charge_order
WHERE state = 3
AND report_time >= ?
AND report_time < ?
AND ${queryField} = ?
ORDER BY report_time ASC`,
[startTime, endTime, splitValue]
);
if (!Array.isArray(orders) || orders.length === 0) {
return {
success: false,
reportDate: targetDate.toISOString().split('T')[0],
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
splitType,
splitValue,
totalOrders: 0,
totalAmount: 0,
error: '该时间段内没有订单数据'
};
}
// 处理数据:将字段名转换为中文,并转换特殊字段的值
const processedOrders = orders.map(order => {
const processed: Record<string, any> = {};
for (const [key, value] of Object.entries(order)) {
// 使用中文字段名
const chineseName = FIELD_MAPPING[key] || key;
// 特殊字段值转换
if (key === 'state' && typeof value === 'number') {
processed[chineseName] = STATE_MAPPING[value] || value;
} else if (key === 'order_type' && typeof value === 'number') {
processed[chineseName] = ORDER_TYPE_MAPPING[value] || value;
} else if (key === 'pay_method' && typeof value === 'number') {
processed[chineseName] = PAY_METHOD_MAPPING[value] || value;
} else if (key === 'pay_status' && typeof value === 'number') {
processed[chineseName] = PAY_STATUS_MAPPING[value] || value;
} else {
processed[chineseName] = value;
}
}
return processed;
});
// 生成Excel文件
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.json_to_sheet(processedOrders);
// 设置列宽
const columnWidths = selectedFields.map(field => ({
wch: Math.max(FIELD_MAPPING[field]?.length || 10, 15)
}));
worksheet['!cols'] = columnWidths;
XLSX.utils.book_append_sheet(workbook, worksheet, '日报');
// 生成文件名
const fileName = `日报_${splitType === 'company_id' ? '企业' : '用户'}_${splitValue}_${targetDate.toISOString().split('T')[0]}.xlsx`;
const reportsDir = path.join(process.cwd(), 'public', 'reports');
// 确保目录存在
mkdirSync(reportsDir, { recursive: true });
const filePath = path.join(reportsDir, fileName);
// 写入文件
writeFileSync(filePath, XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }));
// 计算统计信息
const totalOrders = orders.length;
const totalAmount = orders.reduce((sum: number, order: any) => {
return sum + (parseFloat(order.actual_pay_amount) || 0);
}, 0);
return {
success: true,
reportDate: targetDate.toISOString().split('T')[0],
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
splitType,
splitValue,
totalOrders,
totalAmount,
filePath: `/reports/${fileName}`
};
} catch (error) {
return {
success: false,
reportDate: '',
startTime: '',
endTime: '',
splitType,
splitValue,
totalOrders: 0,
totalAmount: 0,
error: error instanceof Error ? error.message : '未知错误'
};
}
}
// 批量生成日报(用于定时任务)
export async function generateBatchReports(configId: number): Promise<ReportResult[]> {
try {
// 获取配置
const [configs] = await pool.execute<any[]>(
'SELECT * FROM t_daily_report_config WHERE id = ? AND is_active = 1',
[configId]
);
if (!Array.isArray(configs) || configs.length === 0) {
throw new Error('配置不存在或已禁用');
}
const config = configs[0];
const splitType = config.split_type;
const selectedFields = JSON.parse(config.selected_fields);
// 获取所有需要生成日报的企业/用户列表
const queryField = splitType === 'company_id' ? 'company_id' : 'user_id';
// 计算时间范围
const targetDate = new Date();
targetDate.setDate(targetDate.getDate() - 1);
const startTime = new Date(targetDate);
startTime.setHours(8, 0, 0, 0);
const endTime = new Date(targetDate);
endTime.setDate(endTime.getDate() + 1);
endTime.setHours(8, 0, 0, 0);
// 获取该时间段内的所有企业/用户
const [entities] = await pool.execute<any[]>(
`SELECT DISTINCT ${queryField} as entity_id
FROM t_equipment_charge_order
WHERE state = 3
AND report_time >= ?
AND report_time < ?
AND ${queryField} IS NOT NULL`,
[startTime, endTime]
);
if (!Array.isArray(entities) || entities.length === 0) {
return [];
}
// 批量生成日报
const results: ReportResult[] = [];
for (const entity of entities) {
const entityId = entity.entity_id;
const result = await generateDailyReport(splitType, String(entityId), selectedFields);
// 保存到历史记录表
if (result.success) {
await pool.execute(
`INSERT INTO t_daily_report_history
(report_date, start_time, end_time, split_type, split_value, config_id, total_orders, total_amount, file_path, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
result.reportDate,
result.startTime,
result.endTime,
result.splitType,
result.splitValue,
configId,
result.totalOrders,
result.totalAmount,
result.filePath || null,
1
]
);
} else {
await pool.execute(
`INSERT INTO t_daily_report_history
(report_date, start_time, end_time, split_type, split_value, config_id, total_orders, total_amount, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
result.reportDate,
result.startTime,
result.endTime,
result.splitType,
result.splitValue,
configId,
result.totalOrders,
result.totalAmount,
0
]
);
}
results.push(result);
}
return results;
} catch (error) {
throw error;
}
}

22
src/lib/test-db.ts Normal file
View File

@@ -0,0 +1,22 @@
import pool from './db';
async function testDatabase() {
try {
// 测试连接
const connection = await pool.getConnection();
console.log('数据库连接成功');
// 查询订单表的几条数据
const [rows] = await connection.execute(
'SELECT * FROM t_equipment_charge_order LIMIT 5'
);
console.log('查询结果:', rows);
connection.release();
console.log('测试完成');
} catch (error) {
console.error('测试失败:', error);
}
}
testDatabase();

View File

@@ -1,15 +1,58 @@
import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';
import cron from 'node-cron';
import { generateBatchReports } from './lib/report-generator';
import pool from './lib/db';
const dev = process.env.COZE_PROJECT_ENV !== 'PROD';
const hostname = process.env.HOSTNAME || 'localhost';
const port = parseInt(process.env.PORT || '5000', 10);
const port = parseInt(process.env.DEPLOY_RUN_PORT || '5000', 10);
// Create Next.js app
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
// 定时任务:每天早8:01自动生成日报
function startDailyReportTask() {
// 每天早上8:01执行
cron.schedule('1 8 * * *', async () => {
console.log('开始自动生成日报...', new Date().toLocaleString());
try {
// 获取所有启用的配置
const [configs] = await pool.execute(
'SELECT * FROM t_daily_report_config WHERE is_active = 1'
);
if (!Array.isArray(configs) || configs.length === 0) {
console.log('没有启用的配置,跳过日报生成');
return;
}
// 为每个配置生成日报
for (const config of configs) {
const configItem = config as { id: number; config_name: string };
console.log(`正在生成配置 ${configItem.config_name} 的日报...`);
try {
const results = await generateBatchReports(configItem.id);
console.log(`配置 ${configItem.config_name} 生成完成,共 ${results.length} 个日报`);
} catch (error) {
console.error(`配置 ${configItem.config_name} 生成失败:`, error);
}
}
console.log('日报生成完成', new Date().toLocaleString());
} catch (error) {
console.error('日报自动生成失败:', error);
}
}, {
timezone: 'Asia/Shanghai'
});
console.log('定时任务已启动:每天早8:01自动生成日报');
}
app.prepare().then(() => {
const server = createServer(async (req, res) => {
try {
@@ -31,5 +74,8 @@ app.prepare().then(() => {
dev ? 'development' : process.env.COZE_PROJECT_ENV
}`,
);
// 启动定时任务
startDailyReportTask();
});
});