Commit b0e80189 by 江名洋

feat(harmony): 重构子品牌分析报表与预览

- 新增子品牌 OEM 历史批次预览接口
- 按品牌排序输出明细并生成汇总行
- 前端移除 SheetJS 依赖并优化预览面板样式
1 parent a8264da7
Sheets: ['模板', '鸿蒙子品牌(20260723)']
--- Sheet: 模板 (HIDDEN) ---
--- Sheet: 鸿蒙子品牌(20260723) (rows=284, cols=38) ---
Row 01: ['门店', '兜底指标', '区域(省)', '直营与否', '区域运营', '飞行督导', '线上运营', '品牌', '交付数', '_', '触客情况', '_', '整车延保成交订单数', '整车延保渗透率', '触客成交率', '安心包', '安心包渗透率', '电池', '电池渗透率', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
Row 02: ['_', '_', '_', '_', '_', '_', '_', '_', '主机厂', '产值表', '触客数', '触客率', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
Row 03: ['鸿蒙智行授权用户中心•合肥蒙城北路', '尊界', '_', '安徽省', '直营', '刘淑君', '_', '杨欣/石楚伦', '_', '0', '0', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E3<>"直营","服务商",IF(J3=0,"暂无交车",IF(OR(ISBLANK(Q3', '无', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
Row 04: ['鸿蒙智行授权用户中心•合肥蒙城北路', '智界', '_', '安徽省', '直营', '刘淑君', '_', '杨欣/石楚伦', '_', '12', '12', '0', '_', '0', '_', '2', '_', '_', '0', '_', '0', '_', '否', '=IF(E4<>"直营","服务商",IF(J4=0,"暂无交车",IF(OR(ISBLANK(Q4', '无', '0.1667', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
Row 05: ['鸿蒙智行授权用户中心•合肥蒙城北路', '享界', '_', '安徽省', '直营', '刘淑君', '_', '杨欣/石楚伦', '_', '2', '2', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E5<>"直营","服务商",IF(J5=0,"暂无交车",IF(OR(ISBLANK(Q5', '无', '0.5', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
Row 06: ['鸿蒙智行授权用户中心•六安东方汽车城', '智界', '_', '安徽省', '直营', '刘淑君', '_', '杨欣/石楚伦', '_', '7', '7', '0', '_', '0', '_', '2', '_', '_', '0', '_', '0', '_', '否', '=IF(E6<>"直营","服务商",IF(J6=0,"暂无交车",IF(OR(ISBLANK(Q6', '无', '0.2857', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
Row 07: ['鸿蒙智行授权用户中心•六安东方汽车城', '享界', '_', '安徽省', '直营', '刘淑君', '_', '杨欣/石楚伦', '_', '3', '3', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E7<>"直营","服务商",IF(J7=0,"暂无交车",IF(OR(ISBLANK(Q7', '无', '0.3333', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
Row 08: ['鸿蒙智行授权用户中心•宿州城东汽车城', '尚界', '_', '安徽省', '_', '_', '_', '_', '_', '1', '1', '0', '_', '0', '_', '0', '_', '_', '0', '_', '0', '_', '否', '=IF(E8<>"直营","服务商",IF(J8=0,"暂无交车",IF(OR(ISBLANK(Q8', '触客', '0', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 09: ['鸿蒙智行授权用户中心•宿州城东汽车城', '智界', '_', '安徽省', '_', '_', '_', '_', '_', '2', '2', '0', '_', '0', '_', '0', '_', '_', '0', '_', '0', '_', '否', '=IF(E9<>"直营","服务商",IF(J9=0,"暂无交车",IF(OR(ISBLANK(Q9', '触客', '0', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 10: ['鸿蒙智行授权用户中心•宿州城东汽车城', '享界', '_', '安徽省', '_', '_', '_', '_', '_', '2', '2', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E10<>"直营","服务商",IF(J10=0,"暂无交车",IF(OR(ISBLANK(', '触客', '0.5', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 11: ['鸿蒙智行授权用户中心•北京姚家园', '尊界', '_', '北京市', '非直营', '王峰', '_', '黄英/杨文豪', '_', '1', '1', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E11<>"直营","服务商",IF(J11=0,"暂无交车",IF(OR(ISBLANK(', '无', '1', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 12: ['鸿蒙智行授权用户中心•北京姚家园', '智界', '_', '北京市', '非直营', '王峰', '_', '黄英/杨文豪', '_', '19', '19', '0', '_', '0', '_', '23', '_', '_', '0', '_', '0', '_', '否', '=IF(E12<>"直营","服务商",IF(J12=0,"暂无交车",IF(OR(ISBLANK(', '无', '1.2105', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 13: ['鸿蒙智行授权用户中心•北京姚家园', '享界', '_', '北京市', '非直营', '王峰', '_', '黄英/杨文豪', '_', '3', '3', '0', '_', '0', '_', '8', '_', '_', '0', '_', '0', '_', '否', '=IF(E13<>"直营","服务商",IF(J13=0,"暂无交车",IF(OR(ISBLANK(', '无', '2.6667', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 14: ['鸿蒙智行智界用户中心•北京通州博瑞汽车园', '智界', '触客60%', '北京市', '直营', '王峰', '_', '_', '_', '10', '10', '0', '_', '0', '_', '9', '_', '_', '0', '_', '0', '_', '否', '=IF(E14<>"直营","服务商",IF(J14=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.9', '0', '0', '0.6', '0', '0', '0', '0', '0', '0', '0', '0', '0']
Row 15: ['鸿蒙智行尚界用户中心•北京安宁庄东路', '尚界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '13', '13', '0', '_', '0', '_', '9', '_', '_', '0', '_', '0', '_', '否', '=IF(E15<>"直营","服务商",IF(J15=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.6923', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 16: ['鸿蒙智行授权用户中心•北京玉泉路', '尊界', '兜底(服务商承担):按有效触客,原厂单延保<60%', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '1', '1', '0', '_', '0', '_', '0', '_', '_', '0', '_', '0', '_', '是', '=IF(E16<>"直营","服务商",IF(J16=0,"暂无交车",IF(OR(ISBLANK(', '触客', '0', '0', '0', '0.6', '0', '0', '1', '0', '0', '/', '/', '/', '/']
Row 17: ['鸿蒙智行授权用户中心•北京玉泉路', '尚界', '兜底(服务商承担):按有效触客,原厂单延保<60%', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '1', '1', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E17<>"直营","服务商",IF(J17=0,"暂无交车",IF(OR(ISBLANK(', '触客', '1', '0', '0', '0.6', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 18: ['鸿蒙智行授权用户中心•北京玉泉路', '智界', '兜底(服务商承担):按有效触客,原厂单延保<60%', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '15', '15', '0', '_', '0', '_', '10', '_', '_', '0', '_', '0', '_', '否', '=IF(E18<>"直营","服务商",IF(J18=0,"暂无交车",IF(OR(ISBLANK(', '触客', '0.6667', '0', '0', '0.6', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 19: ['鸿蒙智行授权用户中心•北京玉泉路', '享界', '兜底(服务商承担):按有效触客,原厂单延保<60%', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '5', '5', '0', '_', '0', '_', '3', '_', '_', '0', '_', '0', '_', '否', '=IF(E19<>"直营","服务商",IF(J19=0,"暂无交车",IF(OR(ISBLANK(', '触客', '0.6', '0', '0', '0.6', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 20: ['鸿蒙智行授权用户中心•北京首钢园', '尊界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '2', '2', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E20<>"直营","服务商",IF(J20=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.5', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 21: ['鸿蒙智行授权用户中心•北京首钢园', '尚界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '45', '45', '0', '_', '0', '_', '27', '_', '_', '0', '_', '0', '_', '否', '=IF(E21<>"直营","服务商",IF(J21=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.6', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 22: ['鸿蒙智行授权用户中心•北京首钢园', '智界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '35', '35', '0', '_', '0', '_', '18', '_', '_', '0', '_', '0', '_', '否', '=IF(E22<>"直营","服务商",IF(J22=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.5143', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 23: ['鸿蒙智行授权用户中心•北京首钢园', '享界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '11', '11', '0', '_', '0', '_', '7', '_', '_', '0', '_', '0', '_', '否', '=IF(E23<>"直营","服务商",IF(J23=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.6364', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 24: ['鸿蒙智行尚界用户中心•北京首都机场', '尚界', '_', '北京市', '直营', '王峰', '_', '黄英/杨文豪', '_', '26', '26', '0', '_', '0', '_', '13', '_', '_', '0', '_', '0', '_', '否', '=IF(E24<>"直营","服务商",IF(J24=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.5', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
Row 25: ['鸿蒙智行授权用户中心•北京首都机场', '智界', '_', '北京市', '_', '_', '_', '_', '_', '34', '34', '0', '_', '0', '_', '10', '_', '_', '0', '_', '0', '_', '否', '=IF(E25<>"直营","服务商",IF(J25=0,"暂无交车",IF(OR(ISBLANK(', '触客', '0.2941', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 26: ['鸿蒙智行授权用户中心•北京首都机场', '享界', '_', '北京市', '_', '_', '_', '_', '_', '4', '4', '0', '_', '0', '_', '3', '_', '_', '0', '_', '0', '_', '否', '=IF(E26<>"直营","服务商",IF(J26=0,"暂无交车",IF(OR(ISBLANK(', '触客', '0.75', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 27: ['鸿蒙智行授权用户中心•北京丰管路', '尊界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '3', '3', '0', '_', '0', '_', '1', '_', '_', '0', '_', '0', '_', '否', '=IF(E27<>"直营","服务商",IF(J27=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.3333', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 28: ['鸿蒙智行授权用户中心•北京丰管路', '尚界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '42', '42', '0', '_', '0', '_', '14', '_', '_', '0', '_', '0', '_', '否', '=IF(E28<>"直营","服务商",IF(J28=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.3333', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Row 29: ['鸿蒙智行授权用户中心•北京丰管路', '智界', '_', '北京市', '非直营', '王峰', '李晓晨/黄正', '黄英/杨文豪', '_', '29', '29', '0', '_', '0', '_', '8', '_', '_', '0', '_', '0', '_', '否', '=IF(E29<>"直营","服务商",IF(J29=0,"暂无交车",IF(OR(ISBLANK(', '无', '0.2759', '0', '0', '0', '0', '0', '0', '0', '0', '/', '/', '/', '/']
Template 001: rows=3, cols=38
Row 01: ['基础门店信息', '_', '_', '_', '_', '_', '_', '_', '_', '主机厂交付数', '_', '_', '_', '产值表数据', '_', '_', '_', '_', '_', '_', '_', '_', '是否触发兜底', '_', '_', '当前转化率', '_', '_', '需达标转化率', '_', '_', '需达标订单差额', '_', '_', '赔付金额', '_', '_', '总赔付金额']
Row 02: ['门店', '品牌', '兜底指标', '区域(省)', '直营与否', '区域运营', '飞行督导', '线上运营', '特殊情况', '复合交付数', '主机厂交付数', '产值交付数', '主机厂跟产值表差距', '门店触客数', '触客率', '整车延保成交订单数', '整车延保渗透率', '触客成交率', '安心包', '安心包渗透率', '电池', '电池渗透率', '是否触发兜底', '门店等级', '兜底类型', '整车延保转化率', '安心包转化率', '电池延保转化率', '需达标_整车延保', '需达标_安心包', '需达标_电池延保', '差额_整车延保', '差额_安心包', '差额_电池延保', '赔付_整车延保', '赔付_安心包', '赔付_电池延保', '总赔付金额']
Row 03: ['示例门店(尊界)', '尊界', '兜底:触客渗透率60%', '广东省', '直营', '区域运营', '飞行督导', '线上运营', '_', '10', '10', '10', '=J3-L3', '8', '=IF(L3>0,N3/L3,0)', '5', '=IF(L3>0,P3/L3,0)', '=IF(N3>0,P3/N3,0)', '2', '=IF(L3>0,S3/L3,0)', '1', '=IF(L3>0,U3/L3,0)', '=IF(OR(Z3<AC3,AA3<AD3,AB3<AE3),"是","否")', '=IF(E3<>"直营","服务商",IF(J3=0,"暂无交车",IF(OR(ISBLANK(Q3', '触客', '=IF($N3>0,P3/$N3,IF($L3>0,P3/$L3,0))', '=IF($N3>0,S3/$N3,IF($L3>0,S3/$L3,0))', '=IF($N3>0,U3/$N3,IF($L3>0,U3/$L3,0))', '0.6', '0', '0', '=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AC3-P3,0))', '=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AD3-S3,0))', '=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AE3-U3,0))', '600', '0', '0', '=IF(E3="直营",AI3+AJ3+AK3,"/")']
Merged cells: [<MergedCellRange Z1:AB1>, <MergedCellRange AF1:AH1>, <MergedCellRange AC1:AE1>, <MergedCellRange AI1:AK1>, <MergedCellRange A1:I1>, <MergedCellRange N1:V1>]
Template 003: rows=8, cols=19
Sheet names: ['模板']
Row 01: ['门店', '兜底指标', '区域(省)', '直营与否', '区域运营', '飞行督导', '线上运营', '品牌', '交付数', '_', '触客情况', '_', '整车延保成交订单数', '整车延保渗透率', '触客成交率', '安心包', '安心包渗透率', '电池', '电池渗透率']
Row 02: ['_', '_', '_', '_', '_', '_', '_', '_', '主机厂', '产值表', '触客数', '触客率', '_', '_', '_', '_', '_', '_', '_']
Row 03: ['_', '_', '_', '_', '_', '_', '_', '四界', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
Row 04: ['_', '_', '_', '_', '_', '_', '_', '尊界', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
Row 05: ['_', '_', '_', '_', '_', '_', '_', '尚界', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
Row 06: ['_', '_', '_', '_', '_', '_', '_', '智界', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
Row 07: ['_', '_', '_', '_', '_', '_', '_', '享界', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
Row 08: ['恩施华启汽车销售服务有限公司', '兜底:【整车延保】月触客渗透率≤50%,按400元', '湖北省', '直营', '刘淑君', '喻桥', '杨欣/石楚伦', '尊界', '0', '0', '0', '=IF(I8>0,K8/I8,0)', '0', '=IF(I8>0,M8/I8,0)', '=IF(K8>0,M8/K8,0)', '0', '=IF(I8>0,P8/I8,0)', '0', '=IF(I8>0,R8/I8,0)']
Merged cells: [<MergedCellRange P1:P2>, <MergedCellRange N1:N2>, <MergedCellRange K1:L1>, <MergedCellRange Q1:Q2>, <MergedCellRange C1:C2>, <MergedCellRange B1:B2>, <MergedCellRange D1:D2>, <MergedCellRange E1:E2>, <MergedCellRange F1:F2>, <MergedCellRange H1:H2>, <MergedCellRange G1:G2>, <MergedCellRange M1:M2>, <MergedCellRange A1:A2>, <MergedCellRange O1:O2>, <MergedCellRange I1:J1>, <MergedCellRange S1:S2>, <MergedCellRange R1:R2>]
输出模板-鸿蒙子品牌-模板001.xlsx
输出模板-鸿蒙子品牌-模板003.xlsx
......@@ -1242,7 +1242,8 @@ async def sub_brand_upload(
store_df = None
if store_batch_no:
store_df = HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)
preview = HarmonyAnalysisService.preview_sub_brand_data(file_path, store_df=store_df)
preview = HarmonyAnalysisService.preview_sub_brand_data(
file_path, store_df=store_df, start_date=start_date, end_date=end_date)
if preview.get("total", 0) == 0:
raise ValueError("未解析到有效子品牌数据,请使用「主机厂数据-鸿蒙子品牌-模板001.xlsx」")
except ValueError as e:
......@@ -1320,6 +1321,48 @@ async def sub_brand_save_batch(
raise HTTPException(status_code=500, detail=f"保存批次失败: {str(e)}")
@router.get("/harmony/sub-brand/batch-data")
async def sub_brand_batch_data(
batch_no: str = Query(...),
store_batch_no: str = Query(None),
start_date: str = Query(None),
end_date: str = Query(None),
):
"""加载子品牌 OEM 历史批次预览"""
from app.services.upload_service import _get_conn
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute(
"""SELECT remark, data_period_start, data_period_end, file_name
FROM upload_batch
WHERE batch_no=%s AND data_type='harmony_sub_brand_oem' AND status != 3""",
(batch_no,),
)
row = cur.fetchone()
finally:
conn.close()
if not row or not row.get("remark") or not os.path.exists(row["remark"]):
raise HTTPException(status_code=404, detail="子品牌批次不存在或文件已丢失")
global _sub_brand_file
_sub_brand_file = row["remark"]
store_df = None
if store_batch_no:
store_df = HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)
sd = start_date or str(row.get("data_period_start") or "")[:10]
ed = end_date or str(row.get("data_period_end") or "")[:10]
preview = HarmonyAnalysisService.preview_sub_brand_data(
row["remark"], store_df=store_df, start_date=sd or None, end_date=ed or None)
preview["batch_no"] = batch_no
preview["file_name"] = row.get("file_name") or ""
return {"status": "success", "data": preview}
@router.post("/harmony/sub-brand/generate")
async def sub_brand_generate(
start_date: str = Form(None),
......@@ -1357,11 +1400,18 @@ async def sub_brand_generate(
end_date=end_date,
store_batch_no=store_batch_no,
)
detail_rows = max(0, len(HarmonyAnalysisService.read_sub_brand_data(
file_path,
store_df=HarmonyAnalysisService.load_store_df_from_batch(store_batch_no)
if store_batch_no else None,
)))
return {
"status": "success",
"message": "鸿蒙子品牌分析报表已生成",
"file_path": output_path,
"download_url": f"/api/harmony/sub-brand/download?file={os.path.basename(output_path)}",
"detail_rows": detail_rows,
"summary_rows": 5,
}
except Exception as e:
logger.error(f"Sub-brand analysis generate failed: {e}", exc_info=True)
......
......@@ -48,6 +48,9 @@ HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797)
# 鸿蒙子品牌映射
SUB_BRAND_NAMES = {"智界": "智界", "享界": "享界", "尊界": "尊界", "尚界": "尚界"}
SUB_BRAND_ID_MAP = {"尊界": 2740, "尚界": 2797, "智界": 2698, "享界": 2741}
SUB_BRAND_ID_TO_NAME = {v: k for k, v in SUB_BRAND_ID_MAP.items()}
SUB_BRAND_SORT_ORDER = {"尊界": 0, "尚界": 1, "智界": 2, "享界": 3}
# first_brand_id(鸿蒙智行,参考 generate_weekly_comparison.py)
FIRST_BRAND_ID = 2365
......@@ -63,9 +66,15 @@ THIN_BORDER = Border(
top=Side(style="thin"), bottom=Side(style="thin")
)
# 百分比列(1-indexed,38列模板)
# 百分比列(1-indexed,38列模板 — 鸿蒙主报表)
PERCENT_COLS = {15, 17, 18, 20, 22, 26, 27, 28, 29, 30, 31}
# 鸿蒙子品牌输出模板(19列)
SUB_BRAND_PERCENT_COLS = {12, 14, 15, 17, 19}
SUB_BRAND_SUMMARY_LABELS = ["四界", "尊界", "尚界", "智界", "享界"]
SUB_BRAND_SUMMARY_START_ROW = 3
SUB_BRAND_DATA_START_ROW = 8
def _safe_float(val, default=0.0):
try:
......@@ -573,6 +582,150 @@ class HarmonyAnalysisService:
if conn:
conn.close()
@staticmethod
def _query_harmony_sub_brand_performance(store_brand_pairs: list,
start_date: str,
end_date: str) -> dict:
"""
按门店+子品牌查询产值数据。
返回: {(门店名, 品牌): {delivery, touch, yb_orders, ...}}
"""
from app.core.config import settings
if not store_brand_pairs:
return {}
store_names = sorted({
str(n).strip() for n, _ in store_brand_pairs if n and str(n).strip()
})
if not store_names:
return {}
conn = None
try:
conn = pymysql.connect(
host=settings.DB_HOST,
port=settings.DB_PORT,
user=settings.DB_USER,
password=settings.DB_PASSWORD,
database=settings.DB_NAME,
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor,
)
query_names = list(store_names)
_HM_SUFFIX_WHITELIST = {"海南丰盛利华汽车销售服务有限公司"}
for name in store_names:
if name in _HM_SUFFIX_WHITELIST:
hm_name = name + "(鸿蒙)"
if hm_name not in query_names:
query_names.append(hm_name)
placeholders = ", ".join(["%s"] * len(query_names))
brand_placeholders = ", ".join(["%s"] * len(HARMONY_BRAND_IDS))
sql = f"""
SELECT
m.merchant_name,
m.brand_id,
m.total_delivery,
m.total_touch,
m.total_yb_orders,
m.total_axb_orders,
m.total_battery_orders,
m.province_name,
m.area_supervision,
m.flight_supervision,
m.online_supervision,
sc.operation_mode
FROM (
SELECT
merchant_id,
merchant_name,
brand_id,
province_name,
area_supervision,
flight_supervision,
online_supervision,
SUM(IFNULL(delivery_count, 0)) AS total_delivery,
SUM(IFNULL(sum_extended_warranty_to_shop, 0)) AS total_touch,
SUM(IFNULL(sum_extended_warranty, 0)) AS total_yb_orders,
SUM(IFNULL(sum_ax_package, 0)) AS total_axb_orders,
SUM(IFNULL(sum_battery_extended, 0)) AS total_battery_orders
FROM dws_merchant_daily_wide
WHERE report_date >= %s AND report_date <= %s
AND first_brand_id = %s
AND brand_id IN ({brand_placeholders})
AND scene_type = '0'
GROUP BY merchant_id, merchant_name, brand_id,
province_name, area_supervision,
flight_supervision, online_supervision
) m
LEFT JOIN ods_store_config sc
ON m.merchant_id = sc.merchant_id AND sc.deleted_flag = 'N'
WHERE m.merchant_name IN ({placeholders})
"""
params = [start_date, end_date, FIRST_BRAND_ID] + list(HARMONY_BRAND_IDS) + query_names
with conn.cursor() as cur:
cur.execute(sql, params)
rows = cur.fetchall()
db_map = {}
for row in rows:
brand_name = SUB_BRAND_ID_TO_NAME.get(int(row["brand_id"] or 0), "")
if not brand_name:
continue
name = row["merchant_name"]
payload = {
"delivery": int(row["total_delivery"] or 0),
"touch": int(row["total_touch"] or 0),
"yb_orders": int(row["total_yb_orders"] or 0),
"axb_orders": int(row["total_axb_orders"] or 0),
"battery_orders": int(row["total_battery_orders"] or 0),
"province_name": row.get("province_name") or "",
"area_supervision": row.get("area_supervision") or "",
"flight_supervision": row.get("flight_supervision") or "",
"online_supervision": row.get("online_supervision") or "",
"operation_mode": row.get("operation_mode") or "非直营",
}
db_map[(name, brand_name)] = payload
result = {}
for store_name, brand in store_brand_pairs:
store_name = str(store_name).strip()
brand = str(brand).strip()
if not store_name or not brand:
continue
perf = db_map.get((store_name, brand))
if perf:
result[(store_name, brand)] = perf
logger.info(
f"Sub-brand DB query: {len(store_brand_pairs)} pairs, "
f"({start_date} ~ {end_date}), matched {len(result)}"
)
return result
except Exception as e:
logger.error(f"Sub-brand DB query failed: {e}", exc_info=True)
return {}
finally:
if conn:
conn.close()
@staticmethod
def _lookup_sub_brand_perf(db_perf: dict, store_name: str, legal_name: str, brand: str) -> dict:
"""按用户中心名/法人名 + 品牌查找产值"""
brand = str(brand or "").strip()
for name in (store_name, legal_name):
name = str(name or "").strip()
if not name:
continue
perf = db_perf.get((name, brand))
if perf:
return perf
return {}
# ──────────────── 报表生成 ────────────────
@staticmethod
......@@ -891,7 +1044,7 @@ class HarmonyAnalysisService:
merged["整车延保成交数"] = oem["主机厂出单数"].fillna(0).astype(int)
merged["安心包达成数量"] = 0
merged["电池延保成交数"] = 0
return merged.drop(columns=["法人门店名", "子品牌"], errors="ignore")
return merged.drop(columns=["子品牌"], errors="ignore")
@staticmethod
def _read_sub_brand_legacy(file_path: str) -> pd.DataFrame:
......@@ -957,24 +1110,91 @@ class HarmonyAnalysisService:
return HarmonyAnalysisService._read_sub_brand_legacy(file_path)
@staticmethod
def preview_sub_brand_data(file_path: str, store_df: pd.DataFrame = None) -> dict:
"""返回子品牌预览数据(供前端表格展示)"""
def preview_sub_brand_data(file_path: str, store_df: pd.DataFrame = None,
start_date: str = None, end_date: str = None) -> dict:
"""返回子品牌预览数据(对齐输出模板19列结构)"""
df = HarmonyAnalysisService.read_sub_brand_data(file_path, store_df=store_df)
if df.empty:
return {"columns": [], "rows": [], "total": 0}
columns = [
"门店名", "品牌", "区域(省)", "直营与否", "主机厂交付数",
"整车延保成交数", "兜底指标",
return {"columns": [], "rows": [], "total": 0, "summary": [], "brand_counts": {}}
if not end_date:
end_date = date.today().strftime("%Y-%m-%d")
if not start_date:
start_date = date.today().replace(day=1).strftime("%Y-%m-%d")
pairs = [
(str(r.get("门店名", "")).strip(), str(r.get("品牌", "")).strip())
for _, r in df.iterrows()
if str(r.get("门店名", "")).strip() and str(r.get("品牌", "")).strip()
]
preview_cols = [c for c in columns if c in df.columns]
preview_df = df[preview_cols].head(100).fillna("")
db_perf = HarmonyAnalysisService._query_harmony_sub_brand_performance(
pairs, start_date, end_date)
preview_rows = []
for _, row in df.iterrows():
uc_name = str(row.get("门店名", "")).strip()
legal_name = str(row.get("法人门店名", "")).strip()
brand = str(row.get("品牌", "")).strip()
perf = HarmonyAnalysisService._lookup_sub_brand_perf(
db_perf, uc_name, legal_name, brand)
metrics = HarmonyAnalysisService._sub_brand_row_metrics(row, perf)
display_name = legal_name or uc_name
preview_rows.append({
"门店名": display_name,
"品牌": brand,
"兜底指标": str(row.get("兜底指标", "") or ""),
"区域(省)": str(row.get("区域(省)", "") or perf.get("province_name", "")),
"直营与否": str(row.get("直营与否", "") or perf.get("operation_mode", "")),
"主机厂交付数": int(metrics["factory"]),
"产值表交付数": int(metrics["value_delivery"]),
"触客数": int(metrics["touch"]),
"整车延保成交数": int(metrics["yb_orders"]),
"安心包达成数量": int(metrics["axb_orders"]),
"电池延保成交数": int(metrics["battery_orders"]),
})
preview_df = pd.DataFrame(preview_rows)
preview_df["_sort"] = preview_df["品牌"].map(SUB_BRAND_SORT_ORDER).fillna(99)
preview_df = preview_df.sort_values(["门店名", "_sort"]).drop(columns=["_sort"])
summary = HarmonyAnalysisService._build_sub_brand_summary(preview_df)
brand_counts = preview_df["品牌"].value_counts().to_dict()
matched_guarantee = int(
preview_df["兜底指标"].astype(str).str.strip().replace("nan", "").ne("").sum()
)
columns = list(preview_df.columns)
head = preview_df.head(150).fillna("")
return {
"columns": preview_cols,
"rows": preview_df.astype(object).to_dict(orient="records"),
"total": len(df),
"columns": columns,
"rows": head.astype(object).to_dict(orient="records"),
"total": len(preview_df),
"summary": summary,
"brand_counts": brand_counts,
"matched_guarantee": matched_guarantee,
"period": f"{start_date} ~ {end_date}",
}
@staticmethod
def _build_sub_brand_summary(df: pd.DataFrame) -> list:
"""构建与输出模板一致的顶部汇总行"""
numeric_cols = [
"主机厂交付数", "产值表交付数", "触客数",
"整车延保成交数", "安心包达成数量", "电池延保成交数",
]
summary = []
for label in SUB_BRAND_SUMMARY_LABELS:
if label == "四界":
sub = df
else:
sub = df[df["品牌"] == label]
item = {"品牌": label, "门店名": ""}
for col in numeric_cols:
item[col] = int(sub[col].sum()) if col in sub.columns and not sub.empty else 0
summary.append(item)
return summary
@staticmethod
def _parse_guarantee_text(text: str) -> dict:
"""
解析兜底指标文本,提取兜底类型、需达标转化率、赔付金额。
......@@ -1113,23 +1333,24 @@ class HarmonyAnalysisService:
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})"
ws.title = sheet_name
ws_template.sheet_state = 'hidden'
ws.freeze_panes = "I3"
HarmonyAnalysisService._clear_sheet_data(ws)
# DB查询产值数据(作为补充,优先使用文件中的产值数据)
store_names = [str(n) for n in raw_df["门店名"].tolist() if pd.notna(n)]
db_perf = HarmonyAnalysisService._query_harmony_store_performance(
store_names, start_date, end_date) if store_names else {}
pairs = [
(str(r.get("门店名", "")).strip(), str(r.get("品牌", "")).strip())
for _, r in raw_df.iterrows()
if str(r.get("门店名", "")).strip() and str(r.get("品牌", "")).strip()
]
db_perf = HarmonyAnalysisService._query_harmony_sub_brand_performance(
pairs, start_date, end_date) if pairs else {}
# 构建适配 _write_data_rows 的 merged_df
# 构建明细 DataFrame,按门店+品牌排序(尊界→尚界→智界→享界)
merged_rows = []
for _, row in raw_df.iterrows():
store_name = str(row.get("门店名", ""))
......@@ -1148,6 +1369,7 @@ class HarmonyAnalysisService:
merged_rows.append({
"门店名": store_name,
"法人门店名": str(row.get("法人门店名", "")).strip() if pd.notna(row.get("法人门店名")) else "",
"品牌": str(row.get("品牌", "")),
"兜底指标": str(row.get("兜底指标", "")) if pd.notna(row.get("兜底指标")) else "",
"区域(省)": str(row.get("区域(省)", "")) if pd.notna(row.get("区域(省)")) else "",
......@@ -1171,20 +1393,19 @@ class HarmonyAnalysisService:
})
merged_df = pd.DataFrame(merged_rows)
merged_df["_sort_brand"] = merged_df["品牌"].map(SUB_BRAND_SORT_ORDER).fillna(99)
merged_df = merged_df.sort_values(["门店名", "_sort_brand"]).drop(columns=["_sort_brand"])
logger.info(f"Sub-brand merged: {len(merged_df)} stores, db={len(db_perf)}")
logger.info(f"Sub-brand merged: {len(merged_df)} rows, db={len(db_perf)}")
# 为 db_perf 补充产值表交付数
for store_name, perf in db_perf.items():
# db_perf 中的 delivery 是产值表交付数,映射为产值交付数来源
pass # 已在后续写入逻辑中使用
formula_map, skip_external_cols = HarmonyAnalysisService._extract_sub_brand_formulas_from_template(
ws_template)
# 写入数据
next_row = HarmonyAnalysisService._write_data_rows(
ws, merged_df, db_perf, formula_map, skip_external_cols,
start_date, end_date)
HarmonyAnalysisService._write_sub_brand_summary_rows(ws, merged_df, db_perf)
next_row = HarmonyAnalysisService._write_sub_brand_data_rows(
ws, merged_df, db_perf, formula_map, skip_external_cols)
# 自动筛选
# 自动筛选(表头第2行)
from openpyxl.utils import get_column_letter
last_col = get_column_letter(ws.max_column)
ws.auto_filter.ref = f"A2:{last_col}{next_row - 1}"
......@@ -1194,6 +1415,169 @@ class HarmonyAnalysisService:
return output_path
@staticmethod
def _extract_sub_brand_formulas_from_template(ws):
"""从子品牌19列模板示例行提取公式"""
formula_map = {}
skip_external_cols = set()
sample_row = SUB_BRAND_DATA_START_ROW
for col in range(1, ws.max_column + 1):
cell = ws.cell(row=sample_row, 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 _sub_brand_row_metrics(store_row, perf: dict) -> dict:
"""计算单条子品牌明细行的数值字段(主机厂 OEM 优先,产值表按子品牌 DB 补充)"""
factory_delivery = _safe_float(store_row.get("交付数", store_row.get("主机厂交付数", 0)))
db_delivery = _safe_float(perf.get("delivery", 0))
touch = _safe_float(store_row.get("触客数", 0))
if touch == 0:
touch = _safe_float(perf.get("touch", 0))
yb_orders = _safe_float(store_row.get("整车延保成交数", 0))
if yb_orders == 0:
yb_orders = _safe_float(perf.get("yb_orders", 0))
axb_orders = _safe_float(store_row.get("安心包达成数量", 0))
if axb_orders == 0:
axb_orders = _safe_float(perf.get("axb_orders", 0))
battery_orders = _safe_float(store_row.get("电池延保成交数", 0))
if battery_orders == 0:
battery_orders = _safe_float(perf.get("battery_orders", 0))
return {
"factory": factory_delivery,
"value_delivery": db_delivery,
"touch": touch,
"yb_orders": yb_orders,
"axb_orders": axb_orders,
"battery_orders": battery_orders,
}
@staticmethod
def _write_sub_brand_summary_rows(ws, merged_df: pd.DataFrame, db_perf: dict):
"""写入顶部汇总行:四界/尊界/尚界/智界/享界(门店列为空,品牌列标识)"""
metrics_list = []
for _, store_row in merged_df.iterrows():
uc_name = str(store_row.get("门店名", "")).strip()
legal_name = str(store_row.get("法人门店名", "")).strip()
brand = str(store_row.get("品牌", "")).strip()
perf = HarmonyAnalysisService._lookup_sub_brand_perf(
db_perf, uc_name, legal_name, brand)
m = HarmonyAnalysisService._sub_brand_row_metrics(store_row, perf)
m["品牌"] = brand
metrics_list.append(m)
for i, label in enumerate(SUB_BRAND_SUMMARY_LABELS):
row_num = SUB_BRAND_SUMMARY_START_ROW + i
if label == "四界":
subset = metrics_list
else:
subset = [m for m in metrics_list if m["品牌"] == label]
ws.cell(row=row_num, column=8, value=label)
totals = {
9: sum(m["factory"] for m in subset),
10: sum(m["value_delivery"] for m in subset),
11: sum(m["touch"] for m in subset),
13: sum(m["yb_orders"] for m in subset),
16: sum(m["axb_orders"] for m in subset),
18: sum(m["battery_orders"] for m in subset),
}
for col, val in totals.items():
cell = ws.cell(row=row_num, column=col, value=int(val) if val == int(val) else val)
cell.font = DATA_FONT
cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center")
cell.number_format = "0"
for col in SUB_BRAND_PERCENT_COLS:
formula_tpl = {
12: f"=IF(I{row_num}>0,K{row_num}/I{row_num},0)",
14: f"=IF(I{row_num}>0,M{row_num}/I{row_num},0)",
15: f"=IF(K{row_num}>0,M{row_num}/K{row_num},0)",
17: f"=IF(I{row_num}>0,P{row_num}/I{row_num},0)",
19: f"=IF(I{row_num}>0,R{row_num}/I{row_num},0)",
}[col]
cell = ws.cell(row=row_num, column=col, value=formula_tpl)
cell.font = DATA_FONT
cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center")
cell.number_format = "0.00%"
@staticmethod
def _write_sub_brand_data_rows(ws, merged_df, db_perf, formula_map, skip_external_cols,
start_row=SUB_BRAND_DATA_START_ROW):
"""写入子品牌19列明细行"""
def _style_cell(r, c, value, is_formula=False):
cell = ws.cell(row=r, column=c, value=value)
cell.font = DATA_FONT
cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
if is_formula:
cell.number_format = "0.00%" if c in SUB_BRAND_PERCENT_COLS else "0"
elif isinstance(value, (int, float)):
cell.number_format = "0.00%" if c in SUB_BRAND_PERCENT_COLS else "0"
return cell
def _apply_formula(r, c):
if c in skip_external_cols or c not in formula_map:
return
tpl = formula_map[c]
formula = tpl.replace(f"I{SUB_BRAND_DATA_START_ROW}", f"I{r}")
formula = formula.replace(f"K{SUB_BRAND_DATA_START_ROW}", f"K{r}")
formula = formula.replace(f"M{SUB_BRAND_DATA_START_ROW}", f"M{r}")
formula = formula.replace(f"P{SUB_BRAND_DATA_START_ROW}", f"P{r}")
formula = formula.replace(f"R{SUB_BRAND_DATA_START_ROW}", f"R{r}")
_style_cell(r, c, formula, is_formula=True)
row_num = start_row
for _, store_row in merged_df.iterrows():
uc_name = str(store_row.get("门店名", "")).strip()
if not uc_name:
continue
display_name = str(store_row.get("法人门店名", "")).strip() or uc_name
brand = str(store_row.get("品牌", "")).strip()
legal_name = str(store_row.get("法人门店名", "")).strip()
perf = HarmonyAnalysisService._lookup_sub_brand_perf(
db_perf, uc_name, legal_name, brand)
metrics = HarmonyAnalysisService._sub_brand_row_metrics(store_row, perf)
ws.row_dimensions[row_num].height = 18
_style_cell(row_num, 1, display_name)
_style_cell(row_num, 2, _pick_str(store_row.get("兜底指标")))
_style_cell(row_num, 3, _pick_str(store_row.get("区域(省)", perf.get("province_name", ""))))
_style_cell(row_num, 4, _pick_str(store_row.get("直营与否", perf.get("operation_mode", ""))))
_style_cell(row_num, 5, _pick_str(store_row.get("区域运营", perf.get("area_supervision", ""))))
_style_cell(row_num, 6, _pick_str(store_row.get("飞行督导", perf.get("flight_supervision", ""))))
_style_cell(row_num, 7, _pick_str(store_row.get("线上运营", perf.get("online_supervision", ""))))
_style_cell(row_num, 8, _pick_str(store_row.get("品牌")))
_style_cell(row_num, 9, int(metrics["factory"]))
_style_cell(row_num, 10, int(metrics["value_delivery"]))
_style_cell(row_num, 11, int(metrics["touch"]))
_style_cell(row_num, 13, int(metrics["yb_orders"]))
_style_cell(row_num, 16, int(metrics["axb_orders"]))
_style_cell(row_num, 18, int(metrics["battery_orders"]))
for col in SUB_BRAND_PERCENT_COLS:
_apply_formula(row_num, col)
row_num += 1
return row_num
@staticmethod
def _extract_formulas_from_template(ws):
formula_map = {}
skip_external_cols = set()
......
......@@ -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);
......@@ -27,6 +26,13 @@
background: #fafafa; font-size: 13px; color: #666;
display: flex; align-items: center; justify-content: space-between;
}
.right-panel-meta {
padding: 6px 16px; border-bottom: 1px solid #e8e8e8;
background: #f0f7ff; font-size: 12px; color: #555;
display: flex; flex-wrap: wrap; gap: 4px 16px;
}
.right-panel-meta .meta-label { color: #999; }
.right-panel-meta .meta-value { color: #333; font-weight: 500; }
.right-panel-body { flex: 1; overflow: auto; padding: 0; }
.right-panel-empty {
display: flex; align-items: center; justify-content: center;
......@@ -37,74 +43,75 @@
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-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-select {
flex: 1; padding: 5px 8px; border: 1px solid #d9d9d9;
border-radius: 4px; font-size: 12px; background: #fff;
}
.step-or { font-size: 11px; color: #999; white-space: nowrap; }
.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;
font-size: 12px; color: #999; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap;
}
.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;
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 { font-size: 11px; color: #1890ff; text-decoration: none; white-space: nowrap; }
.btn-save-batch {
margin-top: 6px; padding: 6px 12px; width: 100%;
background: #e6f7ff; color: #1890ff; border: 1px solid #91d5ff;
border-radius: 4px; font-size: 12px; cursor: pointer;
}
.btn-download-tpl:hover { text-decoration: underline; }
.btn-save-batch:hover { background: #bae7ff; }
.btn-save-batch:disabled { opacity: 0.5; cursor: not-allowed; }
.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%;
cursor: pointer; width: 100%;
}
.btn-generate:hover { background: #40a9ff; }
.btn-generate:disabled { background: #d9d9d9; cursor: not-allowed; }
.brand-filter {
padding: 8px 16px; border-bottom: 1px solid #e8e8e8;
display: flex; flex-wrap: wrap; gap: 6px; background: #fafafa;
}
.brand-chip {
padding: 2px 10px; border-radius: 12px; font-size: 11px;
border: 1px solid #d9d9d9; background: #fff; cursor: pointer; color: #666;
}
.brand-chip.active { background: #1890ff; color: #fff; border-color: #1890ff; }
.summary-table { width: 100%; border-collapse: collapse; font-size: 11px; margin-bottom: 0; }
.summary-table th, .summary-table td {
padding: 4px 8px; border-bottom: 1px solid #e8e8e8; text-align: center;
}
.summary-table th { background: #e6f7ff; font-weight: 600; }
.summary-wrap { padding: 8px 12px; border-bottom: 1px solid #e8e8e8; background: #fafffe; }
.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;
text-align: left; font-weight: 600;
}
.preview-table td {
padding: 5px 10px; border-bottom: 1px solid #f0f0f0;
color: #555; max-width: 200px; overflow: hidden; text-overflow: ellipsis;
max-width: 220px; 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;
}
.preview-table tr.summary-row td { background: #f6ffed; font-weight: 600; color: #389e0d; }
.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;
}
.btn-save-batch {
padding: 6px 12px; background: #e6f7ff; color: #1890ff;
border: 1px solid #91d5ff; border-radius: 4px; font-size: 12px;
cursor: pointer;
color: white; border-radius: 4px; font-size: 14px; text-decoration: none; margin-top: 10px;
}
.btn-save-batch:hover { background: #bae7ff; }
.btn-save-batch:disabled { opacity: 0.5; cursor: not-allowed; }
@media (max-width: 900px) {
.analysis-layout { flex-direction: column; height: auto; }
.left-panel { width: 100%; min-width: 0; }
......@@ -116,13 +123,13 @@
<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>
<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>
......@@ -134,35 +141,48 @@
<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-card" id="sb-step-store">
<div class="step-title">&#9312; 门店兜底配置(可选)</div>
<div class="step-row">
<select class="step-select" id="sb-store-batch-select" onchange="onSbStoreBatchSelect()">
<option value="">-- 选择历史批次 --</option>
</select>
</div>
<span style="font-size:11px;color:#999;">用于关联兜底指标;不选则自动取最新鸿蒙门店配置</span>
</div>
<div class="step-card active" id="sb-step-oem">
<div class="step-title">&#9313; 主机厂子品牌数据</div>
<div class="step-row">
<select class="step-select" id="sb-oem-batch-select" onchange="onSbOemBatchSelect()">
<option value="">-- 选择历史批次 --</option>
</select>
</div>
<div class="step-row">
<span class="step-or">或</span>
<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>
&#x1f4c1; <span id="sb-file-name">上传主机厂子品牌数据</span>
</div>
<a class="btn-download-tpl" id="sb-tpl-input" href="#">&#x1f4e5; 输入模板</a>
<a class="btn-download-tpl" id="sb-tpl-output" href="#">&#x1f4e5; 输出模板</a>
<a class="btn-download-tpl" id="sb-tpl-input" href="#">输入</a>
<a class="btn-download-tpl" id="sb-tpl-output" href="#">输出</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>
<button class="btn-save-batch" id="btn-save-sb-batch" style="display:none;margin-top:8px;width:100%;"
<button class="btn-save-batch" id="btn-save-sb-batch" style="display:none;"
onclick="saveSubBrandBatch()">&#x1f4be; 保存为历史批次</button>
</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;">上传「主机厂数据-鸿蒙子品牌-模板001.xlsx」,系统将按尊界/尚界/智界/享界拆分交付数据,并关联门店兜底配置生成报表。</span>
<div style="background:#e6f7ff;padding:6px 14px;border-radius:6px;border:1px solid #91d5ff;font-size:12px;color:#666;">
上传「主机厂数据-鸿蒙子品牌-模板001.xlsx」,按尊界/尚界/智界/享界拆分;产值数据按子品牌从数据库查询,输出对齐「输出模板-鸿蒙子品牌-模板003.xlsx」(19列 + 顶部汇总行)。
</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 · 输出: 输出模板-鸿蒙子品牌-模板001.xlsx</p>
<div style="text-align:center;">
<button class="btn-generate" id="btn-generate-sb-report">&#x1f680; 生成鸿蒙子品牌分析报表</button>
<p style="font-size:11px;color:#999;margin-top:4px;">输出模板-鸿蒙子品牌-模板003.xlsx</p>
</div>
<div class="result-box" id="sb-analysis-result">
......@@ -178,12 +198,13 @@
<div class="right-panel">
<div class="right-panel-header">
<span>&#x1f4ca; 子品牌数据预览</span>
<span id="sb-preview-title">&#x1f4ca; 子品牌数据预览</span>
<span id="sb-preview-count" style="font-size:11px;color:#999;"></span>
</div>
<div class="right-panel-meta" id="sb-preview-meta" style="display:none;"></div>
<div class="brand-filter" id="sb-brand-filter" style="display:none;"></div>
<div class="right-panel-body" id="sb-preview-body">
<div class="right-panel-empty" id="sb-preview-empty">
请上传鸿蒙子品牌数据文件,解析后将在此处预览
</div>
<div class="right-panel-empty">请选择历史批次或上传主机厂子品牌数据</div>
</div>
</div>
</div>
......@@ -194,6 +215,8 @@
<script src="../static/js/api-base.js"></script>
<script>
let sbPreviewCache = null;
let sbActiveBrand = '全部';
function escapeHtml(str) {
const div = document.createElement('div');
......@@ -202,19 +225,86 @@
}
function tplUrl(type) {
const root = window.APP_ROOT || '';
return root + '/api/harmony/sub-brand/template/' + type;
return (window.APP_ROOT || '') + '/api/harmony/sub-brand/template/' + type;
}
function renderSubBrandPreview(data) {
function getSbDates() {
return {
start: document.getElementById('sb-start-date').value,
end: document.getElementById('sb-end-date').value,
};
}
function highlightSbStep(id) {
document.querySelectorAll('.step-card').forEach(c => c.classList.remove('active'));
const el = document.getElementById(id);
if (el) el.classList.add('active');
}
function renderSbMeta(data, extra) {
const meta = document.getElementById('sb-preview-meta');
const parts = [];
if (data.period) parts.push('<span><span class="meta-label">周期:</span><span class="meta-value">' + escapeHtml(data.period) + '</span></span>');
if (extra && extra.source) parts.push('<span><span class="meta-label">来源:</span><span class="meta-value">' + escapeHtml(extra.source) + '</span></span>');
parts.push('<span><span class="meta-label">明细行:</span><span class="meta-value">' + (data.total || 0) + '</span></span>');
if (data.matched_guarantee != null) {
parts.push('<span><span class="meta-label">已关联兜底:</span><span class="meta-value">' + data.matched_guarantee + ' 行</span></span>');
}
meta.innerHTML = parts.join('');
meta.style.display = parts.length ? 'flex' : 'none';
}
function renderSbBrandFilter(data) {
const wrap = document.getElementById('sb-brand-filter');
const counts = data.brand_counts || {};
const chips = ['全部', '四界', '尊界', '尚界', '智界', '享界'];
let html = '';
chips.forEach(b => {
const cnt = b === '全部' ? (data.total || 0) : (b === '四界' ? (data.total || 0) : (counts[b] || 0));
const active = sbActiveBrand === b ? ' active' : '';
html += '<span class="brand-chip' + active + '" data-brand="' + escapeHtml(b) + '">' +
escapeHtml(b) + (cnt ? ' (' + cnt + ')' : '') + '</span>';
});
wrap.innerHTML = html;
wrap.style.display = 'flex';
wrap.querySelectorAll('.brand-chip').forEach(el => {
el.addEventListener('click', () => {
sbActiveBrand = el.dataset.brand;
renderSbBrandFilter(data);
renderSbPreviewBody(data);
});
});
}
function renderSbSummaryTable(summary) {
if (!summary || !summary.length) return '';
const cols = ['品牌', '主机厂交付数', '产值表交付数', '触客数', '整车延保成交数'];
let html = '<div class="summary-wrap"><table class="summary-table"><thead><tr>';
cols.forEach(c => { html += '<th>' + escapeHtml(c) + '</th>'; });
html += '</tr></thead><tbody>';
summary.forEach(row => {
html += '<tr class="summary-row">';
cols.forEach(c => {
html += '<td>' + escapeHtml(String(row[c] != null ? row[c] : '')) + '</td>';
});
html += '</tr>';
});
html += '</tbody></table></div>';
return html;
}
function renderSbPreviewBody(data) {
const columns = data.columns || [];
const rows = data.rows || [];
if (!columns.length || !rows.length) {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty">无数据</div>';
let rows = data.rows || [];
if (sbActiveBrand && sbActiveBrand !== '全部' && sbActiveBrand !== '四界') {
rows = rows.filter(r => String(r['品牌'] || '') === sbActiveBrand);
}
if (!columns.length) {
document.getElementById('sb-preview-body').innerHTML = '<div class="right-panel-empty">无数据</div>';
return;
}
let html = '<table class="preview-table"><thead><tr><th>#</th>';
let html = renderSbSummaryTable(data.summary);
html += '<table class="preview-table"><thead><tr><th>#</th>';
columns.forEach(c => { html += '<th>' + escapeHtml(String(c)) + '</th>'; });
html += '</tr></thead><tbody>';
rows.forEach((row, i) => {
......@@ -229,6 +319,116 @@
document.getElementById('sb-preview-body').innerHTML = html;
}
function renderSubBrandPreview(data, extra) {
sbPreviewCache = data;
document.getElementById('sb-preview-title').textContent = '\u{1f4ca} 子品牌数据预览';
document.getElementById('sb-preview-count').textContent =
sbActiveBrand === '全部' ? '共 ' + (data.total || 0) + ' 条' : '筛选 ' + sbActiveBrand;
renderSbMeta(data, extra);
renderSbBrandFilter(data);
renderSbPreviewBody(data);
}
async function loadSbBatchOptions() {
try {
const [storeRes, oemRes] = await Promise.all([
fetch(window.API_BASE + '/data-import/history?brand=鸿蒙&data_type=store_guarantee'),
fetch(window.API_BASE + '/data-import/history?brand=鸿蒙&data_type=harmony_sub_brand_oem'),
]);
const storeData = await storeRes.json();
const oemData = await oemRes.json();
function fill(selId, rows) {
const sel = document.getElementById(selId);
if (!sel) return;
while (sel.options.length > 1) sel.remove(1);
(rows || []).forEach(r => {
const opt = document.createElement('option');
opt.value = r.batch_no;
opt.textContent = (r.file_name || r.batch_no) + ' [' + (r.data_period_start || '') + '~' + (r.data_period_end || '') + ']';
sel.appendChild(opt);
});
}
if (storeData.status === 'success') fill('sb-store-batch-select', storeData.data);
if (oemData.status === 'success') fill('sb-oem-batch-select', oemData.data);
} catch (e) {
console.error('加载批次失败:', e);
}
}
window.onSbStoreBatchSelect = async function() {
highlightSbStep('sb-step-store');
const batchNo = document.getElementById('sb-store-batch-select').value;
if (!batchNo) return;
try {
const res = await fetch(window.API_BASE + '/analysis/batch-data?batch_no=' + encodeURIComponent(batchNo));
const data = await res.json();
if (data.status === 'success') {
renderSubBrandPreview(data.data, { source: '门店兜底批次 ' + batchNo });
}
} catch (e) {
console.error(e);
}
if (sbPreviewCache && document.getElementById('sb-oem-batch-select').value) {
onSbOemBatchSelect();
}
};
window.onSbOemBatchSelect = async function() {
highlightSbStep('sb-step-oem');
const batchNo = document.getElementById('sb-oem-batch-select').value;
if (!batchNo) return;
const dates = getSbDates();
const storeBatch = document.getElementById('sb-store-batch-select').value;
let url = window.API_BASE + '/harmony/sub-brand/batch-data?batch_no=' + encodeURIComponent(batchNo);
if (storeBatch) url += '&store_batch_no=' + encodeURIComponent(storeBatch);
if (dates.start) url += '&start_date=' + encodeURIComponent(dates.start);
if (dates.end) url += '&end_date=' + encodeURIComponent(dates.end);
document.getElementById('sb-preview-body').innerHTML = '<div class="right-panel-empty">正在加载批次...</div>';
try {
const res = await fetch(url);
const data = await res.json();
if (data.status !== 'success') throw new Error(data.detail || '加载失败');
sbActiveBrand = '全部';
renderSubBrandPreview(data.data, { source: '子品牌 OEM 批次 ' + batchNo });
document.getElementById('sb-file-name').textContent = '\u2705 ' + (data.data.file_name || batchNo);
document.getElementById('sb-drop-zone').classList.add('has-file');
} catch (e) {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">' + escapeHtml(e.message) + '</div>';
}
};
window.onSubBrandFileChange = async function() {
highlightSbStep('sb-step-oem');
const input = document.getElementById('sb-file-input');
if (!input.files.length) return;
document.getElementById('sb-oem-batch-select').value = '';
const file = input.files[0];
document.getElementById('sb-file-name').textContent = '\u2705 ' + file.name;
document.getElementById('sb-drop-zone').classList.add('has-file');
document.getElementById('btn-save-sb-batch').style.display = 'block';
const formData = new FormData();
formData.append('data_file', file);
const dates = getSbDates();
const storeBatch = document.getElementById('sb-store-batch-select').value;
if (dates.start) formData.append('start_date', dates.start);
if (dates.end) formData.append('end_date', dates.end);
if (storeBatch) formData.append('store_batch_no', storeBatch);
document.getElementById('sb-preview-body').innerHTML = '<div class="right-panel-empty">正在解析...</div>';
try {
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 || '上传失败');
sbActiveBrand = '全部';
renderSubBrandPreview(data.data, { source: file.name });
} catch (e) {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">' + escapeHtml(e.message) + '</div>';
}
};
window.saveSubBrandBatch = async function() {
const input = document.getElementById('sb-file-input');
if (!input || !input.files.length) { alert('请先上传文件'); return; }
......@@ -237,20 +437,17 @@
btn.textContent = '\u23f3 保存中...';
const formData = new FormData();
formData.append('data_file', input.files[0]);
const sd = document.getElementById('sb-start-date').value;
const ed = document.getElementById('sb-end-date').value;
if (sd) formData.append('start_date', sd);
if (ed) formData.append('end_date', ed);
const dates = getSbDates();
if (dates.start) formData.append('start_date', dates.start);
if (dates.end) formData.append('end_date', dates.end);
try {
const res = await fetch(window.API_BASE + '/harmony/sub-brand/save-batch', { method: 'POST', body: formData });
const data = await res.json();
if (data.status !== 'success') throw new Error(data.detail || '保存失败');
btn.textContent = '\u2705 已保存 (' + (data.data.batch_no || '') + ')';
btn.style.background = '#f6ffed';
btn.style.borderColor = '#b7eb8f';
btn.style.color = '#52c41a';
loadSbBatchOptions();
} catch (e) {
alert(e.message || '保存失败');
alert(e.message);
btn.disabled = false;
btn.textContent = '\u{1f4be} 保存为历史批次';
}
......@@ -259,101 +456,72 @@
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('sb-tpl-input').href = tplUrl('input');
document.getElementById('sb-tpl-output').href = tplUrl('output');
loadSbBatchOptions();
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 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');
document.getElementById('btn-save-sb-batch').style.display = 'block';
const formData = new FormData();
formData.append('data_file', file);
const sd = document.getElementById('sb-start-date').value;
const ed = document.getElementById('sb-end-date').value;
if (sd) formData.append('start_date', sd);
if (ed) formData.append('end_date', ed);
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 || '上传失败');
}
renderSubBrandPreview(data.data || {});
} catch(e) {
console.error('子品牌上传失败:', e);
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">' + (e.message || '上传失败') + '</div>';
}
};
document.getElementById('btn-generate-sb-report').addEventListener('click', async () => {
document.getElementById('sb-analysis-result').className = 'result-box';
document.getElementById('sb-analysis-error').className = 'result-box';
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;
}
const oemBatch = document.getElementById('sb-oem-batch-select').value;
const hasFile = document.getElementById('sb-file-input').files.length > 0;
if (!oemBatch && !hasFile) {
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = '请先上传或选择主机厂子品牌数据';
return;
}
btnSb.disabled = true;
btnSb.textContent = '\u23f3 正在生成报表...';
const btn = document.getElementById('btn-generate-sb-report');
btn.disabled = true;
btn.textContent = '\u23f3 正在生成...';
const dates = getSbDates();
const storeBatch = document.getElementById('sb-store-batch-select').value;
try {
try {
if (hasFile && !oemBatch) {
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);
uploadForm.append('data_file', document.getElementById('sb-file-input').files[0]);
if (dates.start) uploadForm.append('start_date', dates.start);
if (dates.end) uploadForm.append('end_date', dates.end);
if (storeBatch) uploadForm.append('store_batch_no', storeBatch);
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 =
(window.APP_ROOT || '') + (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 genForm = new FormData();
if (dates.start) genForm.append('start_date', dates.start);
if (dates.end) genForm.append('end_date', dates.end);
if (storeBatch) genForm.append('store_batch_no', storeBatch);
if (oemBatch) genForm.append('oem_batch_no', oemBatch);
const genRes = await fetch(window.API_BASE + '/harmony/sub-brand/generate', { method: 'POST', body: genForm });
const genData = await genRes.json();
if (genData.status !== 'success') throw new Error(genData.detail || '生成失败');
document.getElementById('sb-analysis-result').className = 'result-box success';
const info = [];
if (genData.detail_rows) info.push('明细 ' + genData.detail_rows + ' 行');
info.push('含汇总行 5 行');
info.push('文件: ' + (genData.file_path || ''));
document.getElementById('sb-analysis-result-info').innerHTML = info.join(' · ');
document.getElementById('btn-download-sb-report').href =
(window.APP_ROOT || '') + (genData.download_url || '');
} catch (e) {
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = e.message || '未知错误';
} finally {
btn.disabled = false;
btn.textContent = '\u{1f680} 生成鸿蒙子品牌分析报表';
}
});
});
</script>
<script src="../static/js/auth.js"></script>
......
# -*- coding: utf-8 -*-
"""
从鸿蒙子品牌分析报表提取输出模板。
数据源: 鸿蒙7月1-19号(含主机厂数据).xlsx → Sheet「鸿蒙子品牌7.1-7.19」
结构: 19列, 2行表头; 第3-7行为汇总(四界/尊界/尚界/智界/享界, 门店列为空); 第8行起为门店×品牌明细。
输出:
- app/templates/xlsx/输出模板-鸿蒙子品牌-模板{序号}.xlsx
"""
import glob
import io
import os
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
from openpyxl import Workbook, load_workbook
from openpyxl.formatting.rule import FormulaRule
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
SRC = r"d:\xwechat_files\fatjohnbull_c478\msg\file\2026-07\鸿蒙7月1-19号(含主机厂数据).xlsx"
SRC_SHEET = "鸿蒙子品牌7.1-7.19"
max_no = 0
for f in glob.glob("app/templates/xlsx/输出模板-鸿蒙子品牌-模板[0-9][0-9][0-9].xlsx"):
try:
max_no = max(max_no, int(os.path.splitext(os.path.basename(f))[0][-3:]))
except ValueError:
pass
seq = max(max_no + 1, 2)
OUTPUT_TEMPLATE = f"app/templates/xlsx/输出模板-鸿蒙子品牌-模板{seq:03d}.xlsx"
header_fill = PatternFill("solid", fgColor="BDD7EE")
header_font = Font(name="微软雅黑", bold=True, color="000000", size=10)
sub_fill = PatternFill("solid", fgColor="BDD7EE")
sub_font = Font(name="微软雅黑", bold=True, color="000000", size=10)
value_fill = PatternFill("solid", fgColor="92D050")
value_font = Font(name="微软雅黑", bold=True, color="000000", size=10)
data_font = Font(name="微软雅黑", size=10, color="000000")
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)
PERCENT_COLS = {12, 14, 15, 17, 19}
def write_header_cell(ws, row, col, value, fill=None, font=None):
c = ws.cell(row=row, column=col, value=value)
c.font = font or header_font
c.fill = fill or header_fill
c.alignment = center_align
c.border = thin_border
def write_sub_cell(ws, row, col, value, fill=None):
c = ws.cell(row=row, column=col, value=value)
c.font = sub_font
c.fill = fill or sub_fill
c.alignment = center_align
c.border = thin_border
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
if isinstance(value, (int, float)):
if col in PERCENT_COLS:
c.number_format = "0.00%"
else:
c.number_format = "0"
return c
print(f"读取源表: {SRC_SHEET}")
wb_src = load_workbook(SRC, data_only=True)
ws_src = wb_src[SRC_SHEET]
summary_rows = []
for r in range(3, 8):
brand = ws_src.cell(row=r, column=8).value
if not brand:
continue
summary_rows.append({
"品牌": str(brand).strip(),
"主机厂交付数": ws_src.cell(row=r, column=9).value or 0,
"产值表交付数": ws_src.cell(row=r, column=10).value or 0,
"触客数": ws_src.cell(row=r, column=11).value or 0,
"整车延保成交数": ws_src.cell(row=r, column=13).value or 0,
"安心包": ws_src.cell(row=r, column=16).value or 0,
"电池": ws_src.cell(row=r, column=18).value or 0,
})
print(f"汇总行样本: {[s['品牌'] for s in summary_rows]}")
sample = None
for r in range(8, ws_src.max_row + 1):
store = ws_src.cell(row=r, column=1).value
brand = ws_src.cell(row=r, column=8).value
if store and brand and str(brand).strip() not in ("四界",):
sample = {
"门店": str(store).strip(),
"兜底指标": str(ws_src.cell(row=r, column=2).value or "").strip(),
"区域(省)": str(ws_src.cell(row=r, column=3).value or "").strip(),
"直营与否": str(ws_src.cell(row=r, column=4).value or "").strip(),
"区域运营": str(ws_src.cell(row=r, column=5).value or "").strip(),
"飞行督导": str(ws_src.cell(row=r, column=6).value or "").strip(),
"线上运营": str(ws_src.cell(row=r, column=7).value or "").strip(),
"品牌": str(brand).strip(),
"主机厂交付数": ws_src.cell(row=r, column=9).value or 0,
"产值表交付数": ws_src.cell(row=r, column=10).value or 0,
"触客数": ws_src.cell(row=r, column=11).value or 0,
"整车延保成交数": ws_src.cell(row=r, column=13).value or 0,
"安心包": ws_src.cell(row=r, column=16).value or 0,
"电池": ws_src.cell(row=r, column=18).value or 0,
}
break
wb_src.close()
if not sample:
raise RuntimeError("未找到示例子品牌明细行")
print(f"示例明细: {sample['门店'][:20]} / {sample['品牌']}")
twb = Workbook()
tws = twb.active
tws.title = "模板"
# ── Row 1-2 表头 ──
for col in range(1, 9):
titles = ["门店", "兜底指标", "区域(省)", "直营与否", "区域运营", "飞行督导", "线上运营", "品牌"]
tws.merge_cells(f"{get_column_letter(col)}1:{get_column_letter(col)}2")
write_header_cell(tws, 1, col, titles[col - 1])
tws.merge_cells("I1:J1")
write_header_cell(tws, 1, 9, "交付数")
write_sub_cell(tws, 2, 9, "主机厂")
write_sub_cell(tws, 2, 10, "产值表")
tws.merge_cells("K1:L1")
write_header_cell(tws, 1, 11, "触客情况")
write_sub_cell(tws, 2, 11, "触客数")
write_sub_cell(tws, 2, 12, "触客率")
value_headers = [
(13, "整车延保成交订单数"),
(14, "整车延保渗透率"),
(15, "触客成交率"),
(16, "安心包"),
(17, "安心包渗透率"),
(18, "电池"),
(19, "电池渗透率"),
]
for col, title in value_headers:
tws.merge_cells(f"{get_column_letter(col)}1:{get_column_letter(col)}2")
write_header_cell(tws, 1, col, title, fill=value_fill, font=value_font)
# ── 列宽 (参照源表) ──
widths = {
"A": 21.625, "B": 11.5, "C": 13.375, "D": 10.875, "E": 13.0,
"F": 11.25, "G": 12.0, "H": 13.25, "I": 10.0, "J": 12.375,
"K": 8.625, "L": 8.5, "M": 9.875, "N": 10.5, "O": 9.875,
"P": 10.375, "Q": 9.0, "R": 10.0, "S": 12.75,
}
for col, w in widths.items():
tws.column_dimensions[col].width = w
tws.row_dimensions[1].height = 18
tws.row_dimensions[2].height = 18
# ── Row 3-7: 汇总行占位 (品牌列填四界/尊界/尚界/智界/享界, 数值由报表生成时写入) ──
summary_labels = ["四界", "尊界", "尚界", "智界", "享界"]
for i, label in enumerate(summary_labels):
row = 3 + i
write_data_cell(tws, row, 8, label)
# ── Row 8: 示例明细行 ──
row = 8
write_data_cell(tws, row, 1, sample["门店"])
write_data_cell(tws, row, 2, sample["兜底指标"])
write_data_cell(tws, row, 3, sample["区域(省)"])
write_data_cell(tws, row, 4, sample["直营与否"])
write_data_cell(tws, row, 5, sample["区域运营"])
write_data_cell(tws, row, 6, sample["飞行督导"])
write_data_cell(tws, row, 7, sample["线上运营"])
write_data_cell(tws, row, 8, sample["品牌"])
write_data_cell(tws, row, 9, sample["主机厂交付数"])
write_data_cell(tws, row, 10, sample["产值表交付数"])
write_data_cell(tws, row, 11, sample["触客数"])
write_data_cell(tws, row, 12, f"=IF(I{row}>0,K{row}/I{row},0)")
write_data_cell(tws, row, 13, sample["整车延保成交数"])
write_data_cell(tws, row, 14, f"=IF(I{row}>0,M{row}/I{row},0)")
write_data_cell(tws, row, 15, f"=IF(K{row}>0,M{row}/K{row},0)")
write_data_cell(tws, row, 16, sample["安心包"])
write_data_cell(tws, row, 17, f"=IF(I{row}>0,P{row}/I{row},0)")
write_data_cell(tws, row, 18, sample["电池"])
write_data_cell(tws, row, 19, f"=IF(I{row}>0,R{row}/I{row},0)")
tws.freeze_panes = "I3"
os.makedirs(os.path.dirname(OUTPUT_TEMPLATE), exist_ok=True)
twb.save(OUTPUT_TEMPLATE)
print(f"输出模板: {OUTPUT_TEMPLATE}")
print("列数: 19")
print(f"合并单元格: {len(tws.merged_cells.ranges)}")
print("完成!")
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!