Commit b9c2d6cc by root

Merge branch 'master' of https://gitee.com/komelio/daw

Conflicts:
	temp_uploads/harmony/20260724/鸿蒙-主机厂数据-0701~0705.xlsx
	temp_uploads/reports/20260724/问界-分析-输出-0626~0723.xlsx
2 parents 711fa904 95e907b1
Showing 49 changed files with 1026 additions and 399 deletions
......@@ -289,15 +289,54 @@ def _load_store_df_from_batch(batch_no: str) -> "pd.DataFrame":
conn.close()
def _load_oem_factory_from_batch(batch_no: str) -> dict:
"""从DB加载OEM交付批次,返回 {sheet_name: DataFrame} 格式(兼容read_factory_data输出)"""
def _format_factory_sheet_name(start: str, end: str) -> str:
"""将 yyyy-MM-dd 日期范围格式化为 sheet 名,如 626-722"""
from datetime import datetime
s = datetime.strptime(str(start)[:10], "%Y-%m-%d")
e = datetime.strptime(str(end)[:10], "%Y-%m-%d")
return f"{s.month}{s.day:02d}-{e.month}{e.day:02d}"
def _is_ecology_period(start: str, period_type: str = "") -> bool:
"""判断主机厂数据周期是否为生态月"""
pt = (period_type or "").strip().lower()
if pt == "ecology":
return True
if pt == "nature":
return False
if start and len(str(start)) >= 10:
return int(str(start)[8:10]) >= 20
return False
def _oem_rows_to_factory_df(rows) -> "pd.DataFrame":
import pandas as pd
df = pd.DataFrame(rows)
df['门店名'] = df['store_name']
df['厅店代码'] = df['store_code']
df['区域(省)'] = df['province']
df['交付数'] = pd.to_numeric(df['delivery_count'], errors='coerce').fillna(0)
df['整车延保采购数'] = pd.to_numeric(df['ew_purchase_count'], errors='coerce').fillna(0)
df['安心包采购数'] = pd.to_numeric(df['ax_purchase_count'], errors='coerce').fillna(0)
df['电池延保采购数'] = pd.to_numeric(df['battery_purchase_count'], errors='coerce').fillna(0)
df['轮胎险采购数'] = pd.to_numeric(df['tire_purchase_count'], errors='coerce').fillna(0)
return df.drop_duplicates(subset=["门店名"], keep="first")
def _load_oem_factory_from_batch(batch_no: str) -> tuple:
"""从DB加载OEM交付批次,返回 ({sheet_name: DataFrame}, batch_meta)"""
from app.services.upload_service import _get_conn
import pandas as pd
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute("SELECT id FROM upload_batch WHERE batch_no=%s AND data_type='oem_delivery'", (batch_no,))
cur.execute(
"""SELECT id, data_period_start, data_period_end, period_type
FROM upload_batch
WHERE batch_no=%s AND data_type='oem_delivery' AND status != 3""",
(batch_no,),
)
batch = cur.fetchone()
if not batch:
raise HTTPException(status_code=404, detail=f"批次 {batch_no} 不存在")
......@@ -307,23 +346,56 @@ def _load_oem_factory_from_batch(batch_no: str) -> dict:
delivery_count, ew_purchase_count, ax_purchase_count,
battery_purchase_count, tire_purchase_count
FROM oem_delivery_data WHERE batch_id=%s""",
(batch["id"],))
(batch["id"],),
)
rows = cur.fetchall()
if not rows:
return {}
return {}, {}
start = str(batch.get("data_period_start") or "")[:10]
end = str(batch.get("data_period_end") or "")[:10]
sheet_name = _format_factory_sheet_name(start, end) if start and end else batch_no
meta = {
"period_type": batch.get("period_type") or "",
"data_period_start": start,
"data_period_end": end,
}
return {sheet_name: _oem_rows_to_factory_df(rows)}, meta
finally:
conn.close()
df = pd.DataFrame(rows)
df['门店名'] = df['store_name']
df['厅店代码'] = df['store_code']
df['区域(省)'] = df['province']
df['交付数'] = pd.to_numeric(df['delivery_count'], errors='coerce').fillna(0)
df['整车延保采购数'] = pd.to_numeric(df['ew_purchase_count'], errors='coerce').fillna(0)
df['安心包采购数'] = pd.to_numeric(df['ax_purchase_count'], errors='coerce').fillna(0)
df['电池延保采购数'] = pd.to_numeric(df['battery_purchase_count'], errors='coerce').fillna(0)
df['轮胎险采购数'] = pd.to_numeric(df['tire_purchase_count'], errors='coerce').fillna(0)
# 去重
df = df.drop_duplicates(subset=["门店名"], keep="first")
return {"Sheet1": df}
def _load_oem_factory_by_period(brand: str, start: str, end: str, period_type: str = "") -> dict:
"""按数据周期从DB查找主机厂批次并加载"""
from app.services.upload_service import _get_conn
if not start or not end:
return {}
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute(
"""SELECT batch_no FROM upload_batch
WHERE brand=%s AND data_type='oem_delivery' AND status != 3
AND data_period_start=%s AND data_period_end=%s
AND IFNULL(period_type,'')=%s
ORDER BY id DESC LIMIT 1""",
(brand, start[:10], end[:10], period_type or ""),
)
row = cur.fetchone()
if not row and period_type:
cur.execute(
"""SELECT batch_no FROM upload_batch
WHERE brand=%s AND data_type='oem_delivery' AND status != 3
AND data_period_start=%s AND data_period_end=%s
ORDER BY id DESC LIMIT 1""",
(brand, start[:10], end[:10]),
)
row = cur.fetchone()
if not row:
return {}
sheets, _ = _load_oem_factory_from_batch(row["batch_no"])
return sheets
finally:
conn.close()
......@@ -364,7 +436,9 @@ async def download_analysis_template(template_type: str):
_analysis_store_file = None # 缓存门店文件路径
_analysis_factory_file = None # 缓存主机厂文件路径(含生态月+自然月sheet)
_analysis_factory_file = None # 缓存合并主机厂文件(多 sheet,兼容旧逻辑)
_analysis_ecology_factory_file = None
_analysis_nature_factory_file = None
def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str:
......@@ -395,13 +469,16 @@ def _build_dated_filename(original_name: str, prefix: str, start_date: str = Non
async def analysis_upload(
store_file: Optional[UploadFile] = File(None),
factory_file: Optional[UploadFile] = File(None),
ecology_factory_file: Optional[UploadFile] = File(None),
nature_factory_file: Optional[UploadFile] = File(None),
ecology_start_date: str = Form(None),
ecology_end_date: str = Form(None),
nature_start_date: str = Form(None),
nature_end_date: str = Form(None),
):
"""上传门店数据、主机厂数据(含生态月+自然月多sheet,系统自动按sheet名拆分)"""
"""上传门店数据、主机厂数据(生态月/自然月可分开上传,也支持多 sheet 合并文件)"""
global _analysis_store_file, _analysis_factory_file
global _analysis_ecology_factory_file, _analysis_nature_factory_file
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
......@@ -412,14 +489,39 @@ async def analysis_upload(
_analysis_store_file = file_path
result["messages"].append(f"门店列表已上传: {store_file.filename}")
if factory_file and factory_file.filename:
# 主机厂数据使用生态月日期范围命名
fname = _build_dated_filename(factory_file.filename, "analysis_factory", ecology_start_date, ecology_end_date)
cat = "analysis" if (ecology_start_date and ecology_end_date) else "drafts"
def _save_factory_upload(upload_file, prefix, start_date, end_date):
global _analysis_ecology_factory_file, _analysis_nature_factory_file, _analysis_factory_file
fname = _build_dated_filename(upload_file.filename, prefix, start_date, end_date)
cat = "analysis" if (start_date and end_date) else "drafts"
file_path = _date_path(fname, category=cat)
with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f)
_analysis_factory_file = file_path
shutil.copyfileobj(upload_file.file, f)
if prefix == "analysis_factory_ecology":
_analysis_ecology_factory_file = file_path
elif prefix == "analysis_factory_nature":
_analysis_nature_factory_file = file_path
else:
_analysis_factory_file = file_path
return file_path
if ecology_factory_file and ecology_factory_file.filename:
_save_factory_upload(
ecology_factory_file, "analysis_factory_ecology",
ecology_start_date, ecology_end_date,
)
result["messages"].append(f"生态月主机厂数据已上传: {ecology_factory_file.filename}")
if nature_factory_file and nature_factory_file.filename:
_save_factory_upload(
nature_factory_file, "analysis_factory_nature",
nature_start_date, nature_end_date,
)
result["messages"].append(f"自然月主机厂数据已上传: {nature_factory_file.filename}")
if factory_file and factory_file.filename:
file_path = _save_factory_upload(
factory_file, "analysis_factory", ecology_start_date, ecology_end_date,
)
try:
import pandas as pd
sheets = pd.read_excel(file_path, sheet_name=None)
......@@ -448,17 +550,18 @@ async def analysis_save_batch(
brand: str = Form("问界"),
):
"""将分析页面上传的文件保存为历史批次,便于下次复用"""
if file_type not in ("store", "factory"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory")
if file_type not in ("store", "factory", "ecology", "nature"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory/ecology/nature")
if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件")
# 保存为历史时,按命名规范整理文件名
if file_type == "store":
formal_name = build_store_filename(brand, period_start, period_end)
oem_period_type = ""
else:
# 主机厂数据(含生态月+自然月,用生态月日期范围命名)
formal_name = build_factory_filename(brand, "", period_start, period_end)
oem_period_type = period_type or ("ecology" if file_type == "ecology" else "nature" if file_type == "nature" else "")
formal_name = build_factory_filename(brand, oem_period_type, period_start, period_end)
# 确保文件名唯一并保存到 batch 目录
file_path = _date_path(formal_name, category="batch")
......@@ -490,7 +593,7 @@ async def analysis_save_batch(
brand=brand,
data_period_start=period_start or "",
data_period_end=period_end or "",
period_type=period_type or "",
period_type=oem_period_type,
file_size=file_size,
remark=file_path
)
......@@ -515,9 +618,12 @@ async def analysis_generate(
nature_end_date: str = Form(None),
store_batch_no: str = Form(None),
factory_batch_no: str = Form(None),
ecology_factory_batch_no: str = Form(None),
nature_factory_batch_no: str = Form(None),
):
"""根据已上传的数据或历史批次生成生态系数分析报表(主机厂数据含多sheet自动拆分生态/自然月)"""
"""根据已上传的数据或历史批次生成生态系数分析报表"""
global _analysis_store_file, _analysis_factory_file
global _analysis_ecology_factory_file, _analysis_nature_factory_file
# 加载store_df:优先批次DB数据,其次文件,最后默认模板
if store_batch_no:
......@@ -532,26 +638,53 @@ async def analysis_generate(
else:
raise HTTPException(status_code=400, detail="请先上传门店列表文件")
# 加载主机厂数据:优先批次DB数据,其次文件
# 主机厂数据含多sheet(生态月+自然月),由 build_report 自动按sheet名拆分
factory_data = {}
if factory_batch_no:
factory_data = _load_oem_factory_from_batch(factory_batch_no)
elif _analysis_factory_file and os.path.exists(_analysis_factory_file):
factory_data = AnalysisService.read_factory_data(_analysis_factory_file)
# 加载主机厂数据:批次 / 文件 / 按日期从DB补全
ecology_factory = {}
nature_factory = {}
if not factory_data:
if ecology_factory_batch_no:
sheets, _ = _load_oem_factory_from_batch(ecology_factory_batch_no)
ecology_factory.update(sheets)
if nature_factory_batch_no:
sheets, _ = _load_oem_factory_from_batch(nature_factory_batch_no)
nature_factory.update(sheets)
# 兼容旧版单批次选择
if factory_batch_no and not ecology_factory_batch_no and not nature_factory_batch_no:
sheets, meta = _load_oem_factory_from_batch(factory_batch_no)
if _is_ecology_period(meta.get("data_period_start"), meta.get("period_type")):
ecology_factory.update(sheets)
else:
nature_factory.update(sheets)
if _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file):
ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file)
if _analysis_nature_factory_file and os.path.exists(_analysis_nature_factory_file):
nature_factory = AnalysisService.read_factory_data(_analysis_nature_factory_file)
if _analysis_factory_file and os.path.exists(_analysis_factory_file):
if not ecology_factory and not nature_factory:
ecology_factory = AnalysisService.read_factory_data(_analysis_factory_file)
elif not ecology_factory:
ecology_factory = AnalysisService.read_factory_data(_analysis_factory_file)
elif not nature_factory:
nature_factory = AnalysisService.read_factory_data(_analysis_factory_file)
if ecology_start_date and ecology_end_date and not ecology_factory:
ecology_factory = _load_oem_factory_by_period(
"问界", ecology_start_date, ecology_end_date, "ecology")
if nature_start_date and nature_end_date and not nature_factory:
nature_factory = _load_oem_factory_by_period(
"问界", nature_start_date, nature_end_date, "nature")
if not ecology_factory and not nature_factory:
raise HTTPException(status_code=400, detail="请上传或选择主机厂数据文件")
# 将所有主机厂sheet数据作为 ecology_factory 传入,build_report 会自动拆分
ecology_factory = factory_data
nature_factory = {}
try:
output_path = AnalysisService.build_report(
store_df,
ecology_factory=ecology_factory or {},
nature_factory=nature_factory or {},
ecology_factory=ecology_factory,
nature_factory=nature_factory,
ecology_start=ecology_start_date or None,
ecology_end=ecology_end_date or None,
nature_start=nature_start_date or None,
......@@ -569,7 +702,7 @@ async def analysis_generate(
"download_url": f"api/analysis/download?file={os.path.basename(output_path)}",
"ecology_store_count": len(ecology_stores),
"nature_store_count": len(nature_stores),
"factory_sheets": list(factory_data.keys()) if factory_data else [],
"factory_sheets": list(ecology_factory.keys()) + list(nature_factory.keys()),
}
except Exception as e:
logger.error(f"Analysis generate failed: {e}", exc_info=True)
......@@ -610,10 +743,11 @@ async def analysis_download(file: str = Query(None)):
@router.post("/analysis/preview-file")
async def analysis_preview_file(
file_type: str = Form(...), # "store" or "factory"
file_type: str = Form(...), # "store" or "factory" or "ecology" or "nature"
file: UploadFile = File(...),
):
"""上传分析文件并返回解析后的预览数据"""
"""上传分析文件并返回解析后的预览数据(factory 类型返回多 sheet)"""
import pandas as pd
file_path = _date_path(f"_preview_{file.filename}", category="drafts")
try:
with open(file_path, "wb") as f:
......@@ -621,18 +755,25 @@ async def analysis_preview_file(
if file_type == "store":
df = AnalysisService.read_store_list(file_path)
else:
data = AnalysisService.read_factory_data(file_path)
sheet_names = list(data.keys())
if sheet_names:
df = data[sheet_names[0]]
else:
df = pd.DataFrame()
import pandas as pd
rows = df.head(100).fillna("").to_dict(orient="records")
columns = list(df.columns)
return {"status": "success", "data": {"columns": columns, "rows": rows, "total": len(df)}}
rows = df.head(100).fillna("").to_dict(orient="records")
columns = list(df.columns)
return {"status": "success", "data": {"columns": columns, "rows": rows, "total": len(df)}}
data = AnalysisService.read_factory_data(file_path)
sheets_payload = {}
for name, df in data.items():
sheets_payload[name] = {
"columns": list(df.columns),
"rows": df.head(100).fillna("").to_dict(orient="records"),
"total": len(df),
}
return {
"status": "success",
"data": {
"sheets": sheets_payload,
"sheet_names": list(sheets_payload.keys()),
},
}
except Exception as e:
logger.error(f"Analysis preview file failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"文件解析失败: {str(e)}")
......@@ -652,7 +793,9 @@ async def analysis_batch_data(batch_no: str = Query(...)):
try:
with conn.cursor() as cur:
cur.execute(
"""SELECT id, batch_no, data_type FROM upload_batch
"""SELECT id, batch_no, data_type, period_type,
data_period_start, data_period_end, file_name
FROM upload_batch
WHERE batch_no = %s AND status != 3""",
(batch_no,),
)
......@@ -702,7 +845,15 @@ async def analysis_batch_data(batch_no: str = Query(...)):
return {
"status": "success",
"data": {"columns": columns, "rows": clean_rows, "total": len(rows)},
"data": {
"columns": columns,
"rows": clean_rows,
"total": len(rows),
"period_type": batch.get("period_type") or "",
"data_period_start": str(batch.get("data_period_start") or "")[:10],
"data_period_end": str(batch.get("data_period_end") or "")[:10],
"file_name": batch.get("file_name") or "",
},
}
finally:
conn.close()
......@@ -736,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),
......@@ -783,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:
......@@ -796,7 +987,8 @@ async def harmony_generate(
# 加载factory_df:优先批次DB数据,其次文件
factory_df = None
if factory_batch_no:
factory_df = _load_oem_factory_from_batch(factory_batch_no)
sheets, _ = _load_oem_factory_from_batch(factory_batch_no)
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)
......@@ -808,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:
......
......@@ -407,13 +407,27 @@ class AnalysisService:
start = f"{current_year}-{m1:02d}-{d1:02d}"
end = f"{current_year}-{m2:02d}-{d2:02d}"
return start, end
# 格式2: MDD-MDD (如 626-722,月份1位+日期2位)
m = re.match(r'(\d{1,2})(\d{1,2})\s*[-~]\s*(\d{1,2})(\d{1,2})', s)
# 格式2: MDD-MDD / MMDD-MMDD (如 626-722、0701-0723)
m = re.match(r'(\d{3,4})\s*[-~]\s*(\d{3,4})', s)
if m:
m1, d1, m2, d2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
start = f"{current_year}-{m1:02d}-{d1:02d}"
end = f"{current_year}-{m2:02d}-{d2:02d}"
return start, end
def _parse_mdd_token(token: str):
token = token.strip()
if len(token) == 3:
return int(token[0]), int(token[1:3])
if len(token) == 4:
month = int(token[:2])
day = int(token[2:4])
if 1 <= month <= 12:
return month, day
return int(token[0]), int(token[1:4])
return None, None
m1, d1 = _parse_mdd_token(m.group(1))
m2, d2 = _parse_mdd_token(m.group(2))
if m1 and d1 and m2 and d2:
start = f"{current_year}-{m1:02d}-{d1:02d}"
end = f"{current_year}-{m2:02d}-{d2:02d}"
return start, end
logger.warning(f"Unable to parse date range: {date_range_str}, using yesterday")
yesterday = (date.today() - timedelta(days=1)).strftime('%Y-%m-%d')
return yesterday, yesterday
......@@ -966,10 +980,8 @@ class AnalysisService:
nat_sheets[sn] = df
if not nature_start:
nature_start, nature_end = AnalysisService._parse_date_range(sn)
if eco_sheets:
ecology_factory = eco_sheets
if nat_sheets:
nature_factory = nat_sheets
ecology_factory = eco_sheets
nature_factory = nat_sheets
logger.info(f"Auto-split factory sheets: ecology={list(eco_sheets.keys())}, "
f"nature={list(nat_sheets.keys())}")
......@@ -1032,48 +1044,48 @@ class AnalysisService:
cell.fill = SEPARATOR_FILL
cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center")
# 标签文字放在中间列(约29列),视觉上居中
ws.cell(row=row, column=29).value = label_text
ws.cell(row=row, column=27).font = SEPARATOR_FONT
ws.row_dimensions[row].height = 24
next_row = 4
def _write_section(ws, next_row, label_text, store_subset, factory_sheets,
start_date, end_date, track_first_data=False):
"""标签行 + 数据行(每种数据上方仅一行蓝色标签)"""
nonlocal first_data_row
_write_separator(ws, next_row, label_text)
next_row += 1
if track_first_data and first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet(
ws, store_subset, factory_sheets,
start_date, end_date, formula_map, skip_external_cols, start_row=next_row)
return next_row
next_row = 5
first_data_row = None
# 生态数据标签行
eco_label_text = f"▲ 生态数据({ecology_start} ~ {ecology_end})" if ecology_start and ecology_end else "▲ 生态数据"
if has_ecology:
_write_separator(ws, next_row, eco_label_text)
next_row += 1
eco_label_text = "▲ 生态月数据"
nat_label_text = "▼ 自然月数据"
# 处理生态数据(上部)
# 生态月数据(上部)
if has_ecology:
if first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet(
ws, ecology_stores, ecology_factory,
ecology_start, ecology_end, formula_map, skip_external_cols, start_row=next_row)
next_row = _write_section(
ws, next_row, eco_label_text,
ecology_stores, ecology_factory,
ecology_start, ecology_end, track_first_data=True,
)
else:
reason = "no stores" if len(ecology_stores) == 0 else "no factory data"
logger.info(f"Skipping ecology section ({reason})")
# 自然月数据标签行(中间隔离行)
nat_label_text = f"▼ 自然月数据({nature_start} ~ {nature_end})" if nature_start and nature_end else "▼ 自然月数据"
if has_ecology and has_nature:
_write_separator(ws, next_row, nat_label_text)
next_row += 1
# 处理自然月数据(下部)
# 自然月数据(下部,与生态月拼在同一表)
if has_nature:
# 如果仅自然月(无生态数据),在顶部也加标签
if not has_ecology:
_write_separator(ws, next_row, nat_label_text)
next_row += 1
if first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet(
ws, nature_stores, nature_factory,
nature_start, nature_end, formula_map, skip_external_cols, start_row=next_row)
next_row = _write_section(
ws, next_row, nat_label_text,
nature_stores, nature_factory,
nature_start, nature_end,
track_first_data=(first_data_row is None),
)
else:
reason = "no stores" if len(nature_stores) == 0 else "no factory data"
logger.info(f"Skipping nature section ({reason})")
......@@ -1086,6 +1098,9 @@ class AnalysisService:
last_col_letter = get_column_letter(len(OUTPUT_HEADERS))
ws.auto_filter.ref = f"A3:{last_col_letter}{next_row - 1}"
# 冻结窗格:D5(固定前3行表头 + A~C列)
ws.freeze_panes = "D5"
wb.save(output_path)
logger.info(f"Report generated: {output_path}")
return output_path
......
......@@ -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("需达标转化率_安心包")),
......
......@@ -254,6 +254,31 @@
margin-top: 10px;
}
.preview-sheet-tabs {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 8px 16px;
border-bottom: 1px solid #e8e8e8;
background: #fafafa;
}
.preview-sheet-tab {
padding: 4px 12px;
font-size: 12px;
cursor: pointer;
border-radius: 4px;
border: 1px solid #d9d9d9;
background: #fff;
color: #555;
}
.preview-sheet-tab.active {
background: #1890ff;
border-color: #1890ff;
color: #fff;
}
.preview-sheet-tab.ecology:not(.active) { border-color: #91d5ff; color: #1890ff; }
.preview-sheet-tab.nature:not(.active) { border-color: #b7eb8f; color: #52c41a; }
@media (max-width: 900px) {
.analysis-layout { flex-direction: column; height: auto; }
.left-panel { width: 100%; min-width: 0; }
......@@ -270,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>
......@@ -303,7 +329,7 @@
<button class="btn-save-batch" id="btn-save-store" style="display:none;" onclick="saveBatch('store')">&#x1f4be; 保存为历史批次</button>
</div>
<!-- 步骤2: 主机厂数据(生态+自然月合并为单文件) -->
<!-- 步骤2: 主机厂数据(单文件多 Sheet,按 sheet 名区分生态月/自然月) -->
<div class="step-card" id="step2-card">
<div class="step-title">&#9313; 步骤2: 主机厂数据(含生态月+自然月)</div>
<div class="step-row">
......@@ -315,7 +341,7 @@
<span class="step-or">或</span>
<div class="step-upload-zone" id="factory-drop-zone" onclick="document.getElementById('factory-file-input').click()">
<input type="file" id="factory-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange()">
&#x1f4c1; <span id="factory-file-name">点击上传主机厂数据(含生态月+自然月sheet)</span>
&#x1f4c1; <span id="factory-file-name">点击上传主机厂数据(含生态月+自然月 sheet)</span>
</div>
<a class="btn-download-tpl" href="./api/analysis/template/factory">&#x1f4e5; 模板</a>
</div>
......@@ -331,7 +357,7 @@
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="nature-end-date" title="自然月结束日期">
</div>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份含多sheet的主机厂数据,系统自动按sheet名日期拆分生态月/自然月数据</p>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份含多 Sheet 的主机厂 Excel,系统按 Sheet 名日期自动识别生态月/自然月;右侧预览可切换 Sheet</p>
<button class="btn-save-batch" id="btn-save-factory" style="display:none;" onclick="saveBatch('factory')">&#x1f4be; 保存为历史批次</button>
</div>
......@@ -340,7 +366,7 @@
<button class="btn-generate" id="btn-generate-report">
&#x1f680; 开始生成分析报表
</button>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份主机厂数据(含多sheet),系统自动按sheet名日期拆分生态月/自然月数据,按兜底截止日期分组门店</p>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份主机厂数据(含多 Sheet),系统按 Sheet 名自动拆分生态月/自然月,按兜底截止日期分组门店</p>
</div>
<!-- 生成结果 -->
......@@ -362,6 +388,7 @@
<span id="preview-count" style="font-size:11px;color:#999;"></span>
</div>
<div class="right-panel-meta" id="preview-meta" style="display:none;"></div>
<div class="preview-sheet-tabs" id="preview-sheet-tabs" style="display:none;"></div>
<div class="right-panel-body" id="preview-body">
<div class="right-panel-empty" id="preview-empty">
请在左侧选择历史批次或上传文件,数据将在此处预览
......@@ -431,23 +458,37 @@
await previewFile(formData, '门店列表 - ' + name);
};
// ========== 步骤2: 主机厂数据(单文件,含生态月+自然月sheet) ==========
// ========== 步骤2: 主机厂数据(单文件多 Sheet) ==========
window.onFactoryBatchSelect = async function() {
const sel = document.getElementById('factory-batch-select');
if (!sel.value) return;
highlightStep('step2-card');
document.getElementById('factory-file-input').value = '';
document.getElementById('factory-file-name').textContent = '点击上传主机厂数据(含生态月+自然月 sheet)';
document.getElementById('factory-drop-zone').classList.remove('has-file');
const opt = sel.options[sel.selectedIndex];
if (opt.dataset.periodStart) {
document.getElementById('ecology-start-date').value = opt.dataset.periodStart;
document.getElementById('nature-start-date').value = opt.dataset.periodStart;
}
if (opt.dataset.periodEnd) {
document.getElementById('ecology-end-date').value = opt.dataset.periodEnd;
document.getElementById('nature-end-date').value = opt.dataset.periodEnd;
const ps = opt.dataset.periodStart || '';
const pe = opt.dataset.periodEnd || '';
const pt = opt.dataset.periodType || '';
if (ps && pe) {
if (pt === 'ecology') {
document.getElementById('ecology-start-date').value = ps;
document.getElementById('ecology-end-date').value = pe;
} else if (pt === 'nature') {
document.getElementById('nature-start-date').value = ps;
document.getElementById('nature-end-date').value = pe;
} else {
document.getElementById('ecology-start-date').value = ps;
document.getElementById('ecology-end-date').value = pe;
document.getElementById('nature-start-date').value = ps;
document.getElementById('nature-end-date').value = pe;
}
}
const periodLabel = pt === 'ecology' ? '生态月' : pt === 'nature' ? '自然月' : '';
await loadBatchPreview(sel.value, '主机厂数据 - 历史批次', {
type: '主机厂交付数据',
period: opt.dataset.periodStart ? `${opt.dataset.periodStart} ~ ${opt.dataset.periodEnd}` : '',
periodType: periodLabel,
period: ps ? `${ps} ~ ${pe}` : '',
source: opt.textContent.split(' [')[0],
});
};
......@@ -465,7 +506,10 @@
const formData = new FormData();
formData.append('file_type', 'factory');
formData.append('file', input.files[0]);
await previewFile(formData, '主机厂数据 - ' + name);
await previewFile(formData, '主机厂数据 - ' + name, {
type: '主机厂交付数据',
source: name,
});
};
// ========== 生成报表 ==========
......@@ -485,10 +529,8 @@
const hasStoreBatch = storeBatchSel && storeBatchSel.value;
const hasFactoryBatch = factoryBatchSel && factoryBatchSel.value;
const hasFactory = hasFactoryFile || hasFactoryBatch;
if (!hasFactory) {
alert('请上传或选择主机厂数据(步骤2)');
if (!hasFactoryFile && !hasFactoryBatch) {
alert('请上传或选择主机厂数据(步骤2)');
return;
}
......@@ -581,11 +623,21 @@
opt.value = r.batch_no;
opt.dataset.periodStart = r.data_period_start || '';
opt.dataset.periodEnd = r.data_period_end || '';
opt.textContent = `${r.file_name || r.batch_no} [${r.data_period_start}~${r.data_period_end}]`;
opt.dataset.periodType = periodTypeOfRow(r);
const tag = periodTypeOfRow(r) === 'ecology' ? '生态月' : '自然月';
opt.textContent = `[${tag}] ${r.file_name || r.batch_no} [${r.data_period_start}~${r.data_period_end}]`;
sel.appendChild(opt);
});
}
function periodTypeOfRow(r) {
const pt = (r.period_type || '').toLowerCase();
if (pt === 'ecology') return 'ecology';
if (pt === 'nature') return 'nature';
const day = parseInt((r.data_period_start || '').slice(8, 10), 10);
return day >= 20 ? 'ecology' : 'nature';
}
if (storeData.status === 'success') {
fillSelect('store-batch-select', storeData.data);
}
......@@ -604,7 +656,13 @@
const res = await fetch(window.API_BASE + '/analysis/batch-data?batch_no=' + encodeURIComponent(batchNo));
const data = await res.json();
if (data.status === 'success') {
renderPreviewTable(data.data, title, meta);
const batchMeta = { ...(meta || {}) };
if (data.data.period_type === 'ecology') batchMeta.periodType = '生态月';
else if (data.data.period_type === 'nature') batchMeta.periodType = '自然月';
if (!batchMeta.period && data.data.data_period_start) {
batchMeta.period = `${data.data.data_period_start} ~ ${data.data.data_period_end}`;
}
renderPreviewTable(data.data, title, batchMeta);
} else {
showPreviewError(data.detail || '加载失败');
}
......@@ -614,13 +672,37 @@
}
}
async function previewFile(formData, title) {
function inferSheetPeriodType(sheetName) {
const s = String(sheetName || '').trim().replace(/[()()]/g, '');
const m = s.match(/(\d{3,4})\s*[-~]\s*(\d{3,4})/);
if (!m) return '';
const token = m[1];
let day;
if (token.length === 3) day = parseInt(token.slice(1), 10);
else day = parseInt(token.slice(2), 10);
if (Number.isNaN(day)) return '';
return day >= 20 ? 'ecology' : 'nature';
}
function sheetPeriodLabel(sheetName) {
const pt = inferSheetPeriodType(sheetName);
if (pt === 'ecology') return '生态月';
if (pt === 'nature') return '自然月';
return '';
}
function formatSheetTabLabel(sheetName) {
const label = sheetPeriodLabel(sheetName);
return label ? `${sheetName} (${label})` : sheetName;
}
async function previewFile(formData, title, meta) {
showPreviewLoading(title);
try {
const res = await fetch(window.API_BASE + '/analysis/preview-file', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
renderPreviewTable(data.data, title);
renderPreviewTable(data.data, title, meta);
} else {
showPreviewError(data.detail || '解析失败');
}
......@@ -630,10 +712,85 @@
}
}
let _previewSheetsCache = null;
let _previewActiveSheet = null;
let _previewMetaCache = null;
function hidePreviewSheetTabs() {
const tabs = document.getElementById('preview-sheet-tabs');
tabs.style.display = 'none';
tabs.innerHTML = '';
_previewSheetsCache = null;
_previewActiveSheet = null;
}
function renderPreviewSheetTabs(sheetNames) {
const tabs = document.getElementById('preview-sheet-tabs');
tabs.innerHTML = '';
sheetNames.forEach((name, idx) => {
const btn = document.createElement('button');
btn.type = 'button';
const pt = inferSheetPeriodType(name);
btn.className = 'preview-sheet-tab' + (idx === 0 ? ' active' : '') + (pt ? ' ' + pt : '');
btn.textContent = formatSheetTabLabel(name);
btn.dataset.sheet = name;
btn.onclick = () => switchPreviewSheet(name);
tabs.appendChild(btn);
});
tabs.style.display = 'flex';
}
window.switchPreviewSheet = function(sheetName) {
if (!_previewSheetsCache || !_previewSheetsCache[sheetName]) return;
_previewActiveSheet = sheetName;
document.querySelectorAll('.preview-sheet-tab').forEach(tab => {
tab.classList.toggle('active', tab.dataset.sheet === sheetName);
});
const sheet = _previewSheetsCache[sheetName];
const ptLabel = sheetPeriodLabel(sheetName);
document.getElementById('preview-count').textContent =
'当前 Sheet「' + sheetName + '」' + (ptLabel ? '(' + ptLabel + ')' : '') + ' 共 ' + sheet.total + ' 条';
if (_previewMetaCache) {
const meta = { ..._previewMetaCache, periodType: ptLabel || _previewMetaCache.periodType };
renderPreviewMeta(meta, sheet.total);
}
renderPreviewTableBody(sheet);
};
function renderPreviewTableBody(tableData) {
const { columns, rows } = tableData;
if (!columns.length || !rows.length) {
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">无数据</div>';
return;
}
let html = '<table class="preview-table"><thead><tr>';
html += '<th style="width:40px;text-align:center;">#</th>';
columns.forEach(c => {
html += '<th>' + escapeHtml(String(c)) + '</th>';
});
html += '</tr></thead><tbody>';
rows.forEach((row, i) => {
html += '<tr>';
html += '<td style="text-align:center;color:#999;">' + (i + 1) + '</td>';
columns.forEach(c => {
const val = row[c] !== undefined && row[c] !== null ? String(row[c]) : '';
html += '<td>' + escapeHtml(val) + '</td>';
});
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('preview-body').innerHTML = html;
}
function showPreviewLoading(title) {
document.getElementById('preview-title').textContent = '\u23f3 ' + title;
document.getElementById('preview-count').textContent = '加载中...';
document.getElementById('preview-meta').style.display = 'none';
hidePreviewSheetTabs();
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">正在解析数据...</div>';
}
......@@ -642,15 +799,43 @@
document.getElementById('preview-title').textContent = '\u274c 加载失败';
document.getElementById('preview-count').textContent = '';
document.getElementById('preview-meta').style.display = 'none';
hidePreviewSheetTabs();
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">' + msg + '</div>';
}
function renderPreviewTable(data, title, meta) {
document.getElementById('preview-title').textContent = '\u{1f4ca} ' + title;
document.getElementById('preview-count').textContent = '共 ' + data.total + ' 条';
_previewMetaCache = meta || null;
if (data.sheets && data.sheet_names && data.sheet_names.length) {
_previewSheetsCache = data.sheets;
_previewActiveSheet = data.sheet_names[0];
const first = data.sheets[_previewActiveSheet];
const totalAll = data.sheet_names.reduce((sum, n) => sum + (data.sheets[n].total || 0), 0);
const ecoCount = data.sheet_names.filter(n => inferSheetPeriodType(n) === 'ecology').length;
const natCount = data.sheet_names.filter(n => inferSheetPeriodType(n) === 'nature').length;
let countText = data.sheet_names.length > 1
? `${data.sheet_names.length} 个 Sheet,合计 ${totalAll} 条`
: '共 ' + first.total + ' 条';
if (ecoCount || natCount) {
countText += `(生态月 ${ecoCount} / 自然月 ${natCount})`;
}
document.getElementById('preview-count').textContent = countText;
const sheetMeta = { ...(meta || {}), periodType: sheetPeriodLabel(_previewActiveSheet) };
renderPreviewMeta(sheetMeta, first.total);
renderPreviewSheetTabs(data.sheet_names);
renderPreviewTableBody(first);
return;
}
// 渲染批次元信息
hidePreviewSheetTabs();
document.getElementById('preview-count').textContent = '共 ' + (data.total || 0) + ' 条';
renderPreviewMeta(meta, data.total || 0);
renderPreviewTableBody(data);
}
function renderPreviewMeta(meta, total) {
const metaDiv = document.getElementById('preview-meta');
if (meta) {
let html = '';
......@@ -658,47 +843,26 @@
if (meta.periodType) html += `<span class="meta-item"><span class="meta-label">周期类型:</span><span class="meta-value">${escapeHtml(meta.periodType)}</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;
if (!columns.length || !rows.length) {
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">无数据</div>';
return;
}
let html = '<table class="preview-table"><thead><tr>';
html += '<th style="width:40px;text-align:center;">#</th>';
columns.forEach(c => {
html += '<th>' + escapeHtml(String(c)) + '</th>';
});
html += '</tr></thead><tbody>';
rows.forEach((row, i) => {
html += '<tr>';
html += '<td style="text-align:center;color:#999;">' + (i + 1) + '</td>';
columns.forEach(c => {
const val = row[c] !== undefined && row[c] !== null ? String(row[c]) : '';
html += '<td>' + escapeHtml(val) + '</td>';
});
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('preview-body').innerHTML = html;
}
async function saveBatch(fileType) {
const config = {
store: { inputId: 'store-file-input', btnId: 'btn-save-store' },
factory: { inputId: 'factory-file-input', btnId: 'btn-save-factory', startId: 'ecology-start-date', endId: 'ecology-end-date' },
factory: {
inputId: 'factory-file-input',
btnId: 'btn-save-factory',
startId: 'ecology-start-date',
endId: 'ecology-end-date',
},
};
const cfg = config[fileType];
if (!cfg) return;
const input = document.getElementById(cfg.inputId);
if (!input || !input.files.length) { alert('请先上传文件'); return; }
......
......@@ -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!