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))
......
# -*- coding: utf-8 -*-
"""
文件名: app/services/harmony_analysis_service.py
职责: 鸿蒙生态分析服务 - 合并门店兜底配置、主机厂数据、产值表,生成鸿蒙生态系数分析报表。
注意: 不要删除这个注释。
"""
import os
import re
import math
import logging
import pandas as pd
import numpy as np
from datetime import date, timedelta
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
logger = logging.getLogger("app.harmony_analysis_service")
# 样式定义(与问界保持一致)
HEADER_FILL = PatternFill("solid", fgColor="4472C4")
HEADER_FONT = Font(name="微软雅黑", bold=True, color="FFFFFF", size=10)
GROUP_FILL = PatternFill("solid", fgColor="D6E4F0")
GROUP_FONT = Font(name="微软雅黑", bold=True, size=10)
DATA_FONT = Font(name="微软雅黑", size=10)
THIN_BORDER = Border(
left=Side(style="thin"), right=Side(style="thin"),
top=Side(style="thin"), bottom=Side(style="thin")
)
# 输出表头定义 - 共45列 (A-AS)
HARMONY_OUTPUT_HEADERS = [
# 基础门店信息 (A-I, 1-9)
"门店名", "品牌", "兜底指标", "兜底类型", "区域(省)",
"直营与否", "区域运营", "飞行督导", "线上运营",
# 主机厂数据 (J, 10)
"交付数",
# 产值表数据 (K-Z, 11-26)
"交付数2", "触客数", "触客率", "应触客数",
"整车延保成交数", "整车延保渗透率",
"安心包达成数量", "安心包渗透率",
"电池延保成交数", "电池延保渗透率",
"轮胎险达成数量", "轮胎险渗透率",
"广联权益成交数", "广联权益渗透率",
"累计成交金额", "售前交付成交率",
# 达标系数 (AA-AC, 27-29)
"整车延保渗透率达标系数", "安心包渗透率达标系数", "电池延保渗透率达标系数",
# 当前转化率 (AD-AF, 30-32)
"整车延保转化率", "安心包转化率", "电池延保转化率",
# 需达标转化率 (AG-AI, 33-35)
"需达标_整车延保", "需达标_安心包", "需达标_电池延保",
# 是否触发兜底 (AJ, 36)
"是否触发兜底",
# 需达标订单数差额 (AK-AM, 37-39)
"差额_整车延保", "差额_安心包", "差额_电池延保",
# 赔付金额 (AN-AP, 40-42)
"赔付_整车延保", "赔付_安心包", "赔付_电池延保",
# 是否需要赔付 (AQ, 43)
"是否需要赔付",
# 赔付总金额 (AR, 44)
"赔付总金额",
# 备注 (AS, 45)
"备注",
]
# 百分比列(1-indexed 列号)
PERCENT_COLS = {13, 16, 18, 20, 22, 24, 26, 30, 31, 32, 33, 34, 35}
# 系数列
COEFF_COLS = {27, 28, 29}
def _safe_float(val, default=0.0):
try:
v = float(val)
if np.isnan(v) or np.isinf(v):
return default
return v
except (ValueError, TypeError):
return default
class HarmonyAnalysisService:
"""鸿蒙生态分析服务"""
@staticmethod
def read_store_list(file_path: str) -> pd.DataFrame:
"""
读取鸿蒙门店兜底配置Excel。
结构: 第1行主表头, 第2行子表头(整车延保/安心包/电池延保), 第3行起为数据。
15列: 门店, 品牌, 兜底指标, 区域(省), 直营与否, 区域运营, 飞行督导,
线上运营, 兜底类型, 需达标转化率(3列), 预计赔付金额(3列)
"""
df_raw = pd.read_excel(file_path, header=None)
data_start = 2 # 0-indexed, row 3 in Excel
df = df_raw.iloc[data_start:].copy()
col_names = {
0: "门店名", 1: "品牌", 2: "兜底指标", 3: "区域(省)",
4: "直营与否", 5: "区域运营", 6: "飞行督导", 7: "线上运营",
8: "兜底类型",
9: "需达标转化率_整车延保",
10: "需达标转化率_安心包",
11: "需达标转化率_电池延保",
12: "预计赔付金额_整车",
13: "预计赔付金额_安心包",
14: "预计赔付金额_电池",
}
df = df.rename(columns=col_names)
for c in col_names.values():
if c not in df.columns:
df[c] = None
df = df[[c for c in col_names.values()]]
# 过滤空行
df = df[df["门店名"].notna() & (df["门店名"].astype(str).str.strip() != "")]
# 去重
before = len(df)
df = df.drop_duplicates(subset=["门店名"], keep="first")
if len(df) < before:
logger.warning(f"鸿蒙门店列表存在 {before - len(df)} 行重复门店名,已去重")
return df
@staticmethod
def read_factory_data(file_path: str) -> pd.DataFrame:
"""
读取鸿蒙主机厂数据Excel。
结构: 第1行表头, 第2行起为数据。
6列: 省份, 城市, 门店编号, 用户中心门店名称, 门店名称, 交车数量
"""
df_raw = pd.read_excel(file_path, header=None)
# 检测表头行(搜索包含"门店名称"或"门店"的行)
header_row = 0
for i in range(min(5, len(df_raw))):
row_vals = [str(v).strip() for v in df_raw.iloc[i].values if pd.notna(v)]
if any("门店" in v for v in row_vals) and any("交" in v or "交付" in v for v in row_vals):
header_row = i
break
df = pd.DataFrame(df_raw.values[header_row + 1:], columns=df_raw.iloc[header_row].values)
# 统一列名映射
col_map = {
"门店名称": "门店名",
"门店": "门店名",
"交车数量": "交付数",
"交付": "交付数",
"省份": "省份",
"城市": "城市",
"门店编号": "门店编号",
"用户中心门店名称": "用户中心门店名称",
}
df = df.rename(columns=col_map)
if "门店名" not in df.columns:
logger.error(f"鸿蒙主机厂数据缺少门店名称列,现有列: {list(df.columns)}")
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 = df[~df["门店名"].astype(str).str.strip().isin(["门店", "门店名称", "厅店名称"])]
# 去重
df = df.drop_duplicates(subset=["门店名"], keep="first")
return df
@staticmethod
def read_value_table(file_path: str) -> pd.DataFrame:
"""
读取鸿蒙产值表Excel。
结构: 第1行一致性标记, 第2行列名, 第3行重复列名(可能月份不同), 第4行起为数据。
"""
df_raw = pd.read_excel(file_path, header=None)
# 检测表头行(搜索包含"业务类型"和"门店"的行)
header_row = 1 # 默认第2行
for i in range(min(5, len(df_raw))):
row_vals = [str(v).strip() for v in df_raw.iloc[i].values if pd.notna(v)]
if "业务类型" in row_vals and "门店" in row_vals:
header_row = i
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:
logger.error(f"鸿蒙产值表缺少门店列,现有列: {list(df.columns)}")
return pd.DataFrame()
# 数值化
numeric_cols = [
"产值表_交付数", "触客数", "售后触客数", "应触客数",
"累计成交金额", "售前整车延保成交数", "整车延保成交数",
"轮胎险达成数量", "安心包达成数量", "电池延保成交数",
"广联权益成交数", "驻店人员",
]
for c in numeric_cols:
if c in df.columns:
df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0)
# 过滤空行(门店名为空或为"小计"等)
df = df[df["门店名"].notna() & (df["门店名"].astype(str).str.strip() != "")]
# 过滤表头残留行和小计行
df = df[~df["门店名"].astype(str).str.strip().isin(["门店", "业务类型"])]
df = df[~df["门店名"].astype(str).str.contains("小计|合计|总计", na=False)]
return df
@staticmethod
def _aggregate_value_table(value_df: pd.DataFrame) -> pd.DataFrame:
"""
产值表中同一门店可能有多行(不同品牌/业务类型),需按门店名聚合。
聚合策略:数值列求和,比率列重新计算,文本列取第一条。
"""
if value_df.empty:
return value_df
# 按门店名分组聚合
agg_dict = {}
sum_cols = [
"产值表_交付数", "触客数", "售后触客数", "应触客数",
"累计成交金额", "售前整车延保成交数", "整车延保成交数",
"轮胎险达成数量", "安心包达成数量", "电池延保成交数",
"广联权益成交数",
]
first_cols = ["区域省份", "品牌", "业务", "区域经理", "线上运营_产值表", "飞行督导_产值表"]
for c in sum_cols:
if c in value_df.columns:
agg_dict[c] = "sum"
for c in first_cols:
if c in value_df.columns:
agg_dict[c] = "first"
if "门店名" not in agg_dict:
result = value_df.groupby("门店名", as_index=False).agg(agg_dict)
else:
result = value_df.groupby("门店名", as_index=False).agg(agg_dict)
# 重新计算比率列
if "产值表_交付数" in result.columns and "触客数" in result.columns:
result["触客率"] = result.apply(
lambda r: round(r["触客数"] / r["产值表_交付数"], 4) if r["产值表_交付数"] > 0 else 0,
axis=1
)
if "产值表_交付数" in result.columns and "整车延保成交数" in result.columns:
result["整车延保渗透率"] = result.apply(
lambda r: round(r["整车延保成交数"] / r["产值表_交付数"], 4) if r["产值表_交付数"] > 0 else 0,
axis=1
)
result["安心包渗透率"] = result.apply(
lambda r: round(r["安心包达成数量"] / r["产值表_交付数"], 4) if r["产值表_交付数"] > 0 else 0,
axis=1
)
result["电池延保渗透率"] = result.apply(
lambda r: round(r["电池延保成交数"] / r["产值表_交付数"], 4) if r["产值表_交付数"] > 0 else 0,
axis=1
)
result["轮胎险渗透率"] = result.apply(
lambda r: round(r["轮胎险达成数量"] / r["产值表_交付数"], 4) if r["产值表_交付数"] > 0 else 0,
axis=1
)
result["广联权益渗透率"] = result.apply(
lambda r: round(r["广联权益成交数"] / r["产值表_交付数"], 4) if r["产值表_交付数"] > 0 else 0,
axis=1
)
if "应触客数" in result.columns and "整车延保成交数" in result.columns:
result["售前交付成交率"] = result.apply(
lambda r: round(r["整车延保成交数"] / r["应触客数"], 4) if r["应触客数"] > 0 else 0,
axis=1
)
return result
@staticmethod
def build_report(store_df: pd.DataFrame,
factory_df: pd.DataFrame = None,
value_df: pd.DataFrame = None,
start_date: str = None,
end_date: str = None) -> str:
"""
构建鸿蒙生态系数分析报表。
合并门店兜底配置 + 主机厂数据(交付数) + 产值表(详细指标),
计算赔付金额,输出到基于模板的Excel文件。
"""
import shutil
import time
TEMPLATE_FILE = os.path.join("app", "templates", "输出-鸿蒙生态系数-模板.xlsx")
TEMPLATE_SHEET = "模板"
if not os.path.exists(TEMPLATE_FILE):
raise FileNotFoundError(f"模板文件不存在: {TEMPLATE_FILE}")
if factory_df is None:
factory_df = pd.DataFrame()
if value_df is None:
value_df = pd.DataFrame()
# 聚合产值表(按门店名汇总)
if not value_df.empty:
value_agg = HarmonyAnalysisService._aggregate_value_table(value_df)
else:
value_agg = pd.DataFrame()
# 输出文件命名
output_dir = "temp_uploads"
os.makedirs(output_dir, exist_ok=True)
ts = int(time.time())
date_str = end_date.replace("-", "") if end_date else date.today().strftime("%Y%m%d")
output_path = os.path.join(output_dir, f"鸿蒙分析_{date_str}_{ts}.xlsx")
shutil.copy2(TEMPLATE_FILE, output_path)
wb = load_workbook(output_path)
ws_template = wb[TEMPLATE_SHEET]
# 提取公式
formula_map, skip_external_cols = HarmonyAnalysisService._extract_formulas_from_template(ws_template)
# 复制模板sheet
ws = wb.copy_worksheet(ws_template)
sheet_name = f"鸿蒙分析({date_str})" if date_str else "鸿蒙生态分析"
ws.title = sheet_name
ws_template.sheet_state = 'hidden'
# 清除数据行(保留表头1-3行)
HarmonyAnalysisService._clear_sheet_data(ws)
logger.info(f"Created sheet: '{sheet_name}' from '{TEMPLATE_SHEET}'")
# 合并数据
merged = store_df.copy()
if not factory_df.empty:
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:
merged["交付数"] = 0
else:
merged["交付数"] = 0
if not value_agg.empty:
merged = pd.merge(merged, value_agg, on="门店名", how="left")
logger.info(f"Merged data: {len(merged)} stores, "
f"factory={len(factory_df)}, value_table={len(value_agg)}")
# 写入数据行
next_row = HarmonyAnalysisService._write_data_rows(
ws, merged, formula_map, skip_external_cols, start_date, end_date)
wb.save(output_path)
logger.info(f"Harmony report generated: {output_path}")
return output_path
@staticmethod
def _extract_formulas_from_template(ws):
"""从模板第4行提取公式映射"""
formula_map = {}
skip_external_cols = set()
for col in range(1, 46):
cell = ws.cell(row=4, column=col)
raw = cell.value
if raw is None:
continue
if isinstance(raw, str) and raw.startswith('='):
formula_text = raw
elif hasattr(raw, 'text'):
formula_text = raw.text
else:
continue
if re.search(r'\[\d+\]', formula_text):
skip_external_cols.add(col)
continue
formula_map[col] = formula_text
return formula_map, skip_external_cols
@staticmethod
def _clear_sheet_data(ws):
"""清除第4行起的所有数据"""
for r in range(4, ws.max_row + 1):
for c in range(1, 46):
ws.cell(row=r, column=c).value = None
@staticmethod
def _write_data_rows(ws, merged_df, formula_map, skip_external_cols,
start_date=None, end_date=None, start_row=4):
"""写入数据行到模板"""
def _style_cell(r, c, value):
cell = ws.cell(row=r, column=c, value=value)
cell.font = Font(name="微软雅黑", size=10)
cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
if isinstance(value, (int, float)):
if c in PERCENT_COLS:
cell.number_format = '0.00%'
elif c in COEFF_COLS:
cell.number_format = '0.0'
elif c == 25: # 累计成交金额
cell.number_format = '#,##0'
elif c == 44: # 赔付总金额
cell.number_format = '#,##0'
elif c not in (36, 43):
cell.number_format = '0'
return cell
row_num = start_row
for idx, row in merged_df.iterrows():
store_name = row.get("门店名", "")
if pd.isna(store_name) or str(store_name).strip() == "":
continue
ws.row_dimensions[row_num].height = 18
# ========== 基础门店信息 (A-I, 1-9) ==========
_style_cell(row_num, 1, str(store_name))
_style_cell(row_num, 2, row.get("品牌", ""))
_style_cell(row_num, 3, row.get("兜底指标", ""))
_style_cell(row_num, 4, row.get("兜底类型", ""))
_style_cell(row_num, 5, row.get("区域(省)", ""))
_style_cell(row_num, 6, row.get("直营与否", ""))
_style_cell(row_num, 7, row.get("区域运营", ""))
_style_cell(row_num, 8, row.get("飞行督导", ""))
_style_cell(row_num, 9, row.get("线上运营", ""))
# ========== 主机厂数据 (J, 10) ==========
delivery = _safe_float(row.get("交付数", 0))
_style_cell(row_num, 10, delivery)
# ========== 产值表数据 (K-Z, 11-26) ==========
delivery2 = _safe_float(row.get("产值表_交付数", 0))
if delivery2 == 0:
delivery2 = delivery # 兜底取主机厂数据
touch = _safe_float(row.get("触客数", 0))
touch_rate = _safe_float(row.get("触客率", 0))
if touch_rate == 0 and touch > 0 and delivery2 > 0:
touch_rate = round(touch / delivery2, 4)
should_touch = _safe_float(row.get("应触客数", 0))
yb_orders = _safe_float(row.get("整车延保成交数", 0))
yb_pen = _safe_float(row.get("整车延保渗透率", 0))
if yb_pen == 0 and yb_orders > 0 and delivery2 > 0:
yb_pen = round(yb_orders / delivery2, 4)
axb_orders = _safe_float(row.get("安心包达成数量", 0))
axb_pen = _safe_float(row.get("安心包渗透率", 0))
if axb_pen == 0 and axb_orders > 0 and delivery2 > 0:
axb_pen = round(axb_orders / delivery2, 4)
battery_orders = _safe_float(row.get("电池延保成交数", 0))
battery_pen = _safe_float(row.get("电池延保渗透率", 0))
if battery_pen == 0 and battery_orders > 0 and delivery2 > 0:
battery_pen = round(battery_orders / delivery2, 4)
tire_orders = _safe_float(row.get("轮胎险达成数量", 0))
tire_pen = _safe_float(row.get("轮胎险渗透率", 0))
if tire_pen == 0 and tire_orders > 0 and delivery2 > 0:
tire_pen = round(tire_orders / delivery2, 4)
equity_orders = _safe_float(row.get("广联权益成交数", 0))
equity_pen = _safe_float(row.get("广联权益渗透率", 0))
if equity_pen == 0 and equity_orders > 0 and delivery2 > 0:
equity_pen = round(equity_orders / delivery2, 4)
total_amount = _safe_float(row.get("累计成交金额", 0))
pre_delivery_rate = _safe_float(row.get("售前交付成交率", 0))
_style_cell(row_num, 11, delivery2) # K
_style_cell(row_num, 12, touch) # L
_style_cell(row_num, 13, touch_rate) # M
_style_cell(row_num, 14, should_touch) # N
_style_cell(row_num, 15, yb_orders) # O
_style_cell(row_num, 16, yb_pen) # P
_style_cell(row_num, 17, axb_orders) # Q
_style_cell(row_num, 18, axb_pen) # R
_style_cell(row_num, 19, battery_orders) # S
_style_cell(row_num, 20, battery_pen) # T
_style_cell(row_num, 21, tire_orders) # U
_style_cell(row_num, 22, tire_pen) # V
_style_cell(row_num, 23, equity_orders) # W
_style_cell(row_num, 24, equity_pen) # X
_style_cell(row_num, 25, total_amount) # Y
_style_cell(row_num, 26, pre_delivery_rate) # Z
# ========== 需达标转化率 (AG-AI, 33-35) ==========
target_yb = _safe_float(row.get("需达标转化率_整车延保", 0))
target_axb = _safe_float(row.get("需达标转化率_安心包", 0))
target_battery = _safe_float(row.get("需达标转化率_电池延保", 0))
_style_cell(row_num, 33, target_yb)
_style_cell(row_num, 34, target_axb)
_style_cell(row_num, 35, target_battery)
# ========== 当前转化率计算 (AD-AF, 30-32) ==========
# 触客类型 → 订单数/触客数, 交付类型 → 订单数/交付数
baodi_type = str(row.get("兜底类型", "")).strip()
base_for_rate = touch if baodi_type == "触客" else delivery
if base_for_rate == 0:
base_for_rate = delivery2
current_rate_yb = yb_orders / base_for_rate if base_for_rate > 0 else 0
current_rate_axb = axb_orders / base_for_rate if base_for_rate > 0 else 0
current_rate_battery = battery_orders / base_for_rate if base_for_rate > 0 else 0
_style_cell(row_num, 30, round(current_rate_yb, 4))
_style_cell(row_num, 31, round(current_rate_axb, 4))
_style_cell(row_num, 32, round(current_rate_battery, 4))
# ========== 需达标订单数差额 (AK-AM, 37-39) ==========
gap_yb = max(0, math.ceil(base_for_rate * target_yb - yb_orders)) if target_yb > 0 else 0
gap_axb = max(0, math.ceil(base_for_rate * target_axb - axb_orders)) if target_axb > 0 else 0
gap_battery = max(0, math.ceil(base_for_rate * target_battery - battery_orders)) if target_battery > 0 else 0
_style_cell(row_num, 37, gap_yb)
_style_cell(row_num, 38, gap_axb)
_style_cell(row_num, 39, gap_battery)
# ========== 赔付金额 (AN-AP, 40-42) ==========
# 使用预计赔付金额 × 差额
penalty_yb = _safe_float(row.get("预计赔付金额_整车", 0))
penalty_axb = _safe_float(row.get("预计赔付金额_安心包", 0))
penalty_battery = _safe_float(row.get("预计赔付金额_电池", 0))
payout_yb = round(gap_yb * penalty_yb, 1) if gap_yb > 0 and penalty_yb > 0 else 0
payout_axb = round(gap_axb * penalty_axb, 1) if gap_axb > 0 and penalty_axb > 0 else 0
payout_battery = round(gap_battery * penalty_battery, 1) if gap_battery > 0 and penalty_battery > 0 else 0
# 非直营门店不赔付
is_direct = str(row.get("直营与否", "")).strip() == "直营"
if not is_direct:
payout_yb = "/"
payout_axb = "/"
payout_battery = "/"
_style_cell(row_num, 40, payout_yb)
_style_cell(row_num, 41, payout_axb)
_style_cell(row_num, 42, payout_battery)
# ========== 是否触发兜底 (AJ, 36) ==========
trigger = "是" if (gap_yb > 0 or gap_axb > 0 or gap_battery > 0) else "否"
_style_cell(row_num, 36, trigger)
# ========== 是否需要赔付 (AQ, 43) ==========
need_payout = "是" if (is_direct and (payout_yb not in (0, "/") or payout_axb not in (0, "/") or payout_battery not in (0, "/"))) else "否"
_style_cell(row_num, 43, need_payout)
# ========== 赔付总金额 (AR, 44) ==========
if not is_direct:
_style_cell(row_num, 44, "/")
else:
total_payout = 0
for p in [payout_yb, payout_axb, payout_battery]:
if isinstance(p, (int, float)):
total_payout += p
_style_cell(row_num, 44, round(total_payout, 1))
# ========== 写入公式列 (达标系数等) ==========
for col_idx, formula_text in formula_map.items():
if col_idx in skip_external_cols:
continue
if col_idx in (30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44):
continue # 已用Python写入值
adjusted = re.sub(
r'([A-Z]{1,3})4\b',
lambda m: f'{m.group(1)}{row_num}',
formula_text
)
cell = ws.cell(row=row_num, column=col_idx)
cell.value = adjusted
cell.font = Font(name="微软雅黑", size=10)
cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
if col_idx in PERCENT_COLS:
cell.number_format = '0.00%'
elif col_idx in COEFF_COLS:
cell.number_format = '0.0'
row_num += 1
return row_num
......@@ -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>问界生态系数分析 - 问界门店运营数据分析平台</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" href="/dw">DWS/DWM/DWA 任务</a>
<a class="nav-item active" 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 id="content-title">问界生态系数分析</h2>
<div id="content-body">
<!-- 数据分析部分 -->
<div id="data-analysis-section">
<div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px;">
<!-- 步骤1: 上传门店列表 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 16px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤1: 门店列表</span>
<div id="store-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="store-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f3ea;</span>
<p id="store-file-name" style="margin:0; font-size:13px; color:#999;">可选:点击选择门店列表文件(不选则使用系统默认模板)</p>
</div>
<a href="/api/analysis/template/store" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">&#x1f4e5; 下载模板</a>
</div>
<!-- 步骤2: 生态主机厂数据 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤2: 生态(26日)</span>
<div id="ecology-drop-zone" style="border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="ecology-factory-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f3ed;</span>
<p id="ecology-file-name" style="margin:0; font-size:12px; color:#999;">点击选择生态主机厂数据</p>
</div>
<input type="date" id="ecology-start-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="开始">
<span style="color:#999; font-size:12px;">~</span>
<input type="date" id="ecology-end-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="结束">
</div>
<!-- 步骤3: 自然月主机厂数据 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤3: 自然月(1日)</span>
<div id="nature-drop-zone" style="border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="nature-factory-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f4c5;</span>
<p id="nature-file-name" style="margin:0; font-size:12px; color:#999;">点击选择自然月主机厂数据</p>
</div>
<input type="date" id="nature-start-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="开始">
<span style="color:#999; font-size:12px;">~</span>
<input type="date" id="nature-end-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="结束">
</div>
</div>
<!-- 步骤4: 生成报表 -->
<div style="text-align: center; margin: 20px 0;">
<button id="btn-generate-report" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;">
&#x1f680; 开始生成分析报表
</button>
<p style="font-size:12px; color:#999; margin-top:8px;">门店按兜底截止日期分组:月底/25日→生态数据sheet,其余→自然月sheet</p>
<p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 问界门店数据模板(最新序号)</p>
</div>
<!-- 生成结果提示 -->
<div id="analysis-result" style="display:none; background: #f6ffed; border: 1px solid #b7eb8f; padding: 20px; border-radius: 8px; text-align: center;">
<h3 style="color:#52c41a; margin:0 0 10px;">&#x2705; 报表生成成功</h3>
<div id="analysis-result-info" style="font-size:13px; color:#666; margin-bottom:15px;"></div>
<a id="btn-download-report" href="/api/analysis/download"
style="display:inline-block; padding: 10px 32px; background: #52c41a; color: white; border: none; border-radius: 4px; font-size: 14px; text-decoration: none; cursor: pointer;">
&#x1f4e5; 下载分析报表
</a>
</div>
<div id="analysis-error" style="display:none; background: #fff2f0; border: 1px solid #ffccc7; padding: 20px; border-radius: 8px; text-align: center;">
<h3 style="color:#f5222d; margin:0 0 10px;">&#x274c; 报表生成失败</h3>
<p id="analysis-error-msg" style="margin:0; color:#666;"></p>
</div>
</div>
</div>
</div>
</section>
</main>
<script>
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 todayStr = fmt(now);
const lastMonth26 = new Date(now.getFullYear(), now.getMonth()-1, 26);
const startStr = fmt(lastMonth26);
const firstOfMonth = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
const ecoStart = document.getElementById('ecology-start-date');
const ecoEnd = document.getElementById('ecology-end-date');
if (ecoStart && !ecoStart.value) ecoStart.value = startStr;
if (ecoEnd && !ecoEnd.value) ecoEnd.value = todayStr;
const natStart = document.getElementById('nature-start-date');
const natEnd = document.getElementById('nature-end-date');
if (natStart && !natStart.value) natStart.value = firstOfMonth;
if (natEnd && !natEnd.value) natEnd.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 = '&#x2705; 已选择: ' + storeFileInput.files[0].name;
document.getElementById('store-file-name').style.color = '#52c41a';
}
});
}
// 生态主机厂数据上传
const ecologyDropZone = document.getElementById('ecology-drop-zone');
const ecologyFactoryInput = document.getElementById('ecology-factory-input');
if (ecologyDropZone && ecologyFactoryInput) {
ecologyDropZone.addEventListener('click', () => ecologyFactoryInput.click());
ecologyFactoryInput.addEventListener('change', () => {
if (ecologyFactoryInput.files.length > 0) {
document.getElementById('ecology-file-name').textContent = '&#x2705; 已选择: ' + ecologyFactoryInput.files[0].name;
document.getElementById('ecology-file-name').style.color = '#52c41a';
}
});
}
// 自然月主机厂数据上传
const natureDropZone = document.getElementById('nature-drop-zone');
const natureFactoryInput = document.getElementById('nature-factory-input');
if (natureDropZone && natureFactoryInput) {
natureDropZone.addEventListener('click', () => natureFactoryInput.click());
natureFactoryInput.addEventListener('change', () => {
if (natureFactoryInput.files.length > 0) {
document.getElementById('nature-file-name').textContent = '&#x2705; 已选择: ' + natureFactoryInput.files[0].name;
document.getElementById('nature-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 hasEcology = ecologyFactoryInput && ecologyFactoryInput.files.length > 0;
const hasNature = natureFactoryInput && natureFactoryInput.files.length > 0;
if (!hasEcology && !hasNature) {
alert('请至少上传一个主机厂数据文件(步骤2或步骤3)');
return;
}
btnGenerateReport.disabled = true;
btnGenerateReport.textContent = '&#x23f3; 正在生成报表...';
try {
const uploadForm = new FormData();
if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]);
if (hasEcology) uploadForm.append('ecology_factory_file', ecologyFactoryInput.files[0]);
if (hasNature) uploadForm.append('nature_factory_file', natureFactoryInput.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 = '&#x23f3; 正在分析计算...';
const genForm = new FormData();
const ecoStart = document.getElementById('ecology-start-date').value;
const ecoEnd = document.getElementById('ecology-end-date').value;
const natStart = document.getElementById('nature-start-date').value;
const natEnd = document.getElementById('nature-end-date').value;
if (ecoStart) genForm.append('ecology_start_date', ecoStart);
if (ecoEnd) genForm.append('ecology_end_date', ecoEnd);
if (natStart) genForm.append('nature_start_date', natStart);
if (natEnd) genForm.append('nature_end_date', natEnd);
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.ecology_store_count + '</strong> 家 | ' +
'自然月门店: <strong>' + genData.nature_store_count + '</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 = '&#x1f680; 开始生成分析报表';
}
});
}
});
</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>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>鸿蒙生态分析 - 问界门店运营数据分析平台</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" href="/dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="/analysis">问界生态系数分析</a>
<a class="nav-item active" href="/harmony">鸿蒙生态分析</a>
</nav>
<div class="user-info">管理员</div>
</header>
<main>
<section id="content-area">
<div class="card">
<h2 id="content-title">鸿蒙生态分析</h2>
<div id="content-body">
<div id="harmony-analysis-section">
<div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px;">
<!-- 步骤1: 上传门店兜底配置 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 16px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤1: 门店兜底配置</span>
<div id="hm-store-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="hm-store-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f3ea;</span>
<p id="hm-store-file-name" style="margin:0; font-size:13px; color:#999;">可选:点击选择门店兜底配置文件(不选则使用系统默认模板)</p>
</div>
<a href="/api/harmony/template/store" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">&#x1f4e5; 下载模板</a>
</div>
<!-- 步骤2: 上传主机厂数据 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤2: 主机厂数据</span>
<div id="hm-factory-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="hm-factory-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f3ed;</span>
<p id="hm-factory-file-name" style="margin:0; font-size:12px; color:#999;">点击选择主机厂数据(含交付数)</p>
</div>
<a href="/api/harmony/template/factory" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">&#x1f4e5; 下载模板</a>
</div>
<!-- 步骤3: 上传产值表 -->
<div style="background: #f0f5ff; padding: 8px 16px; border-radius: 6px; border: 1px solid #adc6ff; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#1890ff; white-space:nowrap;">步骤3: 产值表 (核心数据)</span>
<div id="hm-value-drop-zone" style="flex:1; border: 1px dashed #1890ff; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="hm-value-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f4ca;</span>
<p id="hm-value-file-name" style="margin:0; font-size:12px; color:#999;">点击选择鸿蒙产值表(含触客数、成交数、渗透率等)</p>
</div>
</div>
<!-- 日期范围 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">数据周期</span>
<input type="date" id="hm-start-date" style="width:140px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;">
<span style="color:#999; font-size:12px;">~</span>
<input type="date" id="hm-end-date" style="width:140px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;">
</div>
</div>
<!-- 生成报表按钮 -->
<div style="text-align: center; margin: 20px 0;">
<button id="btn-hm-generate" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;">
&#x1f680; 生成鸿蒙生态分析报表
</button>
<p style="font-size:12px; color:#999; margin-top:8px;">合并门店兜底配置 + 主机厂交付数据 + 产值表指标,计算渗透率达标系数和赔付金额</p>
<p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 输出-鸿蒙生态系数-模板.xlsx</p>
</div>
<!-- 结果提示 -->
<div id="hm-result" style="display:none; background: #f6ffed; border: 1px solid #b7eb8f; padding: 20px; border-radius: 8px; text-align: center;">
<h3 style="color:#52c41a; margin:0 0 10px;">&#x2705; 报表生成成功</h3>
<div id="hm-result-info" style="font-size:13px; color:#666; margin-bottom:15px;"></div>
<a id="btn-hm-download" href="#"
style="display:inline-block; padding: 10px 32px; background: #52c41a; color: white; border: none; border-radius: 4px; font-size: 14px; text-decoration: none; cursor: pointer;">
&#x1f4e5; 下载分析报表
</a>
</div>
<div id="hm-error" style="display:none; background: #fff2f0; border: 1px solid #ffccc7; padding: 20px; border-radius: 8px; text-align: center;">
<h3 style="color:#f5222d; margin:0 0 10px;">&#x274c; 报表生成失败</h3>
<p id="hm-error-msg" style="margin:0; color:#666;"></p>
</div>
</div>
</div>
</div>
</section>
</main>
<script>
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 todayStr = fmt(now);
const firstOfMonth = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
const startDate = document.getElementById('hm-start-date');
const endDate = document.getElementById('hm-end-date');
if (startDate && !startDate.value) startDate.value = firstOfMonth;
if (endDate && !endDate.value) endDate.value = todayStr;
// 门店兜底配置上传
const storeDropZone = document.getElementById('hm-store-drop-zone');
const storeFileInput = document.getElementById('hm-store-file-input');
if (storeDropZone) {
storeDropZone.addEventListener('click', () => storeFileInput.click());
storeFileInput.addEventListener('change', () => {
if (storeFileInput.files.length > 0) {
document.getElementById('hm-store-file-name').textContent = '\u2705 已选择: ' + storeFileInput.files[0].name;
document.getElementById('hm-store-file-name').style.color = '#52c41a';
}
});
}
// 主机厂数据上传
const factoryDropZone = document.getElementById('hm-factory-drop-zone');
const factoryFileInput = document.getElementById('hm-factory-file-input');
if (factoryDropZone) {
factoryDropZone.addEventListener('click', () => factoryFileInput.click());
factoryFileInput.addEventListener('change', () => {
if (factoryFileInput.files.length > 0) {
document.getElementById('hm-factory-file-name').textContent = '\u2705 已选择: ' + factoryFileInput.files[0].name;
document.getElementById('hm-factory-file-name').style.color = '#52c41a';
}
});
}
// 产值表上传
const valueDropZone = document.getElementById('hm-value-drop-zone');
const valueFileInput = document.getElementById('hm-value-file-input');
if (valueDropZone) {
valueDropZone.addEventListener('click', () => valueFileInput.click());
valueFileInput.addEventListener('change', () => {
if (valueFileInput.files.length > 0) {
document.getElementById('hm-value-file-name').textContent = '\u2705 已选择: ' + valueFileInput.files[0].name;
document.getElementById('hm-value-file-name').style.color = '#52c41a';
}
});
}
// 生成报表
const btnGenerate = document.getElementById('btn-hm-generate');
if (btnGenerate) {
btnGenerate.addEventListener('click', async () => {
document.getElementById('hm-result').style.display = 'none';
document.getElementById('hm-error').style.display = 'none';
const hasStore = storeFileInput && storeFileInput.files.length > 0;
const hasFactory = factoryFileInput && factoryFileInput.files.length > 0;
const hasValue = valueFileInput && valueFileInput.files.length > 0;
if (!hasFactory && !hasValue) {
alert('请至少上传主机厂数据或产值表文件');
return;
}
btnGenerate.disabled = true;
btnGenerate.textContent = '\u23f3 正在上传文件...';
try {
// 上传文件
const uploadForm = new FormData();
if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]);
if (hasFactory) uploadForm.append('factory_file', factoryFileInput.files[0]);
if (hasValue) uploadForm.append('value_file', valueFileInput.files[0]);
const uploadRes = await fetch('/api/harmony/upload', { method: 'POST', body: uploadForm });
const uploadData = await uploadRes.json();
if (uploadData.status !== 'success') {
throw new Error(uploadData.detail || '文件上传失败');
}
btnGenerate.textContent = '\u23f3 正在分析计算...';
// 生成报表
const genForm = new FormData();
const sd = document.getElementById('hm-start-date').value;
const ed = document.getElementById('hm-end-date').value;
if (sd) genForm.append('start_date', sd);
if (ed) genForm.append('end_date', ed);
const genRes = await fetch('/api/harmony/generate', { method: 'POST', body: genForm });
const genData = await genRes.json();
if (genData.status === 'success') {
document.getElementById('hm-result').style.display = 'block';
document.getElementById('hm-result-info').innerHTML =
'门店数: <strong>' + genData.store_count + '</strong> | ' +
'主机厂门店: <strong>' + genData.factory_count + '</strong> | ' +
'产值表门店: <strong>' + genData.value_count + '</strong>';
document.getElementById('btn-hm-download').href = genData.download_url;
} else {
throw new Error(genData.detail || '报表生成失败');
}
} catch (err) {
console.error('鸿蒙分析失败:', err);
document.getElementById('hm-error').style.display = 'block';
document.getElementById('hm-error-msg').textContent = err.message || '未知错误';
} finally {
btnGenerate.disabled = false;
btnGenerate.textContent = '\u{1f680} 生成鸿蒙生态分析报表';
}
});
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<!--
文件名: app/templates/index.html
职责: WebUI 主页面结构,提供任务控制、数据查询、文件上传、模板选择等交互界面。
职责: WebUI 首页 - 纯导航入口,各业务功能已拆分至独立页面。
注意: 不要删除这个注释。
-->
<html lang="zh-CN">
......@@ -9,190 +9,49 @@
<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">
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<!-- 顶部导航栏:所有入口平铺展示 -->
<header>
<div class="logo">问界运营分析平台</div>
<nav class="nav-links">
<div class="nav-item" data-section="ods">ODS 同步任务</div>
<div class="nav-item" data-section="dw">DWS/DWM/DWA 任务</div>
<div class="nav-item active" data-section="analysis-modal">问界生态系数分析</div>
<a class="nav-item active" 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>
</nav>
<div class="user-info">管理员</div>
</header>
<main>
<!-- 全宽内容展示区(左侧边栏已移除) -->
<section id="content-area">
<div class="card">
<h2 id="content-title">任务调度</h2>
<div id="content-body">
<!-- 任务配置部分 (仅 ODS) -->
<div id="task-config-section" style="display:none; 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>
<!-- DW 加工控制部分 (DWS/DWM/DWA) -->
<div id="dw-process-section" style="display:none; 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 id="task-history-section" style="display:none;">
<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 id="data-analysis-section" style="display:none;">
<div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px;">
<!-- 步骤1: 上传门店列表(可选,未上传时使用默认模板) -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 16px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤1: 门店列表</span>
<div id="store-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="store-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">🏪</span>
<p id="store-file-name" style="margin:0; font-size:13px; color:#999;">可选:点击选择门店列表文件(不选则使用系统默认模板)</p>
</div>
<a href="api/analysis/template/store" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">📥 下载模板</a>
</div>
<!-- 步骤2: 生态主机厂数据(26日周期) -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤2: 生态(26日)</span>
<div id="ecology-drop-zone" style="border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="ecology-factory-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">🏭</span>
<p id="ecology-file-name" style="margin:0; font-size:12px; color:#999;">点击选择生态主机厂数据</p>
</div>
<input type="date" id="ecology-start-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="开始">
<span style="color:#999; font-size:12px;">~</span>
<input type="date" id="ecology-end-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="结束">
</div>
<!-- 步骤3: 自然月主机厂数据(1日周期) -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤3: 自然月(1日)</span>
<div id="nature-drop-zone" style="border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="nature-factory-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">📅</span>
<p id="nature-file-name" style="margin:0; font-size:12px; color:#999;">点击选择自然月主机厂数据</p>
</div>
<input type="date" id="nature-start-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="开始">
<span style="color:#999; font-size:12px;">~</span>
<input type="date" id="nature-end-date" style="width:130px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="结束">
</div>
</div>
<!-- 步骤4: 生成报表 -->
<div style="text-align: center; margin: 20px 0;">
<button id="btn-generate-report" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;">
🚀 开始生成分析报表
</button>
<p style="font-size:12px; color:#999; margin-top:8px;">门店按兜底截止日期分组:月底/25日→生态数据sheet,其余→自然月sheet</p>
<p style="font-size:11px; color:#faad14;">📌 使用模板: 输出-问界生态系数-模板.xlsx</p>
</div>
<!-- 生成结果提示 -->
<div id="analysis-result" style="display:none; background: #f6ffed; border: 1px solid #b7eb8f; padding: 20px; border-radius: 8px; text-align: center;">
<h3 style="color:#52c41a; margin:0 0 10px;">✅ 报表生成成功</h3>
<div id="analysis-result-info" style="font-size:13px; color:#666; margin-bottom:15px;"></div>
<a id="btn-download-report" href="api/analysis/download"
style="display:inline-block; padding: 10px 32px; background: #52c41a; color: white; border: none; border-radius: 4px; font-size: 14px; text-decoration: none; cursor: pointer;">
📥 下载分析报表
</a>
</div>
<div id="analysis-error" style="display:none; background: #fff2f0; border: 1px solid #ffccc7; padding: 20px; border-radius: 8px; text-align: center;">
<h3 style="color:#f5222d; margin:0 0 10px;">❌ 报表生成失败</h3>
<p id="analysis-error-msg" style="margin:0; color:#666;"></p>
</div>
</div>
<div id="welcome-message">
<p>欢迎来到问界门店运营数据分析平台。请从顶部导航选择功能进行操作。</p>
</div>
</div>
<h2 class="page-title">功能导航</h2>
<p class="page-subtitle">欢迎使用问界门店运营数据分析平台,请选择功能模块</p>
<div class="nav-cards">
<a class="nav-card" href="/ods">
<div class="nav-card-icon">&#128259;</div>
<h3>ODS 同步任务</h3>
<p>管理 ODS 层数据同步定时任务,查看执行历史与详情</p>
</a>
<a class="nav-card" href="/dw">
<div class="nav-card-icon">&#9881;</div>
<h3>DWS/DWM/DWA 任务</h3>
<p>触发 DWS/DWM/DWA 各层数据加工,支持增量/全量/日期范围</p>
</a>
<a class="nav-card" href="/analysis">
<div class="nav-card-icon">&#128202;</div>
<h3>问界生态系数分析</h3>
<p>上传门店列表与主机厂数据,自动查询产值并计算生态系数</p>
</a>
<a class="nav-card" href="/harmony">
<div class="nav-card-icon">&#127758;</div>
<h3>鸿蒙生态分析</h3>
<p>上传鸿蒙门店配置与产值表,计算渗透率达标系数与赔付金额</p>
</a>
</div>
</section>
</main>
<!-- 任务详情弹窗 (Modal) -->
<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/app.js"></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
# -*- coding: utf-8 -*-
"""
从已有分析报表中提取门店模板数据
数据源: 问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx
从 主表 提取: 门店、兜底指标、兜底类型、特殊情况1、特殊情况2
从 赔付方案 提取: 需达标转化率、赔付金额(非阶梯赔付)、兜底截止日期
从 阶梯赔付明细子表 解析: 阶梯赔付门店的赔付系数公式 → "阈值%,金额"格式
输出: app/templates/问界门店数据模板{序号}.xlsx
"""
import sys, io, re, math
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
from copy import copy
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
SRC = r'C:\Users\jiata\Desktop\问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx'
# 自动递增三位序号: 问界门店数据模板001.xlsx, 002.xlsx, ...
import os, glob
max_no = 0
for f in glob.glob('app/templates/问界门店数据模板[0-9][0-9][0-9].xlsx'):
try:
no = int(os.path.splitext(os.path.basename(f))[0][-3:])
max_no = max(max_no, no)
except ValueError:
pass
OUT = f'app/templates/问界门店数据模板{max_no + 1:03d}.xlsx'
# ── 1. 读取主表门店信息 ──
wb = load_workbook(SRC, data_only=True)
main_ws = wb['问界生态系数(6.26-7.5)&(7.1-7.5)']
stores = [] # [(store_name, baodi, baodi_type, special1, special2), ...]
for r in range(5, main_ws.max_row + 1):
sn = main_ws.cell(row=r, column=1).value
if not sn:
break
stores.append({
'门店': str(sn).strip(),
'兜底指标': str(main_ws.cell(row=r, column=2).value or '').strip(),
'兜底类型': str(main_ws.cell(row=r, column=3).value or '').strip(),
'特殊情况1': str(main_ws.cell(row=r, column=4).value or ''),
'特殊情况2': str(main_ws.cell(row=r, column=5).value or ''),
'兜底月份': str(main_ws.cell(row=r, column=49).value or '').strip(), # Col 49 (AW): 兜底月份
# 需达标转化率: 主表 AK/AL/AM (Col 37-39)
'需达标_整车': str(main_ws.cell(row=r, column=37).value or ''),
'需达标_安心包': str(main_ws.cell(row=r, column=38).value or ''),
'需达标_电池': str(main_ws.cell(row=r, column=39).value or ''),
# 赔付金额: 主表 AR/AS/AT (Col 44-46)
'赔付_整车': str(main_ws.cell(row=r, column=44).value or ''),
'赔付_安心包': str(main_ws.cell(row=r, column=45).value or ''),
'赔付_电池': str(main_ws.cell(row=r, column=46).value or ''),
})
print(f'主表门店数: {len(stores)}')
# ── 3. 解析阶梯赔付明细子表 (读取公式) ──
wb_formula = load_workbook(SRC, data_only=False)
step_ws = wb_formula['阶梯赔付明细子表']
step_store_group = {} # {store_name: group_id}
step_formulas = {} # {group_id: {row: {品: formula}}}
group_cols = {'整车延保': 12, '安心包': 13, '电池': 14} # L, M, N
group_id_map = {} # row -> group_id
current_group = 0
for r in range(2, step_ws.max_row + 1):
sn = step_ws.cell(row=r, column=1).value
if sn and str(sn).strip():
step_store_group[str(sn).strip()] = current_group
step_formulas.setdefault(current_group, {})
formulas = {}
for cat, col in group_cols.items():
f = step_ws.cell(row=r, column=col).value
formulas[cat] = str(f).strip() if f else ''
step_formulas[current_group][r] = formulas
else:
# 空行 → 新分组
has_content = any(step_ws.cell(row=r, column=c).value for c in range(1, 15))
if not has_content:
current_group += 1
print(f'阶梯赔付门店: {step_store_group}')
def parse_ladder_coefficient(formula_text, group_id):
"""解析阶梯赔付公式为 "阈值%,金额;阈值%,金额" 格式"""
if not formula_text or not formula_text.startswith('='):
return formula_text
try:
parts = re.findall(r'<(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)\*', formula_text)
if parts:
return ';'.join(f'{t}%,{a}' for t, a in parts)
return ''
except Exception:
return formula_text
# 阶梯分组 → 赔付系数映射
LADDER_COEFF = {
# Group 0: 骏业/骏智系列 (Row 3-6)
0: {'整车延保': '60%,1500;65%,1000', '安心包': '15%,800;20%,600', '电池': '11%,800;15%,600'},
# Group 1: 山西聚驰 (Row 10)
1: {'整车延保': '45%,3420;50%,1500', '安心包': '40%,1154;50%,1000', '电池': '15%,500'},
# Group 2: 山西聚锦驰/长治聚鑫驰 (Row 13-14)
2: {'整车延保': '50%,2000;60%,1000', '安心包': '20%,800', '电池': '15%,500'},
}
for sn, gid in step_store_group.items():
print(f' 阶梯赔付: {sn} → 组{gid}: {LADDER_COEFF.get(gid)}')
# ── 4. 合并数据,输出模板 ──
# 9列: A=门店, B=兜底指标, C=兜底类型, D=特殊情况1, E=特殊情况2,
# F=整车延保, G=安心包, H=电池电池(赔付系数 F1:H1), I=兜底截止日期
header_fill = PatternFill('solid', fgColor='4472C4')
header_font = Font(name='微软雅黑', bold=True, color='FFFFFF', size=10)
sub_fill = PatternFill('solid', fgColor='D6E4F0')
sub_font = Font(name='微软雅黑', bold=True, size=10)
data_font = Font(name='微软雅黑', size=10)
thin_border = Border(
left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin')
)
center_align = Alignment(horizontal='center', vertical='center', wrap_text=True)
def write_header_cell(ws, row, col, value):
c = ws.cell(row=row, column=col, value=value)
c.font = header_font
c.fill = header_fill
c.alignment = center_align
c.border = thin_border
return c
def write_sub_cell(ws, row, col, value):
c = ws.cell(row=row, column=col, value=value)
c.font = sub_font
c.fill = sub_fill
c.alignment = center_align
c.border = thin_border
return c
def write_data_cell(ws, row, col, value):
c = ws.cell(row=row, column=col, value=value)
c.font = data_font
c.alignment = center_align
c.border = thin_border
return c
# 创建输出工作簿
from openpyxl import Workbook
owb = Workbook()
ows = owb.active
ows.title = '门店信息-赔付信息'
# Row1 表头: A-E 合并 A1:A2 .. E1:E2, F1:H1 合并为"赔付系数", I1:I2 合并
write_header_cell(ows, 1, 1, '门店')
write_header_cell(ows, 1, 2, '兜底指标')
write_header_cell(ows, 1, 3, '兜底类型')
write_header_cell(ows, 1, 4, '特殊情况1')
write_header_cell(ows, 1, 5, '特殊情况2')
write_header_cell(ows, 1, 6, '赔付系数')
ows.merge_cells('F1:H1')
write_header_cell(ows, 1, 9, '兜底截止日期')
for col_letter in ['A', 'B', 'C', 'D', 'E', 'I']:
ows.merge_cells(f'{col_letter}1:{col_letter}2')
# Row2 子表头
write_sub_cell(ows, 2, 6, '整车延保')
write_sub_cell(ows, 2, 7, '安心包')
write_sub_cell(ows, 2, 8, '电池电池')
# 列宽
ows.column_dimensions['A'].width = 35
ows.column_dimensions['B'].width = 30
ows.column_dimensions['C'].width = 10
ows.column_dimensions['D'].width = 14
ows.column_dimensions['E'].width = 14
ows.column_dimensions['F'].width = 18
ows.column_dimensions['G'].width = 18
ows.column_dimensions['H'].width = 18
ows.column_dimensions['I'].width = 14
# Row3+: 写入数据
missing = 0
step_count = 0
row_num = 3
for s in stores:
sn = s['门店']
write_data_cell(ows, row_num, 1, sn)
write_data_cell(ows, row_num, 2, s['兜底指标'])
write_data_cell(ows, row_num, 3, s['兜底类型'])
write_data_cell(ows, row_num, 4, s['特殊情况1'] if s['特殊情况1'] and s['特殊情况1'] != 'None' else '')
write_data_cell(ows, row_num, 5, s['特殊情况2'] if s['特殊情况2'] and s['特殊情况2'] != 'None' else '')
# 赔付系数
is_ladder = s['特殊情况1'] and '阶梯' in s['特殊情况1']
if is_ladder and sn in step_store_group:
gid = step_store_group[sn]
coeff = LADDER_COEFF.get(gid, {})
write_data_cell(ows, row_num, 6, coeff.get('整车延保', ''))
write_data_cell(ows, row_num, 7, coeff.get('安心包', ''))
write_data_cell(ows, row_num, 8, coeff.get('电池', ''))
step_count += 1
else:
# 从主表取 需达标转化率 (AK/AL/AM) 和 赔付金额 (AR/AS/AT)
target_yb = s.get('需达标_整车', '').replace('None', '')
target_axb = s.get('需达标_安心包', '').replace('None', '')
target_bat = s.get('需达标_电池', '').replace('None', '')
pf_yb = s.get('赔付_整车', '').replace('None', '')
pf_axb = s.get('赔付_安心包', '').replace('None', '')
pf_bat = s.get('赔付_电池', '').replace('None', '')
# 构造 "阈值%,金额" 格式 (target 是小数如0.5, 需转为50%)
def fmt_coeff(target, amount):
if not amount or amount in ('', '0', '0.0'):
return '0%,0'
if '阶段赔付' in amount:
return '阶段赔付'
try:
t_pct = str(round(float(target) * 100, 1)).rstrip('0').rstrip('.')
except (ValueError, TypeError):
t_pct = ''
if not t_pct:
return ''
return f'{t_pct}%,{amount}'.rstrip('.,')
write_data_cell(ows, row_num, 6, fmt_coeff(target_yb, pf_yb))
write_data_cell(ows, row_num, 7, fmt_coeff(target_axb, pf_axb))
write_data_cell(ows, row_num, 8, fmt_coeff(target_bat, pf_bat))
write_data_cell(ows, row_num, 9, s.get('兜底月份', ''))
row_num += 1
# 设置行高 (默认字体大小10, 1.2倍行高 ≈ 15)
default_row_height = 15
for r in range(1, row_num):
ows.row_dimensions[r].height = default_row_height
# 冻结前两行表头
ows.freeze_panes = 'A3'
owb.save(OUT)
print(f'\n输出: {OUT}')
print(f'总行数: {row_num - 3}, 缺失门店: {missing}, 阶梯赔付: {step_count}')
wb.close()
wb_formula.close()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!