app.js 20.6 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 477 478 479 480 481 482 483 484 485
/*
文件名: 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 module = item.getAttribute('data-module');
            showSidebarMenu(module);
            
            // 更新标题
            contentTitle.textContent = item.textContent;

            if (module === 'upload') {
                showUploadPage();
            } else if (module === 'task') {
                loadOdsSyncPage();
            } else if (module === 'analysis') {
                showAnalysisPage();
            }
        });
    });

    // 侧边栏点击事件
    document.addEventListener('click', (e) => {
        if (e.target.classList.contains('menu-item')) {
            const menuItems = document.querySelectorAll('.menu-item');
            menuItems.forEach(i => i.classList.remove('active'));
            e.target.classList.add('active');
            
            const menuText = e.target.textContent.trim();
            console.log('切换功能点:', menuText);
            
            if (menuText === 'ODS 同步任务') {
                loadOdsSyncPage();
            } else if (menuText === 'DWS/DWM/DWA 任务') {
                loadDwProcessPage();
            } else if (menuText === '数据上传' || menuText === '手动上传数据') {
                showUploadPage();
            } else {
                hideAllSections();
                document.getElementById('welcome-message').style.display = 'block';
                document.getElementById('content-title').textContent = menuText;
            }
        }
    });

    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-upload-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';
        document.getElementById('content-title').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';
        document.getElementById('content-title').textContent = 'DWS/DWM/DWA 加工任务';
        refreshHistory('dw');
    }

    // --- 任务历史刷新与轮询 ---
    let pollingTimer = null;
    let currentHistoryType = 'ods'; // 'ods' or 'dw'
    let historyCache = {}; // 缓存历史记录详情,避免转义字符破坏 HTML

    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 showUploadPage() {
        hideAllSections();
        document.getElementById('data-upload-section').style.display = 'block';
        document.getElementById('content-title').textContent = '数据上传';
    }

    // 文件上传逻辑
    const dropZone = document.getElementById('drop-zone');
    const fileInput = document.getElementById('excel-file');
    const uploadModeSelect = document.getElementById('upload-mode-select');
    const odsTableDiv = document.getElementById('ods-table-select-div');
    const dynamicTypeDiv = document.getElementById('dynamic-type-select-div');

    if (uploadModeSelect) {
        uploadModeSelect.addEventListener('change', () => {
            if (uploadModeSelect.value === 'ods') {
                odsTableDiv.style.display = 'block';
                dynamicTypeDiv.style.display = 'none';
            } else {
                odsTableDiv.style.display = 'none';
                dynamicTypeDiv.style.display = 'block';
            }
        });
    }

    if (dropZone) {
        dropZone.addEventListener('click', () => fileInput.click());
        fileInput.addEventListener('change', () => {
            if (fileInput.files.length > 0) {
                document.getElementById('file-display-name').textContent = '已选择: ' + fileInput.files[0].name;
            }
        });
    }

    const btnDoUpload = document.getElementById('btn-do-upload');
    if (btnDoUpload) {
        btnDoUpload.addEventListener('click', async () => {
            if (fileInput.files.length === 0) { alert('请先选择文件'); return; }
            
            const mode = uploadModeSelect.value;
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            
            if (mode === 'ods') {
                formData.append('table_name', document.getElementById('upload-table-name').value);
            } else {
                formData.append('upload_type', document.getElementById('upload-type-select').value);
                formData.append('version_tag', document.getElementById('upload-version-tag').value);
            }

            btnDoUpload.disabled = true;
            btnDoUpload.textContent = '正在解析中...';
            document.getElementById('upload-status-tip').style.display = 'block';

            try {
                const res = await fetch('/api/data/upload', { method: 'POST', body: formData });
                const data = await res.json();
                if (data.status === 'success') {
                    alert(data.message);
                    fileInput.value = '';
                    document.getElementById('file-display-name').textContent = '点击或将 Excel 文件拖拽到此处上传';
                } else { 
                    alert('上传失败: ' + data.detail); 
                }
            } catch (err) { 
                alert('上传出错: ' + err); 
            } finally {
                btnDoUpload.disabled = false;
                btnDoUpload.textContent = '开始解析并上传';
                document.getElementById('upload-status-tip').style.display = 'none';
            }
        });
    }

    // --- 工具函数 ---
    function calculateDuration(start, end) {
        const s = new Date(start);
        const e = new Date(end);
        const diff = (e - s) / 1000;
        return diff.toFixed(1) + 's';
    }

    function showSidebarMenu(module) {
        console.log('切换到模块:', module);
        // 这里可以根据模块动态更新侧边栏内容
    }

    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');
        tbody.innerHTML = '';

        try {
            const data = JSON.parse(info);
            // 如果 data 是数组,渲染成表格
            if (Array.isArray(data)) {
                data.forEach(item => {
                    const tr = document.createElement('tr');
                    const statusClass = item.status === 'success' ? 'status-success' : 'status-failed';
                    
                    tr.innerHTML = `
                        <td>${item.source || item.table || '-'}</td>
                        <td>${item.target || '-'}</td>
                        <td style="font-size: 11px; color: #666;">
                            ${item.range_start ? `从: ${item.range_start}<br>至: ${item.range_end}` : '-'}
                        </td>
                        <td><strong>${item.rows ?? 0}</strong> 行</td>
                        <td><span class="status-tag ${statusClass}">${item.status || 'unknown'}</span></td>
                    `;
                    tbody.appendChild(tr);
                });
            } else {
                // 如果是普通 JSON 对象,展示在第一行
                const tr = document.createElement('tr');
                tr.innerHTML = `<td colspan="4"><pre style="white-space: pre-wrap;">${JSON.stringify(data, null, 2)}</pre></td>`;
                tbody.appendChild(tr);
            }
            
            modal.style.display = 'block';
        } catch(e) { 
            // 解析失败则展示原始文本
            tbody.innerHTML = `<tr><td colspan="4">${info}</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';
        document.getElementById('content-title').textContent = '数据分析';
        
        // 初始化默认日期: 上月26号 至 今天
        const now = new Date();
        const todayStr = now.toISOString().split('T')[0];
        
        // 计算上月26号
        const firstOfThisMonth = new Date(now.getFullYear(), now.getMonth(), 1);
        const lastDayOfLastMonth = new Date(firstOfThisMonth - 86400000);
        const lastMonth26 = new Date(lastDayOfLastMonth.getFullYear(), lastDayOfLastMonth.getMonth(), 26);
        const startStr = lastMonth26.toISOString().split('T')[0];
        
        const startInput = document.getElementById('analysis-start-date');
        const endInput = document.getElementById('analysis-end-date');
        if (startInput && !startInput.value) startInput.value = startStr;
        if (endInput && !endInput.value) endInput.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 factoryDropZone = document.getElementById('factory-drop-zone');
    const factoryFileInput = document.getElementById('factory-file-input');
    if (factoryDropZone) {
        factoryDropZone.addEventListener('click', () => factoryFileInput.click());
        factoryFileInput.addEventListener('change', () => {
            if (factoryFileInput.files.length > 0) {
                document.getElementById('factory-file-name').textContent = '✅ 已选择: ' + factoryFileInput.files[0].name;
                document.getElementById('factory-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 hasFactory = factoryFileInput && factoryFileInput.files.length > 0;

            if (!hasStore && !hasFactory) {
                alert('请至少上传一个文件(门店列表或主机厂数据)');
                return;
            }

            btnGenerateReport.disabled = true;
            btnGenerateReport.textContent = '⏳ 正在生成报表...';

            try {
                // 先上传文件
                const uploadForm = new FormData();
                if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]);
                if (hasFactory) uploadForm.append('factory_file', factoryFileInput.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 startDate = document.getElementById('analysis-start-date').value;
                const endDate = document.getElementById('analysis-end-date').value;
                if (startDate) genForm.append('start_date', startDate);
                if (endDate) genForm.append('end_date', endDate);
                
                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.store_count}</strong> 家 | ` +
                        `主机厂数据Sheet数: <strong>${genData.factory_sheets.length}</strong> | ` +
                        `主机厂数据行数: <strong>${genData.factory_rows}</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 = '🚀 开始生成分析报表';
            }
        });
    }
});