app.js
22.2 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*
文件名: app/static/js/app.js
职责: 前端交互逻辑,处理 API 请求调用、数据动态渲染、图表展示及文件上传。
注意: 不要删除这个注释。
*/
document.addEventListener('DOMContentLoaded', () => {
console.log('问界门店运营数据分析平台加载成功');
// ====================================================================
// 顶部导航栏点击事件(平铺,无下拉)
// ====================================================================
const navItems = document.querySelectorAll('.nav-item');
const contentTitle = document.querySelector('#content-title');
navItems.forEach(item => {
item.addEventListener('click', () => {
// 切换激活状态
navItems.forEach(i => i.classList.remove('active'));
item.classList.add('active');
const section = item.getAttribute('data-section');
if (section === 'ods') {
loadOdsSyncPage();
} else if (section === 'dw') {
loadDwProcessPage();
} else if (section === 'analysis-modal') {
showAnalysisPage();
} else {
hideAllSections();
document.getElementById('welcome-message').style.display = 'block';
contentTitle.textContent = item.textContent.trim();
}
});
});
// ====================================================================
// 通用工具:隐藏所有内容区块
// ====================================================================
function hideAllSections() {
document.getElementById('task-config-section').style.display = 'none';
document.getElementById('dw-process-section').style.display = 'none';
document.getElementById('task-history-section').style.display = 'none';
document.getElementById('data-analysis-section').style.display = 'none';
document.getElementById('analysis-result').style.display = 'none';
document.getElementById('analysis-error').style.display = 'none';
document.getElementById('welcome-message').style.display = 'none';
}
// ====================================================================
// ODS 页面逻辑
// ====================================================================
async function loadOdsSyncPage() {
hideAllSections();
document.getElementById('task-config-section').style.display = 'block';
document.getElementById('task-history-section').style.display = 'block';
contentTitle.textContent = 'ODS 同步任务';
try {
const configRes = await fetch('api/etl/scheduler-config?task_id=sync_ods_data');
const config = await configRes.json();
document.getElementById('conf-task-id').textContent = config.task_id || '-';
document.getElementById('conf-status').textContent = config.status || '-';
document.getElementById('conf-next-run').textContent = config.next_run_time || '-';
document.getElementById('conf-trigger').textContent = config.trigger || '-';
} catch (err) {
console.error('获取配置失败:', err);
}
refreshHistory('ods');
}
// ====================================================================
// DW 加工页面逻辑
// ====================================================================
function loadDwProcessPage() {
hideAllSections();
document.getElementById('dw-process-section').style.display = 'block';
document.getElementById('task-history-section').style.display = 'block';
contentTitle.textContent = 'DWS/DWM/DWA 加工任务';
refreshHistory('dw');
// 初始化默认日期: 上月26号 至 今天
const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const now = new Date();
const todayStr = fmt(now);
const lastMonth26 = new Date(now.getFullYear(), now.getMonth()-1, 26);
const startStr = fmt(lastMonth26);
const startInput = document.getElementById('dw-start-date');
const endInput = document.getElementById('dw-end-date');
if (startInput && !startInput.value) startInput.value = startStr;
if (endInput && !endInput.value) endInput.value = todayStr;
}
// ====================================================================
// 任务历史刷新与轮询
// ====================================================================
let pollingTimer = null;
let currentHistoryType = 'ods';
let historyCache = {};
async function refreshHistory(type) {
if (type) currentHistoryType = type;
try {
const historyRes = await fetch('./api/etl/history?limit=15');
const history = await historyRes.json();
const tbody = document.getElementById('history-tbody');
tbody.innerHTML = '';
let hasRunning = false;
history.forEach(item => {
if (currentHistoryType === 'ods' && !item.task_id.includes('ods')) return;
if (currentHistoryType === 'dw' && !item.task_id.includes('sync')) return;
historyCache[item.id] = item.result_info;
if (item.status === 'running') hasRunning = true;
const tr = document.createElement('tr');
tr.style.borderBottom = '1px solid #f0f0f0';
const duration = item.end_time ? calculateDuration(item.start_time, item.end_time) : (item.status === 'running' ? '执行中...' : '-');
const statusColor = item.status === 'success' ? '#52c41a' : (item.status === 'failed' ? '#f5222d' : '#1890ff');
const tableCount = item.tables_involved ? item.tables_involved.split(',').length : 0;
tr.innerHTML = `
<td style="padding: 12px;">${item.start_time}</td>
<td style="padding: 12px;">${item.data_range || '-'}</td>
<td style="padding: 12px;" title="${item.tables_involved || ''}">${tableCount} 张表</td>
<td style="padding: 12px; color: ${statusColor}">${item.status}</td>
<td style="padding: 12px;"><a href="#" onclick="showTaskDetail('${item.id}'); return false;">查看</a></td>
`;
tbody.appendChild(tr);
});
return hasRunning;
} catch (err) {
console.error('获取历史失败:', err);
return false;
}
}
function startPollingHistory() {
if (pollingTimer) clearInterval(pollingTimer);
let count = 0;
pollingTimer = setInterval(async () => {
count++;
const hasRunning = await refreshHistory();
if (!hasRunning || count > 20) {
clearInterval(pollingTimer);
pollingTimer = null;
}
}, 3000);
}
// ====================================================================
// 按钮点击事件
// ====================================================================
document.getElementById('btn-run-ods').addEventListener('click', async () => {
const btn = document.getElementById('btn-run-ods');
btn.disabled = true;
btn.textContent = '任务已启动...';
try {
const res = await fetch('./api/etl/run-ods', { method: 'POST' });
const data = await res.json();
if (data.status === 'success') {
setTimeout(() => { btn.disabled = false; btn.textContent = '立即同步 ODS'; }, 2000);
refreshHistory('ods');
startPollingHistory();
} else {
alert('执行失败: ' + data.detail);
btn.disabled = false;
}
} catch (err) {
alert('请求出错: ' + err);
btn.disabled = false;
}
});
document.getElementById('btn-run-dw').addEventListener('click', async () => {
const layer = document.getElementById('dw-layer-select').value;
const startDate = document.getElementById('dw-start-date').value;
const endDate = document.getElementById('dw-end-date').value;
const fullSync = document.getElementById('dw-full-sync').checked;
const formData = new FormData();
formData.append('layer', layer);
if (fullSync) {
formData.append('full_sync', 'true');
} else if (startDate && endDate) {
formData.append('start_date', startDate);
formData.append('end_date', endDate);
}
const btn = document.getElementById('btn-run-dw');
btn.disabled = true;
btn.textContent = '加工中...';
try {
const res = await fetch('./api/etl/run-dw', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
setTimeout(() => { btn.disabled = false; btn.textContent = '开始加工'; }, 2000);
refreshHistory('dw');
startPollingHistory();
} else {
alert('执行失败: ' + data.detail);
btn.disabled = false;
}
} catch (err) {
alert('请求出错: ' + err);
btn.disabled = false;
}
});
// ====================================================================
// 工具函数
// ====================================================================
function calculateDuration(start, end) {
const s = new Date(start);
const e = new Date(end);
const diff = (e - s) / 1000;
return diff.toFixed(1) + 's';
}
window.showTaskDetail = function(id) {
const info = historyCache[id];
if (!info || info === "null" || info === "") {
alert("暂无详情数据");
return;
}
const modal = document.getElementById('detail-modal');
const tbody = document.getElementById('detail-tbody');
if (!modal || !tbody) return;
tbody.innerHTML = '';
// 元信息展示区域
var metaDiv = document.getElementById('detail-meta');
if (!metaDiv) {
metaDiv = document.createElement('div');
metaDiv.id = 'detail-meta';
var modalBody = tbody.closest('.modal-body');
if (modalBody) modalBody.insertBefore(metaDiv, modalBody.firstChild);
}
metaDiv.innerHTML = '';
metaDiv.style.display = 'none';
try {
var data = JSON.parse(info);
var itemList = null;
var errorText = null;
if (Array.isArray(data)) {
itemList = data;
} else if (data && typeof data === 'object') {
if (data.start_type || data.node_ip) {
var metaHtml = '';
if (data.start_type) metaHtml += '<span class="meta-tag">启动方式: <b>' + data.start_type + '</b></span>';
if (data.node_ip) metaHtml += '<span class="meta-tag">节点IP: <b>' + data.node_ip + '</b></span>';
metaDiv.innerHTML = metaHtml;
metaDiv.style.display = '';
}
if (data.error) {
errorText = data.error;
} else if (Array.isArray(data.results)) {
itemList = data.results;
}
}
if (errorText) {
tbody.innerHTML =
'<tr><td colspan="5" style="padding:16px;">' +
'<div style="color:#f5222d;font-weight:bold;margin-bottom:8px;">执行失败</div>' +
'<pre style="white-space:pre-wrap;word-break:break-all;background:#fafafa;padding:12px;border-radius:4px;font-size:12px;max-height:300px;overflow:auto;">' + errorText + '</pre>' +
'</td></tr>';
} else if (itemList) {
if (itemList.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;color:#999;">无详细记录</td></tr>';
} else {
var rows = itemList.map(function(item) {
var st = item.status || 'unknown';
var cls = st === 'success' ? 'status-success'
: (st === 'no_data' || st === 'no_valid_data' ? 'status-skip' : 'status-failed');
var rangeText = item.range_start ? '从: ' + item.range_start + '<br>至: ' + item.range_end : '-';
var col1 = item.source || item.table || '-';
var col2 = item.target || item.table || '-';
return '<tr>' +
'<td>' + col1 + '</td>' +
'<td>' + col2 + '</td>' +
'<td style="font-size:11px;color:#666;">' + rangeText + '</td>' +
'<td><strong>' + (item.rows !== undefined ? item.rows : 0) + '</strong> 行</td>' +
'<td><span class="status-tag ' + cls + '">' + st + '</span></td>' +
'</tr>';
});
tbody.innerHTML = rows.join('');
}
} else if (data && typeof data === 'object' && !Array.isArray(data)) {
// 未知对象:键值对展示
tbody.innerHTML = Object.keys(data).map(function(k) {
var v = data[k];
if (typeof v === 'object') v = JSON.stringify(v);
return '<tr><td style="font-weight:600;color:#333;">' + k + '</td><td>' + (v !== null && v !== undefined ? v : '-') + '</td></tr>';
}).join('');
} else {
tbody.innerHTML = '<tr><td colspan="5"><pre style="white-space:pre-wrap;max-height:300px;overflow:auto;font-size:12px;background:#fafafa;padding:12px;border-radius:4px;">' + JSON.stringify(data, null, 2) + '</pre></td></tr>';
}
modal.style.display = 'block';
} catch(e) {
var isError = /error|exception|failed|traceback|interrupt/i.test(info);
tbody.innerHTML =
'<tr><td colspan="5" style="padding:16px;">' +
'<div style="color:' + (isError ? '#f5222d' : '#666') + ';font-weight:bold;margin-bottom:8px;">' +
(isError ? '执行失败' : '执行信息') + '</div>' +
'<pre style="white-space:pre-wrap;word-break:break-all;background:#fafafa;padding:12px;border-radius:4px;font-size:12px;max-height:300px;overflow:auto;">' + info + '</pre>' +
'</td></tr>';
modal.style.display = 'block';
}
};
window.closeModal = function() {
document.getElementById('detail-modal').style.display = 'none';
};
window.onclick = function(event) {
const modal = document.getElementById('detail-modal');
if (event.target == modal) {
modal.style.display = 'none';
}
};
// ====================================================================
// 数据分析页面逻辑
// ====================================================================
function showAnalysisPage() {
hideAllSections();
document.getElementById('data-analysis-section').style.display = 'block';
contentTitle.textContent = '问界生态系数分析';
const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const now = new Date();
const todayStr = fmt(now);
const lastMonth26 = new Date(now.getFullYear(), now.getMonth()-1, 26);
const startStr = fmt(lastMonth26);
const firstOfMonth = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
const ecoStart = document.getElementById('ecology-start-date');
const ecoEnd = document.getElementById('ecology-end-date');
if (ecoStart && !ecoStart.value) ecoStart.value = startStr;
if (ecoEnd && !ecoEnd.value) ecoEnd.value = todayStr;
const natStart = document.getElementById('nature-start-date');
const natEnd = document.getElementById('nature-end-date');
if (natStart && !natStart.value) natStart.value = firstOfMonth;
if (natEnd && !natEnd.value) natEnd.value = todayStr;
}
// 门店列表上传
const storeDropZone = document.getElementById('store-drop-zone');
const storeFileInput = document.getElementById('store-file-input');
if (storeDropZone) {
storeDropZone.addEventListener('click', () => storeFileInput.click());
storeFileInput.addEventListener('change', () => {
if (storeFileInput.files.length > 0) {
document.getElementById('store-file-name').textContent = '✅ 已选择: ' + storeFileInput.files[0].name;
document.getElementById('store-file-name').style.color = '#52c41a';
}
});
}
// 生态主机厂数据上传
const ecologyDropZone = document.getElementById('ecology-drop-zone');
const ecologyFactoryInput = document.getElementById('ecology-factory-input');
if (ecologyDropZone && ecologyFactoryInput) {
ecologyDropZone.addEventListener('click', () => ecologyFactoryInput.click());
ecologyFactoryInput.addEventListener('change', () => {
if (ecologyFactoryInput.files.length > 0) {
document.getElementById('ecology-file-name').textContent = '✅ 已选择: ' + ecologyFactoryInput.files[0].name;
document.getElementById('ecology-file-name').style.color = '#52c41a';
}
});
}
// 自然月主机厂数据上传
const natureDropZone = document.getElementById('nature-drop-zone');
const natureFactoryInput = document.getElementById('nature-factory-input');
if (natureDropZone && natureFactoryInput) {
natureDropZone.addEventListener('click', () => natureFactoryInput.click());
natureFactoryInput.addEventListener('change', () => {
if (natureFactoryInput.files.length > 0) {
document.getElementById('nature-file-name').textContent = '✅ 已选择: ' + natureFactoryInput.files[0].name;
document.getElementById('nature-file-name').style.color = '#52c41a';
}
});
}
// 生成报表按钮
const btnGenerateReport = document.getElementById('btn-generate-report');
if (btnGenerateReport) {
btnGenerateReport.addEventListener('click', async () => {
document.getElementById('analysis-result').style.display = 'none';
document.getElementById('analysis-error').style.display = 'none';
const hasStore = storeFileInput && storeFileInput.files.length > 0;
const hasEcology = ecologyFactoryInput && ecologyFactoryInput.files.length > 0;
const hasNature = natureFactoryInput && natureFactoryInput.files.length > 0;
if (!hasEcology && !hasNature) {
alert('请至少上传一个主机厂数据文件(步骤2或步骤3)');
return;
}
btnGenerateReport.disabled = true;
btnGenerateReport.textContent = '⏳ 正在生成报表...';
try {
const uploadForm = new FormData();
if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]);
if (hasEcology) uploadForm.append('ecology_factory_file', ecologyFactoryInput.files[0]);
if (hasNature) uploadForm.append('nature_factory_file', natureFactoryInput.files[0]);
const uploadRes = await fetch('./api/analysis/upload', {
method: 'POST',
body: uploadForm
});
const uploadData = await uploadRes.json();
if (uploadData.status !== 'success') {
throw new Error(uploadData.detail || '文件上传失败');
}
btnGenerateReport.textContent = '⏳ 正在分析计算...';
const genForm = new FormData();
const ecoStart = document.getElementById('ecology-start-date').value;
const ecoEnd = document.getElementById('ecology-end-date').value;
const natStart = document.getElementById('nature-start-date').value;
const natEnd = document.getElementById('nature-end-date').value;
if (ecoStart) genForm.append('ecology_start_date', ecoStart);
if (ecoEnd) genForm.append('ecology_end_date', ecoEnd);
if (natStart) genForm.append('nature_start_date', natStart);
if (natEnd) genForm.append('nature_end_date', natEnd);
const genRes = await fetch('api/analysis/generate', {
method: 'POST',
body: genForm
});
const genData = await genRes.json();
if (genData.status === 'success') {
document.getElementById('analysis-result').style.display = 'block';
document.getElementById('analysis-result-info').innerHTML =
`生态数据门店: <strong>${genData.ecology_store_count}</strong> 家 | ` +
`自然月门店: <strong>${genData.nature_store_count}</strong> 家`;
document.getElementById('btn-download-report').href = genData.download_url;
} else {
throw new Error(genData.detail || '报表生成失败');
}
} catch (err) {
console.error('分析失败:', err);
document.getElementById('analysis-error').style.display = 'block';
document.getElementById('analysis-error-msg').textContent = err.message || '未知错误';
} finally {
btnGenerateReport.disabled = false;
btnGenerateReport.textContent = '🚀 开始生成分析报表';
}
});
}
// ====================================================================
// 默认加载:模板分析页面
// ====================================================================
showAnalysisPage();
});