Commit 95e907b1 by 江名洋

feat(harmony): Add sub-brand analysis endpoint and update navigation

- Introduced a new endpoint for uploading and previewing sub-brand analysis files.
- Updated the HarmonyAnalysisService to include methods for processing factory data and store data from batch uploads.
- Enhanced the front-end navigation to include links for sub-brand analysis across multiple templates.
- Refactored existing data handling to improve consistency and error handling in file uploads.
1 parent aec18105
Showing 32 changed files with 544 additions and 253 deletions
......@@ -887,6 +887,46 @@ _harmony_store_file = None
_harmony_factory_file = None
@router.post("/harmony/preview-file")
async def harmony_preview_file(
file_type: str = Form(...), # "store" or "factory"
file: UploadFile = File(...),
):
"""上传鸿蒙分析文件并返回解析后的预览数据(单表结构)"""
file_path = _date_path(f"_preview_{file.filename}", category="drafts")
try:
with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f)
if file_type == "store":
df = HarmonyAnalysisService.read_store_list(file_path)
elif file_type == "factory":
df = HarmonyAnalysisService.read_factory_data(file_path)
else:
raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory")
if df is None or df.empty:
return {
"status": "success",
"data": {"columns": [], "rows": [], "total": 0},
}
rows = df.head(100).fillna("").to_dict(orient="records")
columns = [str(c) for c in df.columns]
return {
"status": "success",
"data": {"columns": columns, "rows": rows, "total": len(df)},
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Harmony preview file failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"文件解析失败: {str(e)}")
finally:
if os.path.exists(file_path):
os.remove(file_path)
@router.post("/harmony/upload")
async def harmony_upload(
store_file: Optional[UploadFile] = File(None),
......@@ -934,7 +974,7 @@ async def harmony_generate(
# 加载store_df:优先批次DB数据,其次文件,最后默认模板
if store_batch_no:
store_df = _load_store_df_from_batch(store_batch_no)
store_df = HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)
elif _harmony_store_file and os.path.exists(_harmony_store_file):
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
else:
......@@ -948,7 +988,7 @@ async def harmony_generate(
factory_df = None
if factory_batch_no:
sheets, _ = _load_oem_factory_from_batch(factory_batch_no)
factory_df = sheets
factory_df = HarmonyAnalysisService._coerce_factory_df(sheets)
elif _harmony_factory_file and os.path.exists(_harmony_factory_file):
factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)
......@@ -960,13 +1000,14 @@ async def harmony_generate(
end_date=end_date,
)
factory_count = len(factory_df) if factory_df is not None else 0
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,
"factory_count": factory_count,
"db_store_count": len(store_df),
}
except Exception as e:
......
......@@ -1064,14 +1064,8 @@ class AnalysisService:
next_row = 5
first_data_row = None
eco_label_text = (
f"▲ 生态月数据({ecology_start} ~ {ecology_end})"
if ecology_start and ecology_end else "▲ 生态月数据"
)
nat_label_text = (
f"▼ 自然月数据({nature_start} ~ {nature_end})"
if nature_start and nature_end else "▼ 自然月数据"
)
eco_label_text = "▲ 生态月数据"
nat_label_text = "▼ 自然月数据"
# 生态月数据(上部)
if has_ecology:
......
......@@ -23,6 +23,15 @@ logger = logging.getLogger("app.harmony_analysis_service")
XLSX_DIR = os.path.join("app", "templates", "xlsx")
def _pick_str(val, default=""):
if val is None or (isinstance(val, float) and pd.isna(val)):
return default
s = str(val).strip()
if s in ("", "nan", "None", "NaN"):
return default
return s
def _find_latest_template(prefix: str) -> str:
"""自动查找指定前缀的最新模板文件(按序号最大)。"""
pattern = os.path.join(XLSX_DIR, f"{prefix}[0-9][0-9][0-9].xlsx")
......@@ -141,6 +150,51 @@ class HarmonyAnalysisService:
return df
@staticmethod
def _coerce_factory_df(factory_data) -> pd.DataFrame:
"""统一主机厂数据为含「门店名」「交付数」的 DataFrame(支持 dict / DB 批次结构)。"""
if factory_data is None:
return pd.DataFrame()
if isinstance(factory_data, dict):
frames = [
df for df in factory_data.values()
if isinstance(df, pd.DataFrame) and not df.empty
]
if not frames:
return pd.DataFrame()
factory_data = pd.concat(frames, ignore_index=True)
if not isinstance(factory_data, pd.DataFrame) or factory_data.empty:
return pd.DataFrame()
df = factory_data.copy()
if "门店名" not in df.columns:
if "store_name" in df.columns:
df["门店名"] = df["store_name"]
elif "用户中心门店名称" in df.columns:
df["门店名"] = df["用户中心门店名称"]
if "交付数" not in df.columns:
if "delivery_count" in df.columns:
df["交付数"] = pd.to_numeric(df["delivery_count"], errors="coerce").fillna(0)
else:
for col in df.columns:
c = str(col).replace("\n", "").replace(" ", "").strip()
if c in ("交车数量", "交付量", "交付数量", "交车数", "交付") or "交车" in c:
df["交付数"] = pd.to_numeric(df[col], errors="coerce").fillna(0)
break
if "交付数" not in df.columns:
logger.warning("鸿蒙主机厂数据缺少交付数列,已按 0 处理")
df["交付数"] = 0
else:
df["交付数"] = pd.to_numeric(df["交付数"], errors="coerce").fillna(0)
if "门店名" not in df.columns:
return pd.DataFrame()
df = df[df["门店名"].notna() & (df["门店名"].astype(str).str.strip() != "")]
return df.drop_duplicates(subset=["门店名"], keep="first")
@staticmethod
def read_factory_data(file_path: str) -> pd.DataFrame:
"""读取鸿蒙主机厂数据Excel(6列: 省份, 城市, 门店编号, 用户中心门店名称, 门店名称, 交车数量)"""
df_raw = pd.read_excel(file_path, header=None)
......@@ -153,25 +207,96 @@ class HarmonyAnalysisService:
break
df = pd.DataFrame(df_raw.values[header_row + 1:], columns=df_raw.iloc[header_row].values)
df.columns = [str(c).replace("\n", "").strip() if pd.notna(c) else c for c in df.columns]
col_map = {
"门店名称": "门店名", "门店": "门店名",
"交车数量": "交付数", "交付": "交付数",
"用户中心门店名称": "用户中心门店名",
"门店编号": "门店编号",
"交车数量": "交付数", "交付量": "交付数", "交付数量": "交付数",
"交车数": "交付数", "交付": "交付数",
"省份": "省份", "省区": "省份",
"城市": "城市",
}
df = df.rename(columns=col_map)
if "门店名" not in df.columns and "用户中心门店名" in df.columns:
df["门店名"] = df["用户中心门店名"]
if "门店名" not in df.columns:
logger.error(f"鸿蒙主机厂数据缺少门店名称列")
logger.error("鸿蒙主机厂数据缺少门店名称列")
return pd.DataFrame()
if "交付数" in df.columns:
df["交付数"] = pd.to_numeric(df["交付数"], errors="coerce").fillna(0)
df = df[df["门店名"].notna() & (df["门店名"].astype(str).str.strip() != "")]
df = HarmonyAnalysisService._coerce_factory_df(df)
df = df[~df["门店名"].astype(str).str.strip().isin(["门店", "门店名称", "厅店名称"])]
df = df.drop_duplicates(subset=["门店名"], keep="first")
return df
@staticmethod
def _store_df_from_db_rows(rows) -> pd.DataFrame:
"""将 store_guarantee_config 查询结果转为鸿蒙报表所需的门店 DataFrame"""
if not rows:
return pd.DataFrame()
df = pd.DataFrame(rows)
out = pd.DataFrame()
out["门店名"] = df["store_name"]
out["品牌"] = df["special_case_1"].fillna("")
out["兜底指标"] = df["guarantee_target"].fillna("")
out["区域(省)"] = df["province"].fillna("")
out["直营与否"] = df["direct_sale"].fillna("")
out["区域运营"] = df["area_supervision"].fillna("")
out["飞行督导"] = df["flight_supervision"].fillna("")
out["线上运营"] = df["online_supervision"].fillna("")
out["兜底类型"] = df["guarantee_type"].fillna("")
out["特殊情况"] = df["special_case_2"].fillna("")
out["需达标转化率_整车延保"] = df["ew_conversion_rate"]
out["需达标转化率_安心包"] = df["ax_conversion_rate"]
out["需达标转化率_电池延保"] = df["battery_conversion_rate"]
out["预计赔付金额_整车"] = df["ew_compensation"]
out["预计赔付金额_安心包"] = df["ax_compensation"]
out["预计赔付金额_电池"] = df["battery_compensation"]
return out
@staticmethod
def load_store_df_from_batch(batch_no: str) -> pd.DataFrame:
"""加载鸿蒙门店历史批次,优先从原始 Excel 读取(含品牌列),否则从 DB 还原"""
from app.services.upload_service import _get_conn
from fastapi import HTTPException
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute(
"""SELECT id, remark FROM upload_batch
WHERE batch_no=%s AND data_type='store_guarantee' AND status != 3""",
(batch_no,),
)
batch = cur.fetchone()
if not batch:
raise HTTPException(status_code=404, detail=f"批次 {batch_no} 不存在")
remark = (batch.get("remark") or "").strip()
if remark and os.path.exists(remark):
logger.info(f"Harmony store batch {batch_no}: load from Excel {remark}")
return HarmonyAnalysisService.read_store_list(remark)
cur.execute(
"""SELECT store_name, guarantee_target, guarantee_type,
special_case_1, special_case_2,
province, direct_sale, area_supervision,
flight_supervision, online_supervision,
ew_conversion_rate, ax_conversion_rate, battery_conversion_rate,
ew_compensation, ax_compensation, battery_compensation
FROM store_guarantee_config WHERE batch_id=%s""",
(batch["id"],),
)
rows = cur.fetchall()
if not rows:
raise HTTPException(status_code=400, detail="批次中无数据")
logger.info(f"Harmony store batch {batch_no}: load from DB ({len(rows)} rows)")
return HarmonyAnalysisService._store_df_from_db_rows(rows)
finally:
conn.close()
@staticmethod
def read_value_table(file_path: str) -> pd.DataFrame:
"""读取鸿蒙产值表Excel(多行门店聚合)"""
df_raw = pd.read_excel(file_path, header=None)
......@@ -438,8 +563,7 @@ class HarmonyAnalysisService:
if not os.path.exists(TEMPLATE_FILE):
raise FileNotFoundError(f"模板文件不存在: {TEMPLATE_FILE}")
if factory_df is None:
factory_df = pd.DataFrame()
factory_df = HarmonyAnalysisService._coerce_factory_df(factory_df)
# 默认日期
if not start_date:
......@@ -489,8 +613,10 @@ class HarmonyAnalysisService:
# 合并数据
merged = store_df.copy()
if not factory_df.empty:
merged = pd.merge(merged, factory_df[["门店名", "交付数"]],
on="门店名", how="left", suffixes=("", "_factory"))
merged = pd.merge(
merged, factory_df[["门店名", "交付数"]],
on="门店名", how="left", suffixes=("", "_factory"),
)
if "交付数_factory" in merged.columns:
merged["交付数"] = merged["交付数_factory"].fillna(0)
elif "交付数" not in merged.columns:
......@@ -850,7 +976,7 @@ class HarmonyAnalysisService:
# ========== 基础门店信息 (A-I, 1-9) ==========
is_direct = str(store_row.get("直营与否", perf.get("operation_mode", ""))).strip() == "直营"
_style_cell(row_num, 1, store_name_str)
_style_cell(row_num, 2, store_row.get("品牌", perf.get("brand", "")))
_style_cell(row_num, 2, _pick_str(store_row.get("品牌")))
_style_cell(row_num, 3, store_row.get("兜底指标", ""))
_style_cell(row_num, 4, store_row.get("区域(省)", perf.get("province_name", "")))
_style_cell(row_num, 5, store_row.get("直营与否", perf.get("operation_mode", "")))
......
......@@ -205,6 +205,13 @@ def parse_harmony_store_guarantee(file_path: str) -> List[Dict]:
rows = []
for _, r in df.iterrows():
product_brand = r.get("品牌")
if pd.notna(product_brand):
product_brand = str(product_brand).strip()
if product_brand in ("", "/", "nan", "None"):
product_brand = None
else:
product_brand = None
rows.append({
"store_name": str(r["门店名"]).strip(),
"province": str(r.get("区域(省)", "")) if pd.notna(r.get("区域(省)")) else None,
......@@ -214,6 +221,8 @@ def parse_harmony_store_guarantee(file_path: str) -> List[Dict]:
"online_supervision": str(r.get("线上运营", "")) if pd.notna(r.get("线上运营")) else None,
"guarantee_target": str(r.get("兜底指标", "")) if pd.notna(r.get("兜底指标")) else None,
"guarantee_type": str(r.get("兜底类型", "")) if pd.notna(r.get("兜底类型")) else None,
# 鸿蒙模板「品牌」列(智界/享界等)存入 special_case_1,便于批次回放
"special_case_1": product_brand,
"special_case_2": str(r.get("特殊情况", "")) if pd.notna(r.get("特殊情况")) else None,
"ew_conversion_rate": _parse_rate(r.get("需达标转化率_整车延保")),
"ax_conversion_rate": _parse_rate(r.get("需达标转化率_安心包")),
......
......@@ -295,6 +295,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item active" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......
......@@ -44,6 +44,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item" href="./strategy">策略效果盯防</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......
......@@ -15,6 +15,7 @@
<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>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......
......@@ -5,7 +5,6 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>鸿蒙生态分析 - 问界门店运营数据分析平台</title>
<link rel="stylesheet" href="./static/css/style.css">
<script src="https://cdn.sheetjs.com/xlsx-0.20.1/package/dist/xlsx.full.min.js"></script>
<style>
.analysis-layout {
display: flex; gap: 16px; height: calc(100vh - 160px);
......@@ -120,22 +119,6 @@
color: white; border: none; border-radius: 4px; font-size: 14px;
text-decoration: none; cursor: pointer; margin-top: 10px;
}
.hm-tab-nav {
display: flex; gap: 0; margin-bottom: 14px;
border-bottom: 2px solid #e8e8e8;
}
.hm-tab-btn {
padding: 8px 24px; border: none; background: none;
font-size: 14px; color: #666; cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -2px; transition: all 0.2s;
}
.hm-tab-btn:hover { color: #1890ff; }
.hm-tab-btn.active {
color: #1890ff; border-bottom-color: #1890ff;
font-weight: 600;
}
.hm-tab-content.active { display: block !important; }
@media (max-width: 900px) {
.analysis-layout { flex-direction: column; height: auto; }
.left-panel { width: 100%; min-width: 0; }
......@@ -152,6 +135,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item active" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......@@ -161,15 +145,6 @@
<section id="content-area">
<div class="card">
<h2 id="content-title">鸿蒙生态分析</h2>
<!-- Tab 导航 -->
<div class="hm-tab-nav">
<button class="hm-tab-btn active" data-tab="harmony" onclick="switchTab('harmony')">鸿蒙生态分析</button>
<button class="hm-tab-btn" data-tab="sub-brand" onclick="switchTab('sub-brand')">鸿蒙子品牌分析</button>
</div>
<!-- ===== Tab: 鸿蒙生态分析 ===== -->
<div id="tab-harmony" class="hm-tab-content active">
<div id="content-body">
<div class="analysis-layout">
......@@ -260,65 +235,6 @@
</div>
</div>
</div>
<!-- ===== Tab: 鸿蒙子品牌分析 ===== -->
<div id="tab-sub-brand" class="hm-tab-content" style="display:none;">
<div id="sub-brand-content">
<div class="analysis-layout">
<div class="left-panel">
<div class="step-card active" id="sb-step-upload">
<div class="step-title">&#9312; 上传子品牌数据</div>
<div class="step-row">
<div class="step-upload-zone" id="sb-drop-zone" onclick="document.getElementById('sb-file-input').click()">
<input type="file" id="sb-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onSubBrandFileChange()">
&#x1f4c1; <span id="sb-file-name">点击上传鸿蒙子品牌数据文件(含主机厂数据)</span>
</div>
</div>
<div class="step-date-row">
<input type="date" id="sb-start-date" title="开始日期">
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="sb-end-date" title="结束日期">
</div>
</div>
<div style="background: #e6f7ff; padding: 6px 14px; border-radius: 6px; border: 1px solid #91d5ff; display: flex; align-items: center; gap: 8px;">
<span style="font-size:13px; color:#1890ff;">&#x1f6c8;</span>
<span style="font-size:12px; color:#666;">上传含"鸿蒙子品牌"sheet的Excel文件,系统将自动解析门店数据、兜底条款,计算赔付金额。</span>
</div>
<div style="text-align:center; margin-top:4px;">
<button class="btn-generate" id="btn-generate-sb-report">
&#x1f680; 生成鸿蒙子品牌分析报表
</button>
<p style="font-size:11px;color:#999;margin-top:4px;">使用模板: 输出模板-鸿蒙子品牌-模板001.xlsx</p>
</div>
<div class="result-box" id="sb-analysis-result">
<h3 style="color:#52c41a;margin:0 0 6px;">&#x2705; 报表生成成功</h3>
<div style="font-size:12px;color:#666;margin-bottom:10px;" id="sb-analysis-result-info"></div>
<a class="btn-download" id="btn-download-sb-report" href="#">&#x1f4e5; 下载子品牌分析报表</a>
</div>
<div class="result-box" id="sb-analysis-error">
<h3 style="color:#f5222d;margin:0 0 6px;">&#x274c; 报表生成失败</h3>
<p style="margin:0;color:#666;font-size:12px;" id="sb-analysis-error-msg"></p>
</div>
</div>
<div class="right-panel">
<div class="right-panel-header">
<span>&#x1f4ca; 子品牌数据预览</span>
</div>
<div class="right-panel-body" id="sb-preview-body">
<div class="right-panel-empty" id="sb-preview-empty">
请上传鸿蒙子品牌数据文件,解析后将在此处预览
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</main>
......@@ -479,147 +395,6 @@
}
});
// ========== Tab 切换 ==========
window.switchTab = function(tabName) {
document.querySelectorAll('.hm-tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.hm-tab-content').forEach(c => c.classList.remove('active'));
const btn = document.querySelector(`.hm-tab-btn[data-tab="${tabName}"]`);
if (btn) btn.classList.add('active');
const tab = document.getElementById(`tab-${tabName}`);
if (tab) { tab.classList.add('active'); tab.style.display = 'block'; }
document.getElementById('content-title').textContent =
tabName === 'sub-brand' ? '鸿蒙子品牌分析' : '鸿蒙生态分析';
};
// ========== 子品牌: 文件上传 ==========
window.onSubBrandFileChange = async function() {
const input = document.getElementById('sb-file-input');
if (!input.files.length) return;
const file = input.files[0];
const name = file.name;
document.getElementById('sb-file-name').textContent = '\u2705 ' + name;
document.getElementById('sb-drop-zone').classList.add('has-file');
// 服务端预览
const formData = new FormData();
formData.append('data_file', file);
try {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty">正在解析数据...</div>';
const res = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
// 用前端读取方式预览
const reader = new FileReader();
reader.onload = function(e) {
try {
const wb = XLSX.read(e.target.result, {type: 'array'});
const sheetName = wb.SheetNames.find(s => s.includes('子品牌')) || wb.SheetNames[0];
const ws = wb.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json(ws, {header: 1, defval: ''});
// skip header & subtotals (rows 0-6)
const dataRows = rows.slice(7).filter(r => r[0] && String(r[0]).trim());
const headers = ['门店','品牌','区域','直营','主机厂交付','产值交付','触客数','整车延保成交','安心包','电池','兜底指标'];
const cols = dataRows.length > 0 ? dataRows[0].length : 0;
let html = '<table class="preview-table"><thead><tr><th>#</th>';
headers.slice(0, 11).forEach(h => html += '<th>' + escapeHtml(h) + '</th>');
html += '</tr></thead><tbody>';
dataRows.slice(0, 100).forEach((row, i) => {
html += '<tr><td style="text-align:center;color:#999;">' + (i+1) + '</td>';
html += '<td>' + escapeHtml(String(row[0]||'')) + '</td>'; // 门店
html += '<td>' + escapeHtml(String(row[7]||'')) + '</td>'; // 品牌
html += '<td>' + escapeHtml(String(row[2]||'')) + '</td>'; // 区域
html += '<td>' + escapeHtml(String(row[3]||'')) + '</td>'; // 直营
html += '<td>' + escapeHtml(String(row[8]||'')) + '</td>'; // 主机厂交付
html += '<td>' + escapeHtml(String(row[9]||'')) + '</td>'; // 产值交付
html += '<td>' + escapeHtml(String(row[10]||'')) + '</td>'; // 触客数
html += '<td>' + escapeHtml(String(row[12]||'')) + '</td>'; // 延保成交
html += '<td>' + escapeHtml(String(row[15]||'')) + '</td>'; // 安心包
html += '<td>' + escapeHtml(String(row[17]||'')) + '</td>'; // 电池
html += '<td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;">' + escapeHtml(String(row[1]||'')) + '</td>'; // 兜底指标
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('sb-preview-body').innerHTML = html;
} catch(ex) {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">解析预览失败: ' + ex.message + '</div>';
}
};
reader.readAsArrayBuffer(file);
}
} catch(e) {
console.error('子品牌上传失败:', e);
}
};
// ========== 子品牌: 生成报表 ==========
(function() {
const btnSb = document.getElementById('btn-generate-sb-report');
if (!btnSb) return;
btnSb.addEventListener('click', async () => {
document.getElementById('sb-analysis-result').className = 'result-box';
document.getElementById('sb-analysis-error').className = 'result-box';
const input = document.getElementById('sb-file-input');
if (!input || !input.files.length) {
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = '请先上传子品牌数据文件';
return;
}
btnSb.disabled = true;
btnSb.textContent = '\u23f3 正在生成报表...';
try {
// 先上传
const uploadForm = new FormData();
uploadForm.append('data_file', input.files[0]);
const sd = document.getElementById('sb-start-date').value;
const ed = document.getElementById('sb-end-date').value;
if (sd) uploadForm.append('start_date', sd);
if (ed) uploadForm.append('end_date', ed);
const upRes = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: uploadForm });
const upData = await upRes.json();
if (upData.status !== 'success') throw new Error(upData.detail || '上传失败');
btnSb.textContent = '\u23f3 正在分析计算...';
// 再生成
const genForm = new FormData();
if (sd) genForm.append('start_date', sd);
if (ed) genForm.append('end_date', ed);
const genRes = await fetch(window.API_BASE + '/harmony/sub-brand/generate', { method: 'POST', body: genForm });
const genData = await genRes.json();
if (genData.status === 'success') {
document.getElementById('sb-analysis-result').className = 'result-box success';
document.getElementById('sb-analysis-result-info').innerHTML =
'文件位置: <strong>' + genData.file_path + '</strong>';
document.getElementById('btn-download-sb-report').href = genData.download_url;
} else {
throw new Error(genData.detail || '报表生成失败');
}
} catch (err) {
console.error('子品牌分析失败:', err);
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = err.message || '未知错误';
} finally {
btnSb.disabled = false;
btnSb.textContent = '\u{1f680} 生成鸿蒙子品牌分析报表';
}
});
// 子品牌设置默认日期
const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const now = new Date();
const yesterday = new Date(now); yesterday.setDate(yesterday.getDate()-1);
const sbStart = document.getElementById('sb-start-date');
const sbEnd = document.getElementById('sb-end-date');
if (sbStart && !sbStart.value) sbStart.value = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
if (sbEnd && !sbEnd.value) sbEnd.value = fmt(yesterday);
})();
// ========== 辅助函数 ==========
function highlightStep(cardId) {
......@@ -678,7 +453,7 @@
async function previewFile(formData, title) {
showPreviewLoading(title);
try {
const res = await fetch(window.API_BASE + '/analysis/preview-file', { method: 'POST', body: formData });
const res = await fetch(window.API_BASE + '/harmony/preview-file', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
renderPreviewTable(data.data, title);
......@@ -709,7 +484,8 @@
function renderPreviewTable(data, title, meta) {
document.getElementById('preview-title').textContent = '\u{1f4ca} ' + title;
document.getElementById('preview-count').textContent = '共 ' + data.total + ' 条';
const total = data.total || 0;
document.getElementById('preview-count').textContent = '共 ' + total + ' 条';
const metaDiv = document.getElementById('preview-meta');
if (meta) {
......@@ -717,14 +493,15 @@
if (meta.type) html += `<span class="meta-item"><span class="meta-label">数据类型:</span><span class="meta-value">${escapeHtml(meta.type)}</span></span>`;
if (meta.period) html += `<span class="meta-item"><span class="meta-label">时间范围:</span><span class="meta-value">${escapeHtml(meta.period)}</span></span>`;
if (meta.source) html += `<span class="meta-item"><span class="meta-label">来源:</span><span class="meta-value">${escapeHtml(meta.source)}</span></span>`;
html += `<span class="meta-item"><span class="meta-label">数据行数:</span><span class="meta-value">${data.total}</span></span>`;
html += `<span class="meta-item"><span class="meta-label">数据行数:</span><span class="meta-value">${total}</span></span>`;
metaDiv.innerHTML = html;
metaDiv.style.display = 'flex';
} else {
metaDiv.style.display = 'none';
}
const { columns, rows } = data;
const columns = data.columns || [];
const rows = data.rows || [];
if (!columns.length || !rows.length) {
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">无数据</div>';
......
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>鸿蒙子品牌分析 - 问界门店运营数据分析平台</title>
<link rel="stylesheet" href="/static/css/style.css">
<script src="https://cdn.sheetjs.com/xlsx-0.20.1/package/dist/xlsx.full.min.js"></script>
<style>
.analysis-layout {
display: flex; gap: 16px; height: calc(100vh - 160px);
min-height: 600px; align-items: flex-start; overflow: hidden;
}
.left-panel {
width: 420px; min-width: 380px; height: 100%; overflow-y: auto;
scrollbar-width: none; -ms-overflow-style: none;
display: flex; flex-direction: column; gap: 10px;
}
.left-panel::-webkit-scrollbar { display: none; }
.right-panel {
flex: 1; height: 100%; overflow: hidden;
border: 1px solid #e8e8e8; border-radius: 6px;
background: #fff; display: flex; flex-direction: column;
}
.right-panel-header {
padding: 10px 16px; border-bottom: 1px solid #e8e8e8;
background: #fafafa; font-size: 13px; color: #666;
display: flex; align-items: center; justify-content: space-between;
}
.right-panel-body { flex: 1; overflow: auto; padding: 0; }
.right-panel-empty {
display: flex; align-items: center; justify-content: center;
height: 100%; color: #bbb; font-size: 14px;
}
.step-card {
background: #f8f9fa; padding: 10px 14px;
border-radius: 6px; border: 1px solid #e8e8e8;
}
.step-card.active { border-color: #1890ff; background: #f0f5ff; }
.step-title {
font-size: 14px; font-weight: 600; color: #333;
margin-bottom: 8px;
}
.step-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.step-upload-zone {
flex: 1; border: 1px dashed #d9d9d9; padding: 5px 10px;
border-radius: 4px; cursor: pointer; background: #fff;
font-size: 12px; color: #999; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis;
display: flex; align-items: center; gap: 4px;
}
.step-upload-zone.has-file {
color: #52c41a; border-color: #52c41a; background: #f6ffed;
}
.step-date-row {
display: flex; align-items: center; gap: 6px; margin-top: 6px;
}
.step-date-row input[type="date"] {
width: 130px; padding: 4px 6px; border: 1px solid #d9d9d9;
border-radius: 4px; font-size: 12px;
}
.btn-download-tpl {
font-size: 11px; color: #1890ff; text-decoration: none;
white-space: nowrap; cursor: pointer;
}
.btn-download-tpl:hover { text-decoration: underline; }
.btn-generate {
padding: 12px 48px; background: #1890ff; color: white;
border: none; border-radius: 6px; font-size: 16px;
cursor: pointer; transition: all 0.3s; width: 100%;
}
.btn-generate:hover { background: #40a9ff; }
.btn-generate:disabled { background: #d9d9d9; cursor: not-allowed; }
.preview-table {
width: 100%; border-collapse: collapse; font-size: 12px; white-space: nowrap;
}
.preview-table thead { position: sticky; top: 0; z-index: 2; }
.preview-table th {
background: #fafafa; padding: 6px 10px; border-bottom: 2px solid #e8e8e8;
text-align: left; font-weight: 600; color: #333;
}
.preview-table td {
padding: 5px 10px; border-bottom: 1px solid #f0f0f0;
color: #555; max-width: 200px; overflow: hidden; text-overflow: ellipsis;
}
.preview-table tr:hover td { background: #e6f7ff; }
.result-box {
padding: 16px; border-radius: 8px; text-align: center; display: none;
}
.result-box.success {
display: block; background: #f6ffed; border: 1px solid #b7eb8f;
}
.result-box.error {
display: block; background: #fff2f0; border: 1px solid #ffccc7;
}
.btn-download {
display: inline-block; padding: 10px 32px; background: #52c41a;
color: white; border: none; border-radius: 4px; font-size: 14px;
text-decoration: none; cursor: pointer; margin-top: 10px;
}
@media (max-width: 900px) {
.analysis-layout { flex-direction: column; height: auto; }
.left-panel { width: 100%; min-width: 0; }
.right-panel { min-height: 400px; }
}
</style>
</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" href="/dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="/analysis">问界生态系数分析</a>
<a class="nav-item" href="/harmony">鸿蒙生态分析</a>
<a class="nav-item active" href="/harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item" href="/strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
</header>
<main>
<section id="content-area">
<div class="card">
<h2 id="content-title">鸿蒙子品牌分析</h2>
<div id="content-body">
<div class="analysis-layout">
<div class="left-panel">
<div class="step-card active" id="sb-step-upload">
<div class="step-title">&#9312; 上传子品牌数据</div>
<div class="step-row">
<div class="step-upload-zone" id="sb-drop-zone" onclick="document.getElementById('sb-file-input').click()">
<input type="file" id="sb-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onSubBrandFileChange()">
&#x1f4c1; <span id="sb-file-name">点击上传鸿蒙子品牌数据文件(含主机厂数据)</span>
</div>
<a class="btn-download-tpl" href="/api/harmony/sub-brand/template/output">&#x1f4e5; 模板</a>
</div>
<div class="step-date-row">
<input type="date" id="sb-start-date" title="开始日期">
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="sb-end-date" title="结束日期">
</div>
</div>
<div style="background: #e6f7ff; padding: 6px 14px; border-radius: 6px; border: 1px solid #91d5ff; display: flex; align-items: center; gap: 8px;">
<span style="font-size:13px; color:#1890ff;">&#x1f6c8;</span>
<span style="font-size:12px; color:#666;">上传含「鸿蒙子品牌」Sheet 的 Excel,系统将解析门店数据、兜底条款并计算赔付金额。</span>
</div>
<div style="text-align:center; margin-top:4px;">
<button class="btn-generate" id="btn-generate-sb-report">
&#x1f680; 生成鸿蒙子品牌分析报表
</button>
<p style="font-size:11px;color:#999;margin-top:4px;">使用模板: 输出模板-鸿蒙子品牌-模板001.xlsx</p>
</div>
<div class="result-box" id="sb-analysis-result">
<h3 style="color:#52c41a;margin:0 0 6px;">&#x2705; 报表生成成功</h3>
<div style="font-size:12px;color:#666;margin-bottom:10px;" id="sb-analysis-result-info"></div>
<a class="btn-download" id="btn-download-sb-report" href="#">&#x1f4e5; 下载子品牌分析报表</a>
</div>
<div class="result-box" id="sb-analysis-error">
<h3 style="color:#f5222d;margin:0 0 6px;">&#x274c; 报表生成失败</h3>
<p style="margin:0;color:#666;font-size:12px;" id="sb-analysis-error-msg"></p>
</div>
</div>
<div class="right-panel">
<div class="right-panel-header">
<span>&#x1f4ca; 子品牌数据预览</span>
</div>
<div class="right-panel-body" id="sb-preview-body">
<div class="right-panel-empty" id="sb-preview-empty">
请上传鸿蒙子品牌数据文件,解析后将在此处预览
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</main>
<script>
(function(){
var p = window.location.pathname.replace(/\/$/, '');
var m = p.match(/^(.*)\/harmony(?:\/sub-brand)?$/);
window.API_BASE = ((m ? m[1] : p.replace(/\/[^/]+$/, '')) || '') + '/api';
})();
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
document.addEventListener('DOMContentLoaded', () => {
const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const now = new Date();
const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
const sbStart = document.getElementById('sb-start-date');
const sbEnd = document.getElementById('sb-end-date');
if (sbStart && !sbStart.value) sbStart.value = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
if (sbEnd && !sbEnd.value) sbEnd.value = fmt(yesterday);
window.onSubBrandFileChange = async function() {
const input = document.getElementById('sb-file-input');
if (!input.files.length) return;
const file = input.files[0];
const name = file.name;
document.getElementById('sb-file-name').textContent = '\u2705 ' + name;
document.getElementById('sb-drop-zone').classList.add('has-file');
const formData = new FormData();
formData.append('data_file', file);
try {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty">正在解析数据...</div>';
const res = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: formData });
const data = await res.json();
if (data.status !== 'success') {
throw new Error(data.detail || '上传失败');
}
const reader = new FileReader();
reader.onload = function(e) {
try {
const wb = XLSX.read(e.target.result, {type: 'array'});
const sheetName = wb.SheetNames.find(s => s.includes('子品牌')) || wb.SheetNames[0];
const ws = wb.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json(ws, {header: 1, defval: ''});
const dataRows = rows.slice(7).filter(r => r[0] && String(r[0]).trim());
const headers = ['门店','品牌','区域','直营','主机厂交付','产值交付','触客数','整车延保成交','安心包','电池','兜底指标'];
let html = '<table class="preview-table"><thead><tr><th>#</th>';
headers.forEach(h => html += '<th>' + escapeHtml(h) + '</th>');
html += '</tr></thead><tbody>';
dataRows.slice(0, 100).forEach((row, i) => {
html += '<tr><td style="text-align:center;color:#999;">' + (i+1) + '</td>';
html += '<td>' + escapeHtml(String(row[0]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[7]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[2]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[3]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[8]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[9]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[10]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[12]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[15]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[17]||'')) + '</td>';
html += '<td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;">' + escapeHtml(String(row[1]||'')) + '</td>';
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('sb-preview-body').innerHTML = html;
} catch(ex) {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">解析预览失败: ' + ex.message + '</div>';
}
};
reader.readAsArrayBuffer(file);
} catch(e) {
console.error('子品牌上传失败:', e);
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">' + (e.message || '上传失败') + '</div>';
}
};
const btnSb = document.getElementById('btn-generate-sb-report');
if (btnSb) {
btnSb.addEventListener('click', async () => {
document.getElementById('sb-analysis-result').className = 'result-box';
document.getElementById('sb-analysis-error').className = 'result-box';
const input = document.getElementById('sb-file-input');
if (!input || !input.files.length) {
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = '请先上传子品牌数据文件';
return;
}
btnSb.disabled = true;
btnSb.textContent = '\u23f3 正在生成报表...';
try {
const uploadForm = new FormData();
uploadForm.append('data_file', input.files[0]);
const sd = document.getElementById('sb-start-date').value;
const ed = document.getElementById('sb-end-date').value;
if (sd) uploadForm.append('start_date', sd);
if (ed) uploadForm.append('end_date', ed);
const upRes = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: uploadForm });
const upData = await upRes.json();
if (upData.status !== 'success') throw new Error(upData.detail || '上传失败');
btnSb.textContent = '\u23f3 正在分析计算...';
const genForm = new FormData();
if (sd) genForm.append('start_date', sd);
if (ed) genForm.append('end_date', ed);
const genRes = await fetch(window.API_BASE + '/harmony/sub-brand/generate', { method: 'POST', body: genForm });
const genData = await genRes.json();
if (genData.status === 'success') {
document.getElementById('sb-analysis-result').className = 'result-box success';
document.getElementById('sb-analysis-result-info').innerHTML =
'文件: <strong>' + (genData.file_path || '') + '</strong>';
document.getElementById('btn-download-sb-report').href = genData.download_url;
} else {
throw new Error(genData.detail || '报表生成失败');
}
} catch (err) {
console.error('子品牌分析失败:', err);
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = err.message || '未知错误';
} finally {
btnSb.disabled = false;
btnSb.textContent = '\u{1f680} 生成鸿蒙子品牌分析报表';
}
});
}
});
</script>
<script src="/static/js/auth.js"></script>
</body>
</html>
......@@ -20,6 +20,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......@@ -46,6 +47,16 @@
<h3>问界生态系数分析</h3>
<p>上传门店列表与主机厂数据,自动查询产值并计算生态系数</p>
</a>
<a class="nav-card" href="./harmony">
<div class="nav-card-icon">&#128200;</div>
<h3>鸿蒙生态分析</h3>
<p>上传鸿蒙门店兜底与主机厂数据,自动查询 DB 产值并生成分析报表</p>
</a>
<a class="nav-card" href="./harmony/sub-brand">
<div class="nav-card-icon">&#127991;</div>
<h3>鸿蒙子品牌分析</h3>
<p>上传含子品牌 Sheet 的数据,按智界/享界/尊界/尚界分析赔付</p>
</a>
<a class="nav-card" href="./strategy">
<div class="nav-card-icon">&#128064;</div>
<h3>策略效果盯防</h3>
......
......@@ -15,6 +15,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......
......@@ -190,6 +190,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......
......@@ -198,6 +198,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防(开发中)</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......
......@@ -198,6 +198,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./harmony/sub-brand">鸿蒙子品牌分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
......
......@@ -149,6 +149,7 @@ PAGE_ROUTES = {
"/dw": "dw.html",
"/analysis": "analysis.html",
"/harmony": "harmony.html",
"/harmony/sub-brand": "harmony_sub_brand.html",
"/strategy": "strategy.html",
"/strategy/detail": "strategy_detail.html",
"/strategy/info": "strategy_info.html",
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!