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)}")
...@@ -66,6 +66,7 @@ MODULE_LOG_FILES = { ...@@ -66,6 +66,7 @@ MODULE_LOG_FILES = {
"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))
......
...@@ -13,9 +13,28 @@ from datetime import datetime, timedelta ...@@ -13,9 +13,28 @@ from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any from typing import List, Dict, Optional, Any
import pymysql import pymysql
import pymysql.cursors
from app.core.config import settings from app.core.config import settings
logger = logging.getLogger("app.strategy_service") logger = logging.getLogger("app.strategy_service")
_sql_logger = logging.getLogger("app.strategy_service.sql")
class StrategyLoggingCursor(pymysql.cursors.DictCursor):
"""自定义 DictCursor:记录每条 SQL 的完整语句、参数和执行耗时"""
def execute(self, query, args=None):
start = datetime.now()
try:
result = super().execute(query, args)
elapsed = (datetime.now() - start).total_seconds()
q_display = " ".join(query.replace("\n", " ").split())[:500]
_sql_logger.info(f"[SQL][{elapsed:.4f}s] {q_display} | params={args}")
return result
except Exception:
elapsed = (datetime.now() - start).total_seconds()
q_display = " ".join(query.replace("\n", " ").split())[:500]
_sql_logger.error(f"[SQL][{elapsed:.4f}s] FAILED: {q_display} | params={args}")
raise
# 策略类型映射 # 策略类型映射
STRATEGY_TYPE_MAP = { STRATEGY_TYPE_MAP = {
...@@ -73,12 +92,14 @@ class StrategyService: ...@@ -73,12 +92,14 @@ class StrategyService:
@staticmethod @staticmethod
def _get_raw_conn(): def _get_raw_conn():
return pymysql.connect( conn = pymysql.connect(
host=settings.DB_HOST, port=settings.DB_PORT, host=settings.DB_HOST, port=settings.DB_PORT,
user=settings.DB_USER, password=settings.DB_PASSWORD, user=settings.DB_USER, password=settings.DB_PASSWORD,
database=settings.DB_NAME, charset="utf8mb4", database=settings.DB_NAME, charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor, cursorclass=StrategyLoggingCursor,
) )
logger.info(f"[DB] Connected to {settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}")
return conn
@staticmethod @staticmethod
def _safe_num(val): def _safe_num(val):
...@@ -100,6 +121,17 @@ class StrategyService: ...@@ -100,6 +121,17 @@ class StrategyService:
return d[:10] return d[:10]
return str(d)[:10] return str(d)[:10]
@staticmethod
def _datetime_str(d):
"""将日期时间转为 'YYYY-MM-DD HH:MM' 显示格式"""
if d is None:
return None
if isinstance(d, datetime):
return d.strftime("%Y-%m-%d %H:%M")
if isinstance(d, str):
return d[:16]
return str(d)[:16]
# ──────────── 建表 ──────────── # ──────────── 建表 ────────────
@staticmethod @staticmethod
...@@ -164,20 +196,21 @@ class StrategyService: ...@@ -164,20 +196,21 @@ class StrategyService:
INDEX idx_start_date (start_date) INDEX idx_start_date (start_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""" """
# 兼容旧表:如果没有 monitor_refresh_time 列则添加 # 兼容旧表:如果没有 monitor_refresh_time 列则添加(MySQL 不支持 IF NOT EXISTS)
alter_sql = """ alter_sql = """
ALTER TABLE strategy_analysis_result ALTER TABLE strategy_analysis_result
ADD COLUMN IF NOT EXISTS monitor_refresh_time DATETIME ADD COLUMN monitor_refresh_time DATETIME
""" """
conn = StrategyService._get_raw_conn() conn = StrategyService._get_raw_conn()
try: try:
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute(sql) cur.execute(sql)
# 兼容旧表:添加 monitor_refresh_time 列 # 兼容旧表:添加 monitor_refresh_time 列(忽略 Duplicate column 错误)
try: try:
cur.execute(alter_sql) cur.execute(alter_sql)
except Exception: except Exception as e:
pass if "Duplicate column" not in str(e):
raise
conn.commit() conn.commit()
logger.info("[Strategy] result table ensured") logger.info("[Strategy] result table ensured")
finally: finally:
...@@ -358,14 +391,14 @@ class StrategyService: ...@@ -358,14 +391,14 @@ class StrategyService:
return None return None
return new_rate - old_rate return new_rate - old_rate
delivery_old = base_metrics.get("total_delivery", 0) if base_metrics else 0 delivery_old = float(base_metrics.get("total_delivery", 0)) if base_metrics else 0.0
delivery_new = exec_metrics.get("total_delivery", 0) if exec_metrics else 0 delivery_new = float(exec_metrics.get("total_delivery", 0)) if exec_metrics else 0.0
if delivery_old == 0 and delivery_new == 0: if delivery_old == 0 and delivery_new == 0:
delivery_ratio = 0.0 delivery_ratio = 0.0
elif delivery_old == 0: elif delivery_old == 0:
delivery_ratio = 100.0 delivery_ratio = 100.0
else: else:
delivery_ratio = (delivery_new - delivery_old) / delivery_old * 100.0 delivery_ratio = float((delivery_new - delivery_old) / delivery_old * 100)
product_key_map = { product_key_map = {
"extended_warranty": ("total_ew",), "extended_warranty": ("total_ew",),
...@@ -487,19 +520,33 @@ class StrategyService: ...@@ -487,19 +520,33 @@ class StrategyService:
strategy_id = strategy.get("id") strategy_id = strategy.get("id")
merchant_id = strategy.get("merchant_id") merchant_id = strategy.get("merchant_id")
try: try:
logger.info(f"[Strategy] analyze_single_strategy #{strategy_id}: merchant_id={merchant_id}, "
f"start={StrategyService._date_str(strategy.get('start_date'))}, "
f"end={StrategyService._date_str(strategy.get('end_date'))}")
store = StrategyService._get_store_config(merchant_id) if merchant_id else None store = StrategyService._get_store_config(merchant_id) if merchant_id else None
logger.info(f"[Strategy] store config for #{strategy_id}: province={store.get('province') if store else 'N/A'}, "
f"operation_mode={store.get('operation_mode') if store else 'N/A'}")
periods = StrategyService._parse_period(strategy) periods = StrategyService._parse_period(strategy)
logger.info(f"[Strategy] periods for #{strategy_id}: T-1={periods[0]}, T={periods[1]}, T+1={periods[2]}")
base_metrics = None base_metrics = None
exec_metrics = None exec_metrics = None
if merchant_id and periods[0] and periods[1]: if merchant_id and periods[0] and periods[1]:
base_rows = StrategyService._get_store_daily_metrics(merchant_id, periods[0][0], periods[0][1]) base_rows = StrategyService._get_store_daily_metrics(merchant_id, periods[0][0], periods[0][1])
exec_rows = StrategyService._get_store_daily_metrics(merchant_id, periods[1][0], periods[1][1]) exec_rows = StrategyService._get_store_daily_metrics(merchant_id, periods[1][0], periods[1][1])
logger.info(f"[Strategy] daily metrics for #{strategy_id}: base_rows={len(base_rows)}, exec_rows={len(exec_rows)}")
base_metrics = StrategyService._aggregate_metrics(base_rows) base_metrics = StrategyService._aggregate_metrics(base_rows)
exec_metrics = StrategyService._aggregate_metrics(exec_rows) exec_metrics = StrategyService._aggregate_metrics(exec_rows)
else:
logger.warning(f"[Strategy] skip metrics query for #{strategy_id}: no merchant_id or periods")
effect = StrategyService._classify_effect(base_metrics, exec_metrics) effect = StrategyService._classify_effect(base_metrics, exec_metrics)
baodi = StrategyService._detect_baodi_type(strategy, store) baodi = StrategyService._detect_baodi_type(strategy, store)
monitor_type = StrategyService._detect_monitor_type(strategy, effect["label"]) monitor_type = StrategyService._detect_monitor_type(strategy, effect["label"])
logger.info(f"[Strategy] result for #{strategy_id}: effect={effect['label']}, baodi={baodi}, monitor={monitor_type}")
status_label = PUSH_FLAG_MAP.get(strategy.get("push_flag"), "未知") status_label = PUSH_FLAG_MAP.get(strategy.get("push_flag"), "未知")
province_label = str(store.get("province", "")) if store else "" province_label = str(store.get("province", "")) if store else ""
if not province_label: if not province_label:
...@@ -591,6 +638,8 @@ class StrategyService: ...@@ -591,6 +638,8 @@ class StrategyService:
@staticmethod @staticmethod
def _upsert_result(record: Dict): def _upsert_result(record: Dict):
"""将分析结果 upsert 到结果表""" """将分析结果 upsert 到结果表"""
strategy_id = record.get("strategy_id")
logger.info(f"[Strategy] upsert result for strategy #{strategy_id} (is_valid={record.get('is_valid')}, effect={record.get('effect_label')})")
cols = [ cols = [
"strategy_id", "title", "sub_title", "strategy_type", "strategy_type_name", "strategy_id", "title", "sub_title", "strategy_type", "strategy_type_name",
"merchant_id", "merchant_name", "merchant_code", "province", "city", "merchant_id", "merchant_name", "merchant_code", "province", "city",
...@@ -621,6 +670,7 @@ class StrategyService: ...@@ -621,6 +670,7 @@ class StrategyService:
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute(sql, values) cur.execute(sql, values)
conn.commit() conn.commit()
logger.info(f"[Strategy] upsert done: strategy #{strategy_id} written to DB")
finally: finally:
conn.close() conn.close()
...@@ -730,7 +780,8 @@ class StrategyService: ...@@ -730,7 +780,8 @@ class StrategyService:
@staticmethod @staticmethod
def analyze_and_save_single(strategy_id: int) -> Optional[Dict]: def analyze_and_save_single(strategy_id: int) -> Optional[Dict]:
"""获取单条策略,执行分析并保存到结果表""" """获取单条策略,执行分析并保存到结果表(同步执行,实时完成分析+写入)"""
logger.info(f"[Strategy] ===== analyze_and_save_single START: strategy #{strategy_id} =====")
sql = "SELECT * FROM ods_strategy_info WHERE id = %s AND deleted_flag = 'N'" sql = "SELECT * FROM ods_strategy_info WHERE id = %s AND deleted_flag = 'N'"
conn = StrategyService._get_raw_conn() conn = StrategyService._get_raw_conn()
try: try:
...@@ -741,15 +792,134 @@ class StrategyService: ...@@ -741,15 +792,134 @@ class StrategyService:
conn.close() conn.close()
if not strategy: if not strategy:
logger.warning(f"[Strategy] strategy #{strategy_id} not found")
return None return None
logger.info(f"[Strategy] found strategy #{strategy_id}: title={strategy.get('title')}, merchant_id={strategy.get('merchant_id')}")
result = StrategyService.analyze_single_strategy(strategy) result = StrategyService.analyze_single_strategy(strategy)
if result is None: if result is None:
logger.warning(f"[Strategy] analyze_single_strategy returned None for #{strategy_id}")
return None return None
logger.info(f"[Strategy] analysis result for #{strategy_id}: effect={result.get('effect_label')}, "
f"delivery_old={result.get('delivery_old')}, delivery_new={result.get('delivery_new')}, "
f"delivery_ratio={result.get('delivery_ratio')}")
StrategyService._upsert_result(result) StrategyService._upsert_result(result)
logger.info(f"[Strategy] ===== analyze_and_save_single DONE: strategy #{strategy_id} =====")
return result return result
# ──────────── 自动刷新盯防数据 ────────────
@staticmethod
def get_stale_monitoring_strategies(stale_hours: int = 4) -> List[Dict]:
"""查询超过指定小时未刷新、且仍在观察期内的盯防策略"""
sql = """
SELECT s.id, s.title, s.sub_title, s.strategy_type, s.merchant_id,
s.merchant_name, s.start_date, s.end_date, s.push_flag,
s.description, s.biz, s.created_date, s.created_by
FROM ods_strategy_info s
LEFT JOIN strategy_analysis_result sar
ON s.id = sar.strategy_id AND sar.is_valid = 1
WHERE s.deleted_flag = 'N'
AND s.push_flag IN (1, 4, 5)
AND s.end_date >= CURDATE()
AND (
sar.monitor_refresh_time IS NULL
OR sar.monitor_refresh_time < NOW() - INTERVAL %s HOUR
)
ORDER BY COALESCE(sar.monitor_refresh_time, '2000-01-01') ASC
"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(sql, (stale_hours,))
return cur.fetchall()
finally:
conn.close()
@staticmethod
def auto_refresh_stale_monitoring(stale_hours: int = 4) -> Dict:
"""扫描并自动刷新超时未更新的盯防数据,返回刷新结果统计"""
strategies = StrategyService.get_stale_monitoring_strategies(stale_hours)
logger.info(
f"[Strategy] auto-refresh: found {len(strategies)} stale strategies "
f"(> {stale_hours}h, push_flag IN (1,4,5), end_date >= today)"
)
refreshed = 0
failed = 0
skipped = 0
for strat in strategies:
strategy_id = strat.get("id")
try:
result = StrategyService.analyze_single_strategy(strat)
if result and result.get("is_valid"):
StrategyService._upsert_result(result)
refreshed += 1
else:
failed += 1
except Exception as e:
logger.error(
f"[Strategy] auto-refresh strategy {strategy_id} failed: {e}"
)
failed += 1
logger.info(
f"[Strategy] auto-refresh done: refreshed={refreshed}, "
f"failed={failed}, total={len(strategies)}"
)
return {
"total": len(strategies),
"refreshed": refreshed,
"failed": failed,
"skipped": skipped,
}
@staticmethod
def trigger_auto_refresh_async(stale_hours: int = 4):
"""异步触发盯防数据自动刷新"""
def _run():
try:
StrategyService.auto_refresh_stale_monitoring(stale_hours)
except Exception as e:
logger.error(f"[Strategy] auto-refresh thread error: {e}", exc_info=True)
thread = threading.Thread(target=_run, daemon=True)
thread.start()
return {"message": "auto-refresh monitoring task started"}
@staticmethod
def get_monitoring_refresh_status() -> Dict:
"""获取盯防数据刷新状态概览"""
sql = """
SELECT
COUNT(*) AS total_monitoring,
SUM(CASE WHEN sar.monitor_refresh_time IS NULL THEN 1 ELSE 0 END) AS never_refreshed,
SUM(CASE WHEN sar.monitor_refresh_time IS NOT NULL
AND sar.monitor_refresh_time >= NOW() - INTERVAL 4 HOUR THEN 1 ELSE 0 END) AS fresh,
SUM(CASE WHEN sar.monitor_refresh_time IS NOT NULL
AND sar.monitor_refresh_time < NOW() - INTERVAL 4 HOUR THEN 1 ELSE 0 END) AS stale
FROM ods_strategy_info s
LEFT JOIN strategy_analysis_result sar
ON s.id = sar.strategy_id AND sar.is_valid = 1
WHERE s.deleted_flag = 'N'
AND s.push_flag IN (1, 4, 5)
AND s.end_date >= CURDATE()
"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(sql)
row = cur.fetchone()
return {
"total_monitoring": row.get("total_monitoring", 0) or 0,
"never_refreshed": row.get("never_refreshed", 0) or 0,
"fresh": row.get("fresh", 0) or 0,
"stale": row.get("stale", 0) or 0,
}
finally:
conn.close()
# ──────────── 从 ods_strategy_info 主表 LEFT JOIN 结果表查询列表 ──────────── # ──────────── 从 ods_strategy_info 主表 LEFT JOIN 结果表查询列表 ────────────
@staticmethod @staticmethod
...@@ -845,6 +1015,7 @@ class StrategyService: ...@@ -845,6 +1015,7 @@ class StrategyService:
"sar.province AS sar_province, sar.city AS sar_city, " "sar.province AS sar_province, sar.city AS sar_city, "
"sar.receiver AS sar_receiver, " "sar.receiver AS sar_receiver, "
"sar.status AS sar_status, " "sar.status AS sar_status, "
"sar.monitor_refresh_time, "
"sc.merchant_code, sc.province, sc.city, sc.operation_mode" "sc.merchant_code, sc.province, sc.city, sc.operation_mode"
) )
...@@ -945,6 +1116,7 @@ class StrategyService: ...@@ -945,6 +1116,7 @@ class StrategyService:
"description": r["description"] or "", "description": r["description"] or "",
"created_by": r.get("created_by") or "", "created_by": r.get("created_by") or "",
"biz": r.get("biz") or "", "biz": r.get("biz") or "",
"monitor_refresh_time": StrategyService._datetime_str(r.get("monitor_refresh_time")),
}) })
return { return {
...@@ -1079,6 +1251,7 @@ class StrategyService: ...@@ -1079,6 +1251,7 @@ class StrategyService:
"description": r["description"] or "", "description": r["description"] or "",
"created_by": r.get("created_by") or "", "created_by": r.get("created_by") or "",
"biz": r.get("biz") or "", "biz": r.get("biz") or "",
"monitor_refresh_time": None,
}) })
return { return {
...@@ -1108,6 +1281,10 @@ class StrategyService: ...@@ -1108,6 +1281,10 @@ class StrategyService:
conn.close() conn.close()
return { return {
"provinces": provinces, "provinces": provinces,
"strategy_types": [
{"value": str(k), "label": v}
for k, v in STRATEGY_TYPE_MAP.items()
],
"baodi_types": ["交付", "触客"], "baodi_types": ["交付", "触客"],
"monitor_types": ["业绩下滑盯防", "预警盯防", "新店盯防"], "monitor_types": ["业绩下滑盯防", "预警盯防", "新店盯防"],
"statuses": ["盯防中", "已结束", "未推送", "未完成", "审批中", "已驳回"], "statuses": ["盯防中", "已结束", "未推送", "未完成", "审批中", "已驳回"],
...@@ -1241,6 +1418,7 @@ class StrategyService: ...@@ -1241,6 +1418,7 @@ class StrategyService:
"conclusion": row["conclusion"] or "暂无分析结论", "conclusion": row["conclusion"] or "暂无分析结论",
"weekly_breakdown": weekly_breakdown, "weekly_breakdown": weekly_breakdown,
"before_after": before_after, "before_after": before_after,
"monitor_refresh_time": StrategyService._datetime_str(row.get("monitor_refresh_time")),
} }
@staticmethod @staticmethod
...@@ -1302,6 +1480,7 @@ class StrategyService: ...@@ -1302,6 +1480,7 @@ class StrategyService:
"product_changes": [], "product_changes": [],
}, },
"conclusion": "策略尚未进行分析,请点击「刷新分析」获取效果数据。", "conclusion": "策略尚未进行分析,请点击「刷新分析」获取效果数据。",
"monitor_refresh_time": None,
} }
# ──────────── 兼容旧接口(实时计算,保留备用) ──────────── # ──────────── 兼容旧接口(实时计算,保留备用) ────────────
...@@ -1317,6 +1496,7 @@ class StrategyService: ...@@ -1317,6 +1496,7 @@ class StrategyService:
effect: Optional[str] = None, effect: Optional[str] = None,
start_date: Optional[str] = None, start_date: Optional[str] = None,
end_date: Optional[str] = None, end_date: Optional[str] = None,
strategy_type: Optional[str] = None,
page: int = 1, page: int = 1,
page_size: int = 8, page_size: int = 8,
) -> Dict: ) -> Dict:
...@@ -1326,5 +1506,6 @@ class StrategyService: ...@@ -1326,5 +1506,6 @@ class StrategyService:
monitor_type=monitor_type, status=status, monitor_type=monitor_type, status=status,
operation_mode=operation_mode, effect=effect, operation_mode=operation_mode, effect=effect,
start_date=start_date, end_date=end_date, start_date=start_date, end_date=end_date,
strategy_type=strategy_type,
page=page, page_size=page_size, page=page, page_size=page_size,
) )
...@@ -22,17 +22,8 @@ ...@@ -22,17 +22,8 @@
} }
}; };
// 计算 API 基础路径(兼容 /login 等根级页面) // API 基础路径始终为 /api(FastAPI 统一挂载)
(function() {
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'; 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>
.strategy-stats { display: flex; gap: 16px; margin-bottom: 20px; flex-wrap: wrap; } .strategy-stats { display: flex; gap: 16px; margin-bottom: 20px; flex-wrap: wrap; }
.stat-card { flex: 1; min-width: 150px; background: #fff; border-radius: 8px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); display: flex; align-items: center; gap: 12px; } .stat-card { flex: 1; min-width: 150px; background: #fff; border-radius: 8px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); display: flex; align-items: center; gap: 12px; }
...@@ -89,27 +89,106 @@ ...@@ -89,27 +89,106 @@
.row-actions { display: flex; gap: 6px; justify-content: center; } .row-actions { display: flex; gap: 6px; justify-content: center; }
/* 详情弹窗 */ /* 详情弹窗 */
.modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.45); overflow: auto; } .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.45); overflow: hidden; }
.modal-content { background: #fff; margin: 60px auto; padding: 24px; border-radius: 8px; width: 90%; max-width: 800px; position: relative; } .modal-detail { width: 95%; max-width: 1300px; height: 92vh; margin: 4vh auto; display: flex; flex-direction: column; background: #f5f7fa; border-radius: 8px; }
.modal-close { position: absolute; right: 16px; top: 12px; font-size: 24px; cursor: pointer; color: #999; } .modal-header { display: flex; justify-content: space-between; align-items: center; padding: 16px 24px; background: #fff; border-bottom: 1px solid #f0f0f0; border-radius: 8px 8px 0 0; flex-shrink: 0; }
.modal-title { font-size: 18px; font-weight: 600; margin-bottom: 16px; padding-right: 30px; } .modal-header-actions { display: flex; align-items: center; gap: 12px; }
.metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 16px 0; } .modal-title { font-size: 18px; font-weight: 600; color: #333; }
.metric-card { background: #f8f9fa; padding: 12px; border-radius: 6px; } .modal-close { font-size: 28px; cursor: pointer; color: #999; line-height: 1; }
.metric-label { font-size: 12px; color: #666; margin-bottom: 4px; } .modal-close:hover { color: #333; }
.metric-value { font-size: 18px; font-weight: 700; color: #333; } .modal-body { flex: 1; overflow-y: auto; padding: 16px 24px 24px; }
.conclusion-box { background: #f6ffed; border: 1px solid #b7eb8f; border-radius: 6px; padding: 14px; margin-top: 16px; line-height: 1.8; white-space: pre-wrap; }
.btn-sm { padding: 5px 12px; font-size: 12px; }
.btn { padding: 7px 16px; border-radius: 4px; font-size: 13px; cursor: pointer; border: 1px solid #d9d9d9; background: #fff; color: #333; }
.btn-primary { background: #1890ff; color: #fff; border-color: #1890ff; }
.btn-primary:hover { opacity: 0.9; }
/* 弹窗内的详情布局 */
.detail-container { display: flex; gap: 16px; }
.left-panel { width: 320px; flex-shrink: 0; display: flex; flex-direction: column; gap: 16px; }
.right-panel { flex: 1; display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.card { background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); overflow: hidden; }
.card-header { padding: 14px 16px; border-bottom: 1px solid #f0f0f0; display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 15px; color: #333; justify-content: space-between; }
.card-body { padding: 16px; }
.card-subtitle { font-size: 12px; color: #999; font-weight: normal; }
.info-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #fafafa; font-size: 13px; }
.info-row:last-child { border-bottom: none; }
.info-label { color: #999; flex-shrink: 0; margin-right: 12px; }
.info-value { color: #333; text-align: right; word-break: break-all; }
.tag { display: inline-flex; align-items: center; gap: 4px; padding: 3px 10px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.tag-monitoring { background: #f3e8ff; color: #722ed1; }
.tag-monitoring::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: #722ed1; }
.tag-ended { background: #f5f5f5; color: #999; }
.tag-warning { background: #fff2f0; color: #f5222d; border: 1px solid #ffccc7; }
.tag-alert { background: #fff7e6; color: #fa8c16; border: 1px solid #ffd591; }
.tag-new { background: #e6f7ff; color: #1890ff; border: 1px solid #91d5ff; }
.tag-direct { background: #e6f7ff; color: #1890ff; }
.tag-franchise { background: #fff7e6; color: #fa8c16; }
.tag-baodi { background: #e6f7ff; color: #1890ff; border: 1px solid #91d5ff; }
.effect-summary { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.effect-item { background: #f8f9fa; border-radius: 6px; padding: 14px; text-align: center; }
.effect-item .label { font-size: 12px; color: #999; margin-bottom: 6px; }
.effect-item .value { font-size: 20px; font-weight: 700; }
.effect-item .value.up { color: #52c41a; }
.effect-item .value.down { color: #f5222d; }
.performance-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.performance-table th { background: #fafafa; color: #666; font-weight: 600; padding: 12px 10px; text-align: center; border-bottom: 1px solid #f0f0f0; white-space: nowrap; }
.performance-table td { padding: 14px 10px; border-bottom: 1px solid #f0f0f0; text-align: center; vertical-align: middle; }
.performance-table tr:hover { background: #fafafa; }
.performance-table .period { text-align: left; }
.period-label { font-weight: 500; color: #333; }
.period-range { font-size: 12px; color: #999; margin-top: 2px; }
.rate-cell { display: flex; flex-direction: column; gap: 2px; align-items: center; }
.rate-value { font-weight: 600; }
.rate-value.up { color: #52c41a; }
.rate-value.down { color: #f5222d; }
.rate-status { font-size: 11px; color: #999; }
.comparison-grid { display: grid; grid-template-columns: 1fr auto 1fr; gap: 16px; align-items: center; }
.comparison-box { background: #f8f9fa; border-radius: 8px; padding: 18px; }
.comparison-box.highlight { background: #f3e8ff; }
.comparison-title { font-size: 13px; color: #666; margin-bottom: 12px; }
.comparison-metrics { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.comparison-metric .label { font-size: 12px; color: #999; margin-bottom: 4px; }
.comparison-metric .value { font-size: 18px; font-weight: 700; color: #333; }
.comparison-metric .value.rate::after { content: '%'; font-size: 12px; font-weight: 400; color: #999; }
.arrow-box { display: flex; align-items: center; justify-content: center; }
.arrow-box .arrow { font-size: 24px; color: #1890ff; }
.chart-container { height: 280px; position: relative; }
.chart-legend { display: flex; justify-content: flex-end; gap: 16px; margin-bottom: 10px; font-size: 12px; }
.legend-item { display: flex; align-items: center; gap: 6px; }
.legend-dot { width: 8px; height: 8px; border-radius: 50%; }
.svg-chart { width: 100%; height: 100%; }
.conclusion { background: #f6ffed; border: 1px solid #b7eb8f; border-radius: 6px; padding: 14px; line-height: 1.8; white-space: pre-wrap; font-size: 13px; color: #333; }
.loading { text-align: center; padding: 60px; color: #999; }
.error-tip { text-align: center; padding: 60px; color: #f5222d; }
@media (max-width: 900px) {
.detail-container { flex-direction: column; }
.left-panel { width: 100%; }
.modal-detail { width: 98%; height: 96vh; margin: 2vh auto; }
}
</style> </style>
</head> </head>
<body> <body>
<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>
...@@ -162,6 +241,7 @@ ...@@ -162,6 +241,7 @@
<div class="filter-bar"> <div class="filter-bar">
<input type="text" id="filter-keyword" placeholder="搜索门店名称"> <input type="text" id="filter-keyword" placeholder="搜索门店名称">
<select id="filter-province"><option value="">区域(省)</option></select> <select id="filter-province"><option value="">区域(省)</option></select>
<select id="filter-strategy-type"><option value="">策略类型</option></select>
<select id="filter-baodi"><option value="">兜底类型</option><option value="交付">交付</option><option value="触客">触客</option></select> <select id="filter-baodi"><option value="">兜底类型</option><option value="交付">交付</option><option value="触客">触客</option></select>
<select id="filter-monitor"><option value="">盯防类型</option></select> <select id="filter-monitor"><option value="">盯防类型</option></select>
<select id="filter-status"><option value="">盯防状态</option></select> <select id="filter-status"><option value="">盯防状态</option></select>
...@@ -190,18 +270,26 @@ ...@@ -190,18 +270,26 @@
<!-- 详情弹窗 --> <!-- 详情弹窗 -->
<div id="detail-modal" class="modal"> <div id="detail-modal" class="modal">
<div class="modal-content"> <div class="modal-content modal-detail">
<span class="modal-close" onclick="closeModal()">&times;</span> <div class="modal-header">
<div class="modal-title" id="modal-title">策略详情</div> <div class="modal-title" id="modal-title">策略详情</div>
<div id="modal-body"></div> <div class="modal-header-actions">
<button class="btn btn-sm btn-primary" id="modal-btn-refresh" onclick="refreshInModal()">刷新分析</button>
<span class="modal-close" onclick="closeModal()">&times;</span>
</div>
</div>
<div class="modal-body" id="modal-body">
<div class="loading">正在加载盯防效果数据...</div>
</div>
</div> </div>
</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';
let currentPage = 1; let currentPage = 1;
let currentFilters = {}; let currentFilters = {};
let currentModalId = null;
function formatRatio(val) { function formatRatio(val) {
if (val === null || val === undefined) return '-'; if (val === null || val === undefined) return '-';
...@@ -241,6 +329,7 @@ ...@@ -241,6 +329,7 @@
'<th style="text-align:right">安心包变化</th>', '<th style="text-align:right">安心包变化</th>',
'<th style="text-align:right">电池变化</th>', '<th style="text-align:right">电池变化</th>',
'<th style="text-align:center">整体效果</th>', '<th style="text-align:center">整体效果</th>',
'<th style="text-align:center">数据刷新时间</th>',
'<th style="text-align:center">操作</th>', '<th style="text-align:center">操作</th>',
'</tr></thead><tbody>']; '</tr></thead><tbody>'];
...@@ -253,6 +342,22 @@ ...@@ -253,6 +342,22 @@
const deliveryRatio = delivery.ratio; const deliveryRatio = delivery.ratio;
const deliveryDetail = (delivery.old !== null && delivery.new !== null) ? (delivery.old + '→' + delivery.new) : '-'; const deliveryDetail = (delivery.old !== null && delivery.new !== null) ? (delivery.old + '→' + delivery.new) : '-';
// 计算刷新时间显示
const refreshTime = row.monitor_refresh_time || '';
let refreshDisplay = '<span style="color:#999">-</span>';
if (refreshTime) {
const refreshDate = new Date(refreshTime.replace(' ', 'T'));
const now = new Date();
const diffMs = now - refreshDate;
const diffHours = diffMs / (1000 * 60 * 60);
let color = '#52c41a';
if (diffHours > 24) { color = '#f5222d'; }
else if (diffHours > 4) { color = '#fa8c16'; }
refreshDisplay = '<span style="color:' + color + ';font-size:12px">' + refreshTime + '</span>';
} else if (row.status === '盯防中') {
refreshDisplay = '<span style="color:#f5222d;font-size:11px">从未刷新</span>';
}
const products = row.product_changes || []; const products = row.product_changes || [];
const pMap = {}; const pMap = {};
products.forEach(p => { pMap[p.key] = p; }); products.forEach(p => { pMap[p.key] = p; });
...@@ -273,7 +378,8 @@ ...@@ -273,7 +378,8 @@
'<td class="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(ax.pp_change) + '">' + (ax.pp_change != null ? (ax.pp_change > 0 ? '↑' : (ax.pp_change < 0 ? '↓' : '→')) + ' ' + Math.abs(ax.pp_change).toFixed(1) + 'pp' : '-') + '</span><span class="change-detail">' + (ax.old_rate != null ? ax.old_rate.toFixed(1) + '%→' + ax.new_rate.toFixed(1) + '%' : '-') + '</span></div></td>', '<td class="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(ax.pp_change) + '">' + (ax.pp_change != null ? (ax.pp_change > 0 ? '↑' : (ax.pp_change < 0 ? '↓' : '→')) + ' ' + Math.abs(ax.pp_change).toFixed(1) + 'pp' : '-') + '</span><span class="change-detail">' + (ax.old_rate != null ? ax.old_rate.toFixed(1) + '%→' + ax.new_rate.toFixed(1) + '%' : '-') + '</span></div></td>',
'<td class="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(bt.pp_change) + '">' + (bt.pp_change != null ? (bt.pp_change > 0 ? '↑' : (bt.pp_change < 0 ? '↓' : '→')) + ' ' + Math.abs(bt.pp_change).toFixed(1) + 'pp' : '-') + '</span><span class="change-detail">' + (bt.old_rate != null ? bt.old_rate.toFixed(1) + '%→' + bt.new_rate.toFixed(1) + '%' : '-') + '</span></div></td>', '<td class="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(bt.pp_change) + '">' + (bt.pp_change != null ? (bt.pp_change > 0 ? '↑' : (bt.pp_change < 0 ? '↓' : '→')) + ' ' + Math.abs(bt.pp_change).toFixed(1) + 'pp' : '-') + '</span><span class="change-detail">' + (bt.old_rate != null ? bt.old_rate.toFixed(1) + '%→' + bt.new_rate.toFixed(1) + '%' : '-') + '</span></div></td>',
'<td class="center"><span class="effect-tag ' + row.effect_class + '">' + escapeHtml(row.effect || '-') + '</span></td>', '<td class="center"><span class="effect-tag ' + row.effect_class + '">' + escapeHtml(row.effect || '-') + '</span></td>',
'<td class="center"><div class="row-actions"><button class="btn-analyze" onclick="analyzeSingle(' + row.id + ', this)">刷新分析</button><a class="btn-detail" href="./strategy/detail?id=' + row.id + '">详情</a></div></td>', '<td class="center" style="white-space:nowrap">' + refreshDisplay + '</td>',
'<td class="center"><div class="row-actions"><button class="btn-analyze" onclick="analyzeSingle(' + row.id + ', this)">刷新分析</button><button class="btn-detail" onclick="showDetail(' + row.id + ')">详情</button></div></td>',
'</tr>'); '</tr>');
}); });
...@@ -317,6 +423,7 @@ ...@@ -317,6 +423,7 @@
if (currentFilters.effect) params.append('effect', currentFilters.effect); if (currentFilters.effect) params.append('effect', currentFilters.effect);
if (currentFilters.start_date) params.append('start_date', currentFilters.start_date); if (currentFilters.start_date) params.append('start_date', currentFilters.start_date);
if (currentFilters.end_date) params.append('end_date', currentFilters.end_date); if (currentFilters.end_date) params.append('end_date', currentFilters.end_date);
if (currentFilters.strategy_type) params.append('strategy_type', currentFilters.strategy_type);
params.append('page', currentPage); params.append('page', currentPage);
params.append('page_size', '8'); params.append('page_size', '8');
...@@ -338,6 +445,7 @@ ...@@ -338,6 +445,7 @@
currentFilters = { currentFilters = {
keyword: document.getElementById('filter-keyword').value.trim(), keyword: document.getElementById('filter-keyword').value.trim(),
province: document.getElementById('filter-province').value, province: document.getElementById('filter-province').value,
strategy_type: document.getElementById('filter-strategy-type').value,
baodi_type: document.getElementById('filter-baodi').value, baodi_type: document.getElementById('filter-baodi').value,
monitor_type: document.getElementById('filter-monitor').value, monitor_type: document.getElementById('filter-monitor').value,
status: document.getElementById('filter-status').value, status: document.getElementById('filter-status').value,
...@@ -353,6 +461,7 @@ ...@@ -353,6 +461,7 @@
function resetFilters() { function resetFilters() {
document.getElementById('filter-keyword').value = ''; document.getElementById('filter-keyword').value = '';
document.getElementById('filter-province').value = ''; document.getElementById('filter-province').value = '';
document.getElementById('filter-strategy-type').value = '';
document.getElementById('filter-baodi').value = ''; document.getElementById('filter-baodi').value = '';
document.getElementById('filter-monitor').value = ''; document.getElementById('filter-monitor').value = '';
document.getElementById('filter-status').value = ''; document.getElementById('filter-status').value = '';
...@@ -385,6 +494,16 @@ ...@@ -385,6 +494,16 @@
provinceSel.appendChild(opt); provinceSel.appendChild(opt);
}); });
const typeSel = document.getElementById('filter-strategy-type');
if (opts.strategy_types) {
opts.strategy_types.forEach(t => {
const opt = document.createElement('option');
opt.value = t.value;
opt.textContent = t.label;
typeSel.appendChild(opt);
});
}
const monitorSel = document.getElementById('filter-monitor'); const monitorSel = document.getElementById('filter-monitor');
opts.monitor_types.forEach(t => { opts.monitor_types.forEach(t => {
const opt = document.createElement('option'); const opt = document.createElement('option');
...@@ -405,61 +524,280 @@ ...@@ -405,61 +524,280 @@
} }
} }
// ──── 弹窗详情(从 strategy_detail.html 移植完整渲染逻辑)────
function formatNum(n) {
if (n === null || n === undefined) return '-';
return Number(n).toLocaleString('zh-CN');
}
function formatRate(v) {
if (v === null || v === undefined) return '-';
return Number(v).toFixed(1) + '%';
}
function getStatusClass(status) {
return status === '盯防中' ? 'tag-monitoring' : 'tag-ended';
}
function getMonitorClass(type) {
if (type === '业绩下滑盯防') return 'tag-warning';
if (type === '预警盯防') return 'tag-alert';
return 'tag-new';
}
function renderRateCell(rate, target) {
let cls = '';
if (target !== undefined && target !== null && rate !== null) {
cls = rate >= target ? 'up' : 'down';
}
return '<div class="rate-cell"><span class="rate-value ' + cls + '">' + formatRate(rate) + '</span>' +
(target !== undefined && target !== null ? '<span class="rate-status">达标线' + target + '%</span>' : '') + '</div>';
}
function renderWeeklyTable(weeks, beforeAfter) {
if (!weeks || weeks.length === 0) {
return '<div style="padding:30px;text-align:center;color:#999">暂无周维度明细数据</div>';
}
let baseIdx = 0, execIdx = 0;
const rows = weeks.map((w, idx) => {
const phaseText = w.phase === 'exec' ? '盯防中' : '盯防前';
const phaseClass = w.phase === 'exec' ? 'tag-monitoring' : 'tag-ended';
const weekNo = w.phase === 'exec' ? (++execIdx) : (++baseIdx);
const prev = weeks[idx - 1];
const momDelivery = prev && prev.delivery > 0 ? ((w.delivery - prev.delivery) / prev.delivery * 100) : null;
const ewRate = w.ew_rate;
const axRate = w.ax_rate;
const batteryRate = w.battery_rate;
return '<tr>' +
'<td class="period"><div class="period-label">' + phaseText + ' 第' + weekNo + '周</div><div class="period-range">' + w.week_start.slice(5) + ' ~ ' + w.week_end.slice(5) + '</div></td>' +
'<td>' + formatNum(w.delivery) + '</td>' +
'<td>' + renderRateCell(ewRate, 15) + '</td>' +
'<td>' + renderRateCell(axRate, 20) + '</td>' +
'<td>' + renderRateCell(batteryRate, 7) + '</td>' +
'<td><span class="tag ' + phaseClass + '">' + phaseText + '</span></td>' +
'<td class="' + (momDelivery > 0 ? 'up' : (momDelivery < 0 ? 'down' : '')) + '">' + (momDelivery !== null && momDelivery !== undefined ? formatRatio(momDelivery) : '-') + '</td>' +
'</tr>';
}).join('');
const before = beforeAfter ? beforeAfter.before : null;
const after = beforeAfter ? beforeAfter.after : null;
const summaryRows = [];
if (before && after) {
summaryRows.push('<tr style="background:#fafafa;font-weight:500">' +
'<td class="period"><div class="period-label">' + before.label + '(汇总)</div></td>' +
'<td>' + formatNum(before.delivery) + '</td>' +
'<td>' + renderRateCell(before.ew_rate, 15) + '</td>' +
'<td>' + renderRateCell(before.ax_rate, 20) + '</td>' +
'<td>' + renderRateCell(before.battery_rate, 7) + '</td>' +
'<td><span class="tag tag-ended">盯防前</span></td><td>-</td></tr>');
summaryRows.push('<tr style="background:#f3e8ff;font-weight:500">' +
'<td class="period"><div class="period-label">' + after.label + '(汇总)</div></td>' +
'<td>' + formatNum(after.delivery) + '</td>' +
'<td>' + renderRateCell(after.ew_rate, 15) + '</td>' +
'<td>' + renderRateCell(after.ax_rate, 20) + '</td>' +
'<td>' + renderRateCell(after.battery_rate, 7) + '</td>' +
'<td><span class="tag tag-monitoring">盯防中</span></td>' +
'<td class="up">' + formatRatio(after.delivery > before.delivery ? ((after.delivery - before.delivery) / before.delivery * 100) : 0) + '</td></tr>');
}
return '<table class="performance-table"><thead><tr>' +
'<th style="text-align:left">时间维度</th><th>交付数</th><th>整车延保2</th><th>安心包2</th><th>电池2</th><th>盯防状态</th><th>环比变化</th>' +
'</tr></thead><tbody>' + summaryRows.join('') + rows + '</tbody></table>';
}
function renderComparison(comp) {
if (!comp) return '';
const before = comp.before;
const after = comp.after;
return '<div class="comparison-grid">' +
'<div class="comparison-box">' +
'<div class="comparison-title">' + before.label + '(前' + before.weeks + '周均值)</div>' +
'<div class="comparison-metrics">' +
'<div class="comparison-metric"><div class="label">周均交付数</div><div class="value">' + formatNum(before.delivery) + '</div></div>' +
'<div class="comparison-metric"><div class="label">整车延保2</div><div class="value rate">' + formatRate(before.ew_rate) + '</div></div>' +
'<div class="comparison-metric"><div class="label">安心包2</div><div class="value rate">' + formatRate(before.ax_rate) + '</div></div>' +
'<div class="comparison-metric"><div class="label">电池2</div><div class="value rate">' + formatRate(before.battery_rate) + '</div></div>' +
'</div></div>' +
'<div class="arrow-box"><span class="arrow">→</span></div>' +
'<div class="comparison-box highlight">' +
'<div class="comparison-title">' + after.label + '(后' + after.weeks + '周均值)</div>' +
'<div class="comparison-metrics">' +
'<div class="comparison-metric"><div class="label">周均交付数</div><div class="value">' + formatNum(after.delivery) + '</div></div>' +
'<div class="comparison-metric"><div class="label">整车延保2</div><div class="value rate">' + formatRate(after.ew_rate) + '</div></div>' +
'<div class="comparison-metric"><div class="label">安心包2</div><div class="value rate">' + formatRate(after.ax_rate) + '</div></div>' +
'<div class="comparison-metric"><div class="label">电池2</div><div class="value rate">' + formatRate(after.battery_rate) + '</div></div>' +
'</div></div></div>';
}
function renderTrendChart(weeks) {
if (!weeks || weeks.length === 0) return '<div style="padding:40px;text-align:center;color:#999">暂无趋势数据</div>';
const width = 800, height = 240;
const padding = { top: 20, right: 30, bottom: 40, left: 40 };
const chartW = width - padding.left - padding.right;
const chartH = height - padding.top - padding.bottom;
const keys = ['ew_rate', 'ax_rate', 'battery_rate'];
const colors = ['#1890ff', '#fa8c16', '#52c41a'];
const allValues = weeks.flatMap(w => keys.map(k => w[k]).filter(v => v !== null && v !== undefined));
const maxVal = allValues.length ? Math.max(...allValues, 15) : 100;
const minVal = 0;
function x(i) { return padding.left + (i / (weeks.length - 1 || 1)) * chartW; }
function y(v) { return padding.top + chartH - ((v - minVal) / (maxVal - minVal)) * chartH; }
const lines = keys.map((key, kidx) => {
const points = weeks.map((w, i) => {
const v = w[key];
if (v === null || v === undefined) return '';
return x(i) + ',' + y(v);
}).filter(Boolean).join(' ');
if (!points) return '';
const circles = weeks.map((w, i) => {
const v = w[key];
if (v === null || v === undefined) return '';
return '<circle cx="' + x(i) + '" cy="' + y(v) + '" r="4" fill="' + colors[kidx] + '" stroke="#fff" stroke-width="2"/>';
}).join('');
return '<polyline fill="none" stroke="' + colors[kidx] + '" stroke-width="2.5" points="' + points + '" stroke-linecap="round" stroke-linejoin="round"/>' + circles;
}).join('');
const xAxisLabels = weeks.map((w, i) =>
'<text x="' + x(i) + '" y="' + (height - 12) + '" text-anchor="middle" font-size="11" fill="#999">' + w.week_start.slice(5) + '</text>'
).join('');
const yTicks = [0, 25, 50, 75, 100].filter(t => t <= maxVal);
const yAxis = yTicks.map(t => {
const yy = y(t);
return '<line x1="' + padding.left + '" y1="' + yy + '" x2="' + (width - padding.right) + '" y2="' + yy + '" stroke="#f0f0f0" stroke-dasharray="2,2"/>' +
'<text x="' + (padding.left - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="#999">' + t + '%</text>';
}).join('');
const execIdx = weeks.findIndex(w => w.phase === 'exec');
let execRect = '';
if (execIdx >= 0) {
const x1 = x(execIdx - 0.5), x2 = x(weeks.length - 1 + 0.5);
execRect = '<rect x="' + x1 + '" y="' + padding.top + '" width="' + (x2 - x1) + '" height="' + chartH + '" fill="#f3e8ff" fill-opacity="0.3"/>' +
'<text x="' + ((x1 + x2) / 2) + '" y="' + (padding.top + 14) + '" text-anchor="middle" font-size="11" fill="#722ed1">盯防周期</text>';
}
return '<div class="chart-legend">' +
'<span class="legend-item"><span class="legend-dot" style="background:#1890ff"></span>整车延保2</span>' +
'<span class="legend-item"><span class="legend-dot" style="background:#fa8c16"></span>安心包2</span>' +
'<span class="legend-item"><span class="legend-dot" style="background:#52c41a"></span>电池2</span>' +
'</div>' +
'<svg class="svg-chart" viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="xMidYMid meet">' +
yAxis + execRect + lines + xAxisLabels +
'<line x1="' + padding.left + '" y1="' + (padding.top + chartH) + '" x2="' + (width - padding.right) + '" y2="' + (padding.top + chartH) + '" stroke="#e0e0e0"/>' +
'</svg>';
}
function renderEffectSummary(effect, beforeAfter) {
const dc = effect.delivery_change || {};
const pc = (effect.product_changes || []).reduce((m, p) => { m[p.key] = p; return m; }, {});
const ew = pc.extended_warranty || {};
const ax = pc.ax_package || {};
const battery = pc.battery_extended || {};
const deliveryRatio = dc.ratio;
const ewChange = ew.pp_change;
const axChange = ax.pp_change;
const batteryChange = battery.pp_change;
return '<div class="effect-summary">' +
'<div class="effect-item"><div class="label">交付数变化</div><div class="value ' + (deliveryRatio > 0 ? 'up' : (deliveryRatio < 0 ? 'down' : '')) + '">' + formatRatio(deliveryRatio) + '</div></div>' +
'<div class="effect-item"><div class="label">整车延保2</div><div class="value ' + (ewChange > 0 ? 'up' : (ewChange < 0 ? 'down' : '')) + '">' + (ewChange !== null && ewChange !== undefined ? (ewChange > 0 ? '+' : '') + ewChange.toFixed(1) + 'pp' : '-') + '</div></div>' +
'<div class="effect-item"><div class="label">安心包2</div><div class="value ' + (axChange > 0 ? 'up' : (axChange < 0 ? 'down' : '')) + '">' + (axChange !== null && axChange !== undefined ? (axChange > 0 ? '+' : '') + axChange.toFixed(1) + 'pp' : '-') + '</div></div>' +
'<div class="effect-item"><div class="label">电池2</div><div class="value ' + (batteryChange > 0 ? 'up' : (batteryChange < 0 ? 'down' : '')) + '">' + (batteryChange !== null && batteryChange !== undefined ? (batteryChange > 0 ? '+' : '') + batteryChange.toFixed(1) + 'pp' : '-') + '</div></div>' +
'</div>';
}
function renderDetail(data) {
const s = data.strategy || {};
const store = data.store || {};
const effect = data.effect || {};
const weeks = data.weekly_breakdown || [];
const comp = data.before_after;
const opMode = store.operation_mode || '';
const modeTagClass = opMode.includes('直营') ? 'tag-direct' : 'tag-franchise';
return '<div class="detail-container">' +
'<div class="left-panel">' +
'<div class="card"><div class="card-header">门店信息</div><div class="card-body">' +
'<div class="info-row"><span class="info-label">门店</span><span class="info-value">' + escapeHtml(s.merchant_name || '-') + '</span></div>' +
'<div class="info-row"><span class="info-label">兜底指标</span><span class="info-value"><span class="tag tag-baodi">' + escapeHtml(data.baodi_type || '交付') + '</span></span></div>' +
'<div class="info-row"><span class="info-label">区域(省)</span><span class="info-value">' + escapeHtml(store.province || '-') + '</span></div>' +
'<div class="info-row"><span class="info-label">直营/加盟</span><span class="info-value"><span class="tag ' + modeTagClass + '">' + escapeHtml(opMode || '-') + '</span></span></div>' +
'</div></div>' +
'<div class="card"><div class="card-header">盯防信息</div><div class="card-body">' +
'<div class="info-row"><span class="info-label">盯防类型</span><span class="info-value"><span class="tag ' + getMonitorClass(data.monitor_type) + '">' + escapeHtml(data.monitor_type || '-') + '</span></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.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></div>' +
'<div class="card"><div class="card-header">盯防效果摘要</div><div class="card-body">' + renderEffectSummary(effect, comp) + '</div></div>' +
'</div>' +
'<div class="right-panel">' +
'<div class="card"><div class="card-header"><span>业绩数据明细</span><span class="card-subtitle">兜底指标:交付数 | 盯防周期:' + escapeHtml(s.start_date || '') + ' ~ ' + escapeHtml(s.end_date || '') + '</span></div>' +
'<div class="card-body" style="padding:0">' + renderWeeklyTable(weeks, comp) + '</div></div>' +
'<div class="card"><div class="card-header">盯防前后业绩对比</div><div class="card-body">' + renderComparison(comp) + '</div></div>' +
'<div class="card"><div class="card-header">转化率周趋势</div><div class="card-body"><div class="chart-container">' + renderTrendChart(weeks) + '</div></div></div>' +
'<div class="card"><div class="card-header">分析结论</div><div class="card-body"><div class="conclusion">' + escapeHtml(data.conclusion || '暂无分析结论') + '</div></div></div>' +
'</div></div>';
}
window.showDetail = async function(id) { window.showDetail = async function(id) {
currentModalId = id;
document.getElementById('modal-title').textContent = '策略详情';
document.getElementById('modal-body').innerHTML = '<div class="loading">正在加载盯防效果数据...</div>';
document.getElementById('detail-modal').style.display = 'block';
document.body.style.overflow = 'hidden';
try { try {
const res = await fetch(window.API_BASE + '/strategy/' + id); const res = await fetch(window.API_BASE + '/strategy/' + id);
const json = await res.json(); const json = await res.json();
if (json.status !== 'success') throw new Error(json.detail || '加载失败'); if (json.status !== 'success') throw new Error(json.detail || '加载失败');
document.getElementById('modal-title').textContent = json.data.strategy.title || '策略详情';
document.getElementById('modal-body').innerHTML = renderDetail(json.data);
} catch (err) {
document.getElementById('modal-body').innerHTML = '<div class="error-tip">加载失败: ' + escapeHtml(err.message) + '</div>';
}
};
const data = json.data; window.refreshInModal = async function() {
const strategy = data.strategy || {}; if (!currentModalId) return;
const base = data.base_metrics || {}; const btn = document.getElementById('modal-btn-refresh');
const exec = data.exec_metrics || {}; btn.disabled = true;
const track = data.track_metrics || {}; btn.textContent = '分析中...';
try {
const title = strategy.title || '策略详情'; const res = await fetch(window.API_BASE + '/strategy/analyze/' + currentModalId, { method: 'POST' });
document.getElementById('modal-title').textContent = title; const json = await res.json();
if (json.status === 'success') {
const bodyHtml = [ // 重新加载详情
'<div style="margin-bottom:12px;color:#666;font-size:13px;">', const detailRes = await fetch(window.API_BASE + '/strategy/' + currentModalId);
'策略类型:' + escapeHtml(strategy.strategy_type_name || '-') + ' | ', const detailJson = await detailRes.json();
'盯防类型:' + escapeHtml(data.monitor_type || '-') + ' | ', if (detailJson.status === 'success') {
'状态:' + escapeHtml(strategy.status || '-') + ' | ', document.getElementById('modal-body').innerHTML = renderDetail(detailJson.data);
'周期:' + escapeHtml(strategy.start_date || '') + ' ~ ' + escapeHtml(strategy.end_date || ''), }
'</div>', loadData(); // 后台刷新列表
'<div style="margin-bottom:12px;color:#666;font-size:13px;">', } else {
'门店:' + escapeHtml(strategy.merchant_name || '-') + '(ID: ' + strategy.merchant_id + ')', alert('分析失败: ' + (json.detail || '未知错误'));
'</div>', }
'<h4 style="margin-top:20px;margin-bottom:10px;">周期指标对比</h4>',
'<div class="metric-grid">',
'<div class="metric-card"><div class="metric-label">T-1 交付数</div><div class="metric-value">' + (base.total_delivery || 0) + '</div></div>',
'<div class="metric-card"><div class="metric-label">T 执行期交付数</div><div class="metric-value">' + (exec.total_delivery || 0) + '</div></div>',
'<div class="metric-card"><div class="metric-label">T-1 整车延保渗透率</div><div class="metric-value">' + (base.ew_conversion ? base.ew_conversion.toFixed(2) + '%' : '-') + '</div></div>',
'<div class="metric-card"><div class="metric-label">T 整车延保渗透率</div><div class="metric-value">' + (exec.ew_conversion ? exec.ew_conversion.toFixed(2) + '%' : '-') + '</div></div>',
'<div class="metric-card"><div class="metric-label">T-1 安心包渗透率</div><div class="metric-value">' + (base.ax_conversion ? base.ax_conversion.toFixed(2) + '%' : '-') + '</div></div>',
'<div class="metric-card"><div class="metric-label">T 安心包渗透率</div><div class="metric-value">' + (exec.ax_conversion ? exec.ax_conversion.toFixed(2) + '%' : '-') + '</div></div>',
'<div class="metric-card"><div class="metric-label">T-1 电池延保渗透率</div><div class="metric-value">' + (base.battery_conversion ? base.battery_conversion.toFixed(2) + '%' : '-') + '</div></div>',
'<div class="metric-card"><div class="metric-label">T 电池延保渗透率</div><div class="metric-value">' + (exec.battery_conversion ? exec.battery_conversion.toFixed(2) + '%' : '-') + '</div></div>',
'</div>',
'<div class="conclusion-box">' + escapeHtml(data.conclusion || '暂无分析结论') + '</div>'
].join('');
document.getElementById('modal-body').innerHTML = bodyHtml;
document.getElementById('detail-modal').style.display = 'block';
} catch (err) { } catch (err) {
alert('加载详情失败: ' + err.message); alert('分析失败: ' + err.message);
} finally {
btn.disabled = false;
btn.textContent = '刷新分析';
} }
}; };
window.closeModal = function() { window.closeModal = function() {
document.getElementById('detail-modal').style.display = 'none'; document.getElementById('detail-modal').style.display = 'none';
document.body.style.overflow = '';
currentModalId = null;
}; };
window.onclick = function(event) { window.onclick = function(event) {
const modal = document.getElementById('detail-modal'); const modal = document.getElementById('detail-modal');
if (event.target === modal) { if (event.target === modal) closeModal();
modal.style.display = 'none';
}
}; };
async function analyzeSingle(id, btn) { async function analyzeSingle(id, btn) {
...@@ -486,11 +824,10 @@ ...@@ -486,11 +824,10 @@
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
loadOptions(); loadOptions();
loadData(); loadData();
document.getElementById('btn-search').addEventListener('click', collectFilters); document.getElementById('btn-search').addEventListener('click', collectFilters);
document.getElementById('btn-reset').addEventListener('click', resetFilters); document.getElementById('btn-reset').addEventListener('click', resetFilters);
}); });
</script> </script>
<script src="./static/js/auth.js"></script> <script src="/static/js/auth.js"></script>
</body> </body>
</html> </html>
...@@ -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,14 +1183,6 @@ def generate_conclusion(strategy, store, period_labels, period_metrics, ...@@ -1183,14 +1183,6 @@ def generate_conclusion(strategy, store, period_labels, period_metrics,
lines.append("\n## 二、策略执行效果\n") lines.append("\n## 二、策略执行效果\n")
if exec_m: if exec_m:
# T vs T-1
if base:
lines.append("### 策略执行期 vs 基线期 (T vs T-1)")
ew_delta = _pen_change(base, exec_m, "ew_conversion")
ax_delta = _pen_change(base, exec_m, "ax_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
def rate_pp(delta): def rate_pp(delta):
if delta > 10: return "大幅提升(显著改善)" if delta > 10: return "大幅提升(显著改善)"
if delta > 3: return "明显提升" if delta > 3: return "明显提升"
...@@ -1200,6 +1192,14 @@ def generate_conclusion(strategy, store, period_labels, period_metrics, ...@@ -1200,6 +1192,14 @@ def generate_conclusion(strategy, store, period_labels, period_metrics,
if delta > -10: return "明显下降" if delta > -10: return "明显下降"
return "大幅下降(需关注)" return "大幅下降(需关注)"
# T vs T-1
if base:
lines.append("### 策略执行期 vs 基线期 (T vs T-1)")
ew_delta = _pen_change(base, exec_m, "ew_conversion")
ax_delta = _pen_change(base, exec_m, "ax_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
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!