common.js 6.04 KB
/*
文件名: app/static/js/common.js
职责: 各页面共用的工具函数和交互逻辑(历史记录渲染、任务详情弹窗、轮询)。
注意: 不要删除这个注释。
*/

// ========== 自动计算 API 基础路径 ==========
// 从浏览器地址栏 pathname 动态推导,兼容本地 /ods 和服务器 /daw/ods 两种场景
(function() {
    var p = window.location.pathname;
    if (p.endsWith('/')) p = p.slice(0, -1);
    var idx = p.lastIndexOf('/');
    window.API_BASE = p.substring(0, idx) + '/api';
})();

// ========== 工具函数 ==========
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);
}

// ========== 任务详情弹窗 ==========
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 = '';

    try {
        const data = JSON.parse(info);
        if (Array.isArray(data)) {
            if (data.length === 0) {
                tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;color:#999;">无详细记录</td></tr>`;
            } else {
                data.forEach(item => {
                    const tr = document.createElement('tr');
                    const st = item.status || 'unknown';
                    const cls = st === 'success' ? 'status-success'
                        : (st === 'no_data' || st === 'no_valid_data' ? 'status-skip' : 'status-failed');
                    const rangeText = item.range_start ? '从: ' + item.range_start + '<br>至: ' + item.range_end : '-';
                    tr.innerHTML =
                        `<td>${item.source || item.table || '-'}</td>` +
                        `<td>${item.target || '-'}</td>` +
                        `<td style="font-size:11px;color:#666;">${rangeText}</td>` +
                        `<td><strong>${item.rows ?? 0}</strong> 行</td>` +
                        `<td><span class="status-tag ${cls}">${st}</span></td>`;
                    tbody.appendChild(tr);
                });
            }
        } else {
            tbody.innerHTML = `<tr><td colspan="5"><pre style="white-space:pre-wrap;max-height:300px;overflow:auto;">${JSON.stringify(data, null, 2)}</pre></td></tr>`;
        }
        modal.style.display = 'block';
    } catch(e) {
        // result_info 不是 JSON(如纯文本错误信息),直接展示
        const errText = info || '(无信息)';
        const 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';
    }
};

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';
};