Commit ce23437c by 江名洋

feat(strategy): 添加策略分析任务触发与进度轮询

1 parent 51e01fff
......@@ -19,7 +19,7 @@ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
logger = logging.getLogger("app.harmony_analysis_service")
# 鸿蒙智行 brand_id 集合
HARMONY_BRAND_IDS = (2695, 2698, 2741, 2740, 2797)
HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797)
# 2695=问界, 2698=智界, 2741=享界, 2740=尊界, 2797=尚界
# first_brand_id(鸿蒙智行,参考 generate_weekly_comparison.py)
......@@ -260,7 +260,7 @@ class HarmonyAnalysisService:
def _query_harmony_store_performance(store_names: list, start_date: str, end_date: str) -> dict:
"""
从 dws_merchant_daily_wide 查询鸿蒙门店产值数据。
鸿蒙品牌 ID: 2695(问界), 2698(智界), 2741(享界), 2740(尊界), 2797(尚界)
鸿蒙品牌 ID: 2698(智界), 2741(享界), 2740(尊界), 2797(尚界)
返回: {store_name: {
"delivery": int, "touch": int,
......@@ -401,7 +401,7 @@ class HarmonyAnalysisService:
import shutil
import time
TEMPLATE_FILE = os.path.join("app", "templates", "xlsx", "输出模板-鸿蒙-模板002.xlsx")
TEMPLATE_FILE = os.path.join("app", "templates", "xlsx", "输出模板-鸿蒙-模板004.xlsx")
TEMPLATE_SHEET = "模板"
if not os.path.exists(TEMPLATE_FILE):
......@@ -561,9 +561,12 @@ class HarmonyAnalysisService:
_style_cell(row_num, 9, "") # 特殊情况
# ========== 主机厂交付数 (J-K, 10-11) ==========
factory_delivery = _safe_float(store_row.get("交付数", 0))
_style_cell(row_num, 10, factory_delivery)
factory_delivery: float = _safe_float(store_row.get("交付数", 0))
_style_cell(row_num, 11, factory_delivery)
if factory_delivery == 0:
factory_delivery = perf.get("delivery", 0)
_style_cell(row_num, 10, factory_delivery)
# ========== 产值表交付数 (L, 12) ==========
db_delivery = perf.get("delivery", 0)
......
......@@ -640,7 +640,24 @@ class StrategyService:
page: int = 1,
page_size: int = 8,
) -> Dict:
"""从结果表查询策略列表(高性能)"""
"""从结果表查询策略列表,结果表为空时回退到原始策略表"""
# 先检查结果表是否有数据
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute("SELECT COUNT(*) AS cnt FROM strategy_analysis_result")
result_total = cur.fetchone()["cnt"]
finally:
conn.close()
if result_total == 0:
return StrategyService._get_strategy_list_from_source(
keyword=keyword, province=province,
status=status, start_date=start_date, end_date=end_date,
page=page, page_size=page_size,
)
conditions = ["is_valid = 1"]
params = []
......@@ -674,14 +691,12 @@ class StrategyService:
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, "
......@@ -693,7 +708,6 @@ class StrategyService:
)
stat_row = cur.fetchone()
# 分页数据
offset = (page - 1) * page_size
cur.execute(
f"SELECT * FROM strategy_analysis_result WHERE {where} "
......@@ -705,10 +719,8 @@ class StrategyService:
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,
......@@ -761,6 +773,137 @@ class StrategyService:
"records": records,
}
@staticmethod
def _get_strategy_list_from_source(
keyword: Optional[str] = None,
province: Optional[str] = None,
status: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
page: int = 1,
page_size: int = 8,
) -> Dict:
"""结果表为空时,直接从 ods_strategy_info 读取策略列表(无分析数据)"""
conditions = ["s.deleted_flag = 'N'"]
params = []
if keyword:
conditions.append("(s.title LIKE %s OR s.merchant_name LIKE %s OR s.created_by LIKE %s)")
params.extend([f"%{keyword}%", f"%{keyword}%", f"%{keyword}%"])
if province:
conditions.append("sc.province = %s")
params.append(province)
if status:
# status 对应 push_flag 映射
for push_val, push_label in PUSH_FLAG_MAP.items():
if push_label == status:
conditions.append("s.push_flag = %s")
params.append(push_val)
break
else:
conditions.append("s.push_flag = -1") # never match
if start_date:
conditions.append("s.end_date >= %s")
params.append(start_date)
if end_date:
conditions.append("s.start_date <= %s")
params.append(end_date)
where = " AND ".join(conditions)
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
# 总数
count_sql = (
f"SELECT COUNT(*) AS cnt FROM ods_strategy_info s "
f"LEFT JOIN ods_store_config sc ON s.merchant_id = sc.merchant_id AND sc.deleted_flag = 'N' "
f"WHERE {where}"
)
cur.execute(count_sql, tuple(params))
total = cur.fetchone()["cnt"]
# 统计(从源表无法精确统计 effect/baodi_type/monitor_type,给默认值)
# 盯防中 = push_flag in (1,4)
stat_sql = (
f"SELECT "
f"SUM(CASE WHEN s.push_flag IN (1,4) THEN 1 ELSE 0 END) AS monitoring, "
f"SUM(CASE WHEN s.push_flag = 6 THEN 1 ELSE 0 END) AS ended "
f"FROM ods_strategy_info s "
f"LEFT JOIN ods_store_config sc ON s.merchant_id = sc.merchant_id AND sc.deleted_flag = 'N' "
f"WHERE {where}"
)
cur.execute(stat_sql, tuple(params))
stat_row = cur.fetchone()
# 分页数据
offset = (page - 1) * page_size
data_sql = (
"SELECT s.id, s.title, s.sub_title, s.strategy_type, s.merchant_id, "
"s.merchant_name, s.start_date, s.end_date, s.push_flag, s.description, "
"s.biz, s.created_by, "
"sc.merchant_code, sc.province, sc.city, sc.operation_mode "
"FROM ods_strategy_info s "
"LEFT JOIN ods_store_config sc ON s.merchant_id = sc.merchant_id AND sc.deleted_flag = 'N' "
f"WHERE {where} "
"ORDER BY s.created_date DESC "
"LIMIT %s OFFSET %s"
)
cur.execute(data_sql, tuple(params) + (page_size, offset))
rows = cur.fetchall()
finally:
conn.close()
records = []
for r in rows:
sid = r["id"]
push_flag = r.get("push_flag")
status_label = PUSH_FLAG_MAP.get(push_flag, "未知") if push_flag is not None else "未知"
strategy_type = r.get("strategy_type")
type_name = STRATEGY_TYPE_MAP.get(
StrategyService._safe_num(strategy_type), "未知"
) if strategy_type is not None else "未知"
records.append({
"id": sid,
"title": r["title"] or "",
"sub_title": r["sub_title"] or "",
"strategy_type": strategy_type,
"strategy_type_name": type_name,
"merchant_id": r["merchant_id"],
"merchant_name": r["merchant_name"] or "",
"merchant_code": r.get("merchant_code") or "",
"province": r.get("province") or "",
"city": r.get("city") or "",
"operation_mode": r.get("operation_mode") or "",
"baodi_type": "",
"monitor_type": "",
"status": status_label,
"push_flag": push_flag,
"start_date": StrategyService._date_str(r["start_date"]),
"end_date": StrategyService._date_str(r["end_date"]),
"receiver": r.get("created_by") or "",
"effect": "",
"effect_class": "",
"delivery_change": {"old": 0, "new": 0, "ratio": None},
"product_changes": [],
"description": r["description"] or "",
"created_by": r.get("created_by") or "",
"biz": r.get("biz") or "",
})
return {
"total": total,
"monitoring": stat_row.get("monitoring", 0) or 0,
"up": 0,
"down": 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
......@@ -787,7 +930,7 @@ class StrategyService:
@staticmethod
def get_strategy_detail(strategy_id: int) -> Optional[Dict]:
"""获取单条策略详情(优先从结果表读,回退到实时分析)"""
"""获取单条策略详情(优先从结果表读,回退到原始策略表)"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
......@@ -800,7 +943,8 @@ class StrategyService:
conn.close()
if not row:
return None
# 回退到原始策略表
return StrategyService._get_strategy_detail_from_source(strategy_id)
base_metrics = None
exec_metrics = None
......@@ -870,6 +1014,67 @@ class StrategyService:
"conclusion": row["conclusion"] or "暂无分析结论",
}
@staticmethod
def _get_strategy_detail_from_source(strategy_id: int) -> Optional[Dict]:
"""从原始策略表读取详情(结果表无数据时回退)"""
conn = StrategyService._get_raw_conn()
try:
with conn.cursor() as cur:
cur.execute(
"SELECT s.*, sc.merchant_code, sc.province, sc.city, sc.operation_mode "
"FROM ods_strategy_info s "
"LEFT JOIN ods_store_config sc ON s.merchant_id = sc.merchant_id AND sc.deleted_flag = 'N' "
"WHERE s.id = %s AND s.deleted_flag = 'N'",
(strategy_id,),
)
row = cur.fetchone()
finally:
conn.close()
if not row:
return None
push_flag = row.get("push_flag")
status_label = PUSH_FLAG_MAP.get(push_flag, "未知")
strategy_type = row.get("strategy_type")
type_name = STRATEGY_TYPE_MAP.get(StrategyService._safe_num(strategy_type), "未知")
return {
"strategy": {
"id": row["id"],
"title": row["title"] or "",
"sub_title": row["sub_title"] or "",
"strategy_type": strategy_type,
"strategy_type_name": type_name,
"description": row.get("description"),
"start_date": StrategyService._date_str(row.get("start_date")),
"end_date": StrategyService._date_str(row.get("end_date")),
"push_flag": push_flag,
"status": status_label,
"merchant_id": row.get("merchant_id"),
"merchant_name": row.get("merchant_name") or "",
"created_by": row.get("created_by"),
},
"store": {
"province": row.get("province"),
"city": row.get("city"),
"operation_mode": row.get("operation_mode"),
},
"baodi_type": "",
"monitor_type": "",
"periods": {"T_minus_1": None, "T": None, "T_plus_1": None},
"base_metrics": None,
"exec_metrics": None,
"track_metrics": None,
"effect": {
"label": "",
"class_name": "",
"delivery_change": {"old": 0, "new": 0, "ratio": None},
"product_changes": [],
},
"conclusion": "策略尚未进行分析,请点击「刷新分析」获取效果数据。",
}
# ──────────── 兼容旧接口(实时计算,保留备用) ────────────
@staticmethod
......
......@@ -84,6 +84,15 @@
.loading-mask { text-align: center; padding: 40px; color: #999; font-size: 13px; }
.empty-tip { text-align: center; padding: 40px; color: #999; }
.task-bar { background: #fff; border-radius: 8px; padding: 12px 16px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); display: flex; align-items: center; gap: 12px; }
.task-bar .btn-analyze { padding: 6px 16px; background: #1890ff; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; white-space: nowrap; }
.task-bar .btn-analyze:disabled { background: #ccc; cursor: not-allowed; }
.task-info { font-size: 13px; color: #666; }
.task-info .running-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: #52c41a; animation: pulse 1.2s infinite; margin-right: 4px; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
.progress-bar { flex: 1; min-width: 120px; height: 6px; background: #f0f0f0; border-radius: 3px; overflow: hidden; }
.progress-bar .fill { height: 100%; background: #1890ff; border-radius: 3px; transition: width 0.3s; }
/* 详情弹窗 */
.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; }
......@@ -154,6 +163,15 @@
</div>
</div>
<!-- 分析任务栏 -->
<div class="task-bar" id="task-bar">
<button class="btn-analyze" id="btn-analyze" onclick="triggerAnalyze()">刷新分析</button>
<div class="task-info" id="task-info">就绪,点击按钮开始分析</div>
<div class="progress-bar" id="progress-bar" style="display:none">
<div class="fill" id="progress-fill" style="width:0%"></div>
</div>
</div>
<!-- 筛选栏 -->
<div class="filter-bar">
<input type="text" id="filter-keyword" placeholder="搜索门店名称">
......@@ -265,9 +283,9 @@
'<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="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(ew.pp_change) + '">' + (ew.pp_change != null ? (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 > 0 ? '↑' : (ax.pp_change < 0 ? '↓' : '→')) + ' ' + Math.abs(ax.pp_change).toFixed(1) + 'pp' : '-') + '</span><span class="change-detail">' + (ax.old_rate != null ? ax.old_rate.toFixed(1) + '%→' + ax.new_rate.toFixed(1) + '%' : '-') + '</span></div></td>',
'<td class="right"><div class="change-cell"><span class="change-ratio ' + getChangeClass(bt.pp_change) + '">' + (bt.pp_change != null ? (bt.pp_change > 0 ? '↑' : (bt.pp_change < 0 ? '↓' : '→')) + ' ' + Math.abs(bt.pp_change).toFixed(1) + 'pp' : '-') + '</span><span class="change-detail">' + (bt.old_rate != null ? bt.old_rate.toFixed(1) + '%→' + bt.new_rate.toFixed(1) + '%' : '-') + '</span></div></td>',
'<td class="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>');
......@@ -458,9 +476,105 @@
}
};
let pollTimer = null;
async function triggerAnalyze() {
const btn = document.getElementById('btn-analyze');
const info = document.getElementById('task-info');
btn.disabled = true;
btn.textContent = '触发中...';
info.innerHTML = '正在启动分析任务...';
try {
const res = await fetch(window.API_BASE + '/strategy/analyze', { method: 'POST' });
const json = await res.json();
if (json.status === 'warning') {
info.innerHTML = '<span class="running-dot"></span>' + json.message;
btn.textContent = '分析中...';
btn.disabled = true;
startPolling();
} else if (json.status === 'success') {
info.innerHTML = json.message;
btn.textContent = '分析中...';
btn.disabled = true;
startPolling();
} else {
info.innerHTML = '触发失败: ' + (json.detail || '未知错误');
btn.textContent = '刷新分析';
btn.disabled = false;
}
} catch (err) {
info.innerHTML = '触发失败: ' + escapeHtml(err.message);
btn.textContent = '刷新分析';
btn.disabled = false;
}
}
function startPolling() {
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(pollStatus, 2000);
}
function stopPolling() {
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
}
async function pollStatus() {
try {
const res = await fetch(window.API_BASE + '/strategy/analyze/status');
const json = await res.json();
if (json.status !== 'success') return;
const s = json.data;
const btn = document.getElementById('btn-analyze');
const info = document.getElementById('task-info');
const bar = document.getElementById('progress-bar');
const fill = document.getElementById('progress-fill');
if (s.running) {
bar.style.display = 'flex';
const pct = s.total > 0 ? Math.round(s.completed / s.total * 100) : 0;
fill.style.width = pct + '%';
btn.textContent = '分析中...';
btn.disabled = true;
info.innerHTML = '<span class="running-dot"></span>分析中: ' + (s.completed + s.failed) + '/' + s.total + ' (成功 ' + s.completed + ', 失败 ' + s.failed + ')';
if (s.current) info.innerHTML += ' | 当前策略 #' + s.current;
} else {
bar.style.display = 'none';
stopPolling();
btn.textContent = '刷新分析';
btn.disabled = false;
if (s.total > 0) {
info.innerHTML = '完成: ' + s.completed + ' 条成功, ' + s.failed + ' 条失败 | 共 ' + s.total + ' 条 | ' + (s.finished_at ? s.finished_at.slice(0, 16) : '');
loadData();
} else {
info.innerHTML = '就绪,结果表中有缓存数据';
}
}
} catch (err) {
console.error('轮询状态失败:', err);
}
}
async function checkInitialStatus() {
try {
const res = await fetch(window.API_BASE + '/strategy/analyze/status');
const json = await res.json();
if (json.status !== 'success') return;
const s = json.data;
if (s.running) {
const btn = document.getElementById('btn-analyze');
btn.textContent = '分析中...';
btn.disabled = true;
const info = document.getElementById('task-info');
info.innerHTML = '<span class="running-dot"></span>分析中: ' + (s.completed + s.failed) + '/' + s.total;
startPolling();
}
} catch (err) {}
}
document.addEventListener('DOMContentLoaded', () => {
loadOptions();
loadData();
checkInitialStatus();
document.getElementById('btn-search').addEventListener('click', collectFilters);
document.getElementById('btn-reset').addEventListener('click', resetFilters);
......
......@@ -52,6 +52,12 @@ async def lifespan(app: FastAPI):
# 创建认证表(若不存在)并初始化默认账号
await asyncio.to_thread(_init_auth_tables_sync)
await asyncio.to_thread(_init_default_users_sync)
# 创建策略效果分析结果表
try:
from app.services.strategy_service import StrategyService
await asyncio.to_thread(StrategyService.ensure_result_table)
except Exception as e:
print(f"[!] Failed to create strategy result table: {e}")
# 启动定时任务调度器
await SchedulerManager.start()
yield
......
# -*- coding: utf-8 -*-
"""
从鸿蒙分析报表中提取门店数据模板和主机厂数据模板
从鸿蒙分析报表中提取门店数据模板、主机厂数据模板、输出模板
数据源: 「会议标注」鸿蒙7月1-5号(含主机厂数据).xlsx
从主表提取: 门店、品牌、兜底指标、区域(省)、直营与否、区域运营、飞行督导、线上运营、兜底类型、需达标转化率、赔付金额
......@@ -9,6 +9,7 @@
输出:
- app/templates/xlsx/门店数据-鸿蒙-模板{序号}.xlsx
- app/templates/xlsx/主机厂数据-鸿蒙-模板{序号}.xlsx
- app/templates/xlsx/输出模板-鸿蒙-模板{序号}.xlsx (38列完整模板)
注意: 鸿蒙没有生态店的概念,所有兜底计算周期都是自然月
"""
......@@ -16,6 +17,7 @@ import sys, io, os, glob, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
# ── 配置 ──
SRC = r'C:\Users\jiata\Desktop\「会议标注」鸿蒙7月1-5号(含主机厂数据).xlsx'
......@@ -28,7 +30,8 @@ for f in glob.glob('app/templates/xlsx/门店数据-鸿蒙-模板[0-9][0-9][0-9]
max_no = max(max_no, no)
except ValueError:
pass
STORE_OUT = f'app/templates/xlsx/门店数据-鸿蒙-模板{max_no + 1:03d}.xlsx'
seq_store = max_no + 1
STORE_OUT = f'app/templates/xlsx/门店数据-鸿蒙-模板{seq_store:03d}.xlsx'
max_no2 = 0
for f in glob.glob('app/templates/xlsx/主机厂数据-鸿蒙-模板[0-9][0-9][0-9].xlsx'):
......@@ -37,7 +40,18 @@ for f in glob.glob('app/templates/xlsx/主机厂数据-鸿蒙-模板[0-9][0-9][0
max_no2 = max(max_no2, no)
except ValueError:
pass
FACTORY_OUT = f'app/templates/xlsx/主机厂数据-鸿蒙-模板{max_no2 + 1:03d}.xlsx'
seq_factory = max_no2 + 1
FACTORY_OUT = f'app/templates/xlsx/主机厂数据-鸿蒙-模板{seq_factory:03d}.xlsx'
max_no3 = 0
for f in glob.glob('app/templates/xlsx/输出模板-鸿蒙-模板[0-9][0-9][0-9].xlsx'):
try:
no = int(os.path.splitext(os.path.basename(f))[0][-3:])
max_no3 = max(max_no3, no)
except ValueError:
pass
seq_out = max(max_no3 + 1, 3) # 从003起(001/002保留不覆盖)
OUTPUT_TEMPLATE = f'app/templates/xlsx/输出模板-鸿蒙-模板{seq_out:03d}.xlsx'
# ── 样式 ──
header_fill = PatternFill('solid', fgColor='BDD7EE') # 浅蓝
......@@ -302,4 +316,194 @@ fwb.save(FACTORY_OUT)
print(f'主机厂数据模板输出: {FACTORY_OUT}')
print(f'主机厂数据行数: {row_num - 2}')
# ══════════════════════════════════════════════
# 5. 输出鸿蒙分析模板 (38列) — 格式严格参照 输出模板-鸿蒙-模板003
# ══════════════════════════════════════════════
# 003 格式特点:
# - 仅6个横向合并组, 无纵向合并
# - 独立列使用 centerContinuous 跨列居中
# - 有条件格式: X列门店等级变色, W列"是"标红
print(f'\n构建38列输出模板...')
from openpyxl.formatting.rule import FormulaRule
twb = Workbook()
tws = twb.active
tws.title = '模板'
MERGED_GROUP_H = Alignment(horizontal='center', vertical='center', wrap_text=True)
STANDALONE_H = Alignment(horizontal='centerContinuous', vertical='center', wrap_text=True)
ROW2_ALIGN = Alignment(horizontal='center', vertical='center', wrap_text=True)
ROW3_ALIGN = Alignment(horizontal='center', vertical='center', wrap_text=True)
# ── Row 1: 主表头 (6个横向合并组 + 4个独立标题列) ──
# 横向合并组
H_MERGE_003 = [
(1, 9, '基础门店信息'),
(14, 22, '产值表数据'),
(26, 28, '当前转化率'),
(29, 31, '需达标转化率'),
(32, 34, '需达标订单差额'),
(35, 37, '赔付金额'),
]
for start_col, end_col, title in H_MERGE_003:
tws.merge_cells(f"{get_column_letter(start_col)}1:{get_column_letter(end_col)}1")
c = tws.cell(row=1, column=start_col, value=title)
c.font = header_font
c.fill = header_fill
c.alignment = MERGED_GROUP_H
c.border = thin_border
# 独立列 (J, K, L, M, W, X, Y, AL) — row1 只有 J/W/AL 有标题
STANDALONE_ROW1 = {
10: '主机厂交付数(标红为产值表总交付数)',
23: '是否触发兜底',
38: '总赔付金额',
}
for col_num, title in STANDALONE_ROW1.items():
c = tws.cell(row=1, column=col_num, value=title)
c.font = header_font
c.fill = header_fill
c.alignment = STANDALONE_H
c.border = thin_border
# 无 row1 标题的独立列 (K, L, M, X, Y) — 仅样式
for col_num in [11, 12, 13, 24, 25]:
c = tws.cell(row=1, column=col_num)
c.font = header_font
c.fill = header_fill
c.alignment = STANDALONE_H
c.border = thin_border
# ── Row 2: 子表头 (所有38列, 与003完全一致) ──
ROW2_ALL = {
1: '门店', 2: '品牌', 3: '兜底指标', 4: '区域(省)', 5: '直营与否',
6: '区域运营', 7: '飞行督导', 8: '线上运营', 9: '特殊情况',
10: '主机厂交付数', 11: '主机厂',
12: '产值表交付数', 13: '主机厂跟产值表差距',
14: '门店触客数', 15: '触客率', 16: '整车延保成交订单数',
17: '整车延保渗透率', 18: '触客成交率', 19: '安心包',
20: '安心包渗透率', 21: '电池', 22: '电池渗透率',
23: '是否触发兜底', 24: '门店等级', 25: '兜底类型',
26: '整车延保转化率', 27: '安心包转化率', 28: '电池延保转化率',
29: '需达标_整车延保', 30: '需达标_安心包', 31: '需达标_电池延保',
32: '差额_整车延保', 33: '差额_安心包', 34: '差额_电池延保',
35: '赔付_整车延保', 36: '赔付_安心包', 37: '赔付_电池延保',
38: '总赔付金额',
}
for col_num, title in ROW2_ALL.items():
c = tws.cell(row=2, column=col_num, value=title)
c.font = sub_font
c.fill = sub_fill
c.alignment = ROW2_ALIGN
c.border = thin_border
# ── 列宽 (与003一致) ──
col_widths_003 = {
'A': 35, 'B': 18, 'C': 31.5, 'D': 14, 'E': 10,
'F': 12, 'H': 14, 'I': 12,
'J': 14, 'K': 10,
'L': 14, 'M': 16,
'N': 14, 'O': 10, 'P': 18, 'Q': 14, 'R': 12,
'S': 10, 'T': 14, 'U': 10, 'V': 14,
'X': 12, 'Y': 10,
'Z': 16,
'AC': 14, 'AF': 16, 'AI': 14,
}
for cl, w in col_widths_003.items():
tws.column_dimensions[cl].width = w
tws.row_dimensions[1].height = 18
tws.row_dimensions[2].height = 18
# ── Row 3: 模板示例行 (公式与003完全一致) ──
# 003 的公式基于 L3(产值表交付数) 而非 J3(主机厂)
sample_data_003 = [
# A-I: 基础门店信息 (1-9)
'示例门店', # A(1)
'鸿蒙智行', # B(2) 003用的是"鸿蒙智行"不是"鸿蒙智行/智界"
'兜底:触客渗透率50%', # C(3)
'广东省', # D(4)
'直营', # E(5)
'区域运营', # F(6)
'飞行督导', # G(7)
'线上运营', # H(8)
'', # I(9) 特殊情况 (003中为空)
# J-M: 交付数 (10-13)
10, # J(10) 主机厂交付数
10, # K(11) 主机厂
10, # L(12) 产值表交付数
'=J3-L3', # M(13) 差距
# N-V: 产值表数据 (14-22)
8, # N(14) 门店触客数
'=IF(L3>0,N3/L3,0)', # O(15) 触客率 — 基于L3
5, # P(16) 整车延保成交订单数 (003用5不是2)
'=IF(L3>0,P3/L3,0)', # Q(17) 整车延保渗透率
'=IF(N3>0,P3/N3,0)', # R(18) 触客成交率
2, # S(19) 安心包 (003用2)
'=IF(L3>0,S3/L3,0)', # T(20) 安心包渗透率
1, # U(21) 电池 (003用1)
'=IF(L3>0,U3/L3,0)', # V(22) 电池渗透率
# W-Y: 兜底判断 (23-25)
'=IF(OR(Z3<AC3,AA3<AD3,AB3<AE3),"是","否")', # W(23) 是否触发兜底
'红色门店', # X(24) 门店等级 (003示例用红色)
'触客', # Y(25) 兜底类型
# Z-AB: 当前转化率 (26-28) — 003公式: 优先N3, 否则L3
'=IF($N3>0,P3/$N3,IF($L3>0,P3/$L3,0))', # Z(26) 整车延保转化率
'=IF($N3>0,S3/$N3,IF($L3>0,S3/$L3,0))', # AA(27) 安心包转化率
'=IF($N3>0,U3/$N3,IF($L3>0,U3/$L3,0))', # AB(28) 电池延保转化率
# AC-AE: 需达标转化率 (29-31)
0.5, # AC(29)
0, # AD(30) 003用0
0, # AE(31) 003用0
# AF-AH: 需达标订单差额 (32-34) — 003公式: 无TRIM,无CEILING
'=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AC3-P3,0))', # AF(32)
'=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AD3-S3,0))', # AG(33)
'=MAX(0,ROUND(IF($N3>0,$N3,$L3)*AE3-U3,0))', # AH(34)
# AI-AK: 赔付金额 (35-37)
400, # AI(35)
0, # AJ(36) 003用0
0, # AK(37) 003用0
# AL: 总赔付金额 (38) — 003公式
'=IF(E3="直营",AI3+AJ3+AK3,"/")', # AL(38)
]
PERCENT_COLS_003 = {15, 17, 18, 20, 22, 26, 27, 28, 29, 30, 31}
for col_idx, val in enumerate(sample_data_003, 1):
cell = tws.cell(row=3, column=col_idx, value=val)
cell.font = data_font
cell.border = thin_border
cell.alignment = ROW3_ALIGN
if isinstance(val, (int, float)):
if col_idx in PERCENT_COLS_003:
cell.number_format = '0.00%'
elif col_idx == 38:
cell.number_format = '#,##0'
else:
cell.number_format = '0'
tws.row_dimensions[3].height = 18
# ── 条件格式 (与003一致) ──
# X3:X1000 门店等级变色
tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="红色门店"'], font=Font(color='000000')))
tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="绿色门店"'], font=Font(color='000000')))
tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="黄色门店"'], font=Font(color='000000')))
# W3:W1000 触发兜底标红
tws.conditional_formatting.add('W3:W1000',
FormulaRule(formula=['$W3="是"'],
font=Font(bold=True, color='000000'),
fill=PatternFill('solid', fgColor='FF6B6B')))
tws.freeze_panes = 'A3'
twb.save(OUTPUT_TEMPLATE)
print(f'输出模板: {OUTPUT_TEMPLATE}')
print(f'模板列数: 38')
assert len(tws.merged_cells.ranges) == 6, f'合并单元格数量应为6, 实际{len(tws.merged_cells.ranges)}'
print(f'合并单元格: {[str(mc) for mc in sorted(tws.merged_cells.ranges, key=str)]}')
print('\n全部完成!')
......@@ -51,7 +51,7 @@ WAREHOUSE_DB = {
# 鸿蒙智行 first_brand_id = 2365
# 子品牌: 2695=问界, 2698=智界, 2741=享界, 2740=尊界, 2797=尚界
FIRST_BRAND_ID = 2365
HARMONY_BRAND_IDS = (2695, 2698, 2741, 2740, 2797)
HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797)
HARMONY_BRAND_NAMES = {2695: "问界", 2698: "智界", 2741: "享界", 2740: "尊界", 2797: "尚界"}
......@@ -141,7 +141,7 @@ def query_source_merchant_daily(conn, merchant_id, start_date, end_date):
AND report_date >= %s AND report_date <= %s
AND deleted_flag = 'N'
AND first_brand_id = %s
AND brand_id IN (2695, 2698, 2741, 2740, 2797)
AND brand_id IN ( 2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date
"""
......@@ -218,7 +218,7 @@ def query_ods_staff_daily(conn, merchant_id, start_date, end_date):
AND report_date >= %s AND report_date <= %s
AND deleted_flag = 'N'
AND first_brand_id = %s
AND brand_id IN (2695, 2698, 2741, 2740, 2797)
AND brand_id IN ( 2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date
"""
......@@ -238,7 +238,7 @@ def query_ods_merchant_daily(conn, merchant_id, start_date, end_date):
AND report_date >= %s AND report_date <= %s
AND deleted_flag = 'N'
AND first_brand_id = %s
AND brand_id IN (2695, 2698, 2741, 2740, 2797)
AND brand_id IN (2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date
"""
......@@ -326,7 +326,7 @@ def query_dws_merchant_daily(conn, merchant_id, start_date, end_date):
WHERE merchant_id = %s
AND report_date >= %s AND report_date <= %s
AND first_brand_id = %s
AND brand_id IN (2695, 2698, 2741, 2740, 2797)
AND brand_id IN (2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date, brand_id
"""
......@@ -360,7 +360,7 @@ def query_dws_merchant_aggregate(conn, merchant_id, start_date, end_date):
WHERE m.merchant_id = %s
AND m.report_date >= %s AND m.report_date <= %s
AND m.first_brand_id = %s
AND m.brand_id IN (2695, 2698, 2741, 2740, 2797)
AND m.brand_id IN (2698, 2741, 2740, 2797)
AND m.scene_type = '0'
GROUP BY m.merchant_id, m.merchant_name, m.province_name,
m.area_supervision, m.flight_supervision, m.online_supervision
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!