common.js
11.4 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
/*
文件名: app/static/js/common.js
职责: 各页面共用的工具函数和交互逻辑(历史记录渲染、任务详情弹窗、轮询)。
注意: 不要删除这个注释。
*/
// ========== 自动计算 API 基础路径 ==========
(function() {
var PAGE_SUFFIXES = [
'/harmony/sub-brand', '/strategy/detail', '/strategy/info',
'/harmony', '/analysis', '/strategy', '/ods', '/dw', '/login',
];
var p = window.location.pathname.replace(/\/$/, '');
var root = (!p || p === '/') ? '' : p;
for (var i = 0; i < PAGE_SUFFIXES.length; i++) {
if (root.endsWith(PAGE_SUFFIXES[i])) {
root = root.slice(0, -PAGE_SUFFIXES[i].length) || '';
break;
}
}
window.APP_ROOT = root;
window.API_BASE = root + '/api';
window.STATIC_BASE = root + '/static';
})();
// ========== 工具函数 ==========
function fmtDate(d) {
return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}
function statusColor(status) {
if (status === 'success') return '#52c41a';
if (status === 'failed') return '#f5222d';
return '#1890ff';
}
// ========== 全局状态 ==========
let pollingTimer = null;
let historyCache = {};
// ========== 历史记录渲染 ==========
// fetchHistory(filterFn, taskPattern)
// filterFn: 客户端二次过滤函数(可选)
// taskPattern: 服务端 LIKE 模式(可选),如 '%_ods_sync' 只取 ODS 相关记录
async function fetchHistory(filterFn, taskPattern) {
try {
let url = window.API_BASE + '/etl/history?limit=50';
if (taskPattern) {
url += '&task_pattern=' + encodeURIComponent(taskPattern);
}
const res = await fetch(url);
const history = await res.json();
const tbody = document.getElementById('history-tbody');
if (!tbody) return false;
tbody.innerHTML = '';
let hasRunning = false;
history.forEach(item => {
if (filterFn && !filterFn(item)) 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 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)};">${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 startPolling(filterFn, taskPattern) {
if (pollingTimer) clearInterval(pollingTimer);
let count = 0;
pollingTimer = setInterval(async () => {
count++;
const hasRunning = await fetchHistory(filterFn, taskPattern);
if (!hasRunning || count > 20) {
clearInterval(pollingTimer);
pollingTimer = null;
}
}, 3000);
}
// ========== 任务详情弹窗 ==========
var _originalTheadHTML = null;
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 = '';
// 缓存原始5列表头,用于键值对模式与正常模式之间切换
var thead = (tbody.closest('table') || {}).querySelector ? tbody.closest('table').querySelector('thead') : null;
if (thead && _originalTheadHTML === null) _originalTheadHTML = thead.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);
// 新版 result_info 格式:{node_ip, start_type, results: [...]} 或 {node_ip, start_type, error: "..."}
// 旧版格式:纯数组 [...]
var itemList = null;
var errorText = null;
if (Array.isArray(data)) {
// 旧版格式
itemList = data;
} else if (data && typeof data === 'object') {
// 新版格式:展示元信息,提取 results 或 error
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) {
// 切换回5列表头
if (thead && _originalTheadHTML) thead.innerHTML = _originalTheadHTML;
// 失败任务:展示错误信息
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 : '-';
// DW 任务只有 table 字段,ODS 任务有 source + target 字段
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>';
}).join('');
tbody.innerHTML = rows;
}
} else if (data && typeof data === 'object' && !Array.isArray(data)) {
// 未知格式对象:切换表头为键值对模式,渲染为键值对表格
if (thead) thead.innerHTML = '<tr><th style="width:140px;">字段</th><th>值</th></tr>';
tbody.innerHTML = renderObjectAsTable(data);
} else {
// 纯数组或其他类型:格式化 JSON 展示
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) {
// result_info 不是 JSON(如纯文本错误信息),直接展示
var errText = info || '(无信息)';
var isError = /error|exception|failed|traceback|interrupt/i.test(errText);
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;">${errText}</pre>
</td></tr>`;
modal.style.display = 'block';
}
};
// ========== 通用:将任意对象渲染为键值对表格 ==========
function renderObjectAsTable(obj) {
var rows = '';
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var val = obj[key];
var displayVal;
if (val === null || val === undefined) {
displayVal = '<span style="color:#999;">-</span>';
} else if (typeof val === 'object' && !Array.isArray(val)) {
// 嵌套对象:递归展示
var subRows = [];
var subKeys = Object.keys(val);
for (var j = 0; j < subKeys.length; j++) {
var sk = subKeys[j];
var sv = val[sk];
var svDisplay = (sv === null || sv === undefined) ? '-' : String(sv);
subRows.push('<span style="display:inline-block;margin-right:12px;margin-bottom:4px;"><b>' + sk + ':</b> ' + svDisplay + '</span>');
}
displayVal = subRows.join('');
} else if (Array.isArray(val)) {
if (val.length === 0) {
displayVal = '<span style="color:#999;">空数组</span>';
} else if (typeof val[0] === 'object') {
// 对象数组:展平为摘要
displayVal = '[' + val.length + ' 项] ' + JSON.stringify(val).substring(0, 200) + (JSON.stringify(val).length > 200 ? '...' : '');
} else {
displayVal = val.join(', ');
}
} else if (typeof val === 'boolean') {
displayVal = val ? '<span style="color:#52c41a;">true</span>' : '<span style="color:#f5222d;">false</span>';
} else {
displayVal = String(val);
}
rows += '<tr><td style="font-weight:600;color:#333;white-space:nowrap;vertical-align:top;width:140px;">' + key + '</td>' +
'<td style="word-break:break-all;">' + displayVal + '</td></tr>';
}
return rows;
}
window.closeModal = function() {
const modal = document.getElementById('detail-modal');
if (modal) modal.style.display = 'none';
};
window.onclick = function(event) {
const modal = document.getElementById('detail-modal');
if (modal && event.target == modal) modal.style.display = 'none';
};