Commit 04e42144 by 江名洋

feat: 新增鸿蒙生态分析模块并重构页面路由

1 parent 68bc9113
......@@ -5,12 +5,14 @@
注意: 不要删除这个注释。
"""
import glob, os, re
from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Form, BackgroundTasks
from fastapi.responses import FileResponse
from typing import Optional
from app.services.etl_service import ETLService
from app.services.excel_service import ExcelService
from app.services.analysis_service import AnalysisService
from app.services.harmony_analysis_service import HarmonyAnalysisService
from app.core.scheduler import SchedulerManager
import os
import shutil
......@@ -181,31 +183,52 @@ async def run_dw_sync_get(
# ==================== 数据分析接口 ====================
def _find_latest_wenjie_template():
"""返回最新的问界门店数据模板(最大序号),无带序号文件时回退到旧版"""
tmpl_dir = os.path.join("app", "templates")
max_no = 0
for f in glob.glob(os.path.join(tmpl_dir, "问界门店数据模板[0-9][0-9][0-9].xlsx")):
m = re.search(r"问界门店数据模板(\d{3})\.xlsx", os.path.basename(f))
if m:
max_no = max(max_no, int(m.group(1)))
if max_no > 0:
return os.path.join(tmpl_dir, f"问界门店数据模板{max_no:03d}.xlsx")
# 回退到旧版模板
fallback = os.path.join(tmpl_dir, "门店数据-模板0625.xlsx")
if os.path.exists(fallback):
return fallback
return None
@router.get("/analysis/template/{template_type}")
async def download_analysis_template(template_type: str):
"""下载分析模板文件"""
template_map = {
"store": "门店数据-模板0625.xlsx",
# store 使用动态查找最新带序号的模板
"factory": "主机厂数据-模板.xlsx",
"output": "输出-问界生态系数-模板0625.xlsx",
}
filename = template_map.get(template_type)
if not filename:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
# 查找模板文件
search_paths = [
os.path.join("app", "templates", filename),
os.path.join("docs", "test-demos", filename),
]
file_path = None
for p in search_paths:
if os.path.exists(p):
file_path = p
break
if not file_path:
raise HTTPException(status_code=404, detail=f"模板文件不存在: {filename}")
if template_type == "store":
file_path = _find_latest_wenjie_template()
if not file_path:
raise HTTPException(status_code=404, detail="门店数据模板文件不存在")
filename = os.path.basename(file_path)
else:
filename = template_map.get(template_type)
if not filename:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
# 查找模板文件
search_paths = [
os.path.join("app", "templates", filename),
os.path.join("docs", "test-demos", filename),
]
file_path = None
for p in search_paths:
if os.path.exists(p):
file_path = p
break
if not file_path:
raise HTTPException(status_code=404, detail=f"模板文件不存在: {filename}")
return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
......@@ -282,8 +305,8 @@ async def analysis_generate(
global _analysis_store_file, _analysis_ecology_factory_file, _analysis_nature_factory_file
if not _analysis_store_file or not os.path.exists(_analysis_store_file):
# 未上传时使用模板库中的默认门店数据
default_store = os.path.join("app", "templates", "门店数据-模板0625.xlsx")
# 未上传时使用模板库中最新的默认门店数据
default_store = _find_latest_wenjie_template()
if os.path.exists(default_store):
_analysis_store_file = default_store
else:
......@@ -360,3 +383,149 @@ async def analysis_download(file: str = Query(None)):
filename=output_files[0],
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
# ==================== 鸿蒙生态分析接口 ====================
@router.get("/harmony/template/{template_type}")
async def download_harmony_template(template_type: str):
"""下载鸿蒙分析模板文件"""
template_map = {
"store": "鸿蒙门店数据-模板.xlsx",
"factory": "鸿蒙主机厂数据-模板.xlsx",
"output": "输出-鸿蒙生态系数-模板.xlsx",
}
filename = template_map.get(template_type)
if not filename:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
file_path = os.path.join("app", "templates", filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail=f"模板文件不存在: {filename}")
return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
_harmony_store_file = None
_harmony_factory_file = None
_harmony_value_file = None
@router.post("/harmony/upload")
async def harmony_upload(
store_file: Optional[UploadFile] = File(None),
factory_file: Optional[UploadFile] = File(None),
value_file: Optional[UploadFile] = File(None),
):
"""上传鸿蒙门店兜底配置、主机厂数据、产值表"""
global _harmony_store_file, _harmony_factory_file, _harmony_value_file
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"harmony_store_{store_file.filename}")
with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f)
_harmony_store_file = file_path
result["messages"].append(f"门店兜底配置已上传: {store_file.filename}")
if factory_file and factory_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"harmony_factory_{factory_file.filename}")
with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f)
_harmony_factory_file = file_path
result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")
if value_file and value_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"harmony_value_{value_file.filename}")
with open(file_path, "wb") as f:
shutil.copyfileobj(value_file.file, f)
_harmony_value_file = file_path
result["messages"].append(f"产值表已上传: {value_file.filename}")
if not result["messages"]:
raise HTTPException(status_code=400, detail="请至少上传一个文件")
return result
@router.post("/harmony/generate")
async def harmony_generate(
start_date: str = Form(None),
end_date: str = Form(None),
):
"""根据已上传的数据生成鸿蒙生态分析报表"""
global _harmony_store_file, _harmony_factory_file, _harmony_value_file
# 门店兜底配置:未上传时使用默认模板
if not _harmony_store_file or not os.path.exists(_harmony_store_file):
default_store = os.path.join("app", "templates", "鸿蒙门店数据-模板.xlsx")
if os.path.exists(default_store):
_harmony_store_file = default_store
else:
raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件")
factory_df = None
value_df = None
if _harmony_factory_file and os.path.exists(_harmony_factory_file):
factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)
if _harmony_value_file and os.path.exists(_harmony_value_file):
value_df = HarmonyAnalysisService.read_value_table(_harmony_value_file)
if factory_df is None and value_df is None:
raise HTTPException(status_code=400, detail="请至少上传主机厂数据或产值表文件")
try:
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
output_path = HarmonyAnalysisService.build_report(
store_df,
factory_df=factory_df,
value_df=value_df,
start_date=start_date,
end_date=end_date,
)
return {
"status": "success",
"message": "鸿蒙分析报表已生成",
"file_path": output_path,
"download_url": f"api/harmony/download?file={os.path.basename(output_path)}",
"store_count": len(store_df),
"factory_count": len(factory_df) if factory_df is not None else 0,
"value_count": len(value_df) if value_df is not None else 0,
}
except Exception as e:
logger.error(f"Harmony analysis generate failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")
@router.get("/harmony/download")
async def harmony_download(file: str = Query(None)):
"""下载鸿蒙分析报表"""
output_dir = "temp_uploads"
if file:
file_path = os.path.join(output_dir, file)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="指定的报表文件不存在")
return FileResponse(
file_path, filename=file,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
# 无指定时返回最新的鸿蒙分析文件
output_files = sorted(
[f for f in os.listdir(output_dir) if f.startswith("鸿蒙分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(os.path.join(output_dir, f)),
reverse=True
)
if not output_files:
raise HTTPException(status_code=404, detail="未找到鸿蒙分析报表,请先生成")
file_path = os.path.join(output_dir, output_files[0])
return FileResponse(
file_path,
filename=output_files[0],
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
......@@ -720,9 +720,6 @@ class AnalysisService:
# 清除数据行(保留表头1-3行)
AnalysisService._clear_sheet_data(ws)
# 第3行(表头行)开启自动筛选
ws.auto_filter.ref = f"A3:BA3"
logger.info(f"Created sheet: '{sheet_name}' from '{TEMPLATE_SHEET}'")
# 按兜底截止日期分组门店:25日→生态,其余→自然月
......@@ -956,15 +953,19 @@ class AnalysisService:
# ========== 产值表数据 (P-Z) - 全部从数据库查询 ==========
# P: 交付数2 (DB) — 已在上方提前获取
# Q: 触客数 (DB),兜底类型=触客时限制不超过交付数2
# Q: 触客数 (DB),兜底类型=触客 且 特殊情况2含"安心包专岗"时限制不超过交付数2
customer_count = _safe_float(store_perf.get("touch", 0))
baodi_type = str(store_row.get("兜底类型", "")).strip()
if baodi_type == "触客" and customer_count > delivery2:
special2 = str(store_row.get("特殊情况2", "")).strip()
capped = False
if baodi_type == "触客" and "安心包专岗" in special2 and customer_count > delivery2:
customer_count = delivery2
# R: 触客率 (DB)
capped = True
# R: 触客率 (DB),被限制时同步更新触客率保持一致
touch_rate = _safe_float(store_perf.get("touch_rate", 0.0))
if touch_rate == 0.0 and customer_count > 0 and delivery2 > 0:
touch_rate = round(customer_count / delivery2, 4)
if customer_count > 0 and delivery2 > 0:
if touch_rate == 0.0 or capped:
touch_rate = round(customer_count / delivery2, 4)
# S-V: 订单数据 (DB)
yb_orders = _safe_float(store_perf.get("yb_orders", 0))
......
......@@ -48,6 +48,10 @@ header {
transition: background 0.3s;
}
.nav-item {
color: white;
text-decoration: none;
}
.nav-item:hover, .nav-item.active {
background-color: #34495e;
}
......@@ -151,3 +155,55 @@ h2 {
.status-success { background-color: #f6ffed; border: 1px solid #b7eb8f; color: #52c41a; }
.status-failed { background-color: #fff1f0; border: 1px solid #ffa39e; color: #f5222d; }
.status-info { background-color: #e6f7ff; border: 1px solid #91d5ff; color: #1890ff; }
/* ========== 首页导航卡片 ========== */
.page-title {
text-align: center;
color: #2c3e50;
font-size: 28px;
margin-bottom: 8px;
}
.page-subtitle {
text-align: center;
color: #999;
font-size: 14px;
margin-bottom: 32px;
}
.nav-cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 20px;
max-width: 1200px;
margin: 0 auto;
}
.nav-card {
display: block;
background: white;
border-radius: 10px;
padding: 28px 24px;
text-decoration: none;
color: #333;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
transition: all 0.25s;
border: 1px solid #eee;
}
.nav-card:hover {
transform: translateY(-3px);
box-shadow: 0 6px 20px rgba(0,0,0,0.12);
border-color: #1890ff;
}
.nav-card-icon {
font-size: 36px;
margin-bottom: 14px;
text-align: center;
}
.nav-card h3 {
font-size: 16px;
margin-bottom: 8px;
color: #2c3e50;
}
.nav-card p {
font-size: 13px;
color: #888;
line-height: 1.5;
}
/*
文件名: app/static/js/common.js
职责: 各页面共用的工具函数和交互逻辑(历史记录渲染、任务详情弹窗、轮询)。
注意: 不要删除这个注释。
*/
// ========== 工具函数 ==========
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 = {};
// ========== 历史记录渲染 ==========
async function fetchHistory(filterFn) {
try {
const res = await fetch('/api/etl/history?limit=15');
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) {
if (pollingTimer) clearInterval(pollingTimer);
let count = 0;
pollingTimer = setInterval(async () => {
count++;
const hasRunning = await fetchHistory(filterFn);
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)) {
data.forEach(item => {
const tr = document.createElement('tr');
const cls = 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 ${cls}">${item.status || 'unknown'}</span></td>`;
tbody.appendChild(tr);
});
} else {
tbody.innerHTML = `<tr><td colspan="4"><pre style="white-space:pre-wrap;">${JSON.stringify(data,null,2)}</pre></td></tr>`;
}
modal.style.display = 'block';
} catch(e) {
tbody.innerHTML = `<tr><td colspan="4">${info}</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';
};
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DWS/DWM/DWA 任务 - 问界门店运营数据分析平台</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<header>
<div class="logo">问界运营分析平台</div>
<nav class="nav-links">
<a class="nav-item" href="/">首页</a>
<a class="nav-item" href="/ods">ODS 同步任务</a>
<a class="nav-item active" href="/dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="/analysis">问界生态系数分析</a>
<a class="nav-item" href="/harmony">鸿蒙生态分析</a>
</nav>
<div class="user-info">管理员</div>
</header>
<main>
<section id="content-area">
<div class="card">
<h2>DWS/DWM/DWA 加工任务</h2>
<div>
<!-- DW 加工控制 -->
<div style="margin-bottom: 30px; background: #f0f5ff; padding: 20px; border-radius: 8px;">
<h3 style="margin-bottom:15px; font-size: 16px; color: #1890ff;">数据加工控制</h3>
<div style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
<div>
<label>加工层级: </label>
<select id="dw-layer-select" style="padding: 5px;">
<option value="DWS">DWS (宽表层)</option>
<option value="DWM">DWM (指标层)</option>
<option value="DWA">DWA (应用层)</option>
</select>
</div>
<div>
<label>开始日期: </label>
<input type="date" id="dw-start-date" style="padding: 4px;">
</div>
<div>
<label>结束日期: </label>
<input type="date" id="dw-end-date" style="padding: 4px;">
</div>
<div>
<label style="display: flex; align-items: center; gap: 4px; cursor: pointer; font-weight: normal;">
<input type="checkbox" id="dw-full-sync" style="width: 16px; height: 16px;">
全量覆盖
</label>
</div>
<button id="btn-run-dw" style="padding: 6px 20px; background: #52c41a; color: white; border: none; border-radius: 4px; cursor: pointer;">开始加工</button>
</div>
<p style="margin-top: 10px; font-size: 12px; color: #888;">* 提示:默认执行增量同步(最近一天),勾选"全量覆盖"后执行全量覆盖加工。指定日期范围时按日期范围处理。</p>
</div>
<!-- 历史记录 -->
<div>
<h3 style="margin-bottom:15px; font-size: 16px; color: #666;">执行历史记录</h3>
<table class="data-table" style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background: #fafafa; border-bottom: 1px solid #f0f0f0;">
<th style="padding: 12px; text-align: left;">开始时间</th>
<th style="padding: 12px; text-align: left;">数据范围</th>
<th style="padding: 12px; text-align: left;">涉及表数</th>
<th style="padding: 12px; text-align: left;">状态</th>
<th style="padding: 12px; text-align: left;">详情</th>
</tr>
</thead>
<tbody id="history-tbody"></tbody>
</table>
</div>
</div>
</div>
</section>
</main>
<!-- 任务详情弹窗 -->
<div id="detail-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h3>任务执行详情</h3>
<span class="close-btn" onclick="closeModal()">&times;</span>
</div>
<div class="modal-body">
<table class="detail-table">
<thead><tr><th>源表/内容</th><th>目标表</th><th>时间范围</th><th>影响行数</th><th>状态</th></tr></thead>
<tbody id="detail-tbody"></tbody>
</table>
</div>
</div>
</div>
<script src="/static/js/common.js"></script>
<script>
const DW_FILTER = item => item.task_id.includes('sync');
document.addEventListener('DOMContentLoaded', () => {
const now = new Date();
const lastMonth26 = new Date(now.getFullYear(), now.getMonth()-1, 26);
const start = document.getElementById('dw-start-date');
const end = document.getElementById('dw-end-date');
if (start && !start.value) start.value = fmtDate(lastMonth26);
if (end && !end.value) end.value = fmtDate(now);
fetchHistory(DW_FILTER);
});
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);
fetchHistory(DW_FILTER);
startPolling(DW_FILTER);
} else {
alert('执行失败: ' + data.detail);
btn.disabled = false;
}
} catch (err) {
alert('请求出错: ' + err);
btn.disabled = false;
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ODS 同步任务 - 问界门店运营数据分析平台</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<header>
<div class="logo">问界运营分析平台</div>
<nav class="nav-links">
<a class="nav-item" href="/">首页</a>
<a class="nav-item active" href="/ods">ODS 同步任务</a>
<a class="nav-item" href="/dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="/analysis">问界生态系数分析</a>
<a class="nav-item" href="/harmony">鸿蒙生态分析</a>
</nav>
<div class="user-info">管理员</div>
</header>
<main>
<section id="content-area">
<div class="card">
<h2>ODS 同步任务</h2>
<div>
<!-- 任务配置 -->
<div id="task-config-section" style="margin-bottom: 30px;">
<h3 style="margin-bottom:15px; font-size: 16px; color: #666;">定时任务配置</h3>
<div class="config-grid" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; background: #f8f9fa; padding: 15px; border-radius: 4px;">
<div><strong>任务ID:</strong> <span id="conf-task-id">-</span></div>
<div><strong>状态:</strong> <span id="conf-status">-</span></div>
<div><strong>下次执行:</strong> <span id="conf-next-run">-</span></div>
<div><strong>触发器:</strong> <span id="conf-trigger">-</span></div>
</div>
<div style="margin-top: 15px;">
<button id="btn-run-ods" style="padding: 8px 16px; background: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer;">立即同步 ODS</button>
</div>
</div>
<!-- 历史记录 -->
<div>
<h3 style="margin-bottom:15px; font-size: 16px; color: #666;">执行历史记录</h3>
<table class="data-table" style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background: #fafafa; border-bottom: 1px solid #f0f0f0;">
<th style="padding: 12px; text-align: left;">开始时间</th>
<th style="padding: 12px; text-align: left;">数据范围</th>
<th style="padding: 12px; text-align: left;">涉及表数</th>
<th style="padding: 12px; text-align: left;">状态</th>
<th style="padding: 12px; text-align: left;">详情</th>
</tr>
</thead>
<tbody id="history-tbody"></tbody>
</table>
</div>
</div>
</div>
</section>
</main>
<!-- 任务详情弹窗 -->
<div id="detail-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h3>任务执行详情</h3>
<span class="close-btn" onclick="closeModal()">&times;</span>
</div>
<div class="modal-body">
<table class="detail-table">
<thead><tr><th>源表/内容</th><th>目标表</th><th>时间范围</th><th>影响行数</th><th>状态</th></tr></thead>
<tbody id="detail-tbody"></tbody>
</table>
</div>
</div>
</div>
<script src="/static/js/common.js"></script>
<script>
const ODS_FILTER = item => item.task_id.includes('ods');
document.addEventListener('DOMContentLoaded', async () => {
try {
const res = await fetch('/api/etl/scheduler-config?task_id=sync_ods_data');
const config = await res.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);
}
fetchHistory(ODS_FILTER);
});
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);
fetchHistory(ODS_FILTER);
startPolling(ODS_FILTER);
} else {
alert('执行失败: ' + data.detail);
btn.disabled = false;
}
} catch (err) {
alert('请求出错: ' + err);
btn.disabled = false;
}
});
</script>
</body>
</html>
No preview for this file type
No preview for this file type
......@@ -56,14 +56,23 @@ templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))
# 注册 API 路由
app.include_router(api_router, prefix="/api")
@app.get("/")
async def root(request: Request):
"""返回主页面"""
return templates.TemplateResponse(
request=request,
name="index.html",
context={}
)
# 页面路由映射:路径 → 模板文件名
PAGE_ROUTES = {
"/": "index.html",
"/ods": "ods.html",
"/dw": "dw.html",
"/analysis": "analysis.html",
"/harmony": "harmony.html",
}
def _page_handler(template_name: str):
"""闭包工厂:为指定模板生成页面处理函数"""
async def handler(request: Request):
return templates.TemplateResponse(request=request, name=template_name, context={})
return handler
for path, tpl in PAGE_ROUTES.items():
app.get(path)(_page_handler(tpl))
@app.get("/api/health")
async def health():
......
门店数据明细
================================================================================
门店: 银川华为2. (ID: 44212813)
时间: 2026-06-26 ~ 2026-07-06
生成: 2026-07-08 12:48:56
================================================================================
## 1. ODS 门店日报 (ods_merchant_daily_report_huawei)
日期 交付 触客 延保 安心包 电池 轮胎 金额 员工
------------ ----- ----- ----- ----- ----- ----- ---------- ----
2026-06-26 4 0 0 0 0 0 0.00 0
2026-06-27 4 0 0 0 0 0 0.00 0
2026-06-28 2 0 0 0 0 0 0.00 0
2026-06-29 7 0 0 0 0 0 0.00 0
2026-06-30 4 0 0 0 0 0 0.00 0
2026-07-01 1 0 0 0 0 0 0.00 0
2026-07-02 2 0 0 0 0 0 0.00 0
2026-07-03 3 0 0 0 0 0 0.00 0
2026-07-04 6 0 0 0 0 0 0.00 0
2026-07-05 2 0 0 0 0 0 0.00 0
2026-07-06 1 0 0 0 0 0 0.00 0
## 2. ODS 员工日报聚合 (ods_staff_daily_report_huawei)
日期 交付 触客 延保 安心包 电池 轮胎 金额 员工
------------ ----- ----- ----- ----- ----- ----- ---------- ----
2026-06-26 4 6 1 0 2 0 11560.00 4
2026-06-27 4 7 2 0 1 0 5980.00 5
2026-06-28 2 4 1 0 0 0 0.00 4
2026-06-29 7 9 3 0 0 0 0.00 4
2026-06-30 4 3 1 0 1 1 5380.00 4
2026-07-01 1 0 0 0 0 0 0.00 3
2026-07-02 2 4 1 0 0 0 0.00 3
2026-07-03 3 5 0 0 0 0 0.00 4
2026-07-04 6 11 3 0 0 0 0.00 4
2026-07-05 2 1 1 0 0 0 0.00 2
2026-07-06 1 1 0 0 0 0 0.00 3
## 3. DWS 宽表 (dws_merchant_daily_wide)
日期 交付 触客 延保 安心包 电池 轮胎 金额 员工
------------ ----- ----- ----- ----- ----- ----- ---------- ----
2026-06-26 4 6 3 2 2 0 11560.00 4
2026-06-27 4 7 3 2 1 0 5980.00 5
2026-06-28 2 4 1 1 1 0 6980.00 4
2026-06-29 7 9 4 3 1 0 9980.00 4
2026-06-30 4 3 1 1 1 1 5380.00 4
2026-07-01 1 0 0 0 0 0 0.00 3
2026-07-02 2 4 1 1 0 0 0.00 3
2026-07-03 3 5 0 2 0 0 0.00 4
2026-07-04 6 11 6 2 1 1 4580.00 4
2026-07-05 2 1 1 0 0 0 0.00 2
2026-07-06 1 1 0 0 0 0 0.00 3
================================================================================
汇总对比
================================================================================
指标 ODS门店 ODS员工 DWS 差异(门店-DWS)
-------------- -------- -------- -------- --------------
交付数 36 36 36 +0
触客数 51 51 51 +0
整车延保订单 13 13 20 -7
安心包订单 0 0 14 -14
电池延保订单 4 4 7 -3
轮胎险订单 1 1 2 -1
总订单 0 0 0 +0
电池金额 22920.00 22920.00 44460.00 -21540
员工数 40 40 40 +0
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import pandas as pd
src = r'C:\Users\jiata\Desktop\问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx'
sheets = pd.read_excel(src, sheet_name=None, header=None, dtype=object)
sdf = sheets['模板']
print(f'Shape: {sdf.shape}')
# Print first 6 rows focusing on key columns
key_cols = [0,1,2,3,4,36,37,38,43,44,45,48]
for i in range(min(8, len(sdf))):
vals = []
for j in key_cols:
v = sdf.iloc[i, j]
vals.append(str(v)[:30] if pd.notna(v) else 'NaN')
print(f'Row{i}: {vals}')
# Also check what the dropdown cutoff date column looks like
print(f'\nRow3 cols 48-50: {[str(sdf.iloc[3,j])[:30] if pd.notna(sdf.iloc[3,j]) else "NaN" for j in range(47,51)]}')
# -*- coding: utf-8 -*-
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
from openpyxl import load_workbook
SRC = r'C:\Users\jiata\Desktop\问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx'
wb = load_workbook(SRC, data_only=False)
main_ws = wb['问界生态系数(6.26-7.5)&(7.1-7.5)']
# 主表表头 - 找 AK 列 (Col 37) 附近
print("=== 主表 Row1 表头 (Col 30-40) ===")
for c in range(30, 41):
v = main_ws.cell(row=1, column=c).value
print(f" Col {c} ({chr(64+c)}): {v!r}")
# 主表 天津吉合 (应该是 Row 14)
print("\n=== 主表 天津吉合 (Row 14, Col 1-50) ===")
for c in range(1, 51):
cell = main_ws.cell(row=14, column=c)
v = cell.value
if v is not None:
print(f" Col {c} ({chr(64+c)}): value={v!r}, number_format={cell.number_format!r}")
wb.close()
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!