Commit 3a4651cb by 江名洋

feat(strategy): 新增盯防数据自动刷新与策略类型筛选

1 parent d2b02056
...@@ -542,6 +542,7 @@ async def strategy_list( ...@@ -542,6 +542,7 @@ async def strategy_list(
effect: Optional[str] = Query(None), effect: Optional[str] = Query(None),
start_date: Optional[str] = Query(None), start_date: Optional[str] = Query(None),
end_date: Optional[str] = Query(None), end_date: Optional[str] = Query(None),
strategy_type: Optional[str] = Query(None),
page: int = Query(1, ge=1), page: int = Query(1, ge=1),
page_size: int = Query(8, ge=1, le=100), page_size: int = Query(8, ge=1, le=100),
): ):
...@@ -557,6 +558,7 @@ async def strategy_list( ...@@ -557,6 +558,7 @@ async def strategy_list(
effect=effect, effect=effect,
start_date=start_date, start_date=start_date,
end_date=end_date, end_date=end_date,
strategy_type=strategy_type,
page=page, page=page,
page_size=page_size, page_size=page_size,
) )
...@@ -603,11 +605,14 @@ async def strategy_trigger_analyze(): ...@@ -603,11 +605,14 @@ async def strategy_trigger_analyze():
@router.post("/strategy/analyze/{strategy_id}") @router.post("/strategy/analyze/{strategy_id}")
async def strategy_analyze_single(strategy_id: int): async def strategy_analyze_single(strategy_id: int):
"""对单条策略执行分析并保存结果""" """对单条策略执行分析并保存结果(同步实时执行,分析+写入完成后返回)"""
try: try:
logger.info(f"[API] ==== POST /strategy/analyze/{strategy_id} START ====")
result = StrategyService.analyze_and_save_single(strategy_id) result = StrategyService.analyze_and_save_single(strategy_id)
if result is None: if result is None:
logger.warning(f"[API] POST /strategy/analyze/{strategy_id} returned None")
raise HTTPException(status_code=404, detail=f"策略 #{strategy_id} 未找到或分析失败") raise HTTPException(status_code=404, detail=f"策略 #{strategy_id} 未找到或分析失败")
logger.info(f"[API] ==== POST /strategy/analyze/{strategy_id} DONE, effect={result.get('effect_label')} ====")
return {"status": "success", "message": f"策略 #{strategy_id} 分析完成", "data": result} return {"status": "success", "message": f"策略 #{strategy_id} 分析完成", "data": result}
except HTTPException: except HTTPException:
raise raise
...@@ -625,3 +630,45 @@ async def strategy_analyze_status(): ...@@ -625,3 +630,45 @@ async def strategy_analyze_status():
except Exception as e: except Exception as e:
logger.error(f"Strategy analyze status failed: {e}", exc_info=True) logger.error(f"Strategy analyze status failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"获取任务状态失败: {str(e)}") raise HTTPException(status_code=500, detail=f"获取任务状态失败: {str(e)}")
@router.post("/strategy/refresh-stale")
async def strategy_refresh_stale(stale_hours: int = Query(4, ge=1, le=48)):
"""手动触发超时盯防数据刷新,扫描超过指定小时未更新的盯防策略并自动刷新"""
try:
result = StrategyService.auto_refresh_stale_monitoring(stale_hours)
return {"status": "success", "message": f"刷新完成", "data": result}
except Exception as e:
logger.error(f"Strategy refresh stale failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"刷新盯防数据失败: {str(e)}")
@router.get("/strategy/refresh-status")
async def strategy_refresh_status():
"""查询盯防数据刷新状态(活跃/超时/从未刷新)"""
try:
status = StrategyService.get_monitoring_refresh_status()
return {"status": "success", "data": status}
except Exception as e:
logger.error(f"Strategy refresh status failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询刷新状态失败: {str(e)}")
@router.get("/strategy/stale-list")
async def strategy_stale_list(stale_hours: int = Query(4, ge=1, le=48)):
"""查询超时未刷新的盯防策略列表"""
try:
strategies = StrategyService.get_stale_monitoring_strategies(stale_hours)
items = []
for s in strategies:
items.append({
"id": s["id"],
"title": s.get("title") or "",
"merchant_name": s.get("merchant_name") or "",
"start_date": StrategyService._date_str(s.get("start_date")),
"end_date": StrategyService._date_str(s.get("end_date")),
})
return {"status": "success", "data": {"count": len(items), "items": items}}
except Exception as e:
logger.error(f"Strategy stale list failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询超时策略失败: {str(e)}")
...@@ -65,7 +65,8 @@ MODULE_LOG_FILES = { ...@@ -65,7 +65,8 @@ MODULE_LOG_FILES = {
"app.etl": "etl.log", "app.etl": "etl.log",
"app.api": "api.log", "app.api": "api.log",
"app.db": "db.log", "app.db": "db.log",
"app.scheduler": "scheduler.log", "app.scheduler": "scheduler.log",
"app.strategy_service": "strategy.log",
} }
......
...@@ -48,7 +48,16 @@ class SchedulerManager: ...@@ -48,7 +48,16 @@ class SchedulerManager:
replace_existing=True, replace_existing=True,
) )
# 3. 健康检查 (每 10 分钟执行一次) # 3. 盯防数据自动刷新 (每 1 小时扫描超过 4 小时未刷新的盯防数据)
cls._scheduler.add_job(
cls.auto_refresh_strategy_monitoring,
IntervalTrigger(hours=1, jitter=120),
id="auto_refresh_strategy_monitoring",
max_instances=1,
replace_existing=True,
)
# 4. 健康检查 (每 10 分钟执行一次)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.health_check, cls.health_check,
IntervalTrigger(minutes=10), IntervalTrigger(minutes=10),
...@@ -106,6 +115,23 @@ class SchedulerManager: ...@@ -106,6 +115,23 @@ class SchedulerManager:
StrategyService.run_analysis_task() StrategyService.run_analysis_task()
@classmethod @classmethod
async def auto_refresh_strategy_monitoring(cls):
"""自动刷新盯防数据:扫描超过 4 小时未刷新的盯防策略"""
logger.info(f"[Scheduler] Start auto_refresh_strategy_monitoring at {datetime.now()}")
try:
from app.services.strategy_service import StrategyService
result = await asyncio.get_event_loop().run_in_executor(
None, lambda: StrategyService.auto_refresh_stale_monitoring(stale_hours=4)
)
logger.info(
f"[Scheduler] auto_refresh_strategy_monitoring done: "
f"total={result.get('total', 0)}, refreshed={result.get('refreshed', 0)}, "
f"failed={result.get('failed', 0)}"
)
except Exception as e:
logger.error(f"[Scheduler] auto_refresh_strategy_monitoring failed: {e}")
@classmethod
async def health_check(cls): async def health_check(cls):
"""系统健康检查任务""" """系统健康检查任务"""
logger.info(f"[Scheduler] System health check at {datetime.now()}") logger.info(f"[Scheduler] System health check at {datetime.now()}")
...@@ -437,7 +437,7 @@ class AnalysisService: ...@@ -437,7 +437,7 @@ class AnalysisService:
flight_supervision, flight_supervision,
online_supervision, online_supervision,
SUM(IFNULL(delivery_count, 0)) AS total_delivery, SUM(IFNULL(delivery_count, 0)) AS total_delivery,
SUM(IFNULL(sum_equity_to_shop, 0)) AS total_touch, SUM(IFNULL(sum_extended_warranty_to_shop, 0)) AS total_touch,
SUM(IFNULL(sum_extended_warranty, 0)) AS total_yb_orders, SUM(IFNULL(sum_extended_warranty, 0)) AS total_yb_orders,
SUM(IFNULL(sum_ax_package, 0)) AS total_axb_orders, SUM(IFNULL(sum_ax_package, 0)) AS total_axb_orders,
SUM(IFNULL(sum_battery_extended, 0)) AS total_battery_orders, SUM(IFNULL(sum_battery_extended, 0)) AS total_battery_orders,
......
...@@ -74,8 +74,8 @@ class HarmonyAnalysisService: ...@@ -74,8 +74,8 @@ class HarmonyAnalysisService:
""" """
读取鸿蒙门店兜底配置Excel。 读取鸿蒙门店兜底配置Excel。
结构: 第1行主表头, 第2行子表头(整车延保/安心包/电池延保), 第3行起为数据。 结构: 第1行主表头, 第2行子表头(整车延保/安心包/电池延保), 第3行起为数据。
15列: 门店, 品牌, 兜底指标, 区域(省), 直营与否, 区域运营, 飞行督导, 16列: 门店, 品牌, 兜底指标, 区域(省), 直营与否, 区域运营, 飞行督导,
线上运营, 兜底类型, 需达标转化率(3列), 预计赔付金额(3列) 线上运营, 兜底类型, 特殊情况, 需达标转化率(3列), 预计赔付金额(3列)
""" """
df_raw = pd.read_excel(file_path, header=None) df_raw = pd.read_excel(file_path, header=None)
...@@ -105,6 +105,8 @@ class HarmonyAnalysisService: ...@@ -105,6 +105,8 @@ class HarmonyAnalysisService:
col_map[i] = "线上运营" col_map[i] = "线上运营"
elif h0 == "兜底类型": elif h0 == "兜底类型":
col_map[i] = "兜底类型" col_map[i] = "兜底类型"
elif h0 == "特殊情况":
col_map[i] = "特殊情况"
elif h0 == "需达标转化率": elif h0 == "需达标转化率":
col_map[i] = f"需达标转化率_{sub}" if sub else f"需达标转化率_{i}" col_map[i] = f"需达标转化率_{sub}" if sub else f"需达标转化率_{i}"
elif h0 == "预计赔付金额": elif h0 == "预计赔付金额":
...@@ -118,6 +120,7 @@ class HarmonyAnalysisService: ...@@ -118,6 +120,7 @@ class HarmonyAnalysisService:
required = [ required = [
"门店名", "品牌", "兜底指标", "区域(省)", "直营与否", "门店名", "品牌", "兜底指标", "区域(省)", "直营与否",
"区域运营", "飞行督导", "线上运营", "兜底类型", "区域运营", "飞行督导", "线上运营", "兜底类型",
"特殊情况",
"需达标转化率_整车延保", "需达标转化率_安心包", "需达标转化率_电池延保", "需达标转化率_整车延保", "需达标转化率_安心包", "需达标转化率_电池延保",
"预计赔付金额_整车", "预计赔付金额_安心包", "预计赔付金额_电池", "预计赔付金额_整车", "预计赔付金额_安心包", "预计赔付金额_电池",
] ]
...@@ -331,7 +334,7 @@ class HarmonyAnalysisService: ...@@ -331,7 +334,7 @@ class HarmonyAnalysisService:
flight_supervision, flight_supervision,
online_supervision, online_supervision,
SUM(IFNULL(delivery_count, 0)) AS total_delivery, SUM(IFNULL(delivery_count, 0)) AS total_delivery,
SUM(IFNULL(sum_equity_to_shop, 0)) AS total_touch, SUM(IFNULL(sum_extended_warranty_to_shop, 0)) AS total_touch,
SUM(IFNULL(sum_extended_warranty, 0)) AS total_yb_orders, SUM(IFNULL(sum_extended_warranty, 0)) AS total_yb_orders,
SUM(IFNULL(sum_ax_package, 0)) AS total_axb_orders, SUM(IFNULL(sum_ax_package, 0)) AS total_axb_orders,
SUM(IFNULL(sum_battery_extended, 0)) AS total_battery_orders, SUM(IFNULL(sum_battery_extended, 0)) AS total_battery_orders,
...@@ -572,7 +575,7 @@ class HarmonyAnalysisService: ...@@ -572,7 +575,7 @@ class HarmonyAnalysisService:
_style_cell(row_num, 6, store_row.get("区域运营", perf.get("area_supervision", ""))) _style_cell(row_num, 6, store_row.get("区域运营", perf.get("area_supervision", "")))
_style_cell(row_num, 7, store_row.get("飞行督导", perf.get("flight_supervision", ""))) _style_cell(row_num, 7, store_row.get("飞行督导", perf.get("flight_supervision", "")))
_style_cell(row_num, 8, store_row.get("线上运营", perf.get("online_supervision", ""))) _style_cell(row_num, 8, store_row.get("线上运营", perf.get("online_supervision", "")))
_style_cell(row_num, 9, "") # 特殊情况 _style_cell(row_num, 9, store_row.get("特殊情况", ""))
# ========== 交付数 (J-L, 10-12) ========== # ========== 交付数 (J-L, 10-12) ==========
factory_delivery: float = _safe_float(store_row.get("交付数", 0)) factory_delivery: float = _safe_float(store_row.get("交付数", 0))
...@@ -593,9 +596,16 @@ class HarmonyAnalysisService: ...@@ -593,9 +596,16 @@ class HarmonyAnalysisService:
db_battery = perf.get("battery_orders", 0) db_battery = perf.get("battery_orders", 0)
# ========== 产值表数据 (N-V, 14-22) ========== # ========== 产值表数据 (N-V, 14-22) ==========
# N: 触客数 (DB),兜底类型=触客 且 特殊情况含"安心包专岗"时限制不超过交付数2
touch = _safe_float(store_row.get("触客数", 0)) touch = _safe_float(store_row.get("触客数", 0))
if touch == 0: if touch == 0:
touch = db_touch touch = db_touch
baodi_type = str(store_row.get("兜底指标", "")).strip()
special_cond = str(store_row.get("特殊情况", "")).strip()
capped = False
if baodi_type == "触客" and "安心包专岗" in special_cond and touch > db_delivery:
touch = db_delivery
capped = True
_style_cell(row_num, 14, touch) _style_cell(row_num, 14, touch)
yb_orders = _safe_float(store_row.get("整车延保成交数", 0)) yb_orders = _safe_float(store_row.get("整车延保成交数", 0))
......
...@@ -22,17 +22,8 @@ ...@@ -22,17 +22,8 @@
} }
}; };
// 计算 API 基础路径(兼容 /login 等根级页面) // API 基础路径始终为 /api(FastAPI 统一挂载)
(function() { window.API_BASE = '/api';
var p = window.location.pathname;
if (p.endsWith('/')) p = p.slice(0, -1);
var idx = p.lastIndexOf('/');
window.API_BASE = p.substring(0, idx) + '/api';
// 如果当前就是根路径(如 /login 直接访问),兜底为 /api
if (!window.API_BASE || window.API_BASE === '/api') {
window.API_BASE = '/api';
}
})();
// 登录页不执行后续逻辑 // 登录页不执行后续逻辑
if (window.location.pathname.includes('/login')) { if (window.location.pathname.includes('/login')) {
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>盯防效果数据查看 - 问界门店运营数据分析平台</title> <title>盯防效果数据查看 - 问界门店运营数据分析平台</title>
<link rel="stylesheet" href="./static/css/style.css"> <link rel="stylesheet" href="/static/css/style.css">
<style> <style>
:root { :root {
--primary: #1890ff; --primary: #1890ff;
...@@ -193,19 +193,19 @@ ...@@ -193,19 +193,19 @@
<header> <header>
<div class="logo">问界运营分析平台</div> <div class="logo">问界运营分析平台</div>
<nav class="nav-links"> <nav class="nav-links">
<a class="nav-item" href="./">首页</a> <a class="nav-item" href="/">首页</a>
<a class="nav-item" href="./ods">ODS 同步任务</a> <a class="nav-item" href="/ods">ODS 同步任务</a>
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a> <a class="nav-item" href="/dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="/analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="/harmony">鸿蒙生态分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防</a> <a class="nav-item active" href="/strategy">策略效果盯防</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
<div class="detail-header"> <div class="detail-header">
<div class="breadcrumb"> <div class="breadcrumb">
<a href="./strategy">盯防管理</a> &gt; <span class="current">盯防效果数据查看</span> <a href="/strategy">盯防管理</a> &gt; <span class="current">盯防效果数据查看</span>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button class="btn btn-primary" onclick="history.back()">返回列表</button> <button class="btn btn-primary" onclick="history.back()">返回列表</button>
...@@ -217,7 +217,7 @@ ...@@ -217,7 +217,7 @@
</div> </div>
<script> <script>
(function(){var p=window.location.pathname;if(p.endsWith('/'))p=p.slice(0,-1);var i=p.lastIndexOf('/');window.API_BASE=p.substring(0,i)+'/api';})(); window.API_BASE = '/api';
const PRODUCT_META = { const PRODUCT_META = {
ew: { name: '整车延保', color: '#1890ff' }, ew: { name: '整车延保', color: '#1890ff' },
...@@ -502,6 +502,7 @@ ...@@ -502,6 +502,7 @@
<div class="info-row"><span class="info-label">盯防标题</span><span class="info-value">${escapeHtml(s.title || '-')}</span></div> <div class="info-row"><span class="info-label">盯防标题</span><span class="info-value">${escapeHtml(s.title || '-')}</span></div>
<div class="info-row"><span class="info-label">盯防内容</span><span class="info-value">${escapeHtml(s.description || '-')}</span></div> <div class="info-row"><span class="info-label">盯防内容</span><span class="info-value">${escapeHtml(s.description || '-')}</span></div>
<div class="info-row"><span class="info-label">盯防周期</span><span class="info-value">${escapeHtml(s.start_date || '')} ~ ${escapeHtml(s.end_date || '')}</span></div> <div class="info-row"><span class="info-label">盯防周期</span><span class="info-value">${escapeHtml(s.start_date || '')} ~ ${escapeHtml(s.end_date || '')}</span></div>
<div class="info-row"><span class="info-label">数据刷新时间</span><span class="info-value">${data.monitor_refresh_time ? escapeHtml(data.monitor_refresh_time) : '<span style="color:#f5222d">从未刷新</span>'}</span></div>
<div class="info-row"><span class="info-label">任务接收人</span><span class="info-value">${escapeHtml(s.created_by || '-')}</span></div> <div class="info-row"><span class="info-label">任务接收人</span><span class="info-value">${escapeHtml(s.created_by || '-')}</span></div>
</div> </div>
</div> </div>
...@@ -568,6 +569,6 @@ ...@@ -568,6 +569,6 @@
document.addEventListener('DOMContentLoaded', loadDetail); document.addEventListener('DOMContentLoaded', loadDetail);
</script> </script>
<script src="./static/js/auth.js"></script> <script src="/static/js/auth.js"></script>
</body> </body>
</html> </html>
\ No newline at end of file \ No newline at end of file
...@@ -1183,6 +1183,15 @@ def generate_conclusion(strategy, store, period_labels, period_metrics, ...@@ -1183,6 +1183,15 @@ def generate_conclusion(strategy, store, period_labels, period_metrics,
lines.append("\n## 二、策略执行效果\n") lines.append("\n## 二、策略执行效果\n")
if exec_m: if exec_m:
def rate_pp(delta):
if delta > 10: return "大幅提升(显著改善)"
if delta > 3: return "明显提升"
if delta > 0: return "小幅提升"
if delta == 0: return "持平"
if delta > -3: return "小幅下降"
if delta > -10: return "明显下降"
return "大幅下降(需关注)"
# T vs T-1 # T vs T-1
if base: if base:
lines.append("### 策略执行期 vs 基线期 (T vs T-1)") lines.append("### 策略执行期 vs 基线期 (T vs T-1)")
...@@ -1191,15 +1200,6 @@ def generate_conclusion(strategy, store, period_labels, period_metrics, ...@@ -1191,15 +1200,6 @@ def generate_conclusion(strategy, store, period_labels, period_metrics,
bt_delta = _pen_change(base, exec_m, "battery_conversion") bt_delta = _pen_change(base, exec_m, "battery_conversion")
touch_delta_pp = (exec_m.get("avg_daily_touch", 0) / max(base.get("avg_daily_touch", 0.1), 0.1) - 1) * 100 touch_delta_pp = (exec_m.get("avg_daily_touch", 0) / max(base.get("avg_daily_touch", 0.1), 0.1) - 1) * 100
def rate_pp(delta):
if delta > 10: return "大幅提升(显著改善)"
if delta > 3: return "明显提升"
if delta > 0: return "小幅提升"
if delta == 0: return "持平"
if delta > -3: return "小幅下降"
if delta > -10: return "明显下降"
return "大幅下降(需关注)"
lines.append(f" - 整车延保渗透率变化: {ew_delta:+.1f}pp → {rate_pp(ew_delta)}") lines.append(f" - 整车延保渗透率变化: {ew_delta:+.1f}pp → {rate_pp(ew_delta)}")
lines.append(f" - 安心包渗透率变化: {ax_delta:+.1f}pp → {rate_pp(ax_delta)}") lines.append(f" - 安心包渗透率变化: {ax_delta:+.1f}pp → {rate_pp(ax_delta)}")
lines.append(f" - 电池延保渗透率变化: {bt_delta:+.1f}pp → {rate_pp(bt_delta)}") lines.append(f" - 电池延保渗透率变化: {bt_delta:+.1f}pp → {rate_pp(bt_delta)}")
......
...@@ -116,6 +116,7 @@ for r in range(3, main_ws.max_row + 1): ...@@ -116,6 +116,7 @@ for r in range(3, main_ws.max_row + 1):
'区域运营': safe_str(main_ws.cell(row=r, column=6).value), '区域运营': safe_str(main_ws.cell(row=r, column=6).value),
'飞行督导': safe_str(main_ws.cell(row=r, column=7).value), '飞行督导': safe_str(main_ws.cell(row=r, column=7).value),
'线上运营': safe_str(main_ws.cell(row=r, column=8).value), '线上运营': safe_str(main_ws.cell(row=r, column=8).value),
'特殊情况': safe_str(main_ws.cell(row=r, column=9).value),
'兜底类型': safe_str(main_ws.cell(row=r, column=25).value), '兜底类型': safe_str(main_ws.cell(row=r, column=25).value),
'需达标_整车延保': safe_str(main_ws.cell(row=r, column=29).value), '需达标_整车延保': safe_str(main_ws.cell(row=r, column=29).value),
'需达标_安心包': safe_str(main_ws.cell(row=r, column=30).value), '需达标_安心包': safe_str(main_ws.cell(row=r, column=30).value),
...@@ -126,6 +127,13 @@ for r in range(3, main_ws.max_row + 1): ...@@ -126,6 +127,13 @@ for r in range(3, main_ws.max_row + 1):
}) })
print(f'提取门店数量: {len(stores)}') print(f'提取门店数量: {len(stores)}')
# 调试:打印前5条的特殊情况内容
print('=== 调试:列9(特殊情况)样本数据 ===')
for s in stores[:5]:
print(f" 门店={s['门店'][:20]}, 特殊情况='{s['特殊情况']}'")
# 检查是否有非空的特殊情况
non_empty_count = sum(1 for s in stores if s['特殊情况'])
print(f'包含"特殊情况"数据的门店数: {non_empty_count}/{len(stores)}')
# ══════════════════════════════════════════════ # ══════════════════════════════════════════════
# 2. 提取主机厂数据 # 2. 提取主机厂数据
...@@ -158,10 +166,11 @@ wb.close() ...@@ -158,10 +166,11 @@ wb.close()
# ══════════════════════════════════════════════ # ══════════════════════════════════════════════
# 3. 输出鸿蒙门店数据-模板 # 3. 输出鸿蒙门店数据-模板
# ══════════════════════════════════════════════ # ══════════════════════════════════════════════
# 15列: A=门店, B=品牌, C=兜底指标, D=区域(省), E=直营与否, # 16列: A=门店, B=品牌, C=兜底指标, D=区域(省), E=直营与否,
# F=区域运营, G=飞行督导, H=线上运营, I=兜底类型, # F=区域运营, G=飞行督导, H=线上运营, I=兜底类型,
# J-L=需达标转化率(整车延保/安心包/电池延保), # J=特殊情况(区分安心包专岗等),
# M-O=预计赔付金额(整车/安心包/电池) # K-M=需达标转化率(整车延保/安心包/电池延保),
# N-P=预计赔付金额(整车/安心包/电池)
print(f'\n输出门店模板...') print(f'\n输出门店模板...')
owb = Workbook() owb = Workbook()
...@@ -178,12 +187,13 @@ write_header_cell(ows, 1, 6, '区域运营') ...@@ -178,12 +187,13 @@ write_header_cell(ows, 1, 6, '区域运营')
write_header_cell(ows, 1, 7, '飞行督导') write_header_cell(ows, 1, 7, '飞行督导')
write_header_cell(ows, 1, 8, '线上运营') write_header_cell(ows, 1, 8, '线上运营')
write_header_cell(ows, 1, 9, '兜底类型') write_header_cell(ows, 1, 9, '兜底类型')
write_header_cell(ows, 1, 10, '需达标转化率') write_header_cell(ows, 1, 10, '特殊情况')
write_header_cell(ows, 1, 11, '需达标转化率') write_header_cell(ows, 1, 11, '需达标转化率')
write_header_cell(ows, 1, 12, '需达标转化率') write_header_cell(ows, 1, 12, '需达标转化率')
write_header_cell(ows, 1, 13, '预计赔付金额') write_header_cell(ows, 1, 13, '需达标转化率')
write_header_cell(ows, 1, 14, '预计赔付金额') write_header_cell(ows, 1, 14, '预计赔付金额')
write_header_cell(ows, 1, 15, '预计赔付金额') write_header_cell(ows, 1, 15, '预计赔付金额')
write_header_cell(ows, 1, 16, '预计赔付金额')
# Row 2: 子表头 # Row 2: 子表头
write_sub_cell(ows, 2, 1, '') write_sub_cell(ows, 2, 1, '')
...@@ -195,12 +205,13 @@ write_sub_cell(ows, 2, 6, '') ...@@ -195,12 +205,13 @@ write_sub_cell(ows, 2, 6, '')
write_sub_cell(ows, 2, 7, '') write_sub_cell(ows, 2, 7, '')
write_sub_cell(ows, 2, 8, '') write_sub_cell(ows, 2, 8, '')
write_sub_cell(ows, 2, 9, '') write_sub_cell(ows, 2, 9, '')
write_sub_cell(ows, 2, 10, '整车延保') write_sub_cell(ows, 2, 10, '')
write_sub_cell(ows, 2, 11, '安心包') write_sub_cell(ows, 2, 11, '整车延保')
write_sub_cell(ows, 2, 12, '电池延保') write_sub_cell(ows, 2, 12, '安心包')
write_sub_cell(ows, 2, 13, '整车') write_sub_cell(ows, 2, 13, '电池延保')
write_sub_cell(ows, 2, 14, '安心包') write_sub_cell(ows, 2, 14, '整车')
write_sub_cell(ows, 2, 15, '电池') write_sub_cell(ows, 2, 15, '安心包')
write_sub_cell(ows, 2, 16, '电池')
# 列宽 # 列宽
ows.column_dimensions['A'].width = 35 ows.column_dimensions['A'].width = 35
...@@ -218,6 +229,7 @@ ows.column_dimensions['L'].width = 14 ...@@ -218,6 +229,7 @@ ows.column_dimensions['L'].width = 14
ows.column_dimensions['M'].width = 14 ows.column_dimensions['M'].width = 14
ows.column_dimensions['N'].width = 14 ows.column_dimensions['N'].width = 14
ows.column_dimensions['O'].width = 14 ows.column_dimensions['O'].width = 14
ows.column_dimensions['P'].width = 14
# 写入数据行 # 写入数据行
row_num = 3 row_num = 3
...@@ -231,6 +243,7 @@ for s in stores: ...@@ -231,6 +243,7 @@ for s in stores:
write_data_cell(ows, row_num, 7, s['飞行督导']) write_data_cell(ows, row_num, 7, s['飞行督导'])
write_data_cell(ows, row_num, 8, s['线上运营']) write_data_cell(ows, row_num, 8, s['线上运营'])
write_data_cell(ows, row_num, 9, s['兜底类型']) write_data_cell(ows, row_num, 9, s['兜底类型'])
write_data_cell(ows, row_num, 10, s['特殊情况'])
# 需达标转化率 (小数格式,如 0.5 表示50%) # 需达标转化率 (小数格式,如 0.5 表示50%)
def fmt_target(val): def fmt_target(val):
...@@ -243,9 +256,9 @@ for s in stores: ...@@ -243,9 +256,9 @@ for s in stores:
return str(val) return str(val)
return str(val) return str(val)
write_data_cell(ows, row_num, 10, fmt_target(s['需达标_整车延保'])) write_data_cell(ows, row_num, 11, fmt_target(s['需达标_整车延保']))
write_data_cell(ows, row_num, 11, fmt_target(s['需达标_安心包'])) write_data_cell(ows, row_num, 12, fmt_target(s['需达标_安心包']))
write_data_cell(ows, row_num, 12, fmt_target(s['需达标_电池延保'])) write_data_cell(ows, row_num, 13, fmt_target(s['需达标_电池延保']))
# 预计赔付金额 # 预计赔付金额
def fmt_amount(val): def fmt_amount(val):
...@@ -256,9 +269,9 @@ for s in stores: ...@@ -256,9 +269,9 @@ for s in stores:
except (ValueError, TypeError): except (ValueError, TypeError):
return str(val) return str(val)
write_data_cell(ows, row_num, 13, fmt_amount(s['赔付_整车'])) write_data_cell(ows, row_num, 14, fmt_amount(s['赔付_整车']))
write_data_cell(ows, row_num, 14, fmt_amount(s['赔付_安心包'])) write_data_cell(ows, row_num, 15, fmt_amount(s['赔付_安心包']))
write_data_cell(ows, row_num, 15, fmt_amount(s['赔付_电池'])) write_data_cell(ows, row_num, 16, fmt_amount(s['赔付_电池']))
row_num += 1 row_num += 1
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!