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):
"""下载分析模板文件"""
template_map = {
# store 使用动态查找最新带序号的模板
"factory": "主机厂数据-问界-模板001.xlsx",
"factory": "主机厂数据-问界-模板002.xlsx",
"output": "输出模板-问界-模板001.xlsx",
}
......@@ -364,8 +364,7 @@ async def download_analysis_template(template_type: str):
_analysis_store_file = None # 缓存门店文件路径
_analysis_ecology_factory_file = None # 缓存生态主机厂文件路径
_analysis_nature_factory_file = None # 缓存自然月主机厂文件路径
_analysis_factory_file = None # 缓存主机厂文件路径(含生态月+自然月sheet)
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
@router.post("/analysis/upload")
async def analysis_upload(
store_file: Optional[UploadFile] = File(None),
ecology_factory_file: Optional[UploadFile] = File(None),
nature_factory_file: Optional[UploadFile] = File(None),
factory_file: Optional[UploadFile] = File(None),
ecology_start_date: str = Form(None),
ecology_end_date: str = Form(None),
nature_start_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": []}
if store_file and store_file.filename:
# 门店文件通常不带日期上传,先存入 drafts 目录
fname = _build_dated_filename(store_file.filename, "analysis_store")
file_path = _date_path(fname, category="drafts")
with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f)
global _analysis_store_file
_analysis_store_file = file_path
result["messages"].append(f"门店列表已上传: {store_file.filename}")
def _save_factory(upload_file, prefix, global_var_name, start_date=None, end_date=None):
if not upload_file or not upload_file.filename:
return None
fname = _build_dated_filename(upload_file.filename, f"analysis_{prefix}", start_date, end_date)
# 如果没有日期范围,则存入 drafts 目录
cat = "analysis" if (start_date and end_date) else "drafts"
if factory_file and factory_file.filename:
# 主机厂数据使用生态月日期范围命名
fname = _build_dated_filename(factory_file.filename, "analysis_factory", ecology_start_date, ecology_end_date)
cat = "analysis" if (ecology_start_date and ecology_end_date) else "drafts"
file_path = _date_path(fname, category=cat)
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:
import pandas as pd
sheets = pd.read_excel(file_path, sheet_name=None)
return {
result["factory_info"] = {
"path": file_path,
"sheets": list(sheets.keys()),
"sheet_count": len(sheets),
}
except Exception as e:
return {"path": file_path, "error": str(e)}
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}")
result["factory_info"] = {"path": file_path, "error": str(e)}
result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")
if not result["messages"]:
raise HTTPException(status_code=400, detail="请至少上传一个文件")
......@@ -465,8 +448,8 @@ async def analysis_save_batch(
brand: str = Form("问界"),
):
"""将分析页面上传的文件保存为历史批次,便于下次复用"""
if file_type not in ("store", "ecology", "nature", "factory"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/ecology/nature/factory")
if file_type not in ("store", "factory"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory")
if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件")
......@@ -474,9 +457,8 @@ async def analysis_save_batch(
if file_type == "store":
formal_name = build_store_filename(brand, period_start, period_end)
else:
# 主机厂数据
pt = period_type or ("生态月" if file_type == "ecology" else "自然月")
formal_name = build_factory_filename(brand, pt, period_start, period_end)
# 主机厂数据(含生态月+自然月,用生态月日期范围命名)
formal_name = build_factory_filename(brand, "", period_start, period_end)
# 确保文件名唯一并保存到 batch 目录
file_path = _date_path(formal_name, category="batch")
......@@ -502,14 +484,13 @@ async def analysis_save_batch(
)
else:
from app.services.upload_service import import_oem_delivery
pt = period_type or ("ecology" if file_type == "ecology" else "nature")
result = import_oem_delivery(
file_path=file_path,
original_filename=os.path.basename(file_path),
brand=brand,
data_period_start=period_start or "",
data_period_end=period_end or "",
period_type=pt,
period_type=period_type or "",
file_size=file_size,
remark=file_path
)
......@@ -533,11 +514,10 @@ async def analysis_generate(
nature_start_date: str = Form(None),
nature_end_date: str = Form(None),
store_batch_no: str = Form(None),
ecology_batch_no: str = Form(None),
nature_batch_no: str = Form(None),
factory_batch_no: str = Form(None),
):
"""根据已上传的数据或历史批次生成生态系数分析报表(双sheet:生态数据+自然月)"""
global _analysis_store_file, _analysis_ecology_factory_file, _analysis_nature_factory_file
"""根据已上传的数据或历史批次生成生态系数分析报表(主机厂数据含多sheet自动拆分生态/自然月)"""
global _analysis_store_file, _analysis_factory_file
# 加载store_df:优先批次DB数据,其次文件,最后默认模板
if store_batch_no:
......@@ -552,21 +532,20 @@ async def analysis_generate(
else:
raise HTTPException(status_code=400, detail="请先上传门店列表文件")
ecology_factory = {}
nature_factory = {}
if ecology_batch_no:
ecology_factory = _load_oem_factory_from_batch(ecology_batch_no)
elif _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file):
ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file)
# 加载主机厂数据:优先批次DB数据,其次文件
# 主机厂数据含多sheet(生态月+自然月),由 build_report 自动按sheet名拆分
factory_data = {}
if factory_batch_no:
factory_data = _load_oem_factory_from_batch(factory_batch_no)
elif _analysis_factory_file and os.path.exists(_analysis_factory_file):
factory_data = AnalysisService.read_factory_data(_analysis_factory_file)
if nature_batch_no:
nature_factory = _load_oem_factory_from_batch(nature_batch_no)
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 factory_data:
raise HTTPException(status_code=400, detail="请上传或选择主机厂数据文件")
if not ecology_factory and not nature_factory:
raise HTTPException(status_code=400, detail="请至少上传或选择一个主机厂数据文件(生态或自然月)")
# 将所有主机厂sheet数据作为 ecology_factory 传入,build_report 会自动拆分
ecology_factory = factory_data
nature_factory = {}
try:
output_path = AnalysisService.build_report(
......@@ -590,8 +569,7 @@ async def analysis_generate(
"download_url": f"api/analysis/download?file={os.path.basename(output_path)}",
"ecology_store_count": len(ecology_stores),
"nature_store_count": len(nature_stores),
"ecology_factory_sheets": list(ecology_factory.keys()) if ecology_factory else [],
"nature_factory_sheets": list(nature_factory.keys()) if nature_factory else [],
"factory_sheets": list(factory_data.keys()) if factory_data else [],
}
except Exception as e:
logger.error(f"Analysis generate failed: {e}", exc_info=True)
......
......@@ -137,9 +137,13 @@ OUTPUT_HEADERS = [
# 主机厂数据 (K-Q)
"交付数", "整车延保采购数", "安心包采购数", "电池延保采购数", "轮胎险采购数",
"无忧套餐采购数", "单车产值",
# 产值表数据 (R-AD)
"产值", "单车产值2", "交付数2", "触客数", "触客率", "整车延保成交订单数", "安心包订单总成交数",
"电池延保订单成交数", "轮胎险订单成交数", "整车延保渗透率", "安心包总渗透率",
# 产值表数据 (R-Z) — 与输出模板002对齐
"交付数2", "触客数", "触客率", "整车延保成交订单数", "安心包订单总成交数",
"电池延保订单成交数", "轮胎险订单成交数",
# 产值 & 单车产值2 (AA-AB)
"产值", "单车产值2",
# 渗透率 (AC-AF)
"整车延保渗透率", "安心包总渗透率",
"电池延保渗透率", "轮胎险渗透率",
# 生态系数 (AA-AD)
"整车延保渗透率达标系数", "安心包渗透率达标系数", "电池延保渗透率达标系数", "总分",
......@@ -171,7 +175,7 @@ OUTPUT_HEADERS = [
"去除服务商",
]
# 头部合并行配置
# 头部合并行配置 — 与输出模板002对齐
GROUP_LABELS = [
("基础门店信息\n标红为主机厂无数据,取产值表交付数为分母", 0, 9),
("主机厂数据", 10, 16),
......@@ -1137,11 +1141,13 @@ class AnalysisService:
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
# 根据列和值类型设置数字格式
if isinstance(value, (int, float)):
if c in (22, 27, 28, 29, 30, 37, 38, 39, 40, 41, 42): # 触客率/渗透率/转化率/需达标转化率
if c in (20, 27, 28, 29, 30, 38, 39, 40, 41, 42, 43): # 触客率/渗透率/转化率/需达标转化率
cell.number_format = '0.00%'
elif c in (30, 31, 32, 33): # 生态系数
elif c in (31, 32, 33, 34): # 生态系数
cell.number_format = '0.0'
elif c in (53,): # 门店等级文字
elif c in (25, 26, 17): # 产值/单车产值2/主机厂单车产值
cell.number_format = '#,##0.00'
elif c in (54,): # 门店等级文字
pass
else:
cell.number_format = '0'
......@@ -1256,23 +1262,73 @@ class AnalysisService:
battery_orders = _safe_float(store_perf.get("battery_orders", 0))
tire_orders = _safe_float(store_perf.get("tire_orders", 0))
_style_cell(row_num, 18, output_value) # R 产值
_style_cell(row_num, 19, unit_value2) # S 单车产值2
_style_cell(row_num, 20, delivery2) # T 交付数2
_style_cell(row_num, 21, customer_count) # U 触客数
_style_cell(row_num, 22, touch_rate) # V 触客率
_style_cell(row_num, 23, yb_orders) # W 整车延保成交
_style_cell(row_num, 24, axb_orders) # X 安心包成交
_style_cell(row_num, 25, battery_orders) # Y 电池延保成交
_style_cell(row_num, 26, tire_orders) # Z 轮胎险成交
# W-AJ (cols 23-36): 渗透率/达标系数/总分/采购差异/当前转化率
# 0625模板中这些列均有公式,无需Python写值
# ========== 当前转化率2 计算(用于赔付逻辑)==========
# AH-AJ (cols 34-36): 模板公式计算,此处计算用于赔付算法
# 交付类型→S/K, 触客类型→S/Q
# 注意: baodi_type 和 customer_count 已在上面提前定义
_style_cell(row_num, 18, delivery2) # R 交付数2
_style_cell(row_num, 19, customer_count) # S 触客数
_style_cell(row_num, 20, touch_rate) # T 触客率
_style_cell(row_num, 21, yb_orders) # U 整车延保成交
_style_cell(row_num, 22, axb_orders) # V 安心包成交
_style_cell(row_num, 23, battery_orders) # W 电池延保成交
_style_cell(row_num, 24, tire_orders) # X 轮胎险成交
_style_cell(row_num, 25, output_value) # Y 产值
_style_cell(row_num, 26, unit_value2) # Z 单车产值2
# ========== 渗透率 (AA-AD, cols 27-30) — 分母为主机厂交付数 ==========
yb_penetration = round(yb_orders / delivery, 4) if delivery > 0 else 0
axb_penetration = round(axb_orders / delivery, 4) if delivery > 0 else 0
battery_penetration = round(battery_orders / delivery, 4) if delivery > 0 else 0
tire_penetration = round(tire_orders / delivery, 4) if delivery > 0 else 0
_style_cell(row_num, 27, yb_penetration)
_style_cell(row_num, 28, axb_penetration)
_style_cell(row_num, 29, battery_penetration)
_style_cell(row_num, 30, tire_penetration)
# ========== 生态系数 (AE-AH, cols 31-34) ==========
if yb_penetration <= 0.45:
yb_coef = 0
elif yb_penetration < 0.50:
yb_coef = 0.8
elif yb_penetration < 0.60:
yb_coef = 1
elif yb_penetration < 0.70:
yb_coef = 1.2
else:
yb_coef = 1.3
if axb_penetration >= 5:
axb_coef = 0
elif axb_penetration >= 0.30:
axb_coef = 1.3
elif axb_penetration >= 0.22:
axb_coef = 1.2
elif axb_penetration >= 0.17:
axb_coef = 1
elif axb_penetration >= 0.12:
axb_coef = 0.8
else:
axb_coef = 0
if battery_penetration >= 5:
battery_coef = 0
elif battery_penetration >= 0.22:
battery_coef = 1.3
elif battery_penetration >= 0.16:
battery_coef = 1.2
elif battery_penetration >= 0.13:
battery_coef = 1
elif battery_penetration >= 0.10:
battery_coef = 0.8
else:
battery_coef = 0
total_score = round(yb_coef + axb_coef + battery_coef, 1)
_style_cell(row_num, 31, yb_coef)
_style_cell(row_num, 32, axb_coef)
_style_cell(row_num, 33, battery_coef)
_style_cell(row_num, 34, total_score)
# ========== 主机厂采购差异 (AI-AK, cols 35-37) ==========
_style_cell(row_num, 35, yb_purchase - yb_orders if (yb_purchase or yb_orders) else "")
_style_cell(row_num, 36, axb_purchase - axb_orders if (axb_purchase or axb_orders) else "")
_style_cell(row_num, 37, battery_purchase - battery_orders if (battery_purchase or battery_orders) else "")
# ========== 当前转化率 (AL-AN, cols 38-40) ==========
if baodi_type == "触客":
base_for_rate = _safe_float(customer_count, 0) # Q
current_rate_yb = yb_orders / base_for_rate if base_for_rate > 0 else 0
......@@ -1284,7 +1340,11 @@ class AnalysisService:
current_rate_axb = axb_orders / base_for_rate if base_for_rate > 0 else 0
current_rate_battery = battery_orders / base_for_rate if base_for_rate > 0 else 0
# ========== 需达标转化率 (AN-AP, cols 40-42) ==========
_style_cell(row_num, 38, round(current_rate_yb, 4))
_style_cell(row_num, 39, round(current_rate_axb, 4))
_style_cell(row_num, 40, round(current_rate_battery, 4))
# ========== 需达标转化率 (AO-AQ, cols 41-43) ==========
# 从门店数据中提取(新格式:达标转化率_* 和 每单赔付金额_* 分开)
coeff_yb = AnalysisService._parse_compensation_coefficient(
threshold_str=store_row.get("达标转化率_整车延保"),
......@@ -1300,18 +1360,24 @@ class AnalysisService:
target_axb = max([t for t, _ in coeff_axb], default=0.0)
target_battery = max([t for t, _ in coeff_battery], default=0.0)
_style_cell(row_num, 40, target_yb)
_style_cell(row_num, 41, target_axb)
_style_cell(row_num, 42, target_battery)
_style_cell(row_num, 41, target_yb)
_style_cell(row_num, 42, target_axb)
_style_cell(row_num, 43, target_battery)
# ========== 是否触发兜底 (AR, col 44) ==========
trigger = "是" if (current_rate_yb < target_yb or current_rate_axb < target_axb or current_rate_battery < target_battery) else "否"
_style_cell(row_num, 44, trigger)
# ========== 需达标订单数差额 (AR-AT, cols 44-46) ==========
# 模板公式自动计算,此处仅计算 gap 值供后续赔付金额使用
# ========== 需达标订单数差额 (AS-AU, cols 45-47) ==========
gap_base = _safe_float(customer_count, 0) if baodi_type == "触客" else _safe_float(delivery, 0)
gap_yb = max(0, math.ceil(gap_base * target_yb - yb_orders)) if target_yb > 0 else 0
gap_axb = max(0, math.ceil(gap_base * target_axb - axb_orders)) if target_axb > 0 else 0
gap_battery = max(0, math.ceil(gap_base * target_battery - battery_orders)) if target_battery > 0 else 0
_style_cell(row_num, 45, gap_yb)
_style_cell(row_num, 46, gap_axb)
_style_cell(row_num, 47, gap_battery)
# ========== 赔付金额 (AU-AW, cols 47-49) ==========
# ========== 赔付金额 (AV-AX, cols 48-50) ==========
# 阶梯赔付算法(类似 IF(rate<11%, CEILING(gap_base*11%-orders,1)*800, IF(rate<15%, CEILING(gap_base*15%-orders,1)*600, 0)) ):
# - 需达标订单数 gap 统一用最高阈值计算(对应 col 41-43)
# - 赔付金额 = gap × 最低阈值对应的单价(即按最低赔付标准支付)
......@@ -1343,21 +1409,43 @@ class AnalysisService:
payout_axb = "/"
payout_battery = "/"
_style_cell(row_num, 47, payout_yb)
_style_cell(row_num, 48, payout_axb)
_style_cell(row_num, 49, payout_battery)
_style_cell(row_num, 48, payout_yb)
_style_cell(row_num, 49, payout_axb)
_style_cell(row_num, 50, payout_battery)
# ========== 赔付总金额 (AX, col 51) ==========
# ========== 是否需要赔付 (AY, col 51) ==========
total_payout = 0
if is_direct:
total_payout = round(_safe_float(payout_yb, 0) + _safe_float(payout_axb, 0) + _safe_float(payout_battery, 0), 1)
need_payout = "是" if total_payout > 0 else "否"
else:
need_payout = "/"
_style_cell(row_num, 51, need_payout)
# ========== 赔付总金额 (AZ, col 52) ==========
if not is_direct:
_style_cell(row_num, 51, "/")
_style_cell(row_num, 52, "/")
else:
_style_cell(row_num, 52, total_payout)
# ========== 兜底月份 (BA, col 53) ==========
_style_cell(row_num, 53, store_row.get("兜底截止日期", ""))
# ========== 门店等级 (BB, col 54) ==========
gap_sum = gap_yb + gap_axb + gap_battery
if trigger == "是" and gap_sum >= 3:
store_grade = "红色门店"
elif total_score < 2.8 or gap_sum > 0:
store_grade = "黄色门店"
else:
_style_cell(row_num, 51, round(payout_yb + payout_axb + payout_battery, 1))
store_grade = "绿色门店"
_style_cell(row_num, 54, store_grade)
# ========== 兜底月份 (AY, col 52) ==========
_style_cell(row_num, 52, store_row.get("兜底截止日期", ""))
# ========== 备注 (BD, col 56) ==========
_style_cell(row_num, 56, "")
# ========== 备注 (BB, col 55) ==========
_style_cell(row_num, 55, "")
# ========== 去除服务商 (BE, col 57) ==========
_style_cell(row_num, 57, "服务商" if str(store_perf.get("operation_mode", "")).strip() != "直营" else "")
# ========== 写入公式列(模板第4行有公式的列,跳过外部引用列)==========
for col_idx, formula_text in formula_map.items():
......
......@@ -230,9 +230,10 @@ def parse_harmony_store_guarantee(file_path: str) -> List[Dict]:
# ============================================================================
FACTORY_KEYWORDS = [
"厅店代码", "厅店名称", "厅店简称", "省区", "赋能商",
"交付量", "整车延保采购量",
"采购量-电池延保", "驾行安心包采购量", "轮胎保障服务采购量",
"厅店代码", "厅店名称", "厅店简称", "省区", "省区别称", "赋能商",
"交付量", "整车延保", "整车延保采购量",
"采购量-电池延保", "电池延保1", "驾行安心包", "驾行安心包采购量",
"轮胎保障服务采购量", "臻享无忧套餐", "单车产值",
]
......@@ -265,11 +266,15 @@ def parse_wenjie_oem_delivery(file_path: str) -> List[Dict]:
col_map = {
"厅店名称": "门店名", "厅店代码": "厅店代码",
"省区": "区域(省)", "赋能商": "赋能商",
"省区": "区域(省)", "省区别称": "区域(省)",
"赋能商": "赋能商",
"交付量": "交付数", "整车延保采购量": "整车延保采购数",
"驾行安心包采购量": "安心包采购数",
"采购量-电池延保": "电池延保采购数",
"整车延保": "整车延保采购数",
"驾行安心包采购量": "安心包采购数", "驾行安心包": "安心包采购数",
"采购量-电池延保": "电池延保采购数", "电池延保1": "电池延保采购数",
"轮胎保障服务采购量": "轮胎险采购数",
"臻享无忧套餐": "无忧套餐采购数",
"单车产值/台": "单车产值", "单车产值": "单车产值",
}
df = df.rename(columns=col_map)
......
......@@ -303,52 +303,36 @@
<button class="btn-save-batch" id="btn-save-store" style="display:none;" onclick="saveBatch('store')">&#x1f4be; 保存为历史批次</button>
</div>
<!-- 步骤2: 生态(26日) -->
<!-- 步骤2: 主机厂数据(生态+自然月合并为单文件) -->
<div class="step-card" id="step2-card">
<div class="step-title">&#9313; 步骤2: 生态(26日)</div>
<div class="step-title">&#9313; 步骤2: 主机厂数据(含生态月+自然月)</div>
<div class="step-row">
<select class="step-select" id="ecology-batch-select" onchange="onFactoryBatchSelect('ecology')">
<select class="step-select" id="factory-batch-select" onchange="onFactoryBatchSelect()">
<option value="">-- 选择历史批次 --</option>
</select>
</div>
<div class="step-row">
<span class="step-or">或</span>
<div class="step-upload-zone" id="ecology-drop-zone" onclick="document.getElementById('ecology-factory-input').click()">
<input type="file" id="ecology-factory-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange('ecology')">
&#x1f4c1; <span id="ecology-file-name">点击上传生态主机厂数据</span>
<div class="step-upload-zone" id="factory-drop-zone" onclick="document.getElementById('factory-file-input').click()">
<input type="file" id="factory-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange()">
&#x1f4c1; <span id="factory-file-name">点击上传主机厂数据(含生态月+自然月sheet)</span>
</div>
<a class="btn-download-tpl" href="./api/analysis/template/factory">&#x1f4e5; 模板</a>
</div>
<div class="step-date-row">
<input type="date" id="ecology-start-date" title="开始日期">
<span style="font-size:11px;color:#999;">生态月:</span>
<input type="date" id="ecology-start-date" title="生态月开始日期">
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="ecology-end-date" title="结束日期">
</div>
<button class="btn-save-batch" id="btn-save-ecology" style="display:none;" onclick="saveBatch('ecology')">&#x1f4be; 保存为历史批次</button>
</div>
<!-- 步骤3: 自然月(1日) -->
<div class="step-card" id="step3-card">
<div class="step-title">&#9314; 步骤3: 自然月(1日)</div>
<div class="step-row">
<select class="step-select" id="nature-batch-select" onchange="onFactoryBatchSelect('nature')">
<option value="">-- 选择历史批次 --</option>
</select>
</div>
<div class="step-row">
<span class="step-or">或</span>
<div class="step-upload-zone" id="nature-drop-zone" onclick="document.getElementById('nature-factory-input').click()">
<input type="file" id="nature-factory-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange('nature')">
&#x1f4c1; <span id="nature-file-name">点击上传自然月主机厂数据</span>
</div>
<a class="btn-download-tpl" href="./api/analysis/template/factory">&#x1f4e5; 模板</a>
<input type="date" id="ecology-end-date" title="生态月结束日期">
</div>
<div class="step-date-row">
<input type="date" id="nature-start-date" title="开始日期">
<span style="font-size:11px;color:#999;">自然月:</span>
<input type="date" id="nature-start-date" title="自然月开始日期">
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="nature-end-date" title="结束日期">
<input type="date" id="nature-end-date" title="自然月结束日期">
</div>
<button class="btn-save-batch" id="btn-save-nature" style="display:none;" onclick="saveBatch('nature')">&#x1f4be; 保存为历史批次</button>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份含多sheet的主机厂数据,系统自动按sheet名日期拆分生态月/自然月数据</p>
<button class="btn-save-batch" id="btn-save-factory" style="display:none;" onclick="saveBatch('factory')">&#x1f4be; 保存为历史批次</button>
</div>
<!-- 生成按钮 -->
......@@ -356,7 +340,7 @@
<button class="btn-generate" id="btn-generate-report">
&#x1f680; 开始生成分析报表
</button>
<p style="font-size:11px;color:#999;margin-top:4px;">门店按兜底截止日期分组:月底/25日→生态数据sheet,其余→自然月sheet</p>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份主机厂数据(含多sheet),系统自动按sheet名日期拆分生态月/自然月数据,按兜底截止日期分组门店</p>
</div>
<!-- 生成结果 -->
......@@ -447,50 +431,41 @@
await previewFile(formData, '门店列表 - ' + name);
};
// ========== 步骤2/3: 主机厂数据 ==========
window.onFactoryBatchSelect = async function(type) {
const prefix = type === 'ecology' ? 'ecology' : 'nature';
const sel = document.getElementById(prefix + '-batch-select');
// ========== 步骤2: 主机厂数据(单文件,含生态月+自然月sheet) ==========
window.onFactoryBatchSelect = async function() {
const sel = document.getElementById('factory-batch-select');
if (!sel.value) return;
const cardId = type === 'ecology' ? 'step2-card' : 'step3-card';
highlightStep(cardId);
const label = type === 'ecology' ? '生态(26日)' : '自然月(1日)';
// 同步日期
highlightStep('step2-card');
const opt = sel.options[sel.selectedIndex];
if (opt.dataset.periodStart) document.getElementById(prefix + '-start-date').value = opt.dataset.periodStart;
if (opt.dataset.periodEnd) document.getElementById(prefix + '-end-date').value = opt.dataset.periodEnd;
await loadBatchPreview(sel.value, label + ' - 历史批次', {
if (opt.dataset.periodStart) {
document.getElementById('ecology-start-date').value = opt.dataset.periodStart;
document.getElementById('nature-start-date').value = opt.dataset.periodStart;
}
if (opt.dataset.periodEnd) {
document.getElementById('ecology-end-date').value = opt.dataset.periodEnd;
document.getElementById('nature-end-date').value = opt.dataset.periodEnd;
}
await loadBatchPreview(sel.value, '主机厂数据 - 历史批次', {
type: '主机厂交付数据',
period: opt.dataset.periodStart ? `${opt.dataset.periodStart} ~ ${opt.dataset.periodEnd}` : '',
source: opt.textContent.split(' [')[0],
periodType: label,
});
};
window.onFactoryFileChange = async function(type) {
const inputId = type === 'ecology' ? 'ecology-factory-input' : 'nature-factory-input';
const zoneId = type === 'ecology' ? 'ecology-drop-zone' : 'nature-drop-zone';
const nameId = type === 'ecology' ? 'ecology-file-name' : 'nature-file-name';
const selId = type === 'ecology' ? 'ecology-batch-select' : 'nature-batch-select';
const cardId = type === 'ecology' ? 'step2-card' : 'step3-card';
const btnId = type === 'ecology' ? 'btn-save-ecology' : 'btn-save-nature';
const input = document.getElementById(inputId);
window.onFactoryFileChange = async function() {
const input = document.getElementById('factory-file-input');
if (!input.files.length) return;
const name = input.files[0].name;
document.getElementById(nameId).textContent = '\u2705 ' + name;
document.getElementById(zoneId).classList.add('has-file');
document.getElementById(selId).value = '';
highlightStep(cardId);
document.getElementById(btnId).style.display = 'block';
document.getElementById('factory-file-name').textContent = '\u2705 ' + name;
document.getElementById('factory-drop-zone').classList.add('has-file');
document.getElementById('factory-batch-select').value = '';
highlightStep('step2-card');
document.getElementById('btn-save-factory').style.display = 'block';
const label = type === 'ecology' ? '生态(26日)' : '自然月(1日)';
const formData = new FormData();
formData.append('file_type', 'factory');
formData.append('file', input.files[0]);
await previewFile(formData, label + ' - ' + name);
await previewFile(formData, '主机厂数据 - ' + name);
};
// ========== 生成报表 ==========
......@@ -501,24 +476,19 @@
document.getElementById('analysis-error').className = 'result-box';
const storeInput = document.getElementById('store-file-input');
const ecoInput = document.getElementById('ecology-factory-input');
const natInput = document.getElementById('nature-factory-input');
const factoryInput = document.getElementById('factory-file-input');
const storeBatchSel = document.getElementById('store-batch-select');
const ecoBatchSel = document.getElementById('ecology-batch-select');
const natBatchSel = document.getElementById('nature-batch-select');
const factoryBatchSel = document.getElementById('factory-batch-select');
const hasStoreFile = storeInput && storeInput.files.length > 0;
const hasEcoFile = ecoInput && ecoInput.files.length > 0;
const hasNatFile = natInput && natInput.files.length > 0;
const hasEcoBatch = ecoBatchSel && ecoBatchSel.value;
const hasNatBatch = natBatchSel && natBatchSel.value;
const hasFactoryFile = factoryInput && factoryInput.files.length > 0;
const hasStoreBatch = storeBatchSel && storeBatchSel.value;
const hasFactoryBatch = factoryBatchSel && factoryBatchSel.value;
const hasEco = hasEcoFile || hasEcoBatch;
const hasNat = hasNatFile || hasNatBatch;
const hasFactory = hasFactoryFile || hasFactoryBatch;
if (!hasEco && !hasNat) {
alert('请至少上传或选择一个主机厂数据(步骤2或步骤3)');
if (!hasFactory) {
alert('请上传或选择主机厂数据(步骤2)');
return;
}
......@@ -528,8 +498,7 @@
try {
const uploadForm = new FormData();
if (hasStoreFile) uploadForm.append('store_file', storeInput.files[0]);
if (hasEcoFile) uploadForm.append('ecology_factory_file', ecoInput.files[0]);
if (hasNatFile) uploadForm.append('nature_factory_file', natInput.files[0]);
if (hasFactoryFile) uploadForm.append('factory_file', factoryInput.files[0]);
// 传日期范围用于文件命名
const eS2 = document.getElementById('ecology-start-date').value;
const eE2 = document.getElementById('ecology-end-date').value;
......@@ -540,7 +509,7 @@
if (nS2) uploadForm.append('nature_start_date', nS2);
if (nE2) uploadForm.append('nature_end_date', nE2);
const anyFile = hasStoreFile || hasEcoFile || hasNatFile;
const anyFile = hasStoreFile || hasFactoryFile;
if (anyFile) {
const uploadRes = await fetch(window.API_BASE + '/analysis/upload', { method: 'POST', body: uploadForm });
const uploadData = await uploadRes.json();
......@@ -560,8 +529,7 @@
if (nE) genForm.append('nature_end_date', nE);
// 传递批次号
if (hasStoreBatch) genForm.append('store_batch_no', storeBatchSel.value);
if (hasEcoBatch) genForm.append('ecology_batch_no', ecoBatchSel.value);
if (hasNatBatch) genForm.append('nature_batch_no', natBatchSel.value);
if (hasFactoryBatch) genForm.append('factory_batch_no', factoryBatchSel.value);
const genRes = await fetch(window.API_BASE + '/analysis/generate', { method: 'POST', body: genForm });
const genData = await genRes.json();
......@@ -597,19 +565,16 @@
async function loadBatchOptions() {
try {
const [storeRes, ecoRes, natRes] = await Promise.all([
const [storeRes, facRes] = await Promise.all([
fetch(window.API_BASE + '/data-import/history?brand=问界&data_type=store_guarantee'),
fetch(window.API_BASE + '/data-import/history?brand=问界&data_type=oem_delivery&period_type=ecology'),
fetch(window.API_BASE + '/data-import/history?brand=问界&data_type=oem_delivery&period_type=nature')
fetch(window.API_BASE + '/data-import/history?brand=问界&data_type=oem_delivery')
]);
const storeData = await storeRes.json();
const ecoData = await ecoRes.json();
const natData = await natRes.json();
const facData = await facRes.json();
function fillSelect(selId, rows) {
const sel = document.getElementById(selId);
if (!sel) return;
// 清空已有选项,仅保留第一条占位项
while (sel.options.length > 1) sel.remove(1);
(rows || []).forEach(r => {
const opt = document.createElement('option');
......@@ -624,11 +589,8 @@
if (storeData.status === 'success') {
fillSelect('store-batch-select', storeData.data);
}
if (ecoData.status === 'success') {
fillSelect('ecology-batch-select', ecoData.data);
}
if (natData.status === 'success') {
fillSelect('nature-batch-select', natData.data);
if (facData.status === 'success') {
fillSelect('factory-batch-select', facData.data);
}
} catch (e) {
console.error('加载历史批次失败:', e);
......@@ -734,8 +696,7 @@
async function saveBatch(fileType) {
const config = {
store: { inputId: 'store-file-input', btnId: 'btn-save-store' },
ecology: { inputId: 'ecology-factory-input', btnId: 'btn-save-ecology', startId: 'ecology-start-date', endId: 'ecology-end-date', periodType: 'ecology' },
nature: { inputId: 'nature-factory-input', btnId: 'btn-save-nature', startId: 'nature-start-date', endId: 'nature-end-date', periodType: 'nature' },
factory: { inputId: 'factory-file-input', btnId: 'btn-save-factory', startId: 'ecology-start-date', endId: 'ecology-end-date' },
};
const cfg = config[fileType];
const input = document.getElementById(cfg.inputId);
......@@ -748,8 +709,7 @@
const formData = new FormData();
formData.append('file_type', fileType);
formData.append('file', input.files[0]);
if (cfg.periodType) {
formData.append('period_type', cfg.periodType);
if (cfg.startId) {
formData.append('period_start', document.getElementById(cfg.startId).value || '');
formData.append('period_end', document.getElementById(cfg.endId).value || '');
}
......@@ -762,7 +722,6 @@
btn.style.background = '#f6ffed';
btn.style.borderColor = '#b7eb8f';
btn.style.color = '#52c41a';
// 刷新下拉列表
loadBatchOptions();
} else {
throw new Error(data.detail || '保存失败');
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!