Commit 8ec096fc by 江名洋

refactor: 统一模板命名规范并调整鸿蒙模板行号

1 parent e33f8378
Showing 29 changed files with 160 additions and 43 deletions
...@@ -186,16 +186,16 @@ async def run_dw_sync_get( ...@@ -186,16 +186,16 @@ async def run_dw_sync_get(
XLSX_DIR = os.path.join("app", "templates", "xlsx") XLSX_DIR = os.path.join("app", "templates", "xlsx")
def _find_latest_wenjie_template(): def _find_latest_wenjie_template():
"""返回最新的问界门店数据模板(最大序号),无带序号文件时回退到旧版""" """返回最新的问界门店数据模板(最大序号),无带序号文件时回退到默认"""
max_no = 0 max_no = 0
for f in glob.glob(os.path.join(XLSX_DIR, "问界门店数据模板[0-9][0-9][0-9].xlsx")): for f in glob.glob(os.path.join(XLSX_DIR, "门店数据-问界-模板[0-9][0-9][0-9].xlsx")):
m = re.search(r"问界门店数据模板(\d{3})\.xlsx", os.path.basename(f)) m = re.search(r"门店数据-问界-模板(\d{3})\.xlsx", os.path.basename(f))
if m: if m:
max_no = max(max_no, int(m.group(1))) max_no = max(max_no, int(m.group(1)))
if max_no > 0: if max_no > 0:
return os.path.join(XLSX_DIR, f"问界门店数据模板{max_no:03d}.xlsx") return os.path.join(XLSX_DIR, f"门店数据-问界-模板{max_no:03d}.xlsx")
# 回退到旧版模板 # 回退到默认模板
fallback = os.path.join(XLSX_DIR, "门店数据-模板0625.xlsx") fallback = os.path.join(XLSX_DIR, "门店数据-问界-模板001.xlsx")
if os.path.exists(fallback): if os.path.exists(fallback):
return fallback return fallback
return None return None
...@@ -205,8 +205,8 @@ async def download_analysis_template(template_type: str): ...@@ -205,8 +205,8 @@ async def download_analysis_template(template_type: str):
"""下载分析模板文件""" """下载分析模板文件"""
template_map = { template_map = {
# store 使用动态查找最新带序号的模板 # store 使用动态查找最新带序号的模板
"factory": "主机厂数据-模板.xlsx", "factory": "主机厂数据-问界-模板001.xlsx",
"output": "输出-问界生态系数-模板0625.xlsx", "output": "输出模板-问界-模板001.xlsx",
} }
if template_type == "store": if template_type == "store":
...@@ -392,9 +392,9 @@ async def analysis_download(file: str = Query(None)): ...@@ -392,9 +392,9 @@ async def analysis_download(file: str = Query(None)):
async def download_harmony_template(template_type: str): async def download_harmony_template(template_type: str):
"""下载鸿蒙分析模板文件""" """下载鸿蒙分析模板文件"""
template_map = { template_map = {
"store": "鸿蒙门店数据-模板.xlsx", "store": "门店数据-鸿蒙-模板001.xlsx",
"factory": "鸿蒙主机厂数据-模板.xlsx", "factory": "主机厂数据-鸿蒙-模板001.xlsx",
"output": "输出-鸿蒙生态系数-模板.xlsx", "output": "输出模板-鸿蒙-模板001.xlsx",
} }
filename = template_map.get(template_type) filename = template_map.get(template_type)
if not filename: if not filename:
...@@ -451,7 +451,7 @@ async def harmony_generate( ...@@ -451,7 +451,7 @@ async def harmony_generate(
# 门店兜底配置:未上传时使用默认模板 # 门店兜底配置:未上传时使用默认模板
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, "鸿蒙门店数据-模板.xlsx") default_store = os.path.join(XLSX_DIR, "门店数据-鸿蒙-模板001.xlsx")
if os.path.exists(default_store): if os.path.exists(default_store):
_harmony_store_file = default_store _harmony_store_file = default_store
else: else:
......
...@@ -545,6 +545,12 @@ class AnalysisService: ...@@ -545,6 +545,12 @@ class AnalysisService:
AND deleted_flag = 'N' AND deleted_flag = 'N'
""" """
# 输出实际执行的SQL,方便定位问题
_debug_sql = sql
for p in (*store_names,):
_debug_sql = _debug_sql.replace("%s", repr(p), 1)
logger.info(f"_query_store_info SQL:\n{_debug_sql}")
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute(sql, (*store_names,)) cur.execute(sql, (*store_names,))
rows = cur.fetchall() rows = cur.fetchall()
...@@ -752,7 +758,7 @@ class AnalysisService: ...@@ -752,7 +758,7 @@ class AnalysisService:
""" """
import shutil import shutil
TEMPLATE_FILE = os.path.join("app", "templates", "xlsx", "输出-问界生态系数-模板0625.xlsx") TEMPLATE_FILE = os.path.join("app", "templates", "xlsx", "输出模板-问界-模板001.xlsx")
TEMPLATE_SHEET = "模板" TEMPLATE_SHEET = "模板"
if not os.path.exists(TEMPLATE_FILE): if not os.path.exists(TEMPLATE_FILE):
......
...@@ -36,9 +36,8 @@ THIN_BORDER = Border( ...@@ -36,9 +36,8 @@ THIN_BORDER = Border(
top=Side(style="thin"), bottom=Side(style="thin") top=Side(style="thin"), bottom=Side(style="thin")
) )
# 百分比列(1-indexed) # 百分比列(1-indexed,38列模板)
PERCENT_COLS = {13, 16, 18, 20, 22, 24, 26, 30, 31, 32, 33, 34, 35} PERCENT_COLS = {15, 17, 18, 20, 22, 26, 27, 28, 29, 30, 31}
COEFF_COLS = {27, 28, 29}
def _safe_float(val, default=0.0): def _safe_float(val, default=0.0):
...@@ -340,6 +339,12 @@ class HarmonyAnalysisService: ...@@ -340,6 +339,12 @@ class HarmonyAnalysisService:
params = [start_date, end_date, FIRST_BRAND_ID] + list(HARMONY_BRAND_IDS) + list(store_names) params = [start_date, end_date, FIRST_BRAND_ID] + list(HARMONY_BRAND_IDS) + list(store_names)
# 输出实际执行的SQL(参数替换%s),方便定位问题
_debug_sql = sql
for p in params:
_debug_sql = _debug_sql.replace("%s", repr(p), 1)
logger.info(f"Harmony DB query SQL:\n{_debug_sql}")
with conn.cursor() as cur: with conn.cursor() as cur:
cur.execute(sql, params) cur.execute(sql, params)
rows = cur.fetchall() rows = cur.fetchall()
...@@ -396,7 +401,7 @@ class HarmonyAnalysisService: ...@@ -396,7 +401,7 @@ class HarmonyAnalysisService:
import shutil import shutil
import time import time
TEMPLATE_FILE = os.path.join("app", "templates", "xlsx", "输出-鸿蒙生态系数-模板.xlsx") TEMPLATE_FILE = os.path.join("app", "templates", "xlsx", "输出模板-鸿蒙-模板002.xlsx")
TEMPLATE_SHEET = "模板" TEMPLATE_SHEET = "模板"
if not os.path.exists(TEMPLATE_FILE): if not os.path.exists(TEMPLATE_FILE):
...@@ -467,11 +472,8 @@ class HarmonyAnalysisService: ...@@ -467,11 +472,8 @@ 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)
# 自动筛选 # 自动筛选(保留模板的分组合并单元格)
from openpyxl.utils import get_column_letter from openpyxl.utils import get_column_letter
for merged_range in list(ws.merged_cells.ranges):
if merged_range.min_row == 1 and merged_range.max_row == 1:
ws.unmerge_cells(str(merged_range))
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"A3:{last_col}{next_row - 1}"
...@@ -484,7 +486,7 @@ class HarmonyAnalysisService: ...@@ -484,7 +486,7 @@ class HarmonyAnalysisService:
formula_map = {} formula_map = {}
skip_external_cols = set() skip_external_cols = set()
for col in range(1, ws.max_column + 1): for col in range(1, ws.max_column + 1):
cell = ws.cell(row=4, column=col) cell = ws.cell(row=3, column=col)
raw = cell.value raw = cell.value
if raw is None: if raw is None:
continue continue
...@@ -502,13 +504,13 @@ class HarmonyAnalysisService: ...@@ -502,13 +504,13 @@ class HarmonyAnalysisService:
@staticmethod @staticmethod
def _clear_sheet_data(ws): def _clear_sheet_data(ws):
for r in range(4, ws.max_row + 1): for r in range(3, ws.max_row + 1):
for c in range(1, ws.max_column + 1): for c in range(1, ws.max_column + 1):
ws.cell(row=r, column=c).value = None ws.cell(row=r, column=c).value = None
@staticmethod @staticmethod
def _write_data_rows(ws, merged_df, db_perf, formula_map, skip_external_cols, def _write_data_rows(ws, merged_df, db_perf, formula_map, skip_external_cols,
start_date=None, end_date=None, start_row=4): start_date=None, end_date=None, start_row=3):
"""写入数据行到模板""" """写入数据行到模板"""
def _style_cell(r, c, value): def _style_cell(r, c, value):
...@@ -519,13 +521,9 @@ class HarmonyAnalysisService: ...@@ -519,13 +521,9 @@ class HarmonyAnalysisService:
if isinstance(value, (int, float)): if isinstance(value, (int, float)):
if c in PERCENT_COLS: if c in PERCENT_COLS:
cell.number_format = '0.00%' cell.number_format = '0.00%'
elif c in COEFF_COLS: elif c == 38: # 总赔付金额
cell.number_format = '0.0'
elif c == 25: # 累计成交金额
cell.number_format = '#,##0'
elif c == 44: # 赔付总金额
cell.number_format = '#,##0' cell.number_format = '#,##0'
elif c not in (36, 43): elif c not in (23,):
cell.number_format = '0' cell.number_format = '0'
return cell return cell
...@@ -729,7 +727,7 @@ class HarmonyAnalysisService: ...@@ -729,7 +727,7 @@ class HarmonyAnalysisService:
if col_idx in (30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45): if col_idx in (30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45):
continue continue
adjusted = re.sub( adjusted = re.sub(
r'([A-Z]{1,3})4\b', r'([A-Z]{1,3})3\b',
lambda m: f'{m.group(1)}{row_num}', lambda m: f'{m.group(1)}{row_num}',
formula_text formula_text
) )
......
...@@ -72,7 +72,7 @@ ...@@ -72,7 +72,7 @@
🚀 开始生成分析报表 🚀 开始生成分析报表
</button> </button>
<p style="font-size:12px; color:#999; margin-top:8px;">门店按兜底截止日期分组:月底/25日→生态数据sheet,其余→自然月sheet</p> <p style="font-size:12px; color:#999; margin-top:8px;">门店按兜底截止日期分组:月底/25日→生态数据sheet,其余→自然月sheet</p>
<p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 问界门店数据模板(最新序号)</p> <p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 门店数据-问界-模板(最新序号)</p>
</div> </div>
<!-- 生成结果提示 --> <!-- 生成结果提示 -->
......
...@@ -70,7 +70,7 @@ ...@@ -70,7 +70,7 @@
&#x1f680; 生成鸿蒙生态分析报表 &#x1f680; 生成鸿蒙生态分析报表
</button> </button>
<p style="font-size:12px; color:#999; margin-top:8px;">合并门店兜底配置 + 主机厂交付数据 + 数据库产值指标,计算渗透率达标系数和赔付金额</p> <p style="font-size:12px; color:#999; margin-top:8px;">合并门店兜底配置 + 主机厂交付数据 + 数据库产值指标,计算渗透率达标系数和赔付金额</p>
<p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 输出-鸿蒙生态系数-模板.xlsx</p> <p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 输出模板-鸿蒙-模板001.xlsx</p>
</div> </div>
<!-- 结果提示 --> <!-- 结果提示 -->
......
# -*- 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]}')
...@@ -7,8 +7,8 @@ ...@@ -7,8 +7,8 @@
从主机厂数据表提取: 省份、城市、门店编号、用户中心门店名称、门店名称、交车数量 从主机厂数据表提取: 省份、城市、门店编号、用户中心门店名称、门店名称、交车数量
输出: 输出:
- app/templates/xlsx/鸿蒙门店数据-模板{序号}.xlsx - app/templates/xlsx/门店数据-鸿蒙-模板{序号}.xlsx
- app/templates/xlsx/鸿蒙主机厂数据-模板{序号}.xlsx - app/templates/xlsx/主机厂数据-鸿蒙-模板{序号}.xlsx
注意: 鸿蒙没有生态店的概念,所有兜底计算周期都是自然月 注意: 鸿蒙没有生态店的概念,所有兜底计算周期都是自然月
""" """
...@@ -22,22 +22,22 @@ SRC = r'C:\Users\jiata\Desktop\「会议标注」鸿蒙7月1-5号(含主机厂 ...@@ -22,22 +22,22 @@ SRC = r'C:\Users\jiata\Desktop\「会议标注」鸿蒙7月1-5号(含主机厂
# ── 自动递增序号 ── # ── 自动递增序号 ──
max_no = 0 max_no = 0
for f in glob.glob('app/templates/xlsx/鸿蒙门店数据-模板[0-9][0-9][0-9].xlsx'): for f in glob.glob('app/templates/xlsx/门店数据-鸿蒙-模板[0-9][0-9][0-9].xlsx'):
try: try:
no = int(os.path.splitext(os.path.basename(f))[0][-3:]) no = int(os.path.splitext(os.path.basename(f))[0][-3:])
max_no = max(max_no, no) max_no = max(max_no, no)
except ValueError: except ValueError:
pass pass
STORE_OUT = f'app/templates/xlsx/鸿蒙门店数据-模板{max_no + 1:03d}.xlsx' STORE_OUT = f'app/templates/xlsx/门店数据-鸿蒙-模板{max_no + 1:03d}.xlsx'
max_no2 = 0 max_no2 = 0
for f in glob.glob('app/templates/xlsx/鸿蒙主机厂数据-模板[0-9][0-9][0-9].xlsx'): for f in glob.glob('app/templates/xlsx/主机厂数据-鸿蒙-模板[0-9][0-9][0-9].xlsx'):
try: try:
no = int(os.path.splitext(os.path.basename(f))[0][-3:]) no = int(os.path.splitext(os.path.basename(f))[0][-3:])
max_no2 = max(max_no2, no) max_no2 = max(max_no2, no)
except ValueError: except ValueError:
pass pass
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='4472C4')
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
从 赔付方案 提取: 需达标转化率、赔付金额(非阶梯赔付)、兜底截止日期 从 赔付方案 提取: 需达标转化率、赔付金额(非阶梯赔付)、兜底截止日期
从 阶梯赔付明细子表 解析: 阶梯赔付门店的赔付系数公式 → "阈值%,金额"格式 从 阶梯赔付明细子表 解析: 阶梯赔付门店的赔付系数公式 → "阈值%,金额"格式
输出: app/templates/问界门店数据模板{序号}.xlsx 输出: app/templates/门店数据-问界-模板{序号}.xlsx
""" """
import sys, io, re, math import sys, io, re, math
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
...@@ -18,16 +18,16 @@ from openpyxl.utils import get_column_letter ...@@ -18,16 +18,16 @@ from openpyxl.utils import get_column_letter
SRC = r'C:\Users\jiata\Desktop\问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx' SRC = r'C:\Users\jiata\Desktop\问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx'
# 自动递增三位序号: 问界门店数据模板001.xlsx, 002.xlsx, ... # 自动递增三位序号: 门店数据-问界-模板001.xlsx, 002.xlsx, ...
import os, glob import os, glob
max_no = 0 max_no = 0
for f in glob.glob('app/templates/xlsx/问界门店数据模板[0-9][0-9][0-9].xlsx'): for f in glob.glob('app/templates/xlsx/门店数据-问界-模板[0-9][0-9][0-9].xlsx'):
try: try:
no = int(os.path.splitext(os.path.basename(f))[0][-3:]) no = int(os.path.splitext(os.path.basename(f))[0][-3:])
max_no = max(max_no, no) max_no = max(max_no, no)
except ValueError: except ValueError:
pass pass
OUT = f'app/templates/xlsx/问界门店数据模板{max_no + 1:03d}.xlsx' OUT = f'app/templates/xlsx/门店数据-问界-模板{max_no + 1:03d}.xlsx'
# ── 1. 读取主表门店信息 ── # ── 1. 读取主表门店信息 ──
wb = load_workbook(SRC, data_only=True) wb = load_workbook(SRC, data_only=True)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!