Commit 093303a9 by 江名洋

refactor(analysis): 合并主机厂上传为单文件并完善报表计算列

1 parent a8414f4c
# -*- coding: utf-8 -*-
"""检查输出模板的合并单元格和表头状态"""
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl
path = "app/templates/xlsx/输出模板-问界-模板001.xlsx"
wb = openpyxl.load_workbook(path)
ws = wb["模板"]
print(f"Sheet: {ws.title}, max_row={ws.max_row}, max_col={ws.max_column}")
print(f"\n=== 合并单元格 ({len(ws.merged_cells.ranges)}个) ===")
for mr in sorted(ws.merged_cells.ranges, key=lambda x: (x.min_row, x.min_col)):
val = ws.cell(row=mr.min_row, column=mr.min_col).value
print(f" Row {mr.min_row}: col {mr.min_col}-{mr.max_col} ({'A-Z'[mr.min_col-1:mr.max_col]}) = {repr(val)[:60]}")
print(f"\n=== 第1行内容 ===")
for c in range(1, ws.max_column + 1):
v = ws.cell(row=1, column=c).value
if v is not None:
print(f" col {c} ({chr(64+c) if c<=26 else 'A'+chr(64+c-26)}): {repr(v)[:80]}")
print(f"\n=== 第2行内容 ===")
for c in range(1, ws.max_column + 1):
v = ws.cell(row=2, column=c).value
if v is not None:
print(f" col {c}: {repr(v)[:80]}")
print(f"\n=== 第3行内容 ===")
for c in range(1, ws.max_column + 1):
v = ws.cell(row=3, column=c).value
print(f" col {c}: {v}")
# -*- coding: utf-8 -*-
"""检查输出模板-问界-模板002.xlsx 的表头和数据对齐情况"""
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl
path = "app/templates/xlsx/输出模板-问界-模板002.xlsx"
wb = openpyxl.load_workbook(path, data_only=False)
print(f"Sheets: {wb.sheetnames}")
for name in wb.sheetnames:
ws = wb[name]
print(f"\n{'='*70}")
print(f"Sheet: '{name}' (max_row={ws.max_row}, max_col={ws.max_column})")
print('='*70)
# 合并单元格
print(f"\n--- 合并单元格 ({len(ws.merged_cells.ranges)}个) ---")
for mr in sorted(ws.merged_cells.ranges, key=lambda x: (x.min_row, x.min_col)):
val = ws.cell(row=mr.min_row, column=mr.min_col).value
print(f" Row {mr.min_row}: col {mr.min_col}-{mr.max_col} = {repr(val)[:60]}")
# 前6行内容
print(f"\n--- 前6行内容 ---")
for r in range(1, min(7, ws.max_row + 1)):
row_vals = []
for c in range(1, ws.max_column + 1):
v = ws.cell(row=r, column=c).value
row_vals.append(f"c{c}={repr(v)[:25]}" if v is not None else f"c{c}=—")
print(f" Row {r}: {' | '.join(row_vals)}")
# 检查第4行是否为公式行
print(f"\n--- 第4行公式检查 ---")
for c in range(1, ws.max_column + 1):
v = ws.cell(row=4, column=c).value
if v is not None and isinstance(v, str) and v.startswith('='):
print(f" col {c}: {v[:80]}")
# -*- coding: utf-8 -*-
"""强制重写输出模板表头:清除所有合并单元格,重写第1/2/3行"""
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
path = "app/templates/xlsx/输出模板-问界-模板001.xlsx"
wb = openpyxl.load_workbook(path)
ws = wb["模板"]
# 1. 强制取消所有合并单元格
all_merges = list(ws.merged_cells.ranges)
print(f"取消 {len(all_merges)} 个合并单元格")
for mr in all_merges:
ws.unmerge_cells(str(mr))
# 2. 强制清除第1-3行所有单元格的值和样式
for r in range(1, 4):
for c in range(1, 60):
cell = ws.cell(row=r, column=c)
cell.value = None
# 新表头(57列)
OUTPUT_HEADERS = [
"门店名", "兜底指标", "兜底类型", "特殊情况1", "特殊情况2",
"区域(省)", "直营与否", "区域运营", "飞行督导", "线上运营",
"交付数", "整车延保采购数", "安心包采购数", "电池延保采购数", "轮胎险采购数",
"无忧套餐采购数", "单车产值",
"产值", "单车产值2", "交付数2", "触客数", "触客率", "整车延保成交订单数", "安心包订单总成交数",
"电池延保订单成交数", "轮胎险订单成交数", "整车延保渗透率", "安心包总渗透率",
"电池延保渗透率", "轮胎险渗透率",
"整车延保渗透率达标系数", "安心包渗透率达标系数", "电池延保渗透率达标系数", "总分",
"整车延保(差异)", "安心包(差异)", "电池(差异)",
"整车延保2", "安心包2", "电池2",
"整车延保3", "安心包3", "电池3",
"是否触发兜底",
"整车延保4", "安心包4", "电池4",
"整车延保5", "安心包5", "电池5",
"是否需要赔付",
"赔付总金额",
"兜底月份",
"门店等级",
"人工审核",
"备注(已确定赔付金额)\n人工确定",
"去除服务商",
]
HEADER_FILL = PatternFill("solid", fgColor="4472C4")
HEADER_FONT = Font(name="微软雅黑", bold=True, color="FFFFFF", size=10)
GROUP_FILL = PatternFill("solid", fgColor="D6E4F0")
GROUP_FONT = Font(name="微软雅黑", bold=True, size=10)
THIN_BORDER = Border(
left=Side(style="thin"), right=Side(style="thin"),
top=Side(style="thin"), bottom=Side(style="thin")
)
# 3. 写入第1行分组标签
GROUP_LABELS = [
("基础门店信息\n标红为主机厂无数据,取产值表交付数为分母", 0, 9),
("主机厂数据", 10, 16),
("产值表数据", 17, 29),
("生态系数", 30, 33),
("主机厂采购差异\n主机厂-产值表系统订单数", 34, 36),
("当前转化率", 37, 39),
("需达标转化率", 40, 42),
("需达标订单数差额", 44, 46),
("赔付金额\n(成本价:整车*0.55+安心包*0.65+电池*0.65)", 47, 49),
("人工核对列", 54, 56),
]
for label, start_col, end_col in GROUP_LABELS:
if start_col <= end_col:
cell = ws.cell(row=1, column=start_col + 1, value=label)
cell.font = GROUP_FONT
cell.fill = GROUP_FILL
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.border = THIN_BORDER
# 填充中间单元格样式
for c in range(start_col + 2, end_col + 2):
mid = ws.cell(row=1, column=c)
mid.fill = GROUP_FILL
mid.border = THIN_BORDER
if end_col > start_col:
ws.merge_cells(start_row=1, start_column=start_col + 1,
end_row=1, end_column=end_col + 1)
# col 43 (是否触发兜底) 单列无分组,设样式
c43 = ws.cell(row=1, column=44)
c43.fill = GROUP_FILL
c43.border = THIN_BORDER
# col 51 (是否需要赔付) 单列
c51 = ws.cell(row=1, column=51)
c51.fill = GROUP_FILL
c51.border = THIN_BORDER
# col 53 (兜底月份) 单列
c53 = ws.cell(row=1, column=53)
c53.fill = GROUP_FILL
c53.border = THIN_BORDER
# 4. 第2行:产值表数据范围的备注
c2_18 = ws.cell(row=2, column=18, value="月度渗透率(分母为主机厂交付数)")
c2_18.font = Font(name="微软雅黑", size=9, color="666666")
c2_18.alignment = Alignment(horizontal="center", vertical="center")
ws.merge_cells(start_row=2, start_column=18, end_row=2, end_column=30)
# 5. 写入第3行列名
for i, header in enumerate(OUTPUT_HEADERS):
cell = ws.cell(row=3, column=i + 1, value=header)
cell.font = HEADER_FONT
cell.fill = HEADER_FILL
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.border = THIN_BORDER
# 6. 清除第4行(旧公式)
for c in range(1, 60):
ws.cell(row=4, column=c).value = None
wb.save(path)
print("模板强制重写完成")
print(f"第3行列数: {len(OUTPUT_HEADERS)}")
# 验证
wb2 = openpyxl.load_workbook(path)
ws2 = wb2["模板"]
print(f"max_col={ws2.max_column}")
print("\n第3行:")
for c in range(1, ws2.max_column + 1):
print(f" col {c}: {ws2.cell(row=3, column=c).value}")
print(f"\n合并单元格: {len(ws2.merged_cells.ranges)}个")
for mr in sorted(ws2.merged_cells.ranges, key=lambda x: (x.min_row, x.min_col)):
val = ws2.cell(row=mr.min_row, column=mr.min_col).value
print(f" Row {mr.min_row}: col {mr.min_col}-{mr.max_col} = {repr(val)[:50]}")
# -*- coding: utf-8 -*-
"""临时脚本:检查模板文件结构"""
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl
def inspect(path, label, max_row=5):
print(f"\n{'='*60}")
print(f"{label}: {path}")
print('='*60)
wb = openpyxl.load_workbook(path, data_only=False)
print(f"Sheets: {wb.sheetnames}")
for name in wb.sheetnames:
ws = wb[name]
print(f"\n--- Sheet: '{name}' (max_row={ws.max_row}, max_col={ws.max_column}) ---")
for r_idx, row in enumerate(ws.iter_rows(min_row=1, max_row=min(max_row, ws.max_row), values_only=True), start=1):
cells = [str(c) if c is not None else "" for c in row]
print(f" Row {r_idx}: {' | '.join(cells)}")
# 新主机厂模板
inspect("app/templates/xlsx/主机厂数据-问界-模板002.xlsx", "新主机厂模板002", max_row=4)
# 旧主机厂模板(对比)
inspect("app/templates/xlsx/主机厂数据-问界-模板001.xlsx", "旧主机厂模板001", max_row=4)
# 当前输出模板
inspect("app/templates/xlsx/输出模板-问界-模板001.xlsx", "输出模板001", max_row=5)
# -*- coding: utf-8 -*-
"""临时脚本:更新输出模板-问界-模板001.xlsx 的表头以匹配新列结构"""
import sys, io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
path = "app/templates/xlsx/输出模板-问界-模板001.xlsx"
wb = openpyxl.load_workbook(path)
ws = wb["模板"]
# 新表头(57列)
OUTPUT_HEADERS = [
# 基础门店信息 (A-J, col 1-10)
"门店名", "兜底指标", "兜底类型", "特殊情况1", "特殊情况2",
"区域(省)", "直营与否", "区域运营", "飞行督导", "线上运营",
# 主机厂数据 (K-Q, col 11-17)
"交付数", "整车延保采购数", "安心包采购数", "电池延保采购数", "轮胎险采购数",
"无忧套餐采购数", "单车产值",
# 产值表数据 (R-AD, col 18-30)
"产值", "单车产值2", "交付数2", "触客数", "触客率", "整车延保成交订单数", "安心包订单总成交数",
"电池延保订单成交数", "轮胎险订单成交数", "整车延保渗透率", "安心包总渗透率",
"电池延保渗透率", "轮胎险渗透率",
# 生态系数 (AE-AH, col 31-34)
"整车延保渗透率达标系数", "安心包渗透率达标系数", "电池延保渗透率达标系数", "总分",
# 主机厂采购差异 (AI-AK, col 35-37)
"整车延保(差异)", "安心包(差异)", "电池(差异)",
# 当前转化率 (AL-AN, col 38-40)
"整车延保2", "安心包2", "电池2",
# 需达标转化率 (AO-AQ, col 41-43)
"整车延保3", "安心包3", "电池3",
# 是否触发兜底 (AR, col 44)
"是否触发兜底",
# 需达标订单数差额 (AS-AU, col 45-47)
"整车延保4", "安心包4", "电池4",
# 赔付金额 (AV-AX, col 48-50)
"整车延保5", "安心包5", "电池5",
# 是否需要赔付 (AY, col 51)
"是否需要赔付",
# 赔付总金额 (AZ, col 52)
"赔付总金额",
# 兜底月份 (BA, col 53)
"兜底月份",
# 门店等级 (BB, col 54)
"门店等级",
# 人工审核 (BC, col 55)
"人工审核",
# 备注 (BD, col 56)
"备注(已确定赔付金额)\n人工确定",
# 去除服务商 (BE, col 57)
"去除服务商",
]
print(f"Total headers: {len(OUTPUT_HEADERS)}")
# 样式定义
HEADER_FILL = PatternFill("solid", fgColor="4472C4")
HEADER_FONT = Font(name="微软雅黑", bold=True, color="FFFFFF", size=10)
GROUP_FILL = PatternFill("solid", fgColor="D6E4F0")
GROUP_FONT = Font(name="微软雅黑", bold=True, size=10)
THIN_BORDER = Border(
left=Side(style="thin"), right=Side(style="thin"),
top=Side(style="thin"), bottom=Side(style="thin")
)
# 1. 先清除所有合并单元格(第1行和第3行)
merged_to_remove = []
for mr in list(ws.merged_cells.ranges):
if mr.min_row <= 3 and mr.max_row <= 3:
merged_to_remove.append(str(mr))
for mr_str in merged_to_remove:
ws.unmerge_cells(mr_str)
print(f"Unmerged {len(merged_to_remove)} ranges in rows 1-3")
# 2. 清除第1行和第3行所有单元格内容
for col in range(1, 60):
try:
ws.cell(row=1, column=col).value = None
except Exception:
pass
try:
ws.cell(row=3, column=col).value = None
except Exception:
pass
# 3. 写入第1行分组标签
GROUP_LABELS = [
("基础门店信息\n标红为主机厂无数据,取产值表交付数为分母", 0, 9),
("主机厂数据", 10, 16),
("产值表数据", 17, 29),
("生态系数", 30, 33),
("主机厂采购差异\n主机厂-产值表系统订单数", 34, 36),
("当前转化率", 37, 39),
("需达标转化率", 40, 42),
("需达标订单数差额", 44, 46),
("赔付金额\n(成本价:整车*0.55+安心包*0.65+电池*0.65)", 47, 49),
("人工核对列", 54, 56),
]
for label, start_col, end_col in GROUP_LABELS:
if start_col <= end_col:
cell = ws.cell(row=1, column=start_col + 1, value=label)
cell.font = GROUP_FONT
cell.fill = GROUP_FILL
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.border = THIN_BORDER
if end_col > start_col:
ws.merge_cells(
start_row=1, start_column=start_col + 1,
end_row=1, end_column=end_col + 1
)
# 4. 写入第3行列名
for i, header in enumerate(OUTPUT_HEADERS):
cell = ws.cell(row=3, column=i + 1, value=header)
cell.font = HEADER_FONT
cell.fill = HEADER_FILL
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
cell.border = THIN_BORDER
# 5. 更新第4行示例公式中的列引用(旧列号→新列号,偏移+3)
# 旧结构中关键列: K(11)交付数, L(12)整车延保, U(21)整车延保成交, V(22)安心包成交, W(23)电池延保成交, X(24)轮胎险成交
# 新结构中: K(11)交付数, L(12)整车延保, W(23)整车延保成交, X(24)安心包成交, Y(25)电池延保成交, Z(26)轮胎险成交
# 渗透率公式 U/K→W/K, V/K→X/K, W/K→Y/K, X/K→Z/K
# 当前转化率 U/K→W/K, V/K→X/K, W/K→Y/K; U/S→W/T, V/S→X/T, W/S→Y/T (S触客→T触客因+3偏移,但交付数2从P(16)→T(20))
# 注意:旧 P(16)交付数2 → 新 T(20)交付数2; 旧 Q(17)触客数 → 新 U(21)触客数
# 需要更新第4行所有公式
import re
col_offset_map = {
# 旧列号(字母)→新列号(字母),基于+3偏移(P→S, Q→T, R→U, S→V, T→W, U→X, V→Y, W→Z, X→AA...)
# 但主机厂数据列K-Q不变(11-17),所以K-Q保持不变
# 产值表数据列从旧P(16)开始→新R(18)开始,偏移+2
# 实际:旧P=新T? 不对。让我重新算。
# 旧: P(16)交付数2, Q(17)触客数, R(18)触客率, S(19)整车延保成交, T(20)安心包成交, U(21)电池延保成交, V(22)轮胎险成交
# W(23)整车延保渗透率, X(24)安心包渗透率, Y(25)电池延保渗透率, Z(26)轮胎险渗透率
# 新: R(18)产值, S(19)单车产值2, T(20)交付数2, U(21)触客数, V(22)触客率, W(23)整车延保成交, X(24)安心包成交
# Y(25)电池延保成交, Z(26)轮胎险成交, AA(27)整车延保渗透率, AB(28)安心包渗透率, AC(29)电池延保渗透率, AD(30)轮胎险渗透率
# 所以旧P→新T, 旧Q→新U, 旧R→新V, 旧S→新W, 旧T→新X, 旧U→新Y, 旧V→新Z
# 旧W→新AA, 旧X→新AB, 旧Y→新AC, 旧Z→新AD
# 后续列也+3(因为新增了3列:无忧套餐、单车产值、产值+单车产值2 = 实际新增4列,但主机厂数据区新增2列,产值表区新增2列)
# 旧AA(27)→新AE(31), 旧AB(28)→新AF(32)... 全部+4?
# 不对。旧总共54列,新总共57列,差3列。主机厂区+2(无忧套餐、单车产值),产值表区+2(产值、单车产值2),但"单车产值"在主机厂区,所以净增3列(无忧套餐+单车产值+产值,单车产值2替代了原单车产值位置?)
# 实际:原无"单车产值"列,新增"无忧套餐采购数"(+1)、"单车产值"(+1)、"产值"(+1)、"单车产值2"(+1) = +4列?但OUTPUT_HEADERS从54→57只+3。
# 检查:原OUTPUT_HEADERS有"交付数2"在col16,现在"交付数2"在col20,偏移+4。但前面主机厂区新增2列(无忧套餐、单车产值),产值表区新增2列(产值、单车产值2),总共+4。
# 但原OUTPUT_HEADERS是54列,新的是57列,差3。说明原来就少了1列?不对,让我重新数原OUTPUT_HEADERS...
# 原来是54项。现在57项。差3。主机厂区+2(无忧套餐、单车产值),产值表区+1(产值,单车产值2是新名替代原无)。
# 所以偏移:K-Q(11-17)不变;R开始(产值表) 偏移+2(因为主机厂区+2);后续生态系数等再+1(产值表区+1)= 总偏移+3
}
# 由于公式更新复杂,且第4行是示例数据行会被清除,这里直接清除第4行公式(代码会从formula_map重新提取)
# 实际上_build_report会先提取formula_map再清除数据,所以需要保留正确的公式
# 但公式列号已变,旧公式会引用错误列。最安全的做法:清除第4行所有公式,让代码用Python值计算
for col in range(1, 58):
ws.cell(row=4, column=col).value = None
# 6. 重新写入第4行基础示例(仅门店名,其余由代码填充)
ws.cell(row=4, column=1).value = "示例门店"
ws.cell(row=4, column=49).value = "25日" # 兜底月份
wb.save(path)
print("模板更新完成")
print(f"Row 3 headers: {[ws.cell(row=3, column=c).value for c in range(1, 58)]}")
...@@ -333,7 +333,7 @@ async def download_analysis_template(template_type: str): ...@@ -333,7 +333,7 @@ async def download_analysis_template(template_type: str):
"""下载分析模板文件""" """下载分析模板文件"""
template_map = { template_map = {
# store 使用动态查找最新带序号的模板 # store 使用动态查找最新带序号的模板
"factory": "主机厂数据-问界-模板001.xlsx", "factory": "主机厂数据-问界-模板002.xlsx",
"output": "输出模板-问界-模板001.xlsx", "output": "输出模板-问界-模板001.xlsx",
} }
...@@ -364,8 +364,7 @@ async def download_analysis_template(template_type: str): ...@@ -364,8 +364,7 @@ async def download_analysis_template(template_type: str):
_analysis_store_file = None # 缓存门店文件路径 _analysis_store_file = None # 缓存门店文件路径
_analysis_ecology_factory_file = None # 缓存生态主机厂文件路径 _analysis_factory_file = None # 缓存主机厂文件路径(含生态月+自然月sheet)
_analysis_nature_factory_file = None # 缓存自然月主机厂文件路径
def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str: def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str:
...@@ -395,59 +394,43 @@ def _build_dated_filename(original_name: str, prefix: str, start_date: str = Non ...@@ -395,59 +394,43 @@ def _build_dated_filename(original_name: str, prefix: str, start_date: str = Non
@router.post("/analysis/upload") @router.post("/analysis/upload")
async def analysis_upload( async def analysis_upload(
store_file: Optional[UploadFile] = File(None), store_file: Optional[UploadFile] = File(None),
ecology_factory_file: Optional[UploadFile] = File(None), factory_file: Optional[UploadFile] = File(None),
nature_factory_file: Optional[UploadFile] = File(None),
ecology_start_date: str = Form(None), ecology_start_date: str = Form(None),
ecology_end_date: str = Form(None), ecology_end_date: str = Form(None),
nature_start_date: str = Form(None), nature_start_date: str = Form(None),
nature_end_date: str = Form(None), nature_end_date: str = Form(None),
): ):
"""上传门店数据、生态主机厂数据(26日周期)、自然月主机厂数据(1日周期)""" """上传门店数据、主机厂数据(含生态月+自然月多sheet,系统自动按sheet名拆分)"""
global _analysis_store_file, _analysis_factory_file
result = {"status": "success", "messages": []} result = {"status": "success", "messages": []}
if store_file and store_file.filename: if store_file and store_file.filename:
# 门店文件通常不带日期上传,先存入 drafts 目录
fname = _build_dated_filename(store_file.filename, "analysis_store") fname = _build_dated_filename(store_file.filename, "analysis_store")
file_path = _date_path(fname, category="drafts") file_path = _date_path(fname, category="drafts")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f) shutil.copyfileobj(store_file.file, f)
global _analysis_store_file
_analysis_store_file = file_path _analysis_store_file = file_path
result["messages"].append(f"门店列表已上传: {store_file.filename}") result["messages"].append(f"门店列表已上传: {store_file.filename}")
def _save_factory(upload_file, prefix, global_var_name, start_date=None, end_date=None): if factory_file and factory_file.filename:
if not upload_file or not upload_file.filename: # 主机厂数据使用生态月日期范围命名
return None fname = _build_dated_filename(factory_file.filename, "analysis_factory", ecology_start_date, ecology_end_date)
fname = _build_dated_filename(upload_file.filename, f"analysis_{prefix}", start_date, end_date) cat = "analysis" if (ecology_start_date and ecology_end_date) else "drafts"
# 如果没有日期范围,则存入 drafts 目录
cat = "analysis" if (start_date and end_date) else "drafts"
file_path = _date_path(fname, category=cat) file_path = _date_path(fname, category=cat)
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(upload_file.file, f) shutil.copyfileobj(factory_file.file, f)
_analysis_factory_file = file_path
try: try:
import pandas as pd import pandas as pd
sheets = pd.read_excel(file_path, sheet_name=None) sheets = pd.read_excel(file_path, sheet_name=None)
return { result["factory_info"] = {
"path": file_path, "path": file_path,
"sheets": list(sheets.keys()), "sheets": list(sheets.keys()),
"sheet_count": len(sheets), "sheet_count": len(sheets),
} }
except Exception as e: except Exception as e:
return {"path": file_path, "error": str(e)} result["factory_info"] = {"path": file_path, "error": str(e)}
result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")
ecology_info = _save_factory(ecology_factory_file, "ecology", "_analysis_ecology_factory_file", ecology_start_date, ecology_end_date)
if ecology_info:
global _analysis_ecology_factory_file
_analysis_ecology_factory_file = ecology_info.get("path") if not ecology_info.get("error") else None
result["ecology_factory_info"] = ecology_info
result["messages"].append(f"生态主机厂数据已上传: {ecology_factory_file.filename}")
nature_info = _save_factory(nature_factory_file, "nature", "_analysis_nature_factory_file", nature_start_date, nature_end_date)
if nature_info:
global _analysis_nature_factory_file
_analysis_nature_factory_file = nature_info.get("path") if not nature_info.get("error") else None
result["nature_factory_info"] = nature_info
result["messages"].append(f"自然月主机厂数据已上传: {nature_factory_file.filename}")
if not result["messages"]: if not result["messages"]:
raise HTTPException(status_code=400, detail="请至少上传一个文件") raise HTTPException(status_code=400, detail="请至少上传一个文件")
...@@ -465,8 +448,8 @@ async def analysis_save_batch( ...@@ -465,8 +448,8 @@ async def analysis_save_batch(
brand: str = Form("问界"), brand: str = Form("问界"),
): ):
"""将分析页面上传的文件保存为历史批次,便于下次复用""" """将分析页面上传的文件保存为历史批次,便于下次复用"""
if file_type not in ("store", "ecology", "nature", "factory"): if file_type not in ("store", "factory"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/ecology/nature/factory") raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory")
if not file.filename: if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件") raise HTTPException(status_code=400, detail="请选择文件")
...@@ -474,9 +457,8 @@ async def analysis_save_batch( ...@@ -474,9 +457,8 @@ async def analysis_save_batch(
if file_type == "store": if file_type == "store":
formal_name = build_store_filename(brand, period_start, period_end) formal_name = build_store_filename(brand, period_start, period_end)
else: else:
# 主机厂数据 # 主机厂数据(含生态月+自然月,用生态月日期范围命名)
pt = period_type or ("生态月" if file_type == "ecology" else "自然月") formal_name = build_factory_filename(brand, "", period_start, period_end)
formal_name = build_factory_filename(brand, pt, period_start, period_end)
# 确保文件名唯一并保存到 batch 目录 # 确保文件名唯一并保存到 batch 目录
file_path = _date_path(formal_name, category="batch") file_path = _date_path(formal_name, category="batch")
...@@ -502,14 +484,13 @@ async def analysis_save_batch( ...@@ -502,14 +484,13 @@ async def analysis_save_batch(
) )
else: else:
from app.services.upload_service import import_oem_delivery from app.services.upload_service import import_oem_delivery
pt = period_type or ("ecology" if file_type == "ecology" else "nature")
result = import_oem_delivery( result = import_oem_delivery(
file_path=file_path, file_path=file_path,
original_filename=os.path.basename(file_path), original_filename=os.path.basename(file_path),
brand=brand, brand=brand,
data_period_start=period_start or "", data_period_start=period_start or "",
data_period_end=period_end or "", data_period_end=period_end or "",
period_type=pt, period_type=period_type or "",
file_size=file_size, file_size=file_size,
remark=file_path remark=file_path
) )
...@@ -533,11 +514,10 @@ async def analysis_generate( ...@@ -533,11 +514,10 @@ async def analysis_generate(
nature_start_date: str = Form(None), nature_start_date: str = Form(None),
nature_end_date: str = Form(None), nature_end_date: str = Form(None),
store_batch_no: str = Form(None), store_batch_no: str = Form(None),
ecology_batch_no: str = Form(None), factory_batch_no: str = Form(None),
nature_batch_no: str = Form(None),
): ):
"""根据已上传的数据或历史批次生成生态系数分析报表(双sheet:生态数据+自然月)""" """根据已上传的数据或历史批次生成生态系数分析报表(主机厂数据含多sheet自动拆分生态/自然月)"""
global _analysis_store_file, _analysis_ecology_factory_file, _analysis_nature_factory_file global _analysis_store_file, _analysis_factory_file
# 加载store_df:优先批次DB数据,其次文件,最后默认模板 # 加载store_df:优先批次DB数据,其次文件,最后默认模板
if store_batch_no: if store_batch_no:
...@@ -552,21 +532,20 @@ async def analysis_generate( ...@@ -552,21 +532,20 @@ async def analysis_generate(
else: else:
raise HTTPException(status_code=400, detail="请先上传门店列表文件") raise HTTPException(status_code=400, detail="请先上传门店列表文件")
ecology_factory = {} # 加载主机厂数据:优先批次DB数据,其次文件
nature_factory = {} # 主机厂数据含多sheet(生态月+自然月),由 build_report 自动按sheet名拆分
factory_data = {}
if ecology_batch_no: if factory_batch_no:
ecology_factory = _load_oem_factory_from_batch(ecology_batch_no) factory_data = _load_oem_factory_from_batch(factory_batch_no)
elif _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file): elif _analysis_factory_file and os.path.exists(_analysis_factory_file):
ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file) factory_data = AnalysisService.read_factory_data(_analysis_factory_file)
if nature_batch_no: if not factory_data:
nature_factory = _load_oem_factory_from_batch(nature_batch_no) raise HTTPException(status_code=400, detail="请上传或选择主机厂数据文件")
elif _analysis_nature_factory_file and os.path.exists(_analysis_nature_factory_file):
nature_factory = AnalysisService.read_factory_data(_analysis_nature_factory_file)
if not ecology_factory and not nature_factory: # 将所有主机厂sheet数据作为 ecology_factory 传入,build_report 会自动拆分
raise HTTPException(status_code=400, detail="请至少上传或选择一个主机厂数据文件(生态或自然月)") ecology_factory = factory_data
nature_factory = {}
try: try:
output_path = AnalysisService.build_report( output_path = AnalysisService.build_report(
...@@ -590,8 +569,7 @@ async def analysis_generate( ...@@ -590,8 +569,7 @@ async def analysis_generate(
"download_url": f"api/analysis/download?file={os.path.basename(output_path)}", "download_url": f"api/analysis/download?file={os.path.basename(output_path)}",
"ecology_store_count": len(ecology_stores), "ecology_store_count": len(ecology_stores),
"nature_store_count": len(nature_stores), "nature_store_count": len(nature_stores),
"ecology_factory_sheets": list(ecology_factory.keys()) if ecology_factory else [], "factory_sheets": list(factory_data.keys()) if factory_data else [],
"nature_factory_sheets": list(nature_factory.keys()) if nature_factory else [],
} }
except Exception as e: except Exception as e:
logger.error(f"Analysis generate failed: {e}", exc_info=True) logger.error(f"Analysis generate failed: {e}", exc_info=True)
......
...@@ -230,9 +230,10 @@ def parse_harmony_store_guarantee(file_path: str) -> List[Dict]: ...@@ -230,9 +230,10 @@ def parse_harmony_store_guarantee(file_path: str) -> List[Dict]:
# ============================================================================ # ============================================================================
FACTORY_KEYWORDS = [ FACTORY_KEYWORDS = [
"厅店代码", "厅店名称", "厅店简称", "省区", "赋能商", "厅店代码", "厅店名称", "厅店简称", "省区", "省区别称", "赋能商",
"交付量", "整车延保采购量", "交付量", "整车延保", "整车延保采购量",
"采购量-电池延保", "驾行安心包采购量", "轮胎保障服务采购量", "采购量-电池延保", "电池延保1", "驾行安心包", "驾行安心包采购量",
"轮胎保障服务采购量", "臻享无忧套餐", "单车产值",
] ]
...@@ -265,11 +266,15 @@ def parse_wenjie_oem_delivery(file_path: str) -> List[Dict]: ...@@ -265,11 +266,15 @@ def parse_wenjie_oem_delivery(file_path: str) -> List[Dict]:
col_map = { col_map = {
"厅店名称": "门店名", "厅店代码": "厅店代码", "厅店名称": "门店名", "厅店代码": "厅店代码",
"省区": "区域(省)", "赋能商": "赋能商", "省区": "区域(省)", "省区别称": "区域(省)",
"赋能商": "赋能商",
"交付量": "交付数", "整车延保采购量": "整车延保采购数", "交付量": "交付数", "整车延保采购量": "整车延保采购数",
"驾行安心包采购量": "安心包采购数", "整车延保": "整车延保采购数",
"采购量-电池延保": "电池延保采购数", "驾行安心包采购量": "安心包采购数", "驾行安心包": "安心包采购数",
"采购量-电池延保": "电池延保采购数", "电池延保1": "电池延保采购数",
"轮胎保障服务采购量": "轮胎险采购数", "轮胎保障服务采购量": "轮胎险采购数",
"臻享无忧套餐": "无忧套餐采购数",
"单车产值/台": "单车产值", "单车产值": "单车产值",
} }
df = df.rename(columns=col_map) df = df.rename(columns=col_map)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!