ImportControl.tsx
7.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import { useRef, useState } from 'react';
import { App as AntdApp, Button, Modal, Progress, Tooltip } from 'antd';
import { InboxOutlined, RollbackOutlined } from '@ant-design/icons';
import { ingestFile, type IngestOutcome } from '@/features/heatmap/data/ingest';
import { clearImportedBundle, saveImportedBundle } from '@/features/heatmap/data/importedDb';
import { useHeatmapStore } from '@/store/useHeatmapStore';
import { fmtDateTime, fmtInt } from '@/utils/format';
const ACCEPT = '.xlsx,.xls,.csv';
/**
* 顶栏的导入控件:选本地 xlsx/csv → 解析 Worker 里算好前端三件套 → 展示解析报告 →
* 确认后写入 IndexedDB 并刷新,刷新后 bootstrap 直接读取导入数据呈现最新点位。
*
* 为什么是「确认后才落库 + 刷新」:
* 导入是覆盖式(一次导入=一份最新数据),一旦写库就顶掉旧的。让用户先在报告里
* 看清「有效 / 拒收 / 时间范围」再决定,避免把脏数据静默换上去;拒收原因直接摊开,
* 方便回源文件改。
*
* 解析全程在 Worker 里,主线程只更新进度条,地图不会冻住。
*/
export function ImportControl() {
const { message } = AntdApp.useApp();
const inputRef = useRef<HTMLInputElement>(null);
const [parsing, setParsing] = useState(false);
const [percent, setPercent] = useState(0);
const [outcome, setOutcome] = useState<IngestOutcome | null>(null);
const [saving, setSaving] = useState(false);
const dataOrigin = useHeatmapStore((s) => s.dataOrigin);
const pick = () => inputRef.current?.click();
async function onFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
e.target.value = ''; // 允许重复选同一文件再次触发
if (!file) return;
setParsing(true);
setPercent(0);
try {
const res = await ingestFile(file, (p) => {
// decode 占前一半,normalize 占后一半,与 Worker 里的阶段划分一致
setPercent(Math.round((p.phase === 'decode' ? p.ratio * 0.5 : 0.5 + p.ratio * 0.5) * 100));
});
setOutcome(res);
} catch (err) {
message.error(err instanceof Error ? err.message : String(err));
} finally {
setParsing(false);
setPercent(0);
}
}
async function apply() {
if (!outcome) return;
setSaving(true);
try {
await saveImportedBundle({
manifest: {
fileName: outcome.report.fileName,
count: outcome.report.count,
rejected: outcome.report.rejected,
importedAt: new Date().toISOString(),
},
meta: outcome.meta,
columns: outcome.columns,
detail: outcome.detail,
});
await reload();
} catch (err) {
setSaving(false);
message.error(`保存失败:${err instanceof Error ? err.message : String(err)}`);
}
}
async function restoreSample() {
try {
await clearImportedBundle();
await reload();
} catch (err) {
message.error(`恢复失败:${err instanceof Error ? err.message : String(err)}`);
}
}
return (
<>
<input
ref={inputRef}
type="file"
accept={ACCEPT}
style={{ display: 'none' }}
onChange={onFile}
/>
{dataOrigin === 'imported' && (
<Tooltip title="清除导入数据,恢复内置示例">
<Button
type="text"
className="hm-header__icon-btn"
icon={<RollbackOutlined />}
onClick={restoreSample}
/>
</Tooltip>
)}
<Tooltip title="导入 xlsx / csv 出险点位,覆盖当前数据">
<Button
type="text"
className="hm-header__icon-btn hm-header__import-btn"
icon={<InboxOutlined />}
loading={parsing}
onClick={pick}
>
{parsing ? `解析中 ${percent}%` : '导入数据'}
</Button>
</Tooltip>
<ImportReportModal outcome={outcome} saving={saving} onClose={() => setOutcome(null)} onApply={apply} />
</>
);
}
function ImportReportModal({
outcome,
saving,
onClose,
onApply,
}: {
outcome: IngestOutcome | null;
saving: boolean;
onClose: () => void;
onApply: () => void;
}) {
if (!outcome) return null;
const r = outcome.report;
const reasons = Object.entries(r.rejectedReasons).filter(([, n]) => n > 0);
const coveredDistricts = Object.keys(r.districtCounts).filter((d) => d !== '未识别').length;
return (
<Modal
open
title={
<span>
<InboxOutlined style={{ marginRight: 8 }} />
导入预览 · {r.fileName}
</span>
}
onCancel={onClose}
okText="应用并刷新"
cancelText="取消"
okButtonProps={{ loading: saving }}
onOk={onApply}
width={460}
>
<div className="hm-import-report">
<div className="hm-import-report__grid">
<Stat label="有效点位" value={fmtInt(r.count)} accent />
<Stat label="拒收行" value={fmtInt(r.rejected)} tone={r.rejected > 0 ? 'warn' : 'ok'} />
<Stat label="空行跳过" value={fmtInt(r.skippedEmpty)} />
<Stat label="覆盖区数" value={fmtInt(coveredDistricts)} />
</div>
<div className="hm-import-report__range">
<span className="hm-import-report__range-label">时间范围</span>
<span className="hm-import-report__range-value">
{fmtDateTime(r.timeMin)} ~ {fmtDateTime(r.timeMax)}
</span>
</div>
{(r.districtUnknown > 0 || r.streetUnknown > 0) && (
<div className="hm-import-report__coverage">
<Progress
percent={Math.round((1 - r.districtUnknown / Math.max(r.count, 1)) * 100)}
size="small"
showInfo={false}
/>
<span>
区未识别 {fmtInt(r.districtUnknown)} 行 · 街道未识别 {fmtInt(r.streetUnknown)} 行
(按地址前缀匹配,未命中会归到「未识别」)
</span>
</div>
)}
{reasons.length > 0 && (
<div className="hm-import-report__reasons">
<div className="hm-import-report__reasons-title">拒收明细</div>
{reasons.map(([reason, n]) => (
<div className="hm-import-report__reason" key={reason}>
<span>{reason}</span>
<b>{fmtInt(n)}</b>
</div>
))}
</div>
)}
{r.count > 0 && r.rejected > 0 && (
<div className="hm-import-report__hint">
注意:本次导入会覆盖当前展示的数据。拒收行不会进入地图,可回源文件修正后重新导入。
</div>
)}
</div>
</Modal>
);
}
function Stat({
label,
value,
accent,
tone,
}: {
label: string;
value: string;
accent?: boolean;
tone?: 'ok' | 'warn';
}) {
return (
<div className="hm-import-report__stat">
<div
className="hm-import-report__stat-value"
data-accent={accent ? '1' : undefined}
data-tone={tone}
>
{value}
</div>
<div className="hm-import-report__stat-label">{label}</div>
</div>
);
}
/** 落库后刷新页面;带短延时让「应用并刷新」的按钮态可见 */
function reload(): Promise<void> {
return new Promise((resolve) => {
window.setTimeout(() => {
window.location.reload();
resolve();
}, 150);
});
}