Commit aec18105 by 江名洋

feat(analysis): Enhance factory data upload and processing

- Introduced new functions for formatting factory sheet names and determining ecology periods.
- Updated the OEM factory data loading function to return structured data with metadata.
- Improved the analysis upload process to support separate uploads for ecology and nature factory data.
- Enhanced the front-end to allow for multi-sheet uploads and improved user interface for sheet previews.
- Refactored date parsing logic to accommodate new date formats.
1 parent b45c55be
......@@ -289,15 +289,54 @@ def _load_store_df_from_batch(batch_no: str) -> "pd.DataFrame":
conn.close()
def _load_oem_factory_from_batch(batch_no: str) -> dict:
"""从DB加载OEM交付批次,返回 {sheet_name: DataFrame} 格式(兼容read_factory_data输出)"""
def _format_factory_sheet_name(start: str, end: str) -> str:
"""将 yyyy-MM-dd 日期范围格式化为 sheet 名,如 626-722"""
from datetime import datetime
s = datetime.strptime(str(start)[:10], "%Y-%m-%d")
e = datetime.strptime(str(end)[:10], "%Y-%m-%d")
return f"{s.month}{s.day:02d}-{e.month}{e.day:02d}"
def _is_ecology_period(start: str, period_type: str = "") -> bool:
"""判断主机厂数据周期是否为生态月"""
pt = (period_type or "").strip().lower()
if pt == "ecology":
return True
if pt == "nature":
return False
if start and len(str(start)) >= 10:
return int(str(start)[8:10]) >= 20
return False
def _oem_rows_to_factory_df(rows) -> "pd.DataFrame":
import pandas as pd
df = pd.DataFrame(rows)
df['门店名'] = df['store_name']
df['厅店代码'] = df['store_code']
df['区域(省)'] = df['province']
df['交付数'] = pd.to_numeric(df['delivery_count'], errors='coerce').fillna(0)
df['整车延保采购数'] = pd.to_numeric(df['ew_purchase_count'], errors='coerce').fillna(0)
df['安心包采购数'] = pd.to_numeric(df['ax_purchase_count'], errors='coerce').fillna(0)
df['电池延保采购数'] = pd.to_numeric(df['battery_purchase_count'], errors='coerce').fillna(0)
df['轮胎险采购数'] = pd.to_numeric(df['tire_purchase_count'], errors='coerce').fillna(0)
return df.drop_duplicates(subset=["门店名"], keep="first")
def _load_oem_factory_from_batch(batch_no: str) -> tuple:
"""从DB加载OEM交付批次,返回 ({sheet_name: DataFrame}, batch_meta)"""
from app.services.upload_service import _get_conn
import pandas as pd
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute("SELECT id FROM upload_batch WHERE batch_no=%s AND data_type='oem_delivery'", (batch_no,))
cur.execute(
"""SELECT id, data_period_start, data_period_end, period_type
FROM upload_batch
WHERE batch_no=%s AND data_type='oem_delivery' AND status != 3""",
(batch_no,),
)
batch = cur.fetchone()
if not batch:
raise HTTPException(status_code=404, detail=f"批次 {batch_no} 不存在")
......@@ -307,23 +346,56 @@ def _load_oem_factory_from_batch(batch_no: str) -> dict:
delivery_count, ew_purchase_count, ax_purchase_count,
battery_purchase_count, tire_purchase_count
FROM oem_delivery_data WHERE batch_id=%s""",
(batch["id"],))
(batch["id"],),
)
rows = cur.fetchall()
if not rows:
return {}
return {}, {}
start = str(batch.get("data_period_start") or "")[:10]
end = str(batch.get("data_period_end") or "")[:10]
sheet_name = _format_factory_sheet_name(start, end) if start and end else batch_no
meta = {
"period_type": batch.get("period_type") or "",
"data_period_start": start,
"data_period_end": end,
}
return {sheet_name: _oem_rows_to_factory_df(rows)}, meta
finally:
conn.close()
df = pd.DataFrame(rows)
df['门店名'] = df['store_name']
df['厅店代码'] = df['store_code']
df['区域(省)'] = df['province']
df['交付数'] = pd.to_numeric(df['delivery_count'], errors='coerce').fillna(0)
df['整车延保采购数'] = pd.to_numeric(df['ew_purchase_count'], errors='coerce').fillna(0)
df['安心包采购数'] = pd.to_numeric(df['ax_purchase_count'], errors='coerce').fillna(0)
df['电池延保采购数'] = pd.to_numeric(df['battery_purchase_count'], errors='coerce').fillna(0)
df['轮胎险采购数'] = pd.to_numeric(df['tire_purchase_count'], errors='coerce').fillna(0)
# 去重
df = df.drop_duplicates(subset=["门店名"], keep="first")
return {"Sheet1": df}
def _load_oem_factory_by_period(brand: str, start: str, end: str, period_type: str = "") -> dict:
"""按数据周期从DB查找主机厂批次并加载"""
from app.services.upload_service import _get_conn
if not start or not end:
return {}
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute(
"""SELECT batch_no FROM upload_batch
WHERE brand=%s AND data_type='oem_delivery' AND status != 3
AND data_period_start=%s AND data_period_end=%s
AND IFNULL(period_type,'')=%s
ORDER BY id DESC LIMIT 1""",
(brand, start[:10], end[:10], period_type or ""),
)
row = cur.fetchone()
if not row and period_type:
cur.execute(
"""SELECT batch_no FROM upload_batch
WHERE brand=%s AND data_type='oem_delivery' AND status != 3
AND data_period_start=%s AND data_period_end=%s
ORDER BY id DESC LIMIT 1""",
(brand, start[:10], end[:10]),
)
row = cur.fetchone()
if not row:
return {}
sheets, _ = _load_oem_factory_from_batch(row["batch_no"])
return sheets
finally:
conn.close()
......@@ -364,7 +436,9 @@ async def download_analysis_template(template_type: str):
_analysis_store_file = None # 缓存门店文件路径
_analysis_factory_file = None # 缓存主机厂文件路径(含生态月+自然月sheet)
_analysis_factory_file = None # 缓存合并主机厂文件(多 sheet,兼容旧逻辑)
_analysis_ecology_factory_file = None
_analysis_nature_factory_file = None
def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str:
......@@ -395,13 +469,16 @@ def _build_dated_filename(original_name: str, prefix: str, start_date: str = Non
async def analysis_upload(
store_file: Optional[UploadFile] = File(None),
factory_file: Optional[UploadFile] = File(None),
ecology_factory_file: Optional[UploadFile] = File(None),
nature_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),
):
"""上传门店数据、主机厂数据(含生态月+自然月多sheet,系统自动按sheet名拆分)"""
"""上传门店数据、主机厂数据(生态月/自然月可分开上传,也支持多 sheet 合并文件)"""
global _analysis_store_file, _analysis_factory_file
global _analysis_ecology_factory_file, _analysis_nature_factory_file
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
......@@ -412,14 +489,39 @@ async def analysis_upload(
_analysis_store_file = file_path
result["messages"].append(f"门店列表已上传: {store_file.filename}")
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"
def _save_factory_upload(upload_file, prefix, start_date, end_date):
global _analysis_ecology_factory_file, _analysis_nature_factory_file, _analysis_factory_file
fname = _build_dated_filename(upload_file.filename, prefix, start_date, end_date)
cat = "analysis" if (start_date and end_date) else "drafts"
file_path = _date_path(fname, category=cat)
with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f)
_analysis_factory_file = file_path
shutil.copyfileobj(upload_file.file, f)
if prefix == "analysis_factory_ecology":
_analysis_ecology_factory_file = file_path
elif prefix == "analysis_factory_nature":
_analysis_nature_factory_file = file_path
else:
_analysis_factory_file = file_path
return file_path
if ecology_factory_file and ecology_factory_file.filename:
_save_factory_upload(
ecology_factory_file, "analysis_factory_ecology",
ecology_start_date, ecology_end_date,
)
result["messages"].append(f"生态月主机厂数据已上传: {ecology_factory_file.filename}")
if nature_factory_file and nature_factory_file.filename:
_save_factory_upload(
nature_factory_file, "analysis_factory_nature",
nature_start_date, nature_end_date,
)
result["messages"].append(f"自然月主机厂数据已上传: {nature_factory_file.filename}")
if factory_file and factory_file.filename:
file_path = _save_factory_upload(
factory_file, "analysis_factory", ecology_start_date, ecology_end_date,
)
try:
import pandas as pd
sheets = pd.read_excel(file_path, sheet_name=None)
......@@ -448,17 +550,18 @@ async def analysis_save_batch(
brand: str = Form("问界"),
):
"""将分析页面上传的文件保存为历史批次,便于下次复用"""
if file_type not in ("store", "factory"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory")
if file_type not in ("store", "factory", "ecology", "nature"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/factory/ecology/nature")
if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件")
# 保存为历史时,按命名规范整理文件名
if file_type == "store":
formal_name = build_store_filename(brand, period_start, period_end)
oem_period_type = ""
else:
# 主机厂数据(含生态月+自然月,用生态月日期范围命名)
formal_name = build_factory_filename(brand, "", period_start, period_end)
oem_period_type = period_type or ("ecology" if file_type == "ecology" else "nature" if file_type == "nature" else "")
formal_name = build_factory_filename(brand, oem_period_type, period_start, period_end)
# 确保文件名唯一并保存到 batch 目录
file_path = _date_path(formal_name, category="batch")
......@@ -490,7 +593,7 @@ async def analysis_save_batch(
brand=brand,
data_period_start=period_start or "",
data_period_end=period_end or "",
period_type=period_type or "",
period_type=oem_period_type,
file_size=file_size,
remark=file_path
)
......@@ -515,9 +618,12 @@ async def analysis_generate(
nature_end_date: str = Form(None),
store_batch_no: str = Form(None),
factory_batch_no: str = Form(None),
ecology_factory_batch_no: str = Form(None),
nature_factory_batch_no: str = Form(None),
):
"""根据已上传的数据或历史批次生成生态系数分析报表(主机厂数据含多sheet自动拆分生态/自然月)"""
"""根据已上传的数据或历史批次生成生态系数分析报表"""
global _analysis_store_file, _analysis_factory_file
global _analysis_ecology_factory_file, _analysis_nature_factory_file
# 加载store_df:优先批次DB数据,其次文件,最后默认模板
if store_batch_no:
......@@ -532,26 +638,53 @@ async def analysis_generate(
else:
raise HTTPException(status_code=400, detail="请先上传门店列表文件")
# 加载主机厂数据:优先批次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)
# 加载主机厂数据:批次 / 文件 / 按日期从DB补全
ecology_factory = {}
nature_factory = {}
if not factory_data:
if ecology_factory_batch_no:
sheets, _ = _load_oem_factory_from_batch(ecology_factory_batch_no)
ecology_factory.update(sheets)
if nature_factory_batch_no:
sheets, _ = _load_oem_factory_from_batch(nature_factory_batch_no)
nature_factory.update(sheets)
# 兼容旧版单批次选择
if factory_batch_no and not ecology_factory_batch_no and not nature_factory_batch_no:
sheets, meta = _load_oem_factory_from_batch(factory_batch_no)
if _is_ecology_period(meta.get("data_period_start"), meta.get("period_type")):
ecology_factory.update(sheets)
else:
nature_factory.update(sheets)
if _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file):
ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file)
if _analysis_nature_factory_file and os.path.exists(_analysis_nature_factory_file):
nature_factory = AnalysisService.read_factory_data(_analysis_nature_factory_file)
if _analysis_factory_file and os.path.exists(_analysis_factory_file):
if not ecology_factory and not nature_factory:
ecology_factory = AnalysisService.read_factory_data(_analysis_factory_file)
elif not ecology_factory:
ecology_factory = AnalysisService.read_factory_data(_analysis_factory_file)
elif not nature_factory:
nature_factory = AnalysisService.read_factory_data(_analysis_factory_file)
if ecology_start_date and ecology_end_date and not ecology_factory:
ecology_factory = _load_oem_factory_by_period(
"问界", ecology_start_date, ecology_end_date, "ecology")
if nature_start_date and nature_end_date and not nature_factory:
nature_factory = _load_oem_factory_by_period(
"问界", nature_start_date, nature_end_date, "nature")
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(
store_df,
ecology_factory=ecology_factory or {},
nature_factory=nature_factory or {},
ecology_factory=ecology_factory,
nature_factory=nature_factory,
ecology_start=ecology_start_date or None,
ecology_end=ecology_end_date or None,
nature_start=nature_start_date or None,
......@@ -569,7 +702,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),
"factory_sheets": list(factory_data.keys()) if factory_data else [],
"factory_sheets": list(ecology_factory.keys()) + list(nature_factory.keys()),
}
except Exception as e:
logger.error(f"Analysis generate failed: {e}", exc_info=True)
......@@ -610,10 +743,11 @@ async def analysis_download(file: str = Query(None)):
@router.post("/analysis/preview-file")
async def analysis_preview_file(
file_type: str = Form(...), # "store" or "factory"
file_type: str = Form(...), # "store" or "factory" or "ecology" or "nature"
file: UploadFile = File(...),
):
"""上传分析文件并返回解析后的预览数据"""
"""上传分析文件并返回解析后的预览数据(factory 类型返回多 sheet)"""
import pandas as pd
file_path = _date_path(f"_preview_{file.filename}", category="drafts")
try:
with open(file_path, "wb") as f:
......@@ -621,18 +755,25 @@ async def analysis_preview_file(
if file_type == "store":
df = AnalysisService.read_store_list(file_path)
else:
data = AnalysisService.read_factory_data(file_path)
sheet_names = list(data.keys())
if sheet_names:
df = data[sheet_names[0]]
else:
df = pd.DataFrame()
import pandas as pd
rows = df.head(100).fillna("").to_dict(orient="records")
columns = list(df.columns)
return {"status": "success", "data": {"columns": columns, "rows": rows, "total": len(df)}}
rows = df.head(100).fillna("").to_dict(orient="records")
columns = list(df.columns)
return {"status": "success", "data": {"columns": columns, "rows": rows, "total": len(df)}}
data = AnalysisService.read_factory_data(file_path)
sheets_payload = {}
for name, df in data.items():
sheets_payload[name] = {
"columns": list(df.columns),
"rows": df.head(100).fillna("").to_dict(orient="records"),
"total": len(df),
}
return {
"status": "success",
"data": {
"sheets": sheets_payload,
"sheet_names": list(sheets_payload.keys()),
},
}
except Exception as e:
logger.error(f"Analysis preview file failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"文件解析失败: {str(e)}")
......@@ -652,7 +793,9 @@ async def analysis_batch_data(batch_no: str = Query(...)):
try:
with conn.cursor() as cur:
cur.execute(
"""SELECT id, batch_no, data_type FROM upload_batch
"""SELECT id, batch_no, data_type, period_type,
data_period_start, data_period_end, file_name
FROM upload_batch
WHERE batch_no = %s AND status != 3""",
(batch_no,),
)
......@@ -702,7 +845,15 @@ async def analysis_batch_data(batch_no: str = Query(...)):
return {
"status": "success",
"data": {"columns": columns, "rows": clean_rows, "total": len(rows)},
"data": {
"columns": columns,
"rows": clean_rows,
"total": len(rows),
"period_type": batch.get("period_type") or "",
"data_period_start": str(batch.get("data_period_start") or "")[:10],
"data_period_end": str(batch.get("data_period_end") or "")[:10],
"file_name": batch.get("file_name") or "",
},
}
finally:
conn.close()
......@@ -796,7 +947,8 @@ async def harmony_generate(
# 加载factory_df:优先批次DB数据,其次文件
factory_df = None
if factory_batch_no:
factory_df = _load_oem_factory_from_batch(factory_batch_no)
sheets, _ = _load_oem_factory_from_batch(factory_batch_no)
factory_df = sheets
elif _harmony_factory_file and os.path.exists(_harmony_factory_file):
factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)
......
......@@ -407,13 +407,27 @@ class AnalysisService:
start = f"{current_year}-{m1:02d}-{d1:02d}"
end = f"{current_year}-{m2:02d}-{d2:02d}"
return start, end
# 格式2: MDD-MDD (如 626-722,月份1位+日期2位)
m = re.match(r'(\d{1,2})(\d{1,2})\s*[-~]\s*(\d{1,2})(\d{1,2})', s)
# 格式2: MDD-MDD / MMDD-MMDD (如 626-722、0701-0723)
m = re.match(r'(\d{3,4})\s*[-~]\s*(\d{3,4})', s)
if m:
m1, d1, m2, d2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
start = f"{current_year}-{m1:02d}-{d1:02d}"
end = f"{current_year}-{m2:02d}-{d2:02d}"
return start, end
def _parse_mdd_token(token: str):
token = token.strip()
if len(token) == 3:
return int(token[0]), int(token[1:3])
if len(token) == 4:
month = int(token[:2])
day = int(token[2:4])
if 1 <= month <= 12:
return month, day
return int(token[0]), int(token[1:4])
return None, None
m1, d1 = _parse_mdd_token(m.group(1))
m2, d2 = _parse_mdd_token(m.group(2))
if m1 and d1 and m2 and d2:
start = f"{current_year}-{m1:02d}-{d1:02d}"
end = f"{current_year}-{m2:02d}-{d2:02d}"
return start, end
logger.warning(f"Unable to parse date range: {date_range_str}, using yesterday")
yesterday = (date.today() - timedelta(days=1)).strftime('%Y-%m-%d')
return yesterday, yesterday
......@@ -966,10 +980,8 @@ class AnalysisService:
nat_sheets[sn] = df
if not nature_start:
nature_start, nature_end = AnalysisService._parse_date_range(sn)
if eco_sheets:
ecology_factory = eco_sheets
if nat_sheets:
nature_factory = nat_sheets
ecology_factory = eco_sheets
nature_factory = nat_sheets
logger.info(f"Auto-split factory sheets: ecology={list(eco_sheets.keys())}, "
f"nature={list(nat_sheets.keys())}")
......@@ -1032,48 +1044,54 @@ class AnalysisService:
cell.fill = SEPARATOR_FILL
cell.border = THIN_BORDER
cell.alignment = Alignment(horizontal="center", vertical="center")
# 标签文字放在中间列(约29列),视觉上居中
ws.cell(row=row, column=29).value = label_text
ws.cell(row=row, column=27).font = SEPARATOR_FONT
ws.row_dimensions[row].height = 24
next_row = 4
def _write_section(ws, next_row, label_text, store_subset, factory_sheets,
start_date, end_date, track_first_data=False):
"""标签行 + 数据行(每种数据上方仅一行蓝色标签)"""
nonlocal first_data_row
_write_separator(ws, next_row, label_text)
next_row += 1
if track_first_data and first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet(
ws, store_subset, factory_sheets,
start_date, end_date, formula_map, skip_external_cols, start_row=next_row)
return next_row
next_row = 5
first_data_row = None
# 生态数据标签行
eco_label_text = f"▲ 生态数据({ecology_start} ~ {ecology_end})" if ecology_start and ecology_end else "▲ 生态数据"
if has_ecology:
_write_separator(ws, next_row, eco_label_text)
next_row += 1
eco_label_text = (
f"▲ 生态月数据({ecology_start} ~ {ecology_end})"
if ecology_start and ecology_end else "▲ 生态月数据"
)
nat_label_text = (
f"▼ 自然月数据({nature_start} ~ {nature_end})"
if nature_start and nature_end else "▼ 自然月数据"
)
# 处理生态数据(上部)
# 生态月数据(上部)
if has_ecology:
if first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet(
ws, ecology_stores, ecology_factory,
ecology_start, ecology_end, formula_map, skip_external_cols, start_row=next_row)
next_row = _write_section(
ws, next_row, eco_label_text,
ecology_stores, ecology_factory,
ecology_start, ecology_end, track_first_data=True,
)
else:
reason = "no stores" if len(ecology_stores) == 0 else "no factory data"
logger.info(f"Skipping ecology section ({reason})")
# 自然月数据标签行(中间隔离行)
nat_label_text = f"▼ 自然月数据({nature_start} ~ {nature_end})" if nature_start and nature_end else "▼ 自然月数据"
if has_ecology and has_nature:
_write_separator(ws, next_row, nat_label_text)
next_row += 1
# 处理自然月数据(下部)
# 自然月数据(下部,与生态月拼在同一表)
if has_nature:
# 如果仅自然月(无生态数据),在顶部也加标签
if not has_ecology:
_write_separator(ws, next_row, nat_label_text)
next_row += 1
if first_data_row is None:
first_data_row = next_row
next_row = AnalysisService._process_one_sheet(
ws, nature_stores, nature_factory,
nature_start, nature_end, formula_map, skip_external_cols, start_row=next_row)
next_row = _write_section(
ws, next_row, nat_label_text,
nature_stores, nature_factory,
nature_start, nature_end,
track_first_data=(first_data_row is None),
)
else:
reason = "no stores" if len(nature_stores) == 0 else "no factory data"
logger.info(f"Skipping nature section ({reason})")
......@@ -1086,6 +1104,9 @@ class AnalysisService:
last_col_letter = get_column_letter(len(OUTPUT_HEADERS))
ws.auto_filter.ref = f"A3:{last_col_letter}{next_row - 1}"
# 冻结窗格:D5(固定前3行表头 + A~C列)
ws.freeze_panes = "D5"
wb.save(output_path)
logger.info(f"Report generated: {output_path}")
return output_path
......
......@@ -254,6 +254,31 @@
margin-top: 10px;
}
.preview-sheet-tabs {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 8px 16px;
border-bottom: 1px solid #e8e8e8;
background: #fafafa;
}
.preview-sheet-tab {
padding: 4px 12px;
font-size: 12px;
cursor: pointer;
border-radius: 4px;
border: 1px solid #d9d9d9;
background: #fff;
color: #555;
}
.preview-sheet-tab.active {
background: #1890ff;
border-color: #1890ff;
color: #fff;
}
.preview-sheet-tab.ecology:not(.active) { border-color: #91d5ff; color: #1890ff; }
.preview-sheet-tab.nature:not(.active) { border-color: #b7eb8f; color: #52c41a; }
@media (max-width: 900px) {
.analysis-layout { flex-direction: column; height: auto; }
.left-panel { width: 100%; min-width: 0; }
......@@ -303,7 +328,7 @@
<button class="btn-save-batch" id="btn-save-store" style="display:none;" onclick="saveBatch('store')">&#x1f4be; 保存为历史批次</button>
</div>
<!-- 步骤2: 主机厂数据(生态+自然月合并为单文件) -->
<!-- 步骤2: 主机厂数据(单文件多 Sheet,按 sheet 名区分生态月/自然月) -->
<div class="step-card" id="step2-card">
<div class="step-title">&#9313; 步骤2: 主机厂数据(含生态月+自然月)</div>
<div class="step-row">
......@@ -315,7 +340,7 @@
<span class="step-or">或</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>
&#x1f4c1; <span id="factory-file-name">点击上传主机厂数据(含生态月+自然月 sheet)</span>
</div>
<a class="btn-download-tpl" href="./api/analysis/template/factory">&#x1f4e5; 模板</a>
</div>
......@@ -331,7 +356,7 @@
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="nature-end-date" title="自然月结束日期">
</div>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份含多sheet的主机厂数据,系统自动按sheet名日期拆分生态月/自然月数据</p>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份含多 Sheet 的主机厂 Excel,系统按 Sheet 名日期自动识别生态月/自然月;右侧预览可切换 Sheet</p>
<button class="btn-save-batch" id="btn-save-factory" style="display:none;" onclick="saveBatch('factory')">&#x1f4be; 保存为历史批次</button>
</div>
......@@ -340,7 +365,7 @@
<button class="btn-generate" id="btn-generate-report">
&#x1f680; 开始生成分析报表
</button>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份主机厂数据(含多sheet),系统自动按sheet名日期拆分生态月/自然月数据,按兜底截止日期分组门店</p>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份主机厂数据(含多 Sheet),系统按 Sheet 名自动拆分生态月/自然月,按兜底截止日期分组门店</p>
</div>
<!-- 生成结果 -->
......@@ -362,6 +387,7 @@
<span id="preview-count" style="font-size:11px;color:#999;"></span>
</div>
<div class="right-panel-meta" id="preview-meta" style="display:none;"></div>
<div class="preview-sheet-tabs" id="preview-sheet-tabs" style="display:none;"></div>
<div class="right-panel-body" id="preview-body">
<div class="right-panel-empty" id="preview-empty">
请在左侧选择历史批次或上传文件,数据将在此处预览
......@@ -431,23 +457,37 @@
await previewFile(formData, '门店列表 - ' + name);
};
// ========== 步骤2: 主机厂数据(单文件,含生态月+自然月sheet) ==========
// ========== 步骤2: 主机厂数据(单文件多 Sheet) ==========
window.onFactoryBatchSelect = async function() {
const sel = document.getElementById('factory-batch-select');
if (!sel.value) return;
highlightStep('step2-card');
document.getElementById('factory-file-input').value = '';
document.getElementById('factory-file-name').textContent = '点击上传主机厂数据(含生态月+自然月 sheet)';
document.getElementById('factory-drop-zone').classList.remove('has-file');
const opt = sel.options[sel.selectedIndex];
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;
const ps = opt.dataset.periodStart || '';
const pe = opt.dataset.periodEnd || '';
const pt = opt.dataset.periodType || '';
if (ps && pe) {
if (pt === 'ecology') {
document.getElementById('ecology-start-date').value = ps;
document.getElementById('ecology-end-date').value = pe;
} else if (pt === 'nature') {
document.getElementById('nature-start-date').value = ps;
document.getElementById('nature-end-date').value = pe;
} else {
document.getElementById('ecology-start-date').value = ps;
document.getElementById('ecology-end-date').value = pe;
document.getElementById('nature-start-date').value = ps;
document.getElementById('nature-end-date').value = pe;
}
}
const periodLabel = pt === 'ecology' ? '生态月' : pt === 'nature' ? '自然月' : '';
await loadBatchPreview(sel.value, '主机厂数据 - 历史批次', {
type: '主机厂交付数据',
period: opt.dataset.periodStart ? `${opt.dataset.periodStart} ~ ${opt.dataset.periodEnd}` : '',
periodType: periodLabel,
period: ps ? `${ps} ~ ${pe}` : '',
source: opt.textContent.split(' [')[0],
});
};
......@@ -465,7 +505,10 @@
const formData = new FormData();
formData.append('file_type', 'factory');
formData.append('file', input.files[0]);
await previewFile(formData, '主机厂数据 - ' + name);
await previewFile(formData, '主机厂数据 - ' + name, {
type: '主机厂交付数据',
source: name,
});
};
// ========== 生成报表 ==========
......@@ -485,10 +528,8 @@
const hasStoreBatch = storeBatchSel && storeBatchSel.value;
const hasFactoryBatch = factoryBatchSel && factoryBatchSel.value;
const hasFactory = hasFactoryFile || hasFactoryBatch;
if (!hasFactory) {
alert('请上传或选择主机厂数据(步骤2)');
if (!hasFactoryFile && !hasFactoryBatch) {
alert('请上传或选择主机厂数据(步骤2)');
return;
}
......@@ -581,11 +622,21 @@
opt.value = r.batch_no;
opt.dataset.periodStart = r.data_period_start || '';
opt.dataset.periodEnd = r.data_period_end || '';
opt.textContent = `${r.file_name || r.batch_no} [${r.data_period_start}~${r.data_period_end}]`;
opt.dataset.periodType = periodTypeOfRow(r);
const tag = periodTypeOfRow(r) === 'ecology' ? '生态月' : '自然月';
opt.textContent = `[${tag}] ${r.file_name || r.batch_no} [${r.data_period_start}~${r.data_period_end}]`;
sel.appendChild(opt);
});
}
function periodTypeOfRow(r) {
const pt = (r.period_type || '').toLowerCase();
if (pt === 'ecology') return 'ecology';
if (pt === 'nature') return 'nature';
const day = parseInt((r.data_period_start || '').slice(8, 10), 10);
return day >= 20 ? 'ecology' : 'nature';
}
if (storeData.status === 'success') {
fillSelect('store-batch-select', storeData.data);
}
......@@ -604,7 +655,13 @@
const res = await fetch(window.API_BASE + '/analysis/batch-data?batch_no=' + encodeURIComponent(batchNo));
const data = await res.json();
if (data.status === 'success') {
renderPreviewTable(data.data, title, meta);
const batchMeta = { ...(meta || {}) };
if (data.data.period_type === 'ecology') batchMeta.periodType = '生态月';
else if (data.data.period_type === 'nature') batchMeta.periodType = '自然月';
if (!batchMeta.period && data.data.data_period_start) {
batchMeta.period = `${data.data.data_period_start} ~ ${data.data.data_period_end}`;
}
renderPreviewTable(data.data, title, batchMeta);
} else {
showPreviewError(data.detail || '加载失败');
}
......@@ -614,13 +671,37 @@
}
}
async function previewFile(formData, title) {
function inferSheetPeriodType(sheetName) {
const s = String(sheetName || '').trim().replace(/[()()]/g, '');
const m = s.match(/(\d{3,4})\s*[-~]\s*(\d{3,4})/);
if (!m) return '';
const token = m[1];
let day;
if (token.length === 3) day = parseInt(token.slice(1), 10);
else day = parseInt(token.slice(2), 10);
if (Number.isNaN(day)) return '';
return day >= 20 ? 'ecology' : 'nature';
}
function sheetPeriodLabel(sheetName) {
const pt = inferSheetPeriodType(sheetName);
if (pt === 'ecology') return '生态月';
if (pt === 'nature') return '自然月';
return '';
}
function formatSheetTabLabel(sheetName) {
const label = sheetPeriodLabel(sheetName);
return label ? `${sheetName} (${label})` : sheetName;
}
async function previewFile(formData, title, meta) {
showPreviewLoading(title);
try {
const res = await fetch(window.API_BASE + '/analysis/preview-file', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
renderPreviewTable(data.data, title);
renderPreviewTable(data.data, title, meta);
} else {
showPreviewError(data.detail || '解析失败');
}
......@@ -630,10 +711,85 @@
}
}
let _previewSheetsCache = null;
let _previewActiveSheet = null;
let _previewMetaCache = null;
function hidePreviewSheetTabs() {
const tabs = document.getElementById('preview-sheet-tabs');
tabs.style.display = 'none';
tabs.innerHTML = '';
_previewSheetsCache = null;
_previewActiveSheet = null;
}
function renderPreviewSheetTabs(sheetNames) {
const tabs = document.getElementById('preview-sheet-tabs');
tabs.innerHTML = '';
sheetNames.forEach((name, idx) => {
const btn = document.createElement('button');
btn.type = 'button';
const pt = inferSheetPeriodType(name);
btn.className = 'preview-sheet-tab' + (idx === 0 ? ' active' : '') + (pt ? ' ' + pt : '');
btn.textContent = formatSheetTabLabel(name);
btn.dataset.sheet = name;
btn.onclick = () => switchPreviewSheet(name);
tabs.appendChild(btn);
});
tabs.style.display = 'flex';
}
window.switchPreviewSheet = function(sheetName) {
if (!_previewSheetsCache || !_previewSheetsCache[sheetName]) return;
_previewActiveSheet = sheetName;
document.querySelectorAll('.preview-sheet-tab').forEach(tab => {
tab.classList.toggle('active', tab.dataset.sheet === sheetName);
});
const sheet = _previewSheetsCache[sheetName];
const ptLabel = sheetPeriodLabel(sheetName);
document.getElementById('preview-count').textContent =
'当前 Sheet「' + sheetName + '」' + (ptLabel ? '(' + ptLabel + ')' : '') + ' 共 ' + sheet.total + ' 条';
if (_previewMetaCache) {
const meta = { ..._previewMetaCache, periodType: ptLabel || _previewMetaCache.periodType };
renderPreviewMeta(meta, sheet.total);
}
renderPreviewTableBody(sheet);
};
function renderPreviewTableBody(tableData) {
const { columns, rows } = tableData;
if (!columns.length || !rows.length) {
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">无数据</div>';
return;
}
let html = '<table class="preview-table"><thead><tr>';
html += '<th style="width:40px;text-align:center;">#</th>';
columns.forEach(c => {
html += '<th>' + escapeHtml(String(c)) + '</th>';
});
html += '</tr></thead><tbody>';
rows.forEach((row, i) => {
html += '<tr>';
html += '<td style="text-align:center;color:#999;">' + (i + 1) + '</td>';
columns.forEach(c => {
const val = row[c] !== undefined && row[c] !== null ? String(row[c]) : '';
html += '<td>' + escapeHtml(val) + '</td>';
});
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('preview-body').innerHTML = html;
}
function showPreviewLoading(title) {
document.getElementById('preview-title').textContent = '\u23f3 ' + title;
document.getElementById('preview-count').textContent = '加载中...';
document.getElementById('preview-meta').style.display = 'none';
hidePreviewSheetTabs();
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">正在解析数据...</div>';
}
......@@ -642,15 +798,43 @@
document.getElementById('preview-title').textContent = '\u274c 加载失败';
document.getElementById('preview-count').textContent = '';
document.getElementById('preview-meta').style.display = 'none';
hidePreviewSheetTabs();
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">' + msg + '</div>';
}
function renderPreviewTable(data, title, meta) {
document.getElementById('preview-title').textContent = '\u{1f4ca} ' + title;
document.getElementById('preview-count').textContent = '共 ' + data.total + ' 条';
_previewMetaCache = meta || null;
if (data.sheets && data.sheet_names && data.sheet_names.length) {
_previewSheetsCache = data.sheets;
_previewActiveSheet = data.sheet_names[0];
const first = data.sheets[_previewActiveSheet];
const totalAll = data.sheet_names.reduce((sum, n) => sum + (data.sheets[n].total || 0), 0);
const ecoCount = data.sheet_names.filter(n => inferSheetPeriodType(n) === 'ecology').length;
const natCount = data.sheet_names.filter(n => inferSheetPeriodType(n) === 'nature').length;
let countText = data.sheet_names.length > 1
? `${data.sheet_names.length} 个 Sheet,合计 ${totalAll} 条`
: '共 ' + first.total + ' 条';
if (ecoCount || natCount) {
countText += `(生态月 ${ecoCount} / 自然月 ${natCount})`;
}
document.getElementById('preview-count').textContent = countText;
const sheetMeta = { ...(meta || {}), periodType: sheetPeriodLabel(_previewActiveSheet) };
renderPreviewMeta(sheetMeta, first.total);
renderPreviewSheetTabs(data.sheet_names);
renderPreviewTableBody(first);
return;
}
// 渲染批次元信息
hidePreviewSheetTabs();
document.getElementById('preview-count').textContent = '共 ' + (data.total || 0) + ' 条';
renderPreviewMeta(meta, data.total || 0);
renderPreviewTableBody(data);
}
function renderPreviewMeta(meta, total) {
const metaDiv = document.getElementById('preview-meta');
if (meta) {
let html = '';
......@@ -658,47 +842,26 @@
if (meta.periodType) html += `<span class="meta-item"><span class="meta-label">周期类型:</span><span class="meta-value">${escapeHtml(meta.periodType)}</span></span>`;
if (meta.period) html += `<span class="meta-item"><span class="meta-label">时间范围:</span><span class="meta-value">${escapeHtml(meta.period)}</span></span>`;
if (meta.source) html += `<span class="meta-item"><span class="meta-label">来源:</span><span class="meta-value">${escapeHtml(meta.source)}</span></span>`;
html += `<span class="meta-item"><span class="meta-label">数据行数:</span><span class="meta-value">${data.total}</span></span>`;
html += `<span class="meta-item"><span class="meta-label">数据行数:</span><span class="meta-value">${total}</span></span>`;
metaDiv.innerHTML = html;
metaDiv.style.display = 'flex';
} else {
metaDiv.style.display = 'none';
}
const { columns, rows } = data;
if (!columns.length || !rows.length) {
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">无数据</div>';
return;
}
let html = '<table class="preview-table"><thead><tr>';
html += '<th style="width:40px;text-align:center;">#</th>';
columns.forEach(c => {
html += '<th>' + escapeHtml(String(c)) + '</th>';
});
html += '</tr></thead><tbody>';
rows.forEach((row, i) => {
html += '<tr>';
html += '<td style="text-align:center;color:#999;">' + (i + 1) + '</td>';
columns.forEach(c => {
const val = row[c] !== undefined && row[c] !== null ? String(row[c]) : '';
html += '<td>' + escapeHtml(val) + '</td>';
});
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('preview-body').innerHTML = html;
}
async function saveBatch(fileType) {
const config = {
store: { inputId: 'store-file-input', btnId: 'btn-save-store' },
factory: { inputId: 'factory-file-input', btnId: 'btn-save-factory', startId: 'ecology-start-date', endId: 'ecology-end-date' },
factory: {
inputId: 'factory-file-input',
btnId: 'btn-save-factory',
startId: 'ecology-start-date',
endId: 'ecology-end-date',
},
};
const cfg = config[fileType];
if (!cfg) return;
const input = document.getElementById(cfg.inputId);
if (!input || !input.files.length) { alert('请先上传文件'); return; }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!