Commit 0a2bdd1a by 江名洋

feat(harmony): 自动查找最新模板并优化交付数与门店等级逻辑

1 parent ce23437c
...@@ -12,7 +12,7 @@ from typing import Optional ...@@ -12,7 +12,7 @@ from typing import Optional
from app.services.etl_service import ETLService 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, _find_latest_template
from app.services.strategy_service import StrategyService, get_task_state 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
...@@ -27,6 +27,8 @@ UPLOAD_DIR = "temp_uploads" ...@@ -27,6 +27,8 @@ UPLOAD_DIR = "temp_uploads"
if not os.path.exists(UPLOAD_DIR): if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR) os.makedirs(UPLOAD_DIR)
XLSX_DIR = os.path.join("app", "templates", "xlsx")
@router.post("/data/upload") @router.post("/data/upload")
async def upload_data( async def upload_data(
background_tasks: BackgroundTasks, background_tasks: BackgroundTasks,
...@@ -391,20 +393,22 @@ async def analysis_download(file: str = Query(None)): ...@@ -391,20 +393,22 @@ async def analysis_download(file: str = Query(None)):
@router.get("/harmony/template/{template_type}") @router.get("/harmony/template/{template_type}")
async def download_harmony_template(template_type: str): async def download_harmony_template(template_type: str):
"""下载鸿蒙分析模板文件""" """下载鸿蒙分析模板文件(自动使用最新版本)"""
template_map = { prefix_map = {
"store": "门店数据-鸿蒙-模板001.xlsx", "store": "门店数据-鸿蒙-模板",
"factory": "主机厂数据-鸿蒙-模板001.xlsx", "factory": "主机厂数据-鸿蒙-模板",
"output": "输出模板-鸿蒙-模板001.xlsx", "output": "输出模板-鸿蒙-模板",
} }
filename = template_map.get(template_type) prefix = prefix_map.get(template_type)
if not filename: if not prefix:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output") raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
file_path = os.path.join(XLSX_DIR, filename) try:
if not os.path.exists(file_path): file_path = _find_latest_template(prefix)
raise HTTPException(status_code=404, detail=f"模板文件不存在: {filename}") except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"未找到类型为 {template_type} 的模板文件")
filename = os.path.basename(file_path)
return FileResponse(file_path, filename=filename, return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
...@@ -450,12 +454,11 @@ async def harmony_generate( ...@@ -450,12 +454,11 @@ async def harmony_generate(
"""根据已上传的数据生成鸿蒙生态分析报表(产值数据从数据库自动查询)""" """根据已上传的数据生成鸿蒙生态分析报表(产值数据从数据库自动查询)"""
global _harmony_store_file, _harmony_factory_file global _harmony_store_file, _harmony_factory_file
# 门店兜底配置:未上传时使用默认模板 # 门店兜底配置:未上传时使用最新模板
if not _harmony_store_file or not os.path.exists(_harmony_store_file): if not _harmony_store_file or not os.path.exists(_harmony_store_file):
default_store = os.path.join(XLSX_DIR, "门店数据-鸿蒙-模板001.xlsx") try:
if os.path.exists(default_store): _harmony_store_file = _find_latest_template("门店数据-鸿蒙-模板")
_harmony_store_file = default_store except FileNotFoundError:
else:
raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件") raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件")
factory_df = None factory_df = None
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
""" """
import os import os
import re import re
import glob
import math import math
import logging import logging
import pandas as pd import pandas as pd
...@@ -18,6 +19,19 @@ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side ...@@ -18,6 +19,19 @@ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
logger = logging.getLogger("app.harmony_analysis_service") logger = logging.getLogger("app.harmony_analysis_service")
XLSX_DIR = os.path.join("app", "templates", "xlsx")
def _find_latest_template(prefix: str) -> str:
"""自动查找指定前缀的最新模板文件(按序号最大)。"""
pattern = os.path.join(XLSX_DIR, f"{prefix}[0-9][0-9][0-9].xlsx")
files = glob.glob(pattern)
if not files:
raise FileNotFoundError(f"未找到模板文件: {pattern}")
# 按序号排序,取最大
files.sort(key=lambda f: int(os.path.splitext(os.path.basename(f))[0][-3:]))
return files[-1]
# 鸿蒙智行 brand_id 集合 # 鸿蒙智行 brand_id 集合
HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797) HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797)
# 2695=问界, 2698=智界, 2741=享界, 2740=尊界, 2797=尚界 # 2695=问界, 2698=智界, 2741=享界, 2740=尊界, 2797=尚界
...@@ -401,7 +415,7 @@ class HarmonyAnalysisService: ...@@ -401,7 +415,7 @@ class HarmonyAnalysisService:
import shutil import shutil
import time import time
TEMPLATE_FILE = os.path.join("app", "templates", "xlsx", "输出模板-鸿蒙-模板004.xlsx") TEMPLATE_FILE = _find_latest_template("输出模板-鸿蒙-模板")
TEMPLATE_SHEET = "模板" TEMPLATE_SHEET = "模板"
if not os.path.exists(TEMPLATE_FILE): if not os.path.exists(TEMPLATE_FILE):
...@@ -560,20 +574,17 @@ class HarmonyAnalysisService: ...@@ -560,20 +574,17 @@ class HarmonyAnalysisService:
_style_cell(row_num, 8, store_row.get("线上运营", perf.get("online_supervision", ""))) _style_cell(row_num, 8, store_row.get("线上运营", perf.get("online_supervision", "")))
_style_cell(row_num, 9, "") # 特殊情况 _style_cell(row_num, 9, "") # 特殊情况
# ========== 主机厂交付数 (J-K, 10-11) ========== # ========== 交付数 (J-L, 10-12) ==========
factory_delivery: float = _safe_float(store_row.get("交付数", 0)) factory_delivery: float = _safe_float(store_row.get("交付数", 0))
db_delivery = perf.get("delivery", 0)
# J(10): 复合交付数 = 主机厂数据优先,没有则用数据库值
composite = factory_delivery if factory_delivery > 0 else db_delivery
_style_cell(row_num, 10, composite)
# K(11): 主机厂交付数 = 纯主机厂数据
_style_cell(row_num, 11, factory_delivery) _style_cell(row_num, 11, factory_delivery)
# L(12): 产值交付数 = 数据库查询值
_style_cell(row_num, 12, db_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)
delivery2 = _safe_float(store_row.get("产值表_交付数", 0))
if delivery2 == 0:
delivery2 = factory_delivery if factory_delivery > 0 else db_delivery
_style_cell(row_num, 12, delivery2)
# ========== DB产值数据 ========== # ========== DB产值数据 ==========
db_touch = perf.get("touch", 0) db_touch = perf.get("touch", 0)
...@@ -604,9 +615,9 @@ class HarmonyAnalysisService: ...@@ -604,9 +615,9 @@ class HarmonyAnalysisService:
# ========== 是否触发兜底 (W, 23) ========== # ========== 是否触发兜底 (W, 23) ==========
baodi_type = str(store_row.get("兜底类型", "")).strip() baodi_type = str(store_row.get("兜底类型", "")).strip()
base_for_rate = touch if baodi_type == "触客" else delivery2 base_for_rate = touch if baodi_type == "触客" else composite
if base_for_rate == 0: if base_for_rate == 0:
base_for_rate = delivery2 base_for_rate = composite
target_yb = _parse_target(store_row.get("需达标转化率_整车延保")) target_yb = _parse_target(store_row.get("需达标转化率_整车延保"))
target_axb = _parse_target(store_row.get("需达标转化率_安心包")) target_axb = _parse_target(store_row.get("需达标转化率_安心包"))
...@@ -624,7 +635,14 @@ class HarmonyAnalysisService: ...@@ -624,7 +635,14 @@ class HarmonyAnalysisService:
_style_cell(row_num, 23, trigger) _style_cell(row_num, 23, trigger)
# ========== 门店等级 (X, 24) ========== # ========== 门店等级 (X, 24) ==========
_style_cell(row_num, 24, "") grade_formula = (
f'=IF(E{row_num}<>"直营","服务商",'
f'IF(J{row_num}=0,"暂无交车",'
f'IF(OR(ISBLANK(Q{row_num}),Q{row_num}=""),"/",'
f'IF(Q{row_num}>=0.5,"绿色门店",'
f'IF(Q{row_num}<0.4,"红色门店","黄色门店")))))'
)
_style_cell(row_num, 24, grade_formula)
# ========== 兜底类型 (Y, 25) ========== # ========== 兜底类型 (Y, 25) ==========
_style_cell(row_num, 25, baodi_type) _style_cell(row_num, 25, baodi_type)
......
...@@ -287,15 +287,15 @@ CREATE TABLE ods_merchant_output_target_config ( ...@@ -287,15 +287,15 @@ CREATE TABLE ods_merchant_output_target_config (
DROP TABLE IF EXISTS ods_strategy_info; DROP TABLE IF EXISTS ods_strategy_info;
CREATE TABLE ods_strategy_info ( CREATE TABLE ods_strategy_info (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID', `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`strategy_type` INT NOT NULL COMMENT '执行策略类型,0-学习类、1-优秀录音分享类、2-带教、3-任务型、4-销售精英到店提拉、5-强力促销、6-最终盘点与低客单产品购入、7-留言、8-带教申请、9-人员更换评估、10-商务政策更新评估、11-多品类拓张、12-流量问题改善', `strategy_type` INT NOT NULL COMMENT '执行策略类型:0-学习类、1-优秀录音分享类、2-带教、3-任务型、4-销售精英到店提拉、5-强力促销、6-最终盘点与低客单产品购入、7-留言、8-带教申请、9-人员更换评估、10-商务政策更新评估、11-多品类拓张、12-流量问题改善',
`title` VARCHAR(20) DEFAULT NULL COMMENT '标题', `title` VARCHAR(20) DEFAULT NULL COMMENT '标题',
`sub_title` VARCHAR(255) DEFAULT NULL COMMENT '副标题', `sub_title` VARCHAR(255) DEFAULT NULL COMMENT '副标题',
`start_date` DATETIME DEFAULT NULL COMMENT '执行开始日期', `start_date` DATETIME DEFAULT NULL COMMENT '执行开始日期',
`end_date` DATETIME DEFAULT NULL COMMENT '执行结束日期', `end_date` DATETIME DEFAULT NULL COMMENT '执行结束日期',
`description` VARCHAR(200) DEFAULT NULL COMMENT '策略说明', `description` VARCHAR(200) DEFAULT NULL COMMENT '策略说明',
`content` TEXT DEFAULT NULL COMMENT '内容', `content` TEXT DEFAULT NULL COMMENT '内容',
`handler_type` VARCHAR(10) DEFAULT NULL COMMENT '处理人类型,0-区域运营,1-驻店人员,用逗号分割', `handler_type` VARCHAR(10) DEFAULT NULL COMMENT '处理人类型:0-区域运营、1-驻店人员(逗号分隔)',
`push_type` INT NOT NULL COMMENT '推送方式,0-定时推送,1-立即推送', `push_type` INT NOT NULL COMMENT '推送方式:0-定时推送、1-立即推送',
`created_by` VARCHAR(64) NOT NULL COMMENT '创建人', `created_by` VARCHAR(64) NOT NULL COMMENT '创建人',
`created_date` DATETIME NOT NULL COMMENT '创建时间', `created_date` DATETIME NOT NULL COMMENT '创建时间',
`updated_by` VARCHAR(64) DEFAULT NULL COMMENT '修改人', `updated_by` VARCHAR(64) DEFAULT NULL COMMENT '修改人',
...@@ -304,10 +304,10 @@ CREATE TABLE ods_strategy_info ( ...@@ -304,10 +304,10 @@ CREATE TABLE ods_strategy_info (
`merchant_id` INT DEFAULT NULL COMMENT '商户号', `merchant_id` INT DEFAULT NULL COMMENT '商户号',
`merchant_name` VARCHAR(255) DEFAULT NULL COMMENT '商户名称', `merchant_name` VARCHAR(255) DEFAULT NULL COMMENT '商户名称',
`biz` INT DEFAULT NULL COMMENT '业务类型:1.延保 2.轻改 3.权益 4.二手车', `biz` INT DEFAULT NULL COMMENT '业务类型:1.延保 2.轻改 3.权益 4.二手车',
`push_flag` INT DEFAULT 0 COMMENT '状态,0-未推送、1-已推送、2-未完成、3-审批中、4-执行中、5-已驳回、6-已完成', `push_flag` INT DEFAULT 0 COMMENT '状态:0-未推送、1-盯防中、2-未完成、3-审批中、4-盯防中、5-已驳回、6-已结束',
`created_uuid` VARCHAR(64) DEFAULT NULL COMMENT '创建人uuid', `created_uuid` VARCHAR(64) DEFAULT NULL COMMENT '创建人uuid',
`data_source` INT DEFAULT 1 COMMENT '数据来源,1-策略中心 2-区域督导助手小程序 3-区域运营助手小程序', `data_source` INT DEFAULT 1 COMMENT '数据来源:1-策略中心、2-区域督导助手小程序、3-区域运营助手小程序',
`data_source_id` BIGINT DEFAULT NULL COMMENT '数据来源id', `data_source_id` BIGINT DEFAULT NULL COMMENT '数据来源ID',
`etl_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT 'ETL抽取时间', `etl_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT 'ETL抽取时间',
PRIMARY KEY (id), PRIMARY KEY (id),
INDEX idx_merchant_id (merchant_id), INDEX idx_merchant_id (merchant_id),
......
...@@ -58,6 +58,9 @@ header_fill = PatternFill('solid', fgColor='BDD7EE') # 浅蓝 ...@@ -58,6 +58,9 @@ header_fill = PatternFill('solid', fgColor='BDD7EE') # 浅蓝
header_font = Font(name='微软雅黑', bold=True, color='000000', size=10) header_font = Font(name='微软雅黑', bold=True, color='000000', size=10)
sub_fill = PatternFill('solid', fgColor='BDD7EE') sub_fill = PatternFill('solid', fgColor='BDD7EE')
sub_font = Font(name='微软雅黑', bold=True, color='000000', size=10) sub_font = Font(name='微软雅黑', bold=True, color='000000', size=10)
# 产值表数据区: 浅橙色背景
orange_fill = PatternFill('solid', fgColor='FFE4C4')
orange_font = Font(name='微软雅黑', bold=True, color='000000', size=10)
data_font = Font(name='微软雅黑', size=10, color='000000') 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'),
...@@ -349,6 +352,10 @@ H_MERGE_003 = [ ...@@ -349,6 +352,10 @@ H_MERGE_003 = [
for start_col, end_col, title in H_MERGE_003: 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") 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 = tws.cell(row=1, column=start_col, value=title)
if start_col == 14:
c.font = orange_font
c.fill = orange_fill
else:
c.font = header_font c.font = header_font
c.fill = header_fill c.fill = header_fill
c.alignment = MERGED_GROUP_H c.alignment = MERGED_GROUP_H
...@@ -356,7 +363,7 @@ for start_col, end_col, title in H_MERGE_003: ...@@ -356,7 +363,7 @@ for start_col, end_col, title in H_MERGE_003:
# 独立列 (J, K, L, M, W, X, Y, AL) — row1 只有 J/W/AL 有标题 # 独立列 (J, K, L, M, W, X, Y, AL) — row1 只有 J/W/AL 有标题
STANDALONE_ROW1 = { STANDALONE_ROW1 = {
10: '主机厂交付数(标红为产值表总交付数)', 10: '主机厂交付数',
23: '是否触发兜底', 23: '是否触发兜底',
38: '总赔付金额', 38: '总赔付金额',
} }
...@@ -379,8 +386,8 @@ for col_num in [11, 12, 13, 24, 25]: ...@@ -379,8 +386,8 @@ for col_num in [11, 12, 13, 24, 25]:
ROW2_ALL = { ROW2_ALL = {
1: '门店', 2: '品牌', 3: '兜底指标', 4: '区域(省)', 5: '直营与否', 1: '门店', 2: '品牌', 3: '兜底指标', 4: '区域(省)', 5: '直营与否',
6: '区域运营', 7: '飞行督导', 8: '线上运营', 9: '特殊情况', 6: '区域运营', 7: '飞行督导', 8: '线上运营', 9: '特殊情况',
10: '主机厂交付数', 11: '主机厂', 10: '复合交付数', 11: '主机厂交付数',
12: '产值表交付数', 13: '主机厂跟产值表差距', 12: '产值交付数', 13: '主机厂跟产值表差距',
14: '门店触客数', 15: '触客率', 16: '整车延保成交订单数', 14: '门店触客数', 15: '触客率', 16: '整车延保成交订单数',
17: '整车延保渗透率', 18: '触客成交率', 19: '安心包', 17: '整车延保渗透率', 18: '触客成交率', 19: '安心包',
20: '安心包渗透率', 21: '电池', 22: '电池渗透率', 20: '安心包渗透率', 21: '电池', 22: '电池渗透率',
...@@ -393,6 +400,10 @@ ROW2_ALL = { ...@@ -393,6 +400,10 @@ ROW2_ALL = {
} }
for col_num, title in ROW2_ALL.items(): for col_num, title in ROW2_ALL.items():
c = tws.cell(row=2, column=col_num, value=title) c = tws.cell(row=2, column=col_num, value=title)
if 14 <= col_num <= 22:
c.font = orange_font
c.fill = orange_fill
else:
c.font = sub_font c.font = sub_font
c.fill = sub_fill c.fill = sub_fill
c.alignment = ROW2_ALIGN c.alignment = ROW2_ALIGN
...@@ -446,7 +457,7 @@ sample_data_003 = [ ...@@ -446,7 +457,7 @@ sample_data_003 = [
'=IF(L3>0,U3/L3,0)', # V(22) 电池渗透率 '=IF(L3>0,U3/L3,0)', # V(22) 电池渗透率
# W-Y: 兜底判断 (23-25) # W-Y: 兜底判断 (23-25)
'=IF(OR(Z3<AC3,AA3<AD3,AB3<AE3),"是","否")', # W(23) 是否触发兜底 '=IF(OR(Z3<AC3,AA3<AD3,AB3<AE3),"是","否")', # W(23) 是否触发兜底
'红色门店', # X(24) 门店等级 (003示例用红色) '=IF(E3<>"直营","服务商",IF(J3=0,"暂无交车",IF(OR(ISBLANK(Q3),Q3=""),"/",IF(Q3>=0.5,"绿色门店",IF(Q3<0.4,"红色门店","黄色门店")))))', # X(24) 门店等级
'触客', # Y(25) 兜底类型 '触客', # Y(25) 兜底类型
# Z-AB: 当前转化率 (26-28) — 003公式: 优先N3, 否则L3 # Z-AB: 当前转化率 (26-28) — 003公式: 优先N3, 否则L3
'=IF($N3>0,P3/$N3,IF($L3>0,P3/$L3,0))', # Z(26) 整车延保转化率 '=IF($N3>0,P3/$N3,IF($L3>0,P3/$L3,0))', # Z(26) 整车延保转化率
...@@ -485,18 +496,20 @@ for col_idx, val in enumerate(sample_data_003, 1): ...@@ -485,18 +496,20 @@ for col_idx, val in enumerate(sample_data_003, 1):
tws.row_dimensions[3].height = 18 tws.row_dimensions[3].height = 18
# ── 条件格式 (与003一致) ── # ── 条件格式 (与003一致) ──
# X3:X1000 门店等级变色 # X3:X1000 门店等级变色(背景填充)
tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="红色门店"'], fill=PatternFill('solid', fgColor='FFC7CE')))
tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="绿色门店"'], fill=PatternFill('solid', fgColor='C6EFCE')))
tws.conditional_formatting.add('X3:X1000', tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="红色门店"'], font=Font(color='000000'))) FormulaRule(formula=['$X3="黄色门店"'], fill=PatternFill('solid', fgColor='FFEB9C')))
tws.conditional_formatting.add('X3:X1000', tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="绿色门店"'], font=Font(color='000000'))) FormulaRule(formula=['$X3="服务商"'], fill=PatternFill('solid', fgColor='E2EFDA')))
tws.conditional_formatting.add('X3:X1000', tws.conditional_formatting.add('X3:X1000',
FormulaRule(formula=['$X3="黄色门店"'], font=Font(color='000000'))) FormulaRule(formula=['$X3="暂无交车"'], fill=PatternFill('solid', fgColor='D9D9D9')))
# W3:W1000 触发兜底标红 # W3:W1000 触发兜底标红(背景填充)
tws.conditional_formatting.add('W3:W1000', tws.conditional_formatting.add('W3:W1000',
FormulaRule(formula=['$W3="是"'], FormulaRule(formula=['$W3="是"'], fill=PatternFill('solid', fgColor='FF6B6B')))
font=Font(bold=True, color='000000'),
fill=PatternFill('solid', fgColor='FF6B6B')))
tws.freeze_panes = 'A3' tws.freeze_panes = 'A3'
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!