Commit 95263477 by 江名洋

feat(strategy): 添加策略渗透率分析功能

1 parent fd234e02
...@@ -583,6 +583,21 @@ async def strategy_detail(strategy_id: int): ...@@ -583,6 +583,21 @@ async def strategy_detail(strategy_id: int):
raise HTTPException(status_code=500, detail=f"查询策略详情失败: {str(e)}") raise HTTPException(status_code=500, detail=f"查询策略详情失败: {str(e)}")
@router.get("/strategy/{strategy_id}/penetration")
async def strategy_penetration_analysis(strategy_id: int):
"""获取策略渗透率分析数据(按天/阶段、员工、品牌、产品维度拆解 + LLM总结)"""
try:
data = StrategyService.get_penetration_analysis(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"Penetration analysis failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"渗透率分析失败: {str(e)}")
# ==================== 策略分析任务控制接口 ==================== # ==================== 策略分析任务控制接口 ====================
@router.post("/strategy/analyze") @router.post("/strategy/analyze")
......
...@@ -13,6 +13,7 @@ from datetime import datetime, timedelta ...@@ -13,6 +13,7 @@ from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any from typing import List, Dict, Optional, Any
import pymysql import pymysql
import httpx
import pymysql.cursors import pymysql.cursors
from app.core.config import settings from app.core.config import settings
...@@ -273,6 +274,274 @@ class StrategyService: ...@@ -273,6 +274,274 @@ class StrategyService:
conn.close() conn.close()
@staticmethod @staticmethod
def _get_daily_penetration(merchant_id: int, start_date: str, end_date: str, periods: Dict) -> List[Dict]:
"""按天获取渗透率数据,标记盯防阶段"""
if not start_date or not end_date or start_date > end_date:
return []
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute("""
SELECT
report_date,
SUM(IFNULL(delivery_count, 0)) AS delivery,
SUM(IFNULL(sum_extended_warranty, 0)) AS ew_orders,
SUM(IFNULL(sum_ax_package, 0)) AS ax_orders,
SUM(IFNULL(sum_battery_extended, 0)) AS battery_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
""", (merchant_id, start_date, end_date))
rows = cur.fetchall()
finally:
conn.close()
t_minus_1 = periods.get("T_minus_1")
t_plus_1 = periods.get("T_plus_1")
t_start = t_minus_1[0] if t_minus_1 else start_date
t_end = t_plus_1[1] if t_plus_1 else end_date
result = []
for r in rows:
d = r["report_date"]
if isinstance(d, str):
d_str = d
else:
d_str = d.strftime("%Y-%m-%d")
phase = "other"
if t_minus_1 and t_minus_1[0] <= d_str <= t_minus_1[1]:
phase = "T-1"
elif t_start <= d_str <= t_end:
phase = "T"
if t_plus_1 and t_plus_1[0] <= d_str <= t_plus_1[1]:
phase = "T+1"
delivery = StrategyService._safe_num(r.get("delivery", 0))
result.append({
"date": d_str,
"phase": phase,
"delivery": delivery,
"ew_rate": round(StrategyService._safe_num(r.get("ew_orders", 0)) / delivery * 100, 1) if delivery else 0,
"ax_rate": round(StrategyService._safe_num(r.get("ax_orders", 0)) / delivery * 100, 1) if delivery else 0,
"battery_rate": round(StrategyService._safe_num(r.get("battery_orders", 0)) / delivery * 100, 1) if delivery else 0,
})
return result
@staticmethod
def _get_staff_penetration(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 []
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute("""
SELECT
staff_name,
SUM(IFNULL(delivery_count, 0)) AS delivery,
SUM(IFNULL(extended_warranty_count, 0)) AS ew_orders,
SUM(IFNULL(ax_package_count, 0)) AS ax_orders,
SUM(IFNULL(battery_extended_warranty_count, 0)) AS battery_orders
FROM dws_staff_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'
AND staff_name IS NOT NULL AND staff_name != ''
GROUP BY staff_name
ORDER BY delivery DESC
""", (merchant_id, start_date, end_date))
rows = cur.fetchall()
finally:
conn.close()
result = []
for r in rows:
delivery = StrategyService._safe_num(r.get("delivery", 0))
result.append({
"staff_name": r["staff_name"],
"delivery": delivery,
"ew_rate": round(StrategyService._safe_num(r.get("ew_orders", 0)) / delivery * 100, 1) if delivery else 0,
"ax_rate": round(StrategyService._safe_num(r.get("ax_orders", 0)) / delivery * 100, 1) if delivery else 0,
"battery_rate": round(StrategyService._safe_num(r.get("battery_orders", 0)) / delivery * 100, 1) if delivery else 0,
})
return result
@staticmethod
def _get_brand_penetration(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 []
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute("""
SELECT
brand_name,
SUM(IFNULL(delivery_count, 0)) AS delivery,
SUM(IFNULL(sum_extended_warranty, 0)) AS ew_orders,
SUM(IFNULL(sum_ax_package, 0)) AS ax_orders,
SUM(IFNULL(sum_battery_extended, 0)) AS battery_orders
FROM dws_merchant_daily_wide
WHERE merchant_id = %s
AND report_date BETWEEN %s AND %s
AND first_brand_id = 2365
AND scene_type = '0'
AND brand_name IS NOT NULL AND brand_name != ''
GROUP BY brand_name, brand_id
ORDER BY delivery DESC
""", (merchant_id, start_date, end_date))
rows = cur.fetchall()
finally:
conn.close()
result = []
for r in rows:
delivery = StrategyService._safe_num(r.get("delivery", 0))
result.append({
"brand_name": r["brand_name"],
"delivery": delivery,
"ew_rate": round(StrategyService._safe_num(r.get("ew_orders", 0)) / delivery * 100, 1) if delivery else 0,
"ax_rate": round(StrategyService._safe_num(r.get("ax_orders", 0)) / delivery * 100, 1) if delivery else 0,
"battery_rate": round(StrategyService._safe_num(r.get("battery_orders", 0)) / delivery * 100, 1) if delivery else 0,
})
return result
@staticmethod
def _get_product_summary(daily_data: List[Dict]) -> Dict:
"""按产品汇总渗透率"""
total_delivery = sum(d.get("delivery", 0) for d in daily_data)
if not total_delivery:
return {"delivery": 0, "ew_rate": 0, "ax_rate": 0, "battery_rate": 0}
# 加权平均
total_ew = sum(d.get("delivery", 0) * d.get("ew_rate", 0) for d in daily_data)
total_ax = sum(d.get("delivery", 0) * d.get("ax_rate", 0) for d in daily_data)
total_battery = sum(d.get("delivery", 0) * d.get("battery_rate", 0) for d in daily_data)
return {
"delivery": total_delivery,
"ew_rate": round(total_ew / total_delivery, 1),
"ax_rate": round(total_ax / total_delivery, 1),
"battery_rate": round(total_battery / total_delivery, 1),
}
@staticmethod
def _generate_penetration_summary(detail: Dict, daily: List, staff: List, brand: List, product: Dict) -> str:
"""使用 LLM 生成渗透率分析总结"""
import asyncio
summary_parts = []
# 产品整体
if product.get("delivery"):
summary_parts.append(
f"盯防周期内总交付{product['delivery']}台,"
f"整车延保渗透率{product['ew_rate']}%,"
f"安心包渗透率{product['ax_rate']}%,"
f"电池渗透率{product['battery_rate']}%。"
)
# 品牌拆解
if brand:
brand_parts = []
for b in brand[:5]:
brand_parts.append(f"{b['brand_name']}(交付{b['delivery']}台,延保{b['ew_rate']}%,安心包{b['ax_rate']}%,电池{b['battery_rate']}%)")
summary_parts.append("各品牌表现:" + ";".join(brand_parts) + "。")
# 员工 TOP3
if staff:
top3 = staff[:3]
staff_parts = []
for s in top3:
staff_parts.append(f"{s['staff_name']}(交付{s['delivery']}台,延保{s['ew_rate']}%,安心包{s['ax_rate']}%,电池{s['battery_rate']}%)")
summary_parts.append("TOP3员工:" + ";".join(staff_parts) + "。")
# 趋势
if daily:
t_minus_1 = [d for d in daily if d["phase"] == "T-1"]
t_phase = [d for d in daily if d["phase"] == "T"]
t_plus_1 = [d for d in daily if d["phase"] == "T+1"]
if t_minus_1:
avg_ew_before = sum(d["ew_rate"] for d in t_minus_1) / len(t_minus_1)
avg_ax_before = sum(d["ax_rate"] for d in t_minus_1) / len(t_minus_1)
avg_battery_before = sum(d["battery_rate"] for d in t_minus_1) / len(t_minus_1)
else:
avg_ew_before = avg_ax_before = avg_battery_before = 0
if t_phase:
avg_ew_during = sum(d["ew_rate"] for d in t_phase) / len(t_phase)
avg_ax_during = sum(d["ax_rate"] for d in t_phase) / len(t_phase)
avg_battery_during = sum(d["battery_rate"] for d in t_phase) / len(t_phase)
else:
avg_ew_during = avg_ax_during = avg_battery_during = 0
if t_plus_1:
avg_ew_after = sum(d["ew_rate"] for d in t_plus_1) / len(t_plus_1)
avg_ax_after = sum(d["ax_rate"] for d in t_plus_1) / len(t_plus_1)
avg_battery_after = sum(d["battery_rate"] for d in t_plus_1) / len(t_plus_1)
else:
avg_ew_after = avg_ax_after = avg_battery_after = 0
summary_parts.append(
f"渗透率趋势:延保 T-1:{avg_ew_before:.1f}%→T:{avg_ew_during:.1f}%"
f"{'→T+1:' + str(round(avg_ew_after,1)) + '%' if t_plus_1 else ''},"
f"安心包 T-1:{avg_ax_before:.1f}%→T:{avg_ax_during:.1f}%"
f"{'→T+1:' + str(round(avg_ax_after,1)) + '%' if t_plus_1 else ''}。"
)
raw_text = "\n".join(summary_parts)
# 尝试用 LLM 润色
if settings.LLM_QWEN_API_KEY:
try:
prompt = f"""你是汽车零售数据分析师。请基于以下数据对门店"{detail['strategy']['merchant_name']}"的盯防策略进行渗透率分析总结(200字以内,专业精炼):
{raw_text}
请从以下角度分析:
1. 整体渗透率水平评价
2. 不同品牌/产品的差异
3. 员工表现差异
4. T-1→T→T+1 的趋势变化
5. 改进建议
直接输出总结文本,不要Markdown格式。"""
async def _call():
async with httpx.AsyncClient(timeout=60.0) as client:
resp = await client.post(
f"{settings.LLM_QWEN_BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {settings.LLM_QWEN_API_KEY}",
"Content-Type": "application/json",
},
json={
"model": settings.LLM_QWEN_MODEL,
"messages": [
{"role": "system", "content": "你是一个专业的汽车零售数据分析师。"},
{"role": "user", "content": prompt},
],
"temperature": 0.3,
},
)
if resp.status_code == 200:
data = resp.json()
return data["choices"][0]["message"]["content"].strip()
return raw_text
loop = asyncio.new_event_loop()
try:
result = loop.run_until_complete(_call())
finally:
loop.close()
return result
except Exception as e:
logger.warning(f"LLM summary failed, fallback to raw: {e}")
return raw_text
@staticmethod
def _get_store_config(merchant_id: int) -> Optional[Dict]: def _get_store_config(merchant_id: int) -> Optional[Dict]:
sql = """ sql = """
SELECT merchant_id, merchant_name, merchant_code, province, city, SELECT merchant_id, merchant_name, merchant_code, province, city,
...@@ -1295,6 +1564,72 @@ class StrategyService: ...@@ -1295,6 +1564,72 @@ class StrategyService:
# ──────────── 详情 ──────────── # ──────────── 详情 ────────────
@staticmethod @staticmethod
def get_penetration_analysis(strategy_id: int) -> Optional[Dict]:
"""获取策略渗透率分析数据(按天/阶段、员工、品牌、产品维度)"""
# 先获取策略基本信息
detail = StrategyService.get_strategy_detail(strategy_id)
if not detail:
return None
merchant_id = detail["strategy"]["merchant_id"]
start_date = detail["strategy"]["start_date"]
end_date = detail["strategy"]["end_date"]
periods = detail.get("periods", {})
# 日维度查询范围:从 T-1 开始到 T+1 结束
t_minus_1 = periods.get("T_minus_1")
t_plus_1 = periods.get("T_plus_1")
daily_start = (t_minus_1[0] if t_minus_1 else start_date) if start_date and end_date else start_date
daily_end = (t_plus_1[1] if t_plus_1 else end_date) if start_date and end_date else end_date
# 1. 按天维度:每天各产品渗透率
daily_penetration = []
if merchant_id and daily_start and daily_end:
daily_penetration = StrategyService._get_daily_penetration(
merchant_id, daily_start, daily_end, periods
)
# 2. 按员工维度:各员工渗透率(盯防周期内)
staff_penetration = []
if merchant_id and start_date and end_date:
staff_penetration = StrategyService._get_staff_penetration(
merchant_id, start_date, end_date
)
# 3. 按品牌维度:各品牌渗透率(盯防周期内)
brand_penetration = []
if merchant_id and start_date and end_date:
brand_penetration = StrategyService._get_brand_penetration(
merchant_id, start_date, end_date
)
# 4. 按产品维度汇总
product_summary = StrategyService._get_product_summary(daily_penetration)
# 5. LLM 总结
llm_summary = ""
try:
llm_summary = StrategyService._generate_penetration_summary(
detail, daily_penetration, staff_penetration, brand_penetration, product_summary
)
except Exception as e:
logger.error(f"LLM penetration summary failed: {e}")
return {
"strategy": detail["strategy"],
"store": detail["store"],
"baodi_type": detail["baodi_type"],
"monitor_type": detail["monitor_type"],
"periods": periods,
"monitor_refresh_time": detail.get("monitor_refresh_time"),
"daily_penetration": daily_penetration,
"staff_penetration": staff_penetration,
"brand_penetration": brand_penetration,
"product_summary": product_summary,
"llm_summary": llm_summary,
}
@staticmethod
def get_strategy_detail(strategy_id: int) -> Optional[Dict]: def get_strategy_detail(strategy_id: int) -> Optional[Dict]:
"""获取单条策略详情(优先从结果表读,回退到原始策略表)""" """获取单条策略详情(优先从结果表读,回退到原始策略表)"""
conn = StrategyService._get_raw_conn() conn = StrategyService._get_raw_conn()
......
...@@ -290,12 +290,29 @@ ...@@ -290,12 +290,29 @@
</div> </div>
</div> </div>
<!-- 渗透率分析弹窗 -->
<div id="info-modal" class="modal">
<div class="modal-content modal-detail">
<div class="modal-header">
<div class="modal-title" id="info-modal-title">渗透率分析</div>
<div class="modal-header-actions">
<span class="modal-close" onclick="closeInfoModal()">&times;</span>
</div>
</div>
<div class="modal-body" id="info-modal-body">
<div class="loading">正在加载渗透率分析数据...</div>
</div>
</div>
</div>
<script> <script>
window.API_BASE = (function(){var p=window.location.pathname;if(p.endsWith('/'))p=p.slice(0,-1);var i=p.lastIndexOf('/');return p.substring(0,i)+'/api';})(); window.API_BASE = (function(){var p=window.location.pathname;if(p.endsWith('/'))p=p.slice(0,-1);var i=p.lastIndexOf('/');return p.substring(0,i)+'/api';})();
let currentPage = 1; let currentPage = 1;
let currentFilters = {}; let currentFilters = {};
let currentModalId = null; let currentModalId = null;
let currentInfoId = null;
function formatRatio(val) { function formatRatio(val) {
if (val === null || val === undefined) return '-'; if (val === null || val === undefined) return '-';
...@@ -753,6 +770,200 @@ ...@@ -753,6 +770,200 @@
'</div></div>'; '</div></div>';
} }
// ──────────── 渗透率分析渲染 ────────────
function renderPenetration(data) {
const s = data.strategy || {};
const store = data.store || {};
const daily = data.daily_penetration || [];
const staff = data.staff_penetration || [];
const brand = data.brand_penetration || [];
const product = data.product_summary || {};
const llm = data.llm_summary || '';
// 按阶段分组
const phaseOrder = ['T-1', 'T', 'T+1'];
const phaseLabels = { 'T-1': '盯防前 (T-1)', 'T': '盯防中 (T)', 'T+1': '盯防后 (T+1)' };
const phaseColors = { 'T-1': '#d9d9d9', 'T': '#722ed1', 'T+1': '#52c41a' };
// 每日渗透率表格
let dailyRows = '';
if (daily.length > 0) {
dailyRows = daily.map(d => {
const color = phaseColors[d.phase] || '#999';
return `<tr>
<td style="text-align:left">${d.date}</td>
<td><span style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;background:${color}15;color:${color};font-weight:500">${phaseLabels[d.phase] || d.phase}</span></td>
<td>${formatNum(d.delivery)}</td>
<td>${renderRateCell2(d.ew_rate, 15)}</td>
<td>${renderRateCell2(d.ax_rate, 20)}</td>
<td>${renderRateCell2(d.battery_rate, 7)}</td>
</tr>`;
}).join('');
}
// 员工表格
let staffRows = '';
if (staff.length > 0) {
staffRows = staff.map(s => `<tr>
<td style="text-align:left">${escapeHtml(s.staff_name)}</td>
<td>${formatNum(s.delivery)}</td>
<td>${renderRateCell2(s.ew_rate, 15)}</td>
<td>${renderRateCell2(s.ax_rate, 20)}</td>
<td>${renderRateCell2(s.battery_rate, 7)}</td>
</tr>`).join('');
}
// 品牌表格
let brandRows = '';
if (brand.length > 0) {
brandRows = brand.map(b => `<tr>
<td style="text-align:left">${escapeHtml(b.brand_name)}</td>
<td>${formatNum(b.delivery)}</td>
<td>${renderRateCell2(b.ew_rate, 15)}</td>
<td>${renderRateCell2(b.ax_rate, 20)}</td>
<td>${renderRateCell2(b.battery_rate, 7)}</td>
</tr>`).join('');
}
// 阶段汇总
let phaseSummaryRows = '';
phaseOrder.forEach(phase => {
const days = daily.filter(d => d.phase === phase);
if (days.length === 0) return;
const totalD = days.reduce((s, d) => s + d.delivery, 0);
const avgEw = days.reduce((s, d) => s + d.ew_rate, 0) / days.length;
const avgAx = days.reduce((s, d) => s + d.ax_rate, 0) / days.length;
const avgBattery = days.reduce((s, d) => s + d.battery_rate, 0) / days.length;
const color = phaseColors[phase] || '#999';
phaseSummaryRows += `<tr style="background:${color}10;font-weight:500">
<td style="text-align:left"><span style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;background:${color}20;color:${color}">${phaseLabels[phase] || phase}</span></td>
<td>${days.length}天</td>
<td>${formatNum(totalD)}</td>
<td>${renderRateCell2(avgEw, 15)}</td>
<td>${renderRateCell2(avgAx, 20)}</td>
<td>${renderRateCell2(avgBattery, 7)}</td>
</tr>`;
});
// 产品汇总卡片
let productCards = '';
if (product.delivery) {
const items = [
{ label: '整车延保', key: 'ew_rate', target: 15, color: '#1890ff' },
{ label: '安心包', key: 'ax_rate', target: 20, color: '#fa8c16' },
{ label: '电池', key: 'battery_rate', target: 7, color: '#52c41a' },
];
productCards = items.map(it => {
const v = product[it.key] || 0;
const ok = v >= it.target;
return `<div class="effect-item">
<div class="label">${it.label}</div>
<div class="value ${ok ? 'up' : 'down'}" style="color:${it.color}">${v.toFixed(1)}%</div>
</div>`;
}).join('');
}
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">${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.title || '-')}</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>
</div>
<div class="card">
<div class="card-header">产品渗透率总览</div>
<div class="card-body">
<div class="effect-summary">${productCards || '<div style="color:#999;text-align:center">暂无数据</div>'}</div>
</div>
</div>
</div>
<div class="right-panel">
<div class="card">
<div class="card-header"><span>按天渗透率变化</span><span class="card-subtitle">T-1 盯防前 → T 盯防中 → T+1 盯防后,逐日展示</span></div>
<div class="card-body" style="padding:0">
${daily.length > 0 ? `<table class="performance-table" style="margin-bottom:12px">
<thead><tr>
<th style="text-align:left">日期</th>
<th>阶段</th>
<th>交付数</th>
<th>整车延保</th>
<th>安心包</th>
<th>电池</th>
</tr></thead>
<tbody>${dailyRows}</tbody>
</table>
<div style="padding:0 12px 12px">
<div style="font-weight:600;font-size:13px;margin-bottom:8px;color:#333">阶段汇总</div>
<table class="performance-table">
<thead><tr>
<th style="text-align:left">阶段</th>
<th>天数</th>
<th>总交付</th>
<th>整车延保(均值)</th>
<th>安心包(均值)</th>
<th>电池(均值)</th>
</tr></thead>
<tbody>${phaseSummaryRows}</tbody>
</table>
</div>` : '<div style="padding:30px;text-align:center;color:#999">暂无日维度数据</div>'}
</div>
</div>
<div class="card">
<div class="card-header">按员工维度 - 门店各员工渗透率</div>
<div class="card-body" style="padding:0">
${staff.length > 0 ? `<table class="performance-table">
<thead><tr>
<th style="text-align:left">员工姓名</th>
<th>交付数</th>
<th>整车延保</th>
<th>安心包</th>
<th>电池</th>
</tr></thead>
<tbody>${staffRows}</tbody>
</table>` : '<div style="padding:30px;text-align:center;color:#999">暂无员工维度数据</div>'}
</div>
</div>
<div class="card">
<div class="card-header">按品牌维度 - 问界 / 智界 等</div>
<div class="card-body" style="padding:0">
${brand.length > 0 ? `<table class="performance-table">
<thead><tr>
<th style="text-align:left">品牌</th>
<th>交付数</th>
<th>整车延保</th>
<th>安心包</th>
<th>电池</th>
</tr></thead>
<tbody>${brandRows}</tbody>
</table>` : '<div style="padding:30px;text-align:center;color:#999">暂无品牌维度数据</div>'}
</div>
</div>
<div class="card">
<div class="card-header">LLM 分析总结</div>
<div class="card-body">
<div class="conclusion">${escapeHtml(llm || '暂无分析总结(请确认 LLM 配置是否正确)')}</div>
</div>
</div>
</div>
</div>`;
}
function renderRateCell2(rate, target) {
if (rate === null || rate === undefined || rate === 0) return '<span style="color:#ccc">-</span>';
let cls = '';
if (target !== undefined && target !== null) {
cls = rate >= target ? 'up' : 'down';
}
return `<span class="rate-value ${cls}">${rate.toFixed(1)}%</span>`;
}
window.showDetail = async function(id) { window.showDetail = async function(id) {
currentModalId = id; currentModalId = id;
document.getElementById('modal-title').textContent = '策略详情'; document.getElementById('modal-title').textContent = '策略详情';
...@@ -770,8 +981,21 @@ ...@@ -770,8 +981,21 @@
} }
}; };
window.showInfo = function(id) { window.showInfo = async function(id) {
window.location.href = './strategy/info?id=' + id; currentInfoId = id;
document.getElementById('info-modal-title').textContent = '渗透率分析';
document.getElementById('info-modal-body').innerHTML = '<div class="loading">正在加载渗透率分析数据...</div>';
document.getElementById('info-modal').style.display = 'block';
document.body.style.overflow = 'hidden';
try {
const res = await fetch(window.API_BASE + '/strategy/' + id + '/penetration');
const json = await res.json();
if (json.status !== 'success') throw new Error(json.detail || '加载失败');
document.getElementById('info-modal-title').textContent = '渗透率分析 - ' + (json.data.strategy.merchant_name || '');
document.getElementById('info-modal-body').innerHTML = renderPenetration(json.data);
} catch (err) {
document.getElementById('info-modal-body').innerHTML = '<div class="error-tip">加载失败: ' + escapeHtml(err.message) + '</div>';
}
}; };
window.refreshInModal = async function() { window.refreshInModal = async function() {
...@@ -807,9 +1031,17 @@ ...@@ -807,9 +1031,17 @@
currentModalId = null; currentModalId = null;
}; };
window.closeInfoModal = function() {
document.getElementById('info-modal').style.display = 'none';
document.body.style.overflow = '';
currentInfoId = null;
};
window.onclick = function(event) { window.onclick = function(event) {
const modal = document.getElementById('detail-modal'); const detailModal = document.getElementById('detail-modal');
if (event.target === modal) closeModal(); if (event.target === detailModal) closeModal();
const infoModal = document.getElementById('info-modal');
if (event.target === infoModal) closeInfoModal();
}; };
async function analyzeSingle(id, btn) { async function analyzeSingle(id, btn) {
......
...@@ -198,7 +198,7 @@ ...@@ -198,7 +198,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 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>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!