feat(platform): paginate daily mileage

This commit is contained in:
lingniu
2026-07-03 22:23:10 +08:00
parent 72aa20b347
commit 39e2788e26
4 changed files with 85 additions and 17 deletions

View File

@@ -138,8 +138,13 @@ func buildDailyMileageSQL(query url.Values) SQLQuery {
args := []any{}
where := []string{"1 = 1"}
if vin := strings.TrimSpace(query.Get("vin")); vin != "" {
where = append(where, "m.vin = ?")
args = append(args, vin)
where = append(where, "(m.vin LIKE ? OR b.plate LIKE ?)")
like := "%" + vin + "%"
args = append(args, like, like)
}
if protocol := strings.TrimSpace(query.Get("protocol")); protocol != "" {
where = append(where, "m.protocol = ?")
args = append(args, protocol)
}
if dateFrom := strings.TrimSpace(query.Get("dateFrom")); dateFrom != "" {
where = append(where, "m.stat_date >= ?")
@@ -149,13 +154,16 @@ func buildDailyMileageSQL(query url.Values) SQLQuery {
where = append(where, "m.stat_date <= ?")
args = append(args, dateTo)
}
countArgs := append([]any(nil), args...)
args = append(args, limit, offset)
fromSQL := `FROM vehicle_daily_mileage m LEFT JOIN vehicle_identity_binding b ON b.vin = m.vin WHERE ` + strings.Join(where, " AND ")
return SQLQuery{
Text: `SELECT m.vin, COALESCE(b.plate, '') AS plate, DATE_FORMAT(m.stat_date, '%Y-%m-%d') AS stat_date, ` +
`m.first_total_mileage_km, m.latest_total_mileage_km, m.daily_mileage_km, m.protocol ` +
`FROM vehicle_daily_mileage m LEFT JOIN vehicle_identity_binding b ON b.vin = m.vin ` +
`WHERE ` + strings.Join(where, " AND ") + ` ORDER BY m.stat_date DESC LIMIT ? OFFSET ?`,
Args: args,
fromSQL + ` ORDER BY m.stat_date DESC, m.vin ASC, m.protocol ASC LIMIT ? OFFSET ?`,
Args: args,
CountText: `SELECT COUNT(*) ` + fromSQL,
CountArgs: countArgs,
}
}

View File

@@ -267,6 +267,12 @@ func (s *ProductionStore) RawFrames(ctx context.Context, query RawFrameQuery) (P
func (s *ProductionStore) DailyMileage(ctx context.Context, query url.Values) (Page[DailyMileageRow], error) {
built := buildDailyMileageSQL(query)
total := 0
if built.CountText != "" {
if err := s.db.QueryRowContext(ctx, built.CountText, built.CountArgs...).Scan(&total); err != nil {
return Page[DailyMileageRow]{}, err
}
}
rows, err := s.db.QueryContext(ctx, built.Text, built.Args...)
if err != nil {
return Page[DailyMileageRow]{}, err
@@ -284,7 +290,10 @@ func (s *ProductionStore) DailyMileage(ctx context.Context, query url.Values) (P
return Page[DailyMileageRow]{}, err
}
limit, offset := buildLimitOffset(query)
return Page[DailyMileageRow]{Items: items, Total: len(items), Limit: limit, Offset: offset}, nil
if built.CountText == "" {
total = len(items)
}
return Page[DailyMileageRow]{Items: items, Total: total, Limit: limit, Offset: offset}, nil
}
func (s *ProductionStore) QualityIssues(ctx context.Context, query url.Values) (Page[QualityIssueRow], error) {

View File

@@ -61,14 +61,23 @@ func TestBuildRealtimeLocationSQL(t *testing.T) {
}
func TestBuildDailyMileageSQL(t *testing.T) {
query := url.Values{"vin": {"VIN001"}, "dateFrom": {"2026-07-01"}, "dateTo": {"2026-07-03"}}
query := url.Values{"vin": {"VIN001"}, "protocol": {"JT808"}, "dateFrom": {"2026-07-01"}, "dateTo": {"2026-07-03"}}
built := buildDailyMileageSQL(query)
if !strings.Contains(built.Text, "vehicle_daily_mileage") || !strings.Contains(built.Text, "vehicle_identity_binding") {
t.Fatalf("SQL = %s", built.Text)
}
if len(built.Args) != 5 || built.Args[0] != "VIN001" || built.Args[3] != 20 || built.Args[4] != 0 {
if !strings.Contains(built.Text, "ORDER BY m.stat_date DESC, m.vin ASC, m.protocol ASC") {
t.Fatalf("SQL should keep stable pagination order: %s", built.Text)
}
if !strings.Contains(built.CountText, "COUNT(*)") || strings.Contains(built.CountText, "LIMIT") {
t.Fatalf("count SQL = %s", built.CountText)
}
if len(built.Args) != 7 || built.Args[0] != "%VIN001%" || built.Args[2] != "JT808" || built.Args[5] != 20 || built.Args[6] != 0 {
t.Fatalf("args = %#v", built.Args)
}
if len(built.CountArgs) != 5 || built.CountArgs[0] != "%VIN001%" || built.CountArgs[2] != "JT808" {
t.Fatalf("count args = %#v", built.CountArgs)
}
}
func TestBuildRawFrameSQL(t *testing.T) {

View File

@@ -1,4 +1,4 @@
import { Card, DatePicker, Form, Table, Tag, Toast } from '@douyinfe/semi-ui';
import { Button, Card, Form, Select, Space, Table, Tag, Toast } from '@douyinfe/semi-ui';
import { useEffect, useState } from 'react';
import { api } from '../api/client';
import type { DailyMileageRow } from '../api/types';
@@ -6,27 +6,69 @@ import { PageHeader } from '../components/PageHeader';
export function Mileage() {
const [rows, setRows] = useState<DailyMileageRow[]>([]);
const [loading, setLoading] = useState(true);
const [filters, setFilters] = useState<Record<string, string>>({});
const [pagination, setPagination] = useState({ currentPage: 1, pageSize: 20, total: 0 });
const load = (values: Record<string, string> = filters, page = pagination.currentPage, pageSize = pagination.pageSize) => {
setLoading(true);
const params = new URLSearchParams({ limit: String(pageSize), offset: String((page - 1) * pageSize) });
if (values?.vin) params.set('vin', values.vin);
if (values?.protocol) params.set('protocol', values.protocol);
if (values?.dateFrom) params.set('dateFrom', values.dateFrom);
if (values?.dateTo) params.set('dateTo', values.dateTo);
api.dailyMileage(params)
.then((nextPage) => {
setRows(nextPage.items);
setPagination({ currentPage: page, pageSize, total: nextPage.total });
})
.catch((error: Error) => Toast.error(error.message))
.finally(() => setLoading(false));
};
useEffect(() => {
api.dailyMileage(new URLSearchParams({ limit: '20' }))
.then((page) => setRows(page.items))
.catch((error: Error) => Toast.error(error.message));
load({}, 1, pagination.pageSize);
}, []);
return (
<div className="vp-page">
<PageHeader title="里程分析" description="每日里程、区间里程和异常差值分析" />
<Card bordered>
<Form layout="horizontal">
<Form.Input field="vin" label="VIN" placeholder="输入 VIN" style={{ width: 260 }} />
<DatePicker type="dateRange" density="compact" />
<Form layout="horizontal" onSubmit={(values) => {
const nextFilters = values as Record<string, string>;
setFilters(nextFilters);
load(nextFilters, 1, pagination.pageSize);
}}>
<Form.Input field="vin" label="关键词" placeholder="VIN / 车牌" style={{ width: 260 }} />
<Form.Select field="protocol" label="协议" placeholder="全部协议" style={{ width: 180 }}>
<Select.Option value="GB32960">GB32960</Select.Option>
<Select.Option value="JT808">JT808</Select.Option>
<Select.Option value="YUTONG_MQTT">YUTONG_MQTT</Select.Option>
</Form.Select>
<Form.Input field="dateFrom" label="开始日期" placeholder="2026-07-01" style={{ width: 160 }} />
<Form.Input field="dateTo" label="结束日期" placeholder="2026-07-03" style={{ width: 160 }} />
<Space>
<Button htmlType="submit" theme="solid" type="primary"></Button>
<Button onClick={() => {
setFilters({});
load({}, 1, pagination.pageSize);
}}></Button>
</Space>
</Form>
</Card>
<Card bordered style={{ marginTop: 16 }}>
<Table
rowKey="vin"
loading={loading}
rowKey={(row?: DailyMileageRow) => `${row?.date ?? ''}-${row?.vin ?? ''}-${row?.source ?? ''}`}
dataSource={rows}
pagination={false}
pagination={{
currentPage: pagination.currentPage,
pageSize: pagination.pageSize,
total: pagination.total,
showSizeChanger: true,
onPageChange: (page) => load(filters, page, pagination.pageSize),
onPageSizeChange: (pageSize) => load(filters, 1, pageSize)
}}
columns={[
{ title: '日期', dataIndex: 'date' },
{ title: 'VIN', dataIndex: 'vin' },