Commit 51e01fff by 江名洋

chore: 移除鸿蒙输出模板生成脚本

1 parent 776ba890
...@@ -13,6 +13,7 @@ from app.services.etl_service import ETLService ...@@ -13,6 +13,7 @@ from app.services.etl_service import ETLService
from app.services.excel_service import ExcelService from app.services.excel_service import ExcelService
from app.services.analysis_service import AnalysisService from app.services.analysis_service import AnalysisService
from app.services.harmony_analysis_service import HarmonyAnalysisService from app.services.harmony_analysis_service import HarmonyAnalysisService
from app.services.strategy_service import StrategyService, get_task_state
from app.core.scheduler import SchedulerManager from app.core.scheduler import SchedulerManager
import os import os
import shutil import shutil
...@@ -513,3 +514,96 @@ async def harmony_download(file: str = Query(None)): ...@@ -513,3 +514,96 @@ async def harmony_download(file: str = Query(None)):
filename=output_files[0], filename=output_files[0],
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
) )
# ==================== 策略效果盯防接口 ====================
@router.get("/strategy/options")
async def strategy_options():
"""获取策略盯防筛选选项"""
try:
return {"status": "success", "data": StrategyService.get_filter_options()}
except Exception as e:
logger.error(f"Strategy options failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@router.get("/strategy/list")
async def strategy_list(
keyword: Optional[str] = Query(None),
province: Optional[str] = Query(None),
baodi_type: Optional[str] = Query(None),
monitor_type: Optional[str] = Query(None),
status: Optional[str] = Query(None),
operation_mode: Optional[str] = Query(None),
effect: Optional[str] = Query(None),
start_date: Optional[str] = Query(None),
end_date: Optional[str] = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(8, ge=1, le=100),
):
"""策略盯防列表:查询策略并计算执行前后效果"""
try:
data = StrategyService.get_strategy_list(
keyword=keyword,
province=province,
baodi_type=baodi_type,
monitor_type=monitor_type,
status=status,
operation_mode=operation_mode,
effect=effect,
start_date=start_date,
end_date=end_date,
page=page,
page_size=page_size,
)
return {"status": "success", "data": data}
except Exception as e:
logger.error(f"Strategy list failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询策略列表失败: {str(e)}")
@router.get("/strategy/{strategy_id}")
async def strategy_detail(strategy_id: int):
"""获取单条策略详情及效果分析"""
try:
data = StrategyService.get_strategy_detail(strategy_id)
if not data:
raise HTTPException(status_code=404, detail="策略不存在")
return {"status": "success", "data": data}
except HTTPException:
raise
except Exception as e:
logger.error(f"Strategy detail failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询策略详情失败: {str(e)}")
# ==================== 策略分析任务控制接口 ====================
@router.post("/strategy/analyze")
async def strategy_trigger_analyze():
"""触发策略效果批量分析任务(异步后台执行)"""
try:
state = get_task_state()
if state.get("running"):
return {
"status": "warning",
"message": "分析任务已在运行中",
"data": state,
}
result = StrategyService.trigger_analysis_async()
return {"status": "success", "message": "分析任务已触发", "data": result}
except Exception as e:
logger.error(f"Strategy analyze trigger failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"触发分析任务失败: {str(e)}")
@router.get("/strategy/analyze/status")
async def strategy_analyze_status():
"""获取策略分析任务进度状态"""
try:
state = get_task_state()
return {"status": "success", "data": state}
except Exception as e:
logger.error(f"Strategy analyze status failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"获取任务状态失败: {str(e)}")
...@@ -39,7 +39,16 @@ class SchedulerManager: ...@@ -39,7 +39,16 @@ class SchedulerManager:
replace_existing=True replace_existing=True
) )
# 2. 健康检查 (每 10 分钟执行一次) # 2. 策略效果分析任务 (每 2 小时执行一次)
cls._scheduler.add_job(
cls.sync_strategy_analysis,
IntervalTrigger(hours=2),
id="sync_strategy_analysis",
max_instances=1,
replace_existing=True,
)
# 3. 健康检查 (每 10 分钟执行一次)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.health_check, cls.health_check,
IntervalTrigger(minutes=10), IntervalTrigger(minutes=10),
...@@ -72,6 +81,31 @@ class SchedulerManager: ...@@ -72,6 +81,31 @@ class SchedulerManager:
logger.error(f"[Scheduler] sync_ods_task failed: {e}") logger.error(f"[Scheduler] sync_ods_task failed: {e}")
@classmethod @classmethod
async def sync_strategy_analysis(cls):
"""策略效果分析定时任务"""
logger.info(f"[Scheduler] Start sync_strategy_analysis at {datetime.now()}")
try:
import asyncio
from app.services.strategy_service import get_task_state
state = get_task_state()
if state.get("running"):
logger.info("[Scheduler] strategy analysis already running, skip")
return
# 在线程池中执行同步方法
await asyncio.get_event_loop().run_in_executor(
None, cls._run_strategy_analysis_sync
)
logger.info(f"[Scheduler] sync_strategy_analysis completed")
except Exception as e:
logger.error(f"[Scheduler] sync_strategy_analysis failed: {e}")
@staticmethod
def _run_strategy_analysis_sync():
"""同步包装,供 run_in_executor 调用"""
from app.services.strategy_service import StrategyService
StrategyService.run_analysis_task()
@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()}")
...@@ -25,12 +25,12 @@ HARMONY_BRAND_IDS = (2695, 2698, 2741, 2740, 2797) ...@@ -25,12 +25,12 @@ HARMONY_BRAND_IDS = (2695, 2698, 2741, 2740, 2797)
# first_brand_id(鸿蒙智行,参考 generate_weekly_comparison.py) # first_brand_id(鸿蒙智行,参考 generate_weekly_comparison.py)
FIRST_BRAND_ID = 2365 FIRST_BRAND_ID = 2365
# 样式定义 # 样式定义(与模板一致:浅蓝/浅橙/浅黄/浅紫/浅绿,字体统一黑色)
HEADER_FILL = PatternFill("solid", fgColor="4472C4") HEADER_FILL = PatternFill("solid", fgColor="BDD7EE")
HEADER_FONT = Font(name="微软雅黑", bold=True, color="FFFFFF", size=10) HEADER_FONT = Font(name="微软雅黑", bold=True, color="000000", size=10)
GROUP_FILL = PatternFill("solid", fgColor="D6E4F0") GROUP_FILL = PatternFill("solid", fgColor="BDD7EE")
GROUP_FONT = Font(name="微软雅黑", bold=True, size=10) GROUP_FONT = Font(name="微软雅黑", bold=True, color="000000", size=10)
DATA_FONT = Font(name="微软雅黑", size=10) DATA_FONT = Font(name="微软雅黑", size=10, color="000000")
THIN_BORDER = Border( THIN_BORDER = Border(
left=Side(style="thin"), right=Side(style="thin"), left=Side(style="thin"), right=Side(style="thin"),
top=Side(style="thin"), bottom=Side(style="thin") top=Side(style="thin"), bottom=Side(style="thin")
...@@ -472,10 +472,10 @@ class HarmonyAnalysisService: ...@@ -472,10 +472,10 @@ class HarmonyAnalysisService:
ws, merged, db_perf, formula_map, skip_external_cols, ws, merged, db_perf, formula_map, skip_external_cols,
start_date, end_date) start_date, end_date)
# 自动筛选(保留模板的分组合并单元格) # 自动筛选(从第2行列名行开始)
from openpyxl.utils import get_column_letter from openpyxl.utils import get_column_letter
last_col = get_column_letter(ws.max_column) last_col = get_column_letter(ws.max_column)
ws.auto_filter.ref = f"A3:{last_col}{next_row - 1}" ws.auto_filter.ref = f"A2:{last_col}{next_row - 1}"
wb.save(output_path) wb.save(output_path)
logger.info(f"Harmony report generated: {output_path}") logger.info(f"Harmony report generated: {output_path}")
...@@ -525,7 +525,7 @@ class HarmonyAnalysisService: ...@@ -525,7 +525,7 @@ class HarmonyAnalysisService:
def _style_cell(r, c, value): def _style_cell(r, c, value):
cell = ws.cell(row=r, column=c, value=value) cell = ws.cell(row=r, column=c, value=value)
cell.font = Font(name="微软雅黑", size=10) cell.font = Font(name="微软雅黑", size=10, color="000000")
cell.border = THIN_BORDER cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
if isinstance(value, (int, float)): if isinstance(value, (int, float)):
......
# -*- coding: utf-8 -*-
"""
文件名: app/services/strategy_service.py
职责: 策略效果盯防服务 - 异步分析策略并写入结果表,列表从结果表查询。
注意: 不要删除这个注释。
"""
import os
import json
import logging
import math
import threading
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any
import pymysql
from app.core.config import settings
logger = logging.getLogger("app.strategy_service")
# 策略类型映射
STRATEGY_TYPE_MAP = {
0: "学习类", 1: "优秀录音分享类", 2: "带教", 3: "任务型",
4: "销售精英到店提拉", 5: "强力促销", 6: "最终盘点与低客单产品购入",
7: "留言", 8: "带教申请", 9: "人员更换评估", 10: "商务政策更新评估",
11: "多品类拓张", 12: "流量问题改善",
}
# 策略状态映射
PUSH_FLAG_MAP = {
0: "未推送", 1: "盯防中", 2: "未完成", 3: "审批中",
4: "盯防中", 5: "已驳回", 6: "已结束",
}
# 产品配置
PRODUCTS = {
"extended_warranty": {"name": "整车延保", "order_col": "sum_extended_warranty", "alias": "延保"},
"ax_package": {"name": "安心包", "order_col": "sum_ax_package", "alias": "安心包"},
"battery_extended": {"name": "电池延保", "order_col": "sum_battery_extended", "alias": "电池"},
}
# 任务状态(模块级变量,供 Web 查询进度)
_task_lock = threading.Lock()
_task_state = {
"running": False, # 是否正在执行
"total": 0, # 待分析总数
"completed": 0, # 已完成数
"failed": 0, # 失败数
"started_at": None, # 开始时间 ISO str
"finished_at": None, # 结束时间 ISO str
"current": None, # 当前正在处理的 strategy_id
"errors": [], # 最近错误列表 [(strategy_id, msg), ...]
}
def _reset_task_state():
with _task_lock:
_task_state.update(
running=False, total=0, completed=0, failed=0,
started_at=None, finished_at=None, current=None, errors=[]
)
def get_task_state() -> Dict:
"""返回当前任务状态快照"""
with _task_lock:
return dict(_task_state)
class StrategyService:
"""策略效果盯防服务"""
# ──────────── 数据库连接 ────────────
@staticmethod
def _get_raw_conn():
return pymysql.connect(
host=settings.DB_HOST, port=settings.DB_PORT,
user=settings.DB_USER, password=settings.DB_PASSWORD,
database=settings.DB_NAME, charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor,
)
@staticmethod
def _safe_num(val):
return val if val is not None else 0
@staticmethod
def _safe_rate(numerator, denominator):
if not denominator or denominator == 0:
return 0.0
return float(numerator) / float(denominator) * 100.0
@staticmethod
def _date_str(d):
if d is None:
return None
if isinstance(d, datetime):
return d.strftime("%Y-%m-%d")
if isinstance(d, str):
return d[:10]
return str(d)[:10]
# ──────────── 建表 ────────────
@staticmethod
def ensure_result_table():
"""确保结果表存在"""
sql = """
CREATE TABLE IF NOT EXISTS strategy_analysis_result (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
strategy_id INT NOT NULL,
title VARCHAR(500),
sub_title VARCHAR(500),
strategy_type INT,
strategy_type_name VARCHAR(100),
merchant_id INT,
merchant_name VARCHAR(200),
merchant_code VARCHAR(100),
province VARCHAR(100),
city VARCHAR(100),
operation_mode VARCHAR(50),
baodi_type VARCHAR(20),
monitor_type VARCHAR(50),
status VARCHAR(20),
push_flag INT,
start_date DATE,
end_date DATE,
receiver VARCHAR(100),
description TEXT,
effect_label VARCHAR(20),
effect_class VARCHAR(20),
effect_score INT,
delivery_old DECIMAL(14,2),
delivery_new DECIMAL(14,2),
delivery_ratio DECIMAL(10,2),
ew_old_rate DECIMAL(10,2),
ew_new_rate DECIMAL(10,2),
ew_pp_change DECIMAL(10,2),
ax_old_rate DECIMAL(10,2),
ax_new_rate DECIMAL(10,2),
ax_pp_change DECIMAL(10,2),
battery_old_rate DECIMAL(10,2),
battery_new_rate DECIMAL(10,2),
battery_pp_change DECIMAL(10,2),
base_metrics_json JSON,
exec_metrics_json JSON,
track_metrics_json JSON,
product_changes_json JSON,
conclusion TEXT,
is_valid TINYINT(1) DEFAULT 1,
error_msg VARCHAR(500),
analysis_time DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_strategy_id (strategy_id),
INDEX idx_merchant_id (merchant_id),
INDEX idx_province (province),
INDEX idx_baodi_type (baodi_type),
INDEX idx_monitor_type (monitor_type),
INDEX idx_status (status),
INDEX idx_effect_label (effect_label),
INDEX idx_operation_mode (operation_mode),
INDEX idx_start_date (start_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(sql)
conn.commit()
logger.info("[Strategy] result table ensured")
finally:
conn.close()
# ──────────── 周期计算 ────────────
@staticmethod
def _parse_period(strategy: Dict) -> tuple:
"""根据策略起止日期计算 T-1 / T / T+1 周期"""
start = StrategyService._date_str(strategy.get("start_date"))
end = StrategyService._date_str(strategy.get("end_date"))
if not start or not end:
return None, None, None
start_dt = datetime.strptime(start, "%Y-%m-%d")
end_dt = datetime.strptime(end, "%Y-%m-%d")
duration_days = (end_dt - start_dt).days + 1
t_minus_start = (start_dt - timedelta(days=duration_days)).strftime("%Y-%m-%d")
t_minus_end = (start_dt - timedelta(days=1)).strftime("%Y-%m-%d")
t_plus_start = (end_dt + timedelta(days=1)).strftime("%Y-%m-%d")
t_plus_end = (end_dt + timedelta(days=duration_days)).strftime("%Y-%m-%d")
today = datetime.now().strftime("%Y-%m-%d")
if t_plus_end > today:
t_plus_end = today
if t_plus_start > t_plus_end:
t_plus_start = None
return (t_minus_start, t_minus_end), (start, end), (t_plus_start, t_plus_end)
# ──────────── 数据查询 ────────────
@staticmethod
def _get_store_daily_metrics(merchant_id: int, start_date: str, end_date: str) -> List[Dict]:
if not start_date or not end_date or start_date > end_date:
return []
sql = """
SELECT
report_date,
SUM(IFNULL(delivery_count, 0)) AS delivery_count,
SUM(IFNULL(sum_equity_to_shop, 0)) AS pre_sale_touch,
SUM(IFNULL(sum_after_sale_to_shop, 0)) AS after_sale_touch,
SUM(IFNULL(sum_extended_warranty, 0)) AS extended_warranty_orders,
SUM(IFNULL(sum_ax_package, 0)) AS ax_package_orders,
SUM(IFNULL(sum_battery_extended, 0)) AS battery_extended_orders,
SUM(IFNULL(sum_order_count, 0)) AS total_orders
FROM dws_merchant_daily_wide
WHERE merchant_id = %s
AND report_date BETWEEN %s AND %s
AND first_brand_id = 2365
AND brand_id = 2695
AND scene_type = '0'
GROUP BY report_date
ORDER BY report_date
"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date))
return cur.fetchall()
finally:
conn.close()
@staticmethod
def _get_store_config(merchant_id: int) -> Optional[Dict]:
sql = """
SELECT merchant_id, merchant_name, merchant_code, province, city,
channel, operation_mode, traffic_grade, primary_brand,
area_manager, online_ops, flight_supervisor, deploy_time
FROM ods_store_config
WHERE merchant_id = %s AND deleted_flag = 'N'
"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(sql, (merchant_id,))
return cur.fetchone()
finally:
conn.close()
# ──────────── 聚合与分析 ────────────
@staticmethod
def _aggregate_metrics(daily_rows: List[Dict]) -> Optional[Dict]:
if not daily_rows:
return None
total_delivery = sum(StrategyService._safe_num(r.get("delivery_count", 0)) for r in daily_rows)
total_pre_touch = sum(StrategyService._safe_num(r.get("pre_sale_touch", 0)) for r in daily_rows)
total_after_touch = sum(StrategyService._safe_num(r.get("after_sale_touch", 0)) for r in daily_rows)
total_ew = sum(StrategyService._safe_num(r.get("extended_warranty_orders", 0)) for r in daily_rows)
total_ax = sum(StrategyService._safe_num(r.get("ax_package_orders", 0)) for r in daily_rows)
total_battery = sum(StrategyService._safe_num(r.get("battery_extended_orders", 0)) for r in daily_rows)
total_orders = sum(StrategyService._safe_num(r.get("total_orders", 0)) for r in daily_rows)
days = len(daily_rows)
return {
"days": days,
"total_delivery": total_delivery,
"total_pre_touch": total_pre_touch,
"total_after_touch": total_after_touch,
"total_touch": total_pre_touch + total_after_touch,
"total_ew": total_ew,
"total_ax": total_ax,
"total_battery": total_battery,
"total_orders": total_orders,
"ew_conversion": StrategyService._safe_rate(total_ew, total_delivery),
"ax_conversion": StrategyService._safe_rate(total_ax, total_delivery),
"battery_conversion": StrategyService._safe_rate(total_battery, total_delivery),
}
@staticmethod
def _classify_effect(base_metrics: Optional[Dict], exec_metrics: Optional[Dict]) -> Dict:
"""根据产品渗透率变化判断整体效果"""
def _pp_change(old_rate, new_rate):
if old_rate is None or new_rate is None:
return None
return new_rate - old_rate
delivery_old = base_metrics.get("total_delivery", 0) if base_metrics else 0
delivery_new = exec_metrics.get("total_delivery", 0) if exec_metrics else 0
if delivery_old == 0 and delivery_new == 0:
delivery_ratio = 0.0
elif delivery_old == 0:
delivery_ratio = 100.0
else:
delivery_ratio = (delivery_new - delivery_old) / delivery_old * 100.0
product_key_map = {
"extended_warranty": ("total_ew",),
"ax_package": ("total_ax",),
"battery_extended": ("total_battery",),
}
product_changes = []
product_score = 0
for key, cfg in PRODUCTS.items():
metric_key = product_key_map[key][0]
old_orders = base_metrics.get(metric_key, 0) if base_metrics else 0
new_orders = exec_metrics.get(metric_key, 0) if exec_metrics else 0
old_rate = StrategyService._safe_rate(old_orders, delivery_old) if delivery_old else 0.0
new_rate = StrategyService._safe_rate(new_orders, delivery_new) if delivery_new else 0.0
pp = _pp_change(old_rate, new_rate)
product_changes.append({
"key": key, "name": cfg["name"], "alias": cfg["alias"],
"old_rate": old_rate, "new_rate": new_rate, "pp_change": pp,
})
if pp is not None:
if pp > 3:
product_score += 2
elif pp > 0:
product_score += 1
elif pp < -3:
product_score -= 2
elif pp < 0:
product_score -= 1
if not exec_metrics:
label = "暂无数据"
class_name = "flat"
elif not base_metrics:
label = "基线缺失"
class_name = "flat"
elif product_score >= 4:
label = "显著提升"
class_name = "up-strong"
elif product_score >= 1:
label = "有所提升"
class_name = "up"
elif product_score <= -4:
label = "效果下降"
class_name = "down-strong"
elif product_score <= -1:
label = "效果下降"
class_name = "down"
else:
label = "基本持平"
class_name = "flat"
return {
"label": label, "class_name": class_name,
"delivery_change": {
"old": delivery_old, "new": delivery_new, "ratio": delivery_ratio,
},
"product_changes": product_changes,
}
@staticmethod
def _detect_baodi_type(strategy: Dict, store: Optional[Dict]) -> str:
text = f"{strategy.get('title', '')} {strategy.get('sub_title', '')} {strategy.get('description', '')}".lower()
if "触客" in text and "交付" not in text:
return "触客"
if "交付" in text:
return "交付"
if store and store.get("baodi_type"):
return str(store.get("baodi_type"))
return "交付"
@staticmethod
def _detect_monitor_type(strategy: Dict, effect_label: str) -> str:
title = (strategy.get("title") or "").lower()
desc = (strategy.get("description") or "").lower()
strategy_type = strategy.get("strategy_type")
text = f"{title} {desc}"
if "新店" in text or "开业" in text or strategy_type == 9:
return "新店盯防"
if effect_label == "效果下降" or "下滑" in text or strategy_type in (5, 6):
return "业绩下滑盯防"
if strategy_type in (2, 4, 8, 11, 12) or "预警" in text or "提升" in text:
return "预警盯防"
return "预警盯防" if effect_label in ("显著提升", "有所提升") else "业绩下滑盯防"
# ──────────── 单条策略分析 ────────────
@staticmethod
def analyze_single_strategy(strategy: Dict) -> Optional[Dict]:
"""对单条策略进行完整分析,返回结果 dict,失败返回 None"""
strategy_id = strategy.get("id")
merchant_id = strategy.get("merchant_id")
try:
store = StrategyService._get_store_config(merchant_id) if merchant_id else None
periods = StrategyService._parse_period(strategy)
base_metrics = None
exec_metrics = None
if merchant_id and periods[0] and periods[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])
base_metrics = StrategyService._aggregate_metrics(base_rows)
exec_metrics = StrategyService._aggregate_metrics(exec_rows)
effect = StrategyService._classify_effect(base_metrics, exec_metrics)
baodi = StrategyService._detect_baodi_type(strategy, store)
monitor_type = StrategyService._detect_monitor_type(strategy, effect["label"])
status_label = PUSH_FLAG_MAP.get(strategy.get("push_flag"), "未知")
province_label = str(store.get("province", "")) if store else ""
if not province_label:
province_label = "未知"
product_changes = effect["product_changes"]
pc_map = {p["key"]: p for p in product_changes}
ew_pc = pc_map.get("extended_warranty", {})
ax_pc = pc_map.get("ax_package", {})
bt_pc = pc_map.get("battery_extended", {})
dc = effect["delivery_change"]
return {
"strategy_id": strategy_id,
"title": strategy.get("title", ""),
"sub_title": strategy.get("sub_title", ""),
"strategy_type": strategy.get("strategy_type"),
"strategy_type_name": STRATEGY_TYPE_MAP.get(StrategyService._safe_num(strategy.get("strategy_type")), "未知"),
"merchant_id": merchant_id,
"merchant_name": strategy.get("merchant_name") or (store.get("merchant_name") if store else ""),
"merchant_code": store.get("merchant_code") if store else "",
"province": province_label,
"city": store.get("city") if store else "",
"operation_mode": str(store.get("operation_mode", "")) if store else "",
"baodi_type": baodi,
"monitor_type": monitor_type,
"status": status_label,
"push_flag": strategy.get("push_flag"),
"start_date": StrategyService._date_str(strategy.get("start_date")),
"end_date": StrategyService._date_str(strategy.get("end_date")),
"receiver": strategy.get("created_by") or "",
"description": strategy.get("description", ""),
"effect_label": effect["label"],
"effect_class": effect["class_name"],
"effect_score": 0, # 后续可扩展
"delivery_old": dc.get("old"),
"delivery_new": dc.get("new"),
"delivery_ratio": dc.get("ratio"),
"ew_old_rate": ew_pc.get("old_rate"),
"ew_new_rate": ew_pc.get("new_rate"),
"ew_pp_change": ew_pc.get("pp_change"),
"ax_old_rate": ax_pc.get("old_rate"),
"ax_new_rate": ax_pc.get("new_rate"),
"ax_pp_change": ax_pc.get("pp_change"),
"battery_old_rate": bt_pc.get("old_rate"),
"battery_new_rate": bt_pc.get("new_rate"),
"battery_pp_change": bt_pc.get("pp_change"),
"base_metrics_json": json.dumps(base_metrics, ensure_ascii=False, default=str) if base_metrics else None,
"exec_metrics_json": json.dumps(exec_metrics, ensure_ascii=False, default=str) if exec_metrics else None,
"track_metrics_json": None,
"product_changes_json": json.dumps(product_changes, ensure_ascii=False, default=str),
"conclusion": StrategyService._build_conclusion(
strategy, base_metrics, exec_metrics, effect, product_changes
),
"is_valid": 1,
"error_msg": None,
"analysis_time": datetime.now(),
}
except Exception as e:
logger.error(f"[Strategy] analyze strategy {strategy_id} error: {e}", exc_info=True)
return {
"strategy_id": strategy_id,
"title": strategy.get("title", ""),
"is_valid": 0,
"error_msg": str(e)[:500],
"analysis_time": datetime.now(),
}
@staticmethod
def _build_conclusion(strategy, base, exec_m, effect, product_changes) -> str:
if not exec_m:
return "策略执行期暂无数据,无法评估效果。"
if not base:
return "缺少基线期数据,无法与策略执行前对比。"
lines = [f"策略「{strategy.get('title', '')}」执行期间:"]
dc = effect.get("delivery_change", {})
if dc.get("ratio") is not None:
arrow = "↑" if dc["ratio"] > 0 else ("↓" if dc["ratio"] < 0 else "→")
lines.append(f"交付数:{dc.get('old', 0)} → {dc.get('new', 0)} ({arrow}{dc['ratio']:+.1f}%)")
for p in product_changes:
pp = p.get("pp_change")
if pp is not None:
arrow = "↑" if pp > 0 else ("↓" if pp < 0 else "→")
lines.append(f"{p['name']}渗透率:{p['old_rate']:.1f}% → {p['new_rate']:.1f}% ({arrow}{pp:+.1f}pp)")
lines.append(f"整体效果:{effect['label']}。")
return "\n".join(lines)
@staticmethod
def _upsert_result(record: Dict):
"""将分析结果 upsert 到结果表"""
cols = [
"strategy_id", "title", "sub_title", "strategy_type", "strategy_type_name",
"merchant_id", "merchant_name", "merchant_code", "province", "city",
"operation_mode", "baodi_type", "monitor_type", "status", "push_flag",
"start_date", "end_date", "receiver", "description",
"effect_label", "effect_class", "effect_score",
"delivery_old", "delivery_new", "delivery_ratio",
"ew_old_rate", "ew_new_rate", "ew_pp_change",
"ax_old_rate", "ax_new_rate", "ax_pp_change",
"battery_old_rate", "battery_new_rate", "battery_pp_change",
"base_metrics_json", "exec_metrics_json", "track_metrics_json",
"product_changes_json", "conclusion",
"is_valid", "error_msg", "analysis_time",
]
placeholders = ", ".join(["%s"] * len(cols))
col_names = ", ".join(cols)
on_dup = ", ".join(
f"{c} = VALUES({c})" for c in cols if c != "strategy_id"
)
sql = f"""
INSERT INTO strategy_analysis_result ({col_names})
VALUES ({placeholders})
ON DUPLICATE KEY UPDATE {on_dup}
"""
values = tuple(record.get(c) for c in cols)
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(sql, values)
conn.commit()
finally:
conn.close()
# ──────────── 异步批量分析任务 ────────────
@staticmethod
def run_analysis_task():
"""
后台批量分析任务:遍历所有策略,逐个分析后写入结果表。
此方法在后台线程中运行。
"""
global _task_state
with _task_lock:
if _task_state["running"]:
logger.warning("[Strategy] analysis task already running, skip")
return
_task_state.update(
running=True, total=0, completed=0, failed=0,
started_at=datetime.now().isoformat(), finished_at=None,
current=None, errors=[],
)
try:
logger.info("[Strategy] === analysis task start ===")
# 1. 确保结果表存在
StrategyService.ensure_result_table()
# 2. 获取所有策略
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(
"SELECT id, title, sub_title, strategy_type, merchant_id, "
"merchant_name, start_date, end_date, push_flag, description, "
"biz, created_date, created_by "
"FROM ods_strategy_info WHERE deleted_flag = 'N' "
"ORDER BY created_date DESC"
)
strategies = cur.fetchall()
finally:
conn.close()
total = len(strategies)
with _task_lock:
_task_state["total"] = total
logger.info(f"[Strategy] total strategies to analyze: {total}")
# 3. 逐个分析
completed = 0
failed = 0
for idx, strategy in enumerate(strategies):
with _task_lock:
_task_state["current"] = strategy.get("id")
_task_state["completed"] = completed
_task_state["failed"] = failed
result = StrategyService.analyze_single_strategy(strategy)
if result:
try:
StrategyService._upsert_result(result)
if result.get("is_valid"):
completed += 1
else:
failed += 1
with _task_lock:
_task_state["errors"].append(
(strategy.get("id"), result.get("error_msg", "未知错误"))
)
if len(_task_state["errors"]) > 20:
_task_state["errors"] = _task_state["errors"][-20:]
except Exception as e:
failed += 1
logger.error(f"[Strategy] upsert result for {strategy.get('id')} failed: {e}")
else:
failed += 1
if (idx + 1) % 20 == 0:
logger.info(f"[Strategy] progress: {idx + 1}/{total} (ok={completed}, fail={failed})")
with _task_lock:
_task_state["completed"] = completed
_task_state["failed"] = failed
_task_state["current"] = None
_task_state["finished_at"] = datetime.now().isoformat()
logger.info(f"[Strategy] === analysis task done: ok={completed}, fail={failed} ===")
except Exception as e:
logger.error(f"[Strategy] analysis task fatal error: {e}", exc_info=True)
with _task_lock:
_task_state["running"] = False
_task_state["finished_at"] = datetime.now().isoformat()
finally:
with _task_lock:
_task_state["running"] = False
if _task_state["finished_at"] is None:
_task_state["finished_at"] = datetime.now().isoformat()
@staticmethod
def trigger_analysis_async():
"""触发异步分析(在后台线程运行)"""
thread = threading.Thread(target=StrategyService.run_analysis_task, daemon=True)
thread.start()
return {"message": "analysis task started"}
# ──────────── 从结果表查询列表 ────────────
@staticmethod
def get_strategy_list_from_results(
keyword: Optional[str] = None,
province: Optional[str] = None,
baodi_type: Optional[str] = None,
monitor_type: Optional[str] = None,
status: Optional[str] = None,
operation_mode: Optional[str] = None,
effect: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
page: int = 1,
page_size: int = 8,
) -> Dict:
"""从结果表查询策略列表(高性能)"""
conditions = ["is_valid = 1"]
params = []
if keyword:
conditions.append("(title LIKE %s OR merchant_name LIKE %s OR receiver LIKE %s)")
params.extend([f"%{keyword}%", f"%{keyword}%", f"%{keyword}%"])
if province:
conditions.append("province = %s")
params.append(province)
if baodi_type:
conditions.append("baodi_type = %s")
params.append(baodi_type)
if monitor_type:
conditions.append("monitor_type = %s")
params.append(monitor_type)
if status:
conditions.append("status = %s")
params.append(status)
if operation_mode:
conditions.append("operation_mode = %s")
params.append(operation_mode)
if effect:
conditions.append("effect_label = %s")
params.append(effect)
if start_date:
conditions.append("end_date >= %s")
params.append(start_date)
if end_date:
conditions.append("start_date <= %s")
params.append(end_date)
where = " AND ".join(conditions)
# 总数 & 统计
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(f"SELECT COUNT(*) AS cnt FROM strategy_analysis_result WHERE {where}", tuple(params))
total = cur.fetchone()["cnt"]
# 统计
cur.execute(
"SELECT "
"SUM(CASE WHEN status = '盯防中' THEN 1 ELSE 0 END) AS monitoring, "
"SUM(CASE WHEN effect_label IN ('显著提升','有所提升') THEN 1 ELSE 0 END) AS up, "
"SUM(CASE WHEN effect_label = '效果下降' THEN 1 ELSE 0 END) AS down, "
"SUM(CASE WHEN status = '已结束' THEN 1 ELSE 0 END) AS ended "
f"FROM strategy_analysis_result WHERE {where}",
tuple(params),
)
stat_row = cur.fetchone()
# 分页数据
offset = (page - 1) * page_size
cur.execute(
f"SELECT * FROM strategy_analysis_result WHERE {where} "
"ORDER BY analysis_time DESC, strategy_id DESC "
"LIMIT %s OFFSET %s",
tuple(params) + (page_size, offset),
)
rows = cur.fetchall()
finally:
conn.close()
# 格式化
records = []
for r in rows:
# 构建 delivery_change / product_changes 供前端使用
dc = {
"old": float(r["delivery_old"]) if r["delivery_old"] is not None else 0,
"new": float(r["delivery_new"]) if r["delivery_new"] is not None else 0,
"ratio": float(r["delivery_ratio"]) if r["delivery_ratio"] is not None else None,
}
product_changes = []
if r.get("product_changes_json"):
try:
product_changes = json.loads(r["product_changes_json"])
except (json.JSONDecodeError, TypeError):
pass
records.append({
"id": r["strategy_id"],
"title": r["title"] or "",
"sub_title": r["sub_title"] or "",
"strategy_type": r["strategy_type"],
"strategy_type_name": r["strategy_type_name"] or "",
"merchant_id": r["merchant_id"],
"merchant_name": r["merchant_name"] or "",
"merchant_code": r["merchant_code"] or "",
"province": r["province"] or "",
"city": r["city"] or "",
"operation_mode": r["operation_mode"] or "",
"baodi_type": r["baodi_type"] or "",
"monitor_type": r["monitor_type"] or "",
"status": r["status"] or "",
"push_flag": r["push_flag"],
"start_date": StrategyService._date_str(r["start_date"]),
"end_date": StrategyService._date_str(r["end_date"]),
"receiver": r["receiver"] or "",
"effect": r["effect_label"] or "",
"effect_class": r["effect_class"] or "",
"delivery_change": dc,
"product_changes": product_changes,
"description": r["description"] or "",
"created_by": r["receiver"] or "",
"biz": "",
})
return {
"total": total,
"monitoring": stat_row.get("monitoring", 0) or 0,
"up": stat_row.get("up", 0) or 0,
"down": stat_row.get("down", 0) or 0,
"ended": stat_row.get("ended", 0) or 0,
"page": page,
"page_size": page_size,
"total_pages": math.ceil(total / page_size) if total else 1,
"records": records,
}
# ──────────── 筛选选项 ────────────
@staticmethod
def get_filter_options() -> Dict:
sql = "SELECT DISTINCT province FROM ods_store_config WHERE deleted_flag = 'N' AND province IS NOT NULL AND province != '' ORDER BY province"
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(sql)
rows = cur.fetchall()
provinces = [r["province"] for r in rows if r.get("province")]
finally:
conn.close()
return {
"provinces": provinces,
"baodi_types": ["交付", "触客"],
"monitor_types": ["业绩下滑盯防", "预警盯防", "新店盯防"],
"statuses": ["盯防中", "已结束", "未推送", "未完成", "审批中", "已驳回"],
"operation_modes": ["直营", "加盟"],
"effects": ["显著提升", "有所提升", "基本持平", "效果下降"],
}
# ──────────── 详情 ────────────
@staticmethod
def get_strategy_detail(strategy_id: int) -> Optional[Dict]:
"""获取单条策略详情(优先从结果表读,回退到实时分析)"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(
"SELECT * FROM strategy_analysis_result WHERE strategy_id = %s",
(strategy_id,),
)
row = cur.fetchone()
finally:
conn.close()
if not row:
return None
base_metrics = None
exec_metrics = None
track_metrics = None
if row.get("base_metrics_json"):
try:
base_metrics = json.loads(row["base_metrics_json"])
except (json.JSONDecodeError, TypeError):
pass
if row.get("exec_metrics_json"):
try:
exec_metrics = json.loads(row["exec_metrics_json"])
except (json.JSONDecodeError, TypeError):
pass
if row.get("track_metrics_json"):
try:
track_metrics = json.loads(row["track_metrics_json"])
except (json.JSONDecodeError, TypeError):
pass
product_changes = []
if row.get("product_changes_json"):
try:
product_changes = json.loads(row["product_changes_json"])
except (json.JSONDecodeError, TypeError):
pass
effect = {
"label": row["effect_label"] or "",
"class_name": row["effect_class"] or "",
"delivery_change": {
"old": float(row["delivery_old"]) if row["delivery_old"] is not None else 0,
"new": float(row["delivery_new"]) if row["delivery_new"] is not None else 0,
"ratio": float(row["delivery_ratio"]) if row["delivery_ratio"] is not None else None,
},
"product_changes": product_changes,
}
return {
"strategy": {
"id": row["strategy_id"],
"title": row["title"] or "",
"sub_title": row["sub_title"] or "",
"strategy_type": row["strategy_type"],
"strategy_type_name": row["strategy_type_name"] or "",
"description": row["description"],
"start_date": StrategyService._date_str(row["start_date"]),
"end_date": StrategyService._date_str(row["end_date"]),
"push_flag": row["push_flag"],
"status": row["status"] or "",
"merchant_id": row["merchant_id"],
"merchant_name": row["merchant_name"] or "",
"created_by": row["receiver"],
},
"store": {
"province": row["province"],
"city": row["city"],
"operation_mode": row["operation_mode"],
},
"baodi_type": row["baodi_type"],
"monitor_type": row["monitor_type"],
"periods": {"T_minus_1": None, "T": None, "T_plus_1": None},
"base_metrics": base_metrics,
"exec_metrics": exec_metrics,
"track_metrics": track_metrics,
"effect": effect,
"conclusion": row["conclusion"] or "暂无分析结论",
}
# ──────────── 兼容旧接口(实时计算,保留备用) ────────────
@staticmethod
def get_strategy_list(
keyword: Optional[str] = None,
province: Optional[str] = None,
baodi_type: Optional[str] = None,
monitor_type: Optional[str] = None,
status: Optional[str] = None,
operation_mode: Optional[str] = None,
effect: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
page: int = 1,
page_size: int = 8,
) -> Dict:
"""默认走结果表查询"""
return StrategyService.get_strategy_list_from_results(
keyword=keyword, province=province, baodi_type=baodi_type,
monitor_type=monitor_type, status=status,
operation_mode=operation_mode, effect=effect,
start_date=start_date, end_date=end_date,
page=page, page_size=page_size,
)
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a> <a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item active" href="./analysis">问界生态系数分析</a> <a class="nav-item active" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
<a class="nav-item active" href="./dw">DWS/DWM/DWA 任务</a> <a class="nav-item active" 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" href="./strategy">策略效果盯防</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
<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 active" href="./harmony">鸿蒙生态分析</a> <a class="nav-item active" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
<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" href="./strategy">策略效果盯防</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
...@@ -45,10 +46,10 @@ ...@@ -45,10 +46,10 @@
<h3>问界生态系数分析</h3> <h3>问界生态系数分析</h3>
<p>上传门店列表与主机厂数据,自动查询产值并计算生态系数</p> <p>上传门店列表与主机厂数据,自动查询产值并计算生态系数</p>
</a> </a>
<a class="nav-card" href="./harmony"> <a class="nav-card" href="./strategy">
<div class="nav-card-icon">&#127758;</div> <div class="nav-card-icon">&#128064;</div>
<h3>鸿蒙生态分析</h3> <h3>策略效果盯防</h3>
<p>上传鸿蒙门店配置与产值表,计算渗透率达标系数与赔付金额</p> <p>追踪策略执行前后门店指标变化,评估策略效果并生成分析结论</p>
</a> </a>
</div> </div>
</section> </section>
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
<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" href="./strategy">策略效果盯防</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>策略效果盯防 - 问界门店运营数据分析平台</title>
<link rel="stylesheet" href="./static/css/style.css">
<style>
.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-icon { width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; }
.stat-icon.blue { background: #e6f7ff; color: #1890ff; }
.stat-icon.purple { background: #f3e8ff; color: #722ed1; }
.stat-icon.green { background: #f6ffed; color: #52c41a; }
.stat-icon.red { background: #fff2f0; color: #f5222d; }
.stat-icon.gray { background: #f5f5f5; color: #666; }
.stat-value { font-size: 24px; font-weight: 700; color: #333; }
.stat-label { font-size: 12px; color: #999; margin-top: 2px; }
.stat-unit { font-size: 12px; color: #999; margin-left: 2px; }
.filter-bar { background: #fff; border-radius: 8px; padding: 14px 16px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.filter-bar input, .filter-bar select { padding: 6px 10px; border: 1px solid #d9d9d9; border-radius: 4px; font-size: 13px; min-width: 120px; }
.filter-bar .date-range { display: flex; align-items: center; gap: 6px; }
.filter-bar button { padding: 6px 16px; background: #1890ff; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; }
.filter-bar button.reset { background: #f5f5f5; color: #666; border: 1px solid #d9d9d9; }
.strategy-table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); font-size: 13px; }
.strategy-table th { background: #fafafa; color: #666; font-weight: 600; padding: 12px 10px; text-align: left; border-bottom: 1px solid #f0f0f0; white-space: nowrap; }
.strategy-table td { padding: 14px 10px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
.strategy-table tr:hover { background: #fafafa; }
.strategy-table .center { text-align: center; }
.strategy-table .right { text-align: right; }
.store-info { display: flex; flex-direction: column; gap: 4px; }
.store-name { font-weight: 600; color: #333; font-size: 14px; }
.store-meta { font-size: 12px; color: #999; }
.store-tag { display: inline-block; padding: 2px 6px; border-radius: 4px; font-size: 11px; margin-right: 4px; }
.store-tag.direct { background: #e6f7ff; color: #1890ff; }
.store-tag.franchise { background: #fff7e6; color: #fa8c16; }
.baodi-tag { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 12px; }
.baodi-tag.delivery { background: #e6f7ff; color: #1890ff; border: 1px solid #91d5ff; }
.baodi-tag.touch { background: #f6ffed; color: #52c41a; border: 1px solid #b7eb8f; }
.monitor-info { display: flex; flex-direction: column; gap: 4px; }
.monitor-title { font-weight: 600; color: #333; }
.monitor-tags { display: flex; gap: 4px; flex-wrap: wrap; }
.monitor-tag { display: inline-block; padding: 2px 6px; border-radius: 4px; font-size: 11px; }
.monitor-tag.warning { background: #fff2f0; color: #f5222d; border: 1px solid #ffccc7; }
.monitor-tag.alert { background: #fff7e6; color: #fa8c16; border: 1px solid #ffd591; }
.monitor-tag.new { background: #e6f7ff; color: #1890ff; border: 1px solid #91d5ff; }
.monitor-receiver { font-size: 12px; color: #666; }
.status-tag { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 12px; font-size: 12px; }
.status-tag.monitoring { background: #f3e8ff; color: #722ed1; }
.status-tag.monitoring::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: #722ed1; }
.status-tag.ended { background: #f5f5f5; color: #999; }
.status-tag.ended::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: #bfbfbf; }
.change-cell { display: flex; flex-direction: column; gap: 2px; }
.change-ratio { font-weight: 600; font-size: 13px; }
.change-ratio.up { color: #52c41a; }
.change-ratio.down { color: #f5222d; }
.change-ratio.flat { color: #999; }
.change-detail { font-size: 11px; color: #999; }
.effect-tag { display: inline-block; padding: 5px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; }
.effect-tag.up-strong { background: #f6ffed; color: #52c41a; }
.effect-tag.up { background: #e6f7ff; color: #1890ff; }
.effect-tag.flat { background: #f5f5f5; color: #666; }
.effect-tag.down { background: #fff7e6; color: #fa8c16; }
.effect-tag.down-strong { background: #fff2f0; color: #f5222d; }
.btn-detail { padding: 5px 12px; border: 1px solid #d9d9d9; background: #fff; border-radius: 4px; cursor: pointer; font-size: 12px; color: #666; }
.btn-detail:hover { color: #1890ff; border-color: #1890ff; }
.pagination { display: flex; justify-content: flex-end; align-items: center; gap: 8px; margin-top: 16px; }
.pagination button { padding: 5px 12px; border: 1px solid #d9d9d9; background: #fff; border-radius: 4px; cursor: pointer; font-size: 12px; }
.pagination button:hover:not(:disabled) { color: #1890ff; border-color: #1890ff; }
.pagination button:disabled { color: #ccc; cursor: not-allowed; }
.pagination .active { background: #1890ff; color: #fff; border-color: #1890ff; }
.pagination-info { font-size: 13px; color: #666; }
.loading-mask { text-align: center; padding: 40px; color: #999; font-size: 13px; }
.empty-tip { text-align: center; padding: 40px; color: #999; }
/* 详情弹窗 */
.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-content { background: #fff; margin: 60px auto; padding: 24px; border-radius: 8px; width: 90%; max-width: 800px; position: relative; }
.modal-close { position: absolute; right: 16px; top: 12px; font-size: 24px; cursor: pointer; color: #999; }
.modal-title { font-size: 18px; font-weight: 600; margin-bottom: 16px; padding-right: 30px; }
.metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 16px 0; }
.metric-card { background: #f8f9fa; padding: 12px; border-radius: 6px; }
.metric-label { font-size: 12px; color: #666; margin-bottom: 4px; }
.metric-value { font-size: 18px; font-weight: 700; color: #333; }
.conclusion-box { background: #f6ffed; border: 1px solid #b7eb8f; border-radius: 6px; padding: 14px; margin-top: 16px; line-height: 1.8; white-space: pre-wrap; }
</style>
</head>
<body>
<header>
<div class="logo">问界运营分析平台</div>
<nav class="nav-links">
<a class="nav-item" href="./">首页</a>
<a class="nav-item" href="./ods">ODS 同步任务</a>
<a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
<a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防</a>
</nav>
<div class="user-info" id="user-info">管理员</div>
</header>
<main>
<section id="content-area">
<div class="card">
<h2 id="content-title">策略效果盯防</h2>
<!-- 统计卡片 -->
<div class="strategy-stats" id="strategy-stats">
<div class="stat-card">
<div class="stat-icon blue">&#128065;</div>
<div>
<div><span class="stat-value" id="stat-total">0</span><span class="stat-unit">条</span></div>
<div class="stat-label">盯防总数</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon purple">&#9679;</div>
<div>
<div><span class="stat-value" id="stat-monitoring">0</span><span class="stat-unit">条</span></div>
<div class="stat-label">盯防中</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon green">&#8599;</div>
<div>
<div><span class="stat-value" id="stat-up">0</span><span class="stat-unit">条</span></div>
<div class="stat-label">效果上升</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon red">&#8600;</div>
<div>
<div><span class="stat-value" id="stat-down">0</span><span class="stat-unit">条</span></div>
<div class="stat-label">效果下降</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon gray">&#10004;</div>
<div>
<div><span class="stat-value" id="stat-ended">0</span><span class="stat-unit">条</span></div>
<div class="stat-label">已结束</div>
</div>
</div>
</div>
<!-- 筛选栏 -->
<div class="filter-bar">
<input type="text" id="filter-keyword" placeholder="搜索门店名称">
<select id="filter-province"><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-status"><option value="">盯防状态</option></select>
<select id="filter-mode"><option value="">直营/加盟</option><option value="直营">直营</option><option value="加盟">加盟</option></select>
<select id="filter-effect"><option value="">效果趋势</option><option value="显著提升">显著提升</option><option value="有所提升">有所提升</option><option value="基本持平">基本持平</option><option value="效果下降">效果下降</option></select>
<div class="date-range">
<input type="date" id="filter-start">
<span>~</span>
<input type="date" id="filter-end">
</div>
<button id="btn-search">查询</button>
<button class="reset" id="btn-reset">重置筛选</button>
<span class="pagination-info" id="filter-result-info"></span>
</div>
<!-- 表格 -->
<div id="strategy-table-wrapper">
<div class="loading-mask">正在加载策略盯防数据...</div>
</div>
<!-- 分页 -->
<div class="pagination" id="pagination"></div>
</div>
</section>
</main>
<!-- 详情弹窗 -->
<div id="detail-modal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeModal()">&times;</span>
<div class="modal-title" id="modal-title">策略详情</div>
<div id="modal-body"></div>
</div>
</div>
<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';})();
let currentPage = 1;
let currentFilters = {};
function formatRatio(val) {
if (val === null || val === undefined) return '-';
const arrow = val > 0 ? '↑' : (val < 0 ? '↓' : '→');
return arrow + ' ' + Math.abs(val).toFixed(1) + '%';
}
function getChangeClass(val) {
if (val === null || val === undefined) return 'flat';
return val > 0 ? 'up' : (val < 0 ? 'down' : 'flat');
}
function renderStats(stats) {
document.getElementById('stat-total').textContent = stats.total || 0;
document.getElementById('stat-monitoring').textContent = stats.monitoring || 0;
document.getElementById('stat-up').textContent = stats.up || 0;
document.getElementById('stat-down').textContent = stats.down || 0;
document.getElementById('stat-ended').textContent = stats.ended || 0;
}
function renderTable(records) {
if (!records || records.length === 0) {
document.getElementById('strategy-table-wrapper').innerHTML = '<div class="empty-tip">暂无策略盯防记录</div>';
return;
}
const html = ['<table class="strategy-table"><thead><tr>',
'<th style="width:40px;text-align:center">#</th>',
'<th>门店信息</th>',
'<th style="width:80px;text-align:center">兜底类型</th>',
'<th>区域</th>',
'<th>盯防信息</th>',
'<th>盯防周期</th>',
'<th style="text-align:center">状态</th>',
'<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>',
'</tr></thead><tbody>'];
records.forEach((row, idx) => {
const opMode = row.operation_mode || '';
const modeTag = opMode.includes('直营') ? '<span class="store-tag direct">直营</span>' : '<span class="store-tag franchise">加盟</span>';
const monitorClass = row.monitor_type === '业绩下滑盯防' ? 'warning' : (row.monitor_type === '预警盯防' ? 'alert' : 'new');
const delivery = row.delivery_change || {};
const deliveryRatio = delivery.ratio;
const deliveryDetail = (delivery.old !== null && delivery.new !== null) ? (delivery.old + '→' + delivery.new) : '-';
const products = row.product_changes || [];
const pMap = {};
products.forEach(p => { pMap[p.key] = p; });
const ew = pMap['extended_warranty'] || {};
const ax = pMap['ax_package'] || {};
const bt = pMap['battery_extended'] || {};
html.push('<tr>',
'<td class="center">' + (idx + 1) + '</td>',
'<td><div class="store-info"><div class="store-name">' + escapeHtml(row.merchant_name || '-') + '</div><div class="store-meta">' + modeTag + ' 运营:' + escapeHtml(row.created_by || '-') + '</div></div></td>',
'<td class="center"><span class="baodi-tag ' + (row.baodi_type === '触客' ? 'touch' : 'delivery') + '">' + (row.baodi_type || '-') + '</span></td>',
'<td>' + escapeHtml(row.province || '-') + '</td>',
'<td><div class="monitor-info"><div class="monitor-title">' + escapeHtml(row.title || '-') + '</div><div class="monitor-tags"><span class="monitor-tag ' + monitorClass + '">' + escapeHtml(row.monitor_type || '-') + '</span></div><div class="monitor-receiver">接收人:' + escapeHtml(row.receiver || '-') + '</div></div></td>',
'<td>' + escapeHtml(row.start_date || '') + ' ~ ' + escapeHtml(row.end_date || '') + '</td>',
'<td class="center"><span class="status-tag ' + (row.status === '盯防中' ? 'monitoring' : 'ended') + '">' + escapeHtml(row.status || '-') + '</span></td>',
'<td class="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(deliveryRatio) + '">' + formatRatio(deliveryRatio) + '</span><span class="change-detail">' + deliveryDetail + '</span></div></td>',
'<td class="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(ew.pp_change) + '">' + (ew.pp_change !== null && ew.pp_change !== undefined ? (ew.pp_change > 0 ? '↑' : (ew.pp_change < 0 ? '↓' : '→')) + ' ' + Math.abs(ew.pp_change).toFixed(1) + 'pp' : '-') + '</span><span class="change-detail">' + (ew.old_rate !== null ? ew.old_rate.toFixed(1) + '%→' + ew.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 !== undefined ? (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 !== undefined ? (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"><button class="btn-detail" onclick="showDetail(' + row.id + ')">详情</button></td>',
'</tr>');
});
html.push('</tbody></table>');
document.getElementById('strategy-table-wrapper').innerHTML = html.join('');
}
function escapeHtml(s) {
if (s === null || s === undefined) return '';
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function renderPagination(data) {
const totalPages = data.total_pages || 1;
const page = data.page || 1;
const html = [];
html.push('<button ' + (page <= 1 ? 'disabled' : '') + ' onclick="goPage(' + (page - 1) + ')">上一页</button>');
for (let i = 1; i <= totalPages; i++) {
if (i === 1 || i === totalPages || (i >= page - 2 && i <= page + 2)) {
html.push('<button class="' + (i === page ? 'active' : '') + '" onclick="goPage(' + i + ')">' + i + '</button>');
} else if (i === page - 3 || i === page + 3) {
html.push('<span>...</span>');
}
}
html.push('<button ' + (page >= totalPages ? 'disabled' : '') + ' onclick="goPage(' + (page + 1) + ')">下一页</button>');
html.push('<span class="pagination-info">显示 ' + ((page - 1) * data.page_size + 1) + ' 到 ' + Math.min(page * data.page_size, data.total) + ' 条,共 ' + data.total + ' 条</span>');
document.getElementById('pagination').innerHTML = html.join('');
}
async function loadData() {
document.getElementById('strategy-table-wrapper').innerHTML = '<div class="loading-mask">正在加载策略盯防数据...</div>';
try {
const params = new URLSearchParams();
if (currentFilters.keyword) params.append('keyword', currentFilters.keyword);
if (currentFilters.province) params.append('province', currentFilters.province);
if (currentFilters.baodi_type) params.append('baodi_type', currentFilters.baodi_type);
if (currentFilters.monitor_type) params.append('monitor_type', currentFilters.monitor_type);
if (currentFilters.status) params.append('status', currentFilters.status);
if (currentFilters.operation_mode) params.append('operation_mode', currentFilters.operation_mode);
if (currentFilters.effect) params.append('effect', currentFilters.effect);
if (currentFilters.start_date) params.append('start_date', currentFilters.start_date);
if (currentFilters.end_date) params.append('end_date', currentFilters.end_date);
params.append('page', currentPage);
params.append('page_size', '8');
const res = await fetch(window.API_BASE + '/strategy/list?' + params.toString());
const json = await res.json();
if (json.status !== 'success') throw new Error(json.detail || '加载失败');
const data = json.data;
renderStats(data);
renderTable(data.records);
renderPagination(data);
} catch (err) {
console.error('加载策略盯防列表失败:', err);
document.getElementById('strategy-table-wrapper').innerHTML = '<div class="empty-tip">加载失败: ' + escapeHtml(err.message) + '</div>';
}
}
function collectFilters() {
currentFilters = {
keyword: document.getElementById('filter-keyword').value.trim(),
province: document.getElementById('filter-province').value,
baodi_type: document.getElementById('filter-baodi').value,
monitor_type: document.getElementById('filter-monitor').value,
status: document.getElementById('filter-status').value,
operation_mode: document.getElementById('filter-mode').value,
effect: document.getElementById('filter-effect').value,
start_date: document.getElementById('filter-start').value,
end_date: document.getElementById('filter-end').value,
};
currentPage = 1;
loadData();
}
function resetFilters() {
document.getElementById('filter-keyword').value = '';
document.getElementById('filter-province').value = '';
document.getElementById('filter-baodi').value = '';
document.getElementById('filter-monitor').value = '';
document.getElementById('filter-status').value = '';
document.getElementById('filter-mode').value = '';
document.getElementById('filter-effect').value = '';
document.getElementById('filter-start').value = '';
document.getElementById('filter-end').value = '';
currentFilters = {};
currentPage = 1;
loadData();
}
window.goPage = function(page) {
currentPage = page;
loadData();
};
async function loadOptions() {
try {
const res = await fetch(window.API_BASE + '/strategy/options');
const json = await res.json();
if (json.status !== 'success') return;
const opts = json.data;
const provinceSel = document.getElementById('filter-province');
opts.provinces.forEach(p => {
const opt = document.createElement('option');
opt.value = p;
opt.textContent = p;
provinceSel.appendChild(opt);
});
const monitorSel = document.getElementById('filter-monitor');
opts.monitor_types.forEach(t => {
const opt = document.createElement('option');
opt.value = t;
opt.textContent = t;
monitorSel.appendChild(opt);
});
const statusSel = document.getElementById('filter-status');
opts.statuses.forEach(s => {
const opt = document.createElement('option');
opt.value = s;
opt.textContent = s;
statusSel.appendChild(opt);
});
} catch (err) {
console.error('加载筛选项失败:', err);
}
}
window.showDetail = async function(id) {
try {
const res = await fetch(window.API_BASE + '/strategy/' + id);
const json = await res.json();
if (json.status !== 'success') throw new Error(json.detail || '加载失败');
const data = json.data;
const strategy = data.strategy || {};
const base = data.base_metrics || {};
const exec = data.exec_metrics || {};
const track = data.track_metrics || {};
const title = strategy.title || '策略详情';
document.getElementById('modal-title').textContent = title;
const bodyHtml = [
'<div style="margin-bottom:12px;color:#666;font-size:13px;">',
'策略类型:' + escapeHtml(strategy.strategy_type_name || '-') + ' | ',
'盯防类型:' + escapeHtml(data.monitor_type || '-') + ' | ',
'状态:' + escapeHtml(strategy.status || '-') + ' | ',
'周期:' + escapeHtml(strategy.start_date || '') + ' ~ ' + escapeHtml(strategy.end_date || ''),
'</div>',
'<div style="margin-bottom:12px;color:#666;font-size:13px;">',
'门店:' + escapeHtml(strategy.merchant_name || '-') + '(ID: ' + strategy.merchant_id + ')',
'</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) {
alert('加载详情失败: ' + err.message);
}
};
window.closeModal = function() {
document.getElementById('detail-modal').style.display = 'none';
};
window.onclick = function(event) {
const modal = document.getElementById('detail-modal');
if (event.target === modal) {
modal.style.display = 'none';
}
};
document.addEventListener('DOMContentLoaded', () => {
loadOptions();
loadData();
document.getElementById('btn-search').addEventListener('click', collectFilters);
document.getElementById('btn-reset').addEventListener('click', resetFilters);
});
</script>
<script src="./static/js/auth.js"></script>
</body>
</html>
No preview for this file type
No preview for this file type
...@@ -114,6 +114,7 @@ PAGE_ROUTES = { ...@@ -114,6 +114,7 @@ PAGE_ROUTES = {
"/dw": "dw.html", "/dw": "dw.html",
"/analysis": "analysis.html", "/analysis": "analysis.html",
"/harmony": "harmony.html", "/harmony": "harmony.html",
"/strategy": "strategy.html",
} }
......
-- 策略效果分析结果表
CREATE TABLE IF NOT EXISTS strategy_analysis_result (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
strategy_id INT NOT NULL COMMENT '策略ID',
title VARCHAR(500) COMMENT '策略标题',
sub_title VARCHAR(500) COMMENT '策略副标题',
strategy_type INT COMMENT '策略类型编码',
strategy_type_name VARCHAR(100) COMMENT '策略类型名称',
merchant_id INT COMMENT '门店ID',
merchant_name VARCHAR(200) COMMENT '门店名称',
merchant_code VARCHAR(100) COMMENT '门店编码',
province VARCHAR(100) COMMENT '省份',
city VARCHAR(100) COMMENT '城市',
operation_mode VARCHAR(50) COMMENT '运营模式: 直营/加盟',
baodi_type VARCHAR(20) COMMENT '兜底类型: 交付/触客',
monitor_type VARCHAR(50) COMMENT '盯防类型: 业绩下滑盯防/预警盯防/新店盯防',
status VARCHAR(20) COMMENT '盯防状态',
push_flag INT COMMENT '推送状态编码',
start_date DATE COMMENT '策略开始日期',
end_date DATE COMMENT '策略结束日期',
receiver VARCHAR(100) COMMENT '接收人/创建人',
description TEXT COMMENT '策略描述',
-- 效果
effect_label VARCHAR(20) COMMENT '整体效果: 显著提升/有所提升/基本持平/效果下降',
effect_class VARCHAR(20) COMMENT '效果CSS类名',
effect_score INT COMMENT '效果评分 0-100',
-- 交付变化
delivery_old DECIMAL(14,2) COMMENT 'T-1 期交付数',
delivery_new DECIMAL(14,2) COMMENT 'T 期交付数',
delivery_ratio DECIMAL(10,2) COMMENT '交付数变化率(%)',
-- 整车延保
ew_old_rate DECIMAL(10,2) COMMENT 'T-1 延保渗透率',
ew_new_rate DECIMAL(10,2) COMMENT 'T 延保渗透率',
ew_pp_change DECIMAL(10,2) COMMENT '延保渗透率百分点变化',
-- 安心包
ax_old_rate DECIMAL(10,2) COMMENT 'T-1 安心包渗透率',
ax_new_rate DECIMAL(10,2) COMMENT 'T 安心包渗透率',
ax_pp_change DECIMAL(10,2) COMMENT '安心包渗透率百分点变化',
-- 电池延保
battery_old_rate DECIMAL(10,2) COMMENT 'T-1 电池延保渗透率',
battery_new_rate DECIMAL(10,2) COMMENT 'T 电池延保渗透率',
battery_pp_change DECIMAL(10,2) COMMENT '电池延保渗透率百分点变化',
-- JSON 详情
base_metrics_json JSON COMMENT 'T-1 基线期指标',
exec_metrics_json JSON COMMENT 'T 执行期指标',
track_metrics_json JSON COMMENT 'T+1 跟踪期指标',
product_changes_json JSON COMMENT '各产品变化详情列表',
conclusion TEXT COMMENT '分析结论',
-- 元数据
is_valid TINYINT(1) DEFAULT 1 COMMENT '数据是否有效(是否有足够数据)',
error_msg VARCHAR(500) COMMENT '分析错误信息',
analysis_time DATETIME COMMENT '分析完成时间',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_strategy_id (strategy_id),
INDEX idx_merchant_id (merchant_id),
INDEX idx_province (province),
INDEX idx_baodi_type (baodi_type),
INDEX idx_monitor_type (monitor_type),
INDEX idx_status (status),
INDEX idx_effect_label (effect_label),
INDEX idx_operation_mode (operation_mode),
INDEX idx_start_date (start_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='策略效果分析结果表';
import pymysql
from app.core.config import settings
conn = pymysql.connect(
host=settings.DB_HOST, port=settings.DB_PORT, user=settings.DB_USER,
password=settings.DB_PASSWORD, database=settings.DB_NAME, charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
)
with conn.cursor() as cur:
cur.execute("SELECT COUNT(*) as c FROM ods_strategy_info WHERE deleted_flag='N'")
strategy_count = cur.fetchone()['c']
cur.execute("SELECT COUNT(*) as c FROM ods_store_config WHERE deleted_flag='N'")
store_count = cur.fetchone()['c']
cur.execute("SELECT id, title, merchant_id, start_date, end_date, push_flag FROM ods_strategy_info WHERE deleted_flag='N' ORDER BY created_date DESC LIMIT 3")
rows = cur.fetchall()
print(f"strategy_count: {strategy_count}")
print(f"store_count: {store_count}")
for r in rows:
print(r)
conn.close()
# -*- coding: utf-8 -*-
"""创建鸿蒙输出模板 输出模板-鸿蒙-模板002.xlsx(38列,参考会议标注源文件表头)"""
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
wb = Workbook()
ws = wb.active
ws.title = '模板'
# ---- 样式 ----
header_fill = PatternFill('solid', fgColor='FF0070C0')
header_font = Font(name='微软雅黑', bold=True, color='FF000000', size=8)
data_font = Font(name='微软雅黑', size=10)
thin_border = Border(left=Side('thin'), right=Side('thin'), top=Side('thin'), bottom=Side('thin'))
center_align = Alignment(horizontal='center', vertical='center', wrap_text=True)
def hc(r, c, v):
cell = ws.cell(row=r, column=c, value=v)
cell.font = header_font; cell.fill = header_fill; cell.alignment = center_align; cell.border = thin_border
return cell
# ---- Row 1: 分组表头 ----
r1 = {
1: '门店', 2: '品牌', 3: '兜底指标', 4: '区域(省)', 5: '直营与否',
6: '区域运营', 7: '飞行督导', 8: '线上运营', 9: '特殊情况',
10: '主机厂交付数\n(标红为产值表总交付数)',
12: '产值表交付数', 13: '主机厂跟产值表差距\n(主机厂-产值表交付数)',
14: '产值表数据',
23: '是否触发兜底', 24: '门店等级', 25: '兜底类型',
26: '当前转化率', 29: '需达标转化率', 32: '需达标订单差额',
35: '赔付金额', 38: '总赔付金额',
}
for c, v in r1.items():
hc(1, c, v)
# ---- Row 2: 子表头 ----
r2 = {
11: '主机厂',
14: '门店触客数', 15: '触客率', 16: '整车延保成交订单数', 17: '整车延保渗透率',
18: '触客成交率', 19: '安心包', 20: '安心包渗透率', 21: '电池', 22: '电池渗透率',
26: '整车延保', 27: '安心包', 28: '电池',
29: '整车延保', 30: '安心包', 31: '电池',
32: '整车延保', 33: '安心包', 34: '电池',
35: '整车延保', 36: '安心包', 37: '电池',
}
for c, v in r2.items():
hc(2, c, v)
# ---- 合并单元格 ----
vert = [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 23, 24, 25, 38] # Row1-Row2 跨行
for c in vert:
ws.merge_cells(f'{get_column_letter(c)}1:{get_column_letter(c)}2')
horiz = [('J', 'K'), ('N', 'V'), ('Z', 'AB'), ('AC', 'AE'), ('AF', 'AH'), ('AI', 'AK')] # Row1 跨列
for s, e in horiz:
ws.merge_cells(f'{s}1:{e}1')
# ---- Row 3: 示例数据+公式 ----
sample = {
1: '示例门店', 2: '鸿蒙智行', 3: '兜底:触客渗透率50%', 4: '广东省', 5: '直营',
6: '区域运营', 7: '飞行督导', 8: '线上运营', 9: '',
10: 10, 11: 10, 12: 10, 14: 8, 16: 5, 19: 2, 21: 1,
24: '', 25: '触客', 29: 0.5, 30: 0, 31: 0, 35: 400, 36: 0, 37: 0,
}
formulas = {
13: '=J3-L3',
15: '=IF(L3>0,N3/L3,0)',
17: '=IF(L3>0,P3/L3,0)',
18: '=IF(N3>0,P3/N3,0)',
20: '=IF(L3>0,S3/L3,0)',
22: '=IF(L3>0,U3/L3,0)',
23: '=IF(OR(Z3<AC3,AA3<AD3,AB3<AE3),"是","否")',
26: '=IF($N3>0,P3/$N3,IF($L3>0,P3/$L3,0))',
27: '=IF($N3>0,S3/$N3,IF($L3>0,S3/$L3,0))',
28: '=IF($N3>0,U3/$N3,IF($L3>0,U3/$L3,0))',
32: '=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AC3-P3,0))',
33: '=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AD3-S3,0))',
34: '=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AE3-U3,0))',
38: '=IF(E3="直营",AI3+AJ3+AK3,"/")',
}
pct_cols = {15, 17, 18, 20, 22, 26, 27, 28, 29, 30, 31}
for c, v in sample.items():
cell = ws.cell(row=3, column=c, value=v)
cell.font = data_font; cell.alignment = center_align; cell.border = thin_border
if isinstance(v, (int, float)):
cell.number_format = '0.00%' if c in pct_cols else '0'
for c, f in formulas.items():
cell = ws.cell(row=3, column=c, value=f)
cell.font = data_font; cell.alignment = center_align; cell.border = thin_border
cell.number_format = '0.00%' if c in pct_cols else ('#,##0' if c == 38 else '0')
# ---- 列宽 ----
widths = {
1:35, 2:18, 3:40, 4:14, 5:10, 6:12, 7:12, 8:14, 9:12, 10:14, 11:10,
12:14, 13:16, 14:14, 15:10, 16:18, 17:14, 18:12, 19:10, 20:14, 21:10,
22:14, 23:14, 24:12, 25:10, 26:16, 27:16, 28:16, 29:14, 30:14, 31:14,
32:16, 33:16, 34:16, 35:14, 36:14, 37:14, 38:14,
}
for c, w in widths.items():
ws.column_dimensions[get_column_letter(c)].width = w
for r in range(1, 4):
ws.row_dimensions[r].height = 18
ws.freeze_panes = 'A3'
out = 'app/templates/xlsx/输出模板-鸿蒙-模板002.xlsx'
wb.save(out)
print(f'Template created: {out}')
print(f'Rows: {ws.max_row}, Cols: {ws.max_column}')
print(f'Merged cells: {[str(m) for m in ws.merged_cells.ranges]}')
...@@ -40,11 +40,11 @@ for f in glob.glob('app/templates/xlsx/主机厂数据-鸿蒙-模板[0-9][0-9][0 ...@@ -40,11 +40,11 @@ for f in glob.glob('app/templates/xlsx/主机厂数据-鸿蒙-模板[0-9][0-9][0
FACTORY_OUT = f'app/templates/xlsx/主机厂数据-鸿蒙-模板{max_no2 + 1:03d}.xlsx' FACTORY_OUT = f'app/templates/xlsx/主机厂数据-鸿蒙-模板{max_no2 + 1:03d}.xlsx'
# ── 样式 ── # ── 样式 ──
header_fill = PatternFill('solid', fgColor='4472C4') header_fill = PatternFill('solid', fgColor='BDD7EE') # 浅蓝
header_font = Font(name='微软雅黑', bold=True, color='FFFFFF', size=10) header_font = Font(name='微软雅黑', bold=True, color='000000', size=10)
sub_fill = PatternFill('solid', fgColor='D6E4F0') sub_fill = PatternFill('solid', fgColor='BDD7EE')
sub_font = Font(name='微软雅黑', bold=True, size=10) sub_font = Font(name='微软雅黑', bold=True, color='000000', size=10)
data_font = Font(name='微软雅黑', size=10) data_font = Font(name='微软雅黑', size=10, color='000000')
thin_border = Border( thin_border = Border(
left=Side(style='thin'), right=Side(style='thin'), left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin') top=Side(style='thin'), bottom=Side(style='thin')
...@@ -151,7 +151,7 @@ owb = Workbook() ...@@ -151,7 +151,7 @@ owb = Workbook()
ows = owb.active ows = owb.active
ows.title = '门店兜底配置' ows.title = '门店兜底配置'
# Row 1: 主表头 # Row 1: 主表头(跨列居中:相同title填相邻格)
write_header_cell(ows, 1, 1, '门店') write_header_cell(ows, 1, 1, '门店')
write_header_cell(ows, 1, 2, '品牌') write_header_cell(ows, 1, 2, '品牌')
write_header_cell(ows, 1, 3, '兜底指标') write_header_cell(ows, 1, 3, '兜底指标')
...@@ -162,9 +162,11 @@ write_header_cell(ows, 1, 7, '飞行督导') ...@@ -162,9 +162,11 @@ 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, '需达标转化率')
ows.merge_cells('J1:L1') write_header_cell(ows, 1, 11, '需达标转化率')
write_header_cell(ows, 1, 12, '需达标转化率')
write_header_cell(ows, 1, 13, '预计赔付金额') write_header_cell(ows, 1, 13, '预计赔付金额')
ows.merge_cells('M1:O1') write_header_cell(ows, 1, 14, '预计赔付金额')
write_header_cell(ows, 1, 15, '预计赔付金额')
# Row 2: 子表头 # Row 2: 子表头
write_sub_cell(ows, 2, 1, '') write_sub_cell(ows, 2, 1, '')
...@@ -183,10 +185,6 @@ write_sub_cell(ows, 2, 13, '整车') ...@@ -183,10 +185,6 @@ 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, '电池')
# Merge A-I header rows
for col_letter in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']:
ows.merge_cells(f'{col_letter}1:{col_letter}2')
# 列宽 # 列宽
ows.column_dimensions['A'].width = 35 ows.column_dimensions['A'].width = 35
ows.column_dimensions['B'].width = 22 ows.column_dimensions['B'].width = 22
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!