Commit a19fc9e6 by 江名洋

feat(analysis): 支持生态与自然月双sheet报表生成

1 parent bf2fcff1
...@@ -212,14 +212,17 @@ async def download_analysis_template(template_type: str): ...@@ -212,14 +212,17 @@ async def download_analysis_template(template_type: str):
_analysis_store_file = None # 缓存门店文件路径 _analysis_store_file = None # 缓存门店文件路径
_analysis_ecology_factory_file = None # 缓存生态主机厂文件路径
_analysis_nature_factory_file = None # 缓存自然月主机厂文件路径
@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),
factory_file: Optional[UploadFile] = File(None), ecology_factory_file: Optional[UploadFile] = File(None),
nature_factory_file: Optional[UploadFile] = File(None),
): ):
"""上传门店数据和主机厂数据""" """上传门店数据、生态主机厂数据(26日周期)、自然月主机厂数据(1日周期)"""
result = {"status": "success", "messages": []} result = {"status": "success", "messages": []}
if store_file and store_file.filename: if store_file and store_file.filename:
...@@ -230,22 +233,36 @@ async def analysis_upload( ...@@ -230,22 +233,36 @@ async def analysis_upload(
_analysis_store_file = file_path _analysis_store_file = file_path
result["messages"].append(f"门店列表已上传: {store_file.filename}") result["messages"].append(f"门店列表已上传: {store_file.filename}")
factory_paths = {} def _save_factory(upload_file, prefix, global_var_name):
if factory_file and factory_file.filename: if not upload_file or not upload_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"analysis_factory_{factory_file.filename}") return None
file_path = os.path.join(UPLOAD_DIR, f"analysis_{prefix}_{upload_file.filename}")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f) shutil.copyfileobj(upload_file.file, f)
# 读取sheet信息
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)
factory_paths["path"] = file_path return {
factory_paths["sheets"] = list(sheets.keys()) "path": file_path,
factory_paths["sheet_count"] = len(sheets) "sheets": list(sheets.keys()),
"sheet_count": len(sheets),
}
except Exception as e: except Exception as e:
factory_paths["error"] = str(e) return {"path": file_path, "error": str(e)}
result["factory_info"] = factory_paths
result["messages"].append(f"主机厂数据已上传: {factory_file.filename}") ecology_info = _save_factory(ecology_factory_file, "ecology", "_analysis_ecology_factory_file")
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")
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="请至少上传一个文件")
...@@ -256,43 +273,54 @@ async def analysis_upload( ...@@ -256,43 +273,54 @@ async def analysis_upload(
@router.post("/analysis/generate") @router.post("/analysis/generate")
async def analysis_generate( async def analysis_generate(
background_tasks: BackgroundTasks, background_tasks: BackgroundTasks,
start_date: str = Form(None), ecology_start_date: str = Form(None),
end_date: str = Form(None) ecology_end_date: str = Form(None),
nature_start_date: str = Form(None),
nature_end_date: str = Form(None)
): ):
"""根据已上传的数据生成生态系数分析报表""" """根据已上传的数据生成生态系数分析报表(双sheet:生态数据+自然月)"""
global _analysis_store_file global _analysis_store_file, _analysis_ecology_factory_file, _analysis_nature_factory_file
if not _analysis_store_file or not os.path.exists(_analysis_store_file): if not _analysis_store_file or not os.path.exists(_analysis_store_file):
raise HTTPException(status_code=400, detail="请先上传门店列表文件") raise HTTPException(status_code=400, detail="请先上传门店列表文件")
# 查找最近上传的主机厂数据文件 ecology_factory = None
factory_files = sorted( nature_factory = None
[f for f in os.listdir(UPLOAD_DIR) if f.startswith("analysis_factory_") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(os.path.join(UPLOAD_DIR, f)), if _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file):
reverse=True ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file)
)
if not factory_files:
raise HTTPException(status_code=400, detail="请先上传主机厂数据文件")
factory_path = os.path.join(UPLOAD_DIR, factory_files[0]) if _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:
raise HTTPException(status_code=400, detail="请至少上传一个主机厂数据文件(生态或自然月)")
try: try:
store_df = AnalysisService.read_store_list(_analysis_store_file) store_df = AnalysisService.read_store_list(_analysis_store_file)
factory_sheets = AnalysisService.read_factory_data(factory_path)
output_path = AnalysisService.build_report( output_path = AnalysisService.build_report(
store_df, factory_sheets, store_df,
start_date=start_date or None, ecology_factory=ecology_factory or {},
end_date=end_date or None nature_factory=nature_factory or {},
ecology_start=ecology_start_date or None,
ecology_end=ecology_end_date or None,
nature_start=nature_start_date or None,
nature_end=nature_end_date or None
) )
# 统计信息
ecology_stores = store_df[store_df["兜底截止日期"].apply(AnalysisService._is_ecology_deadline)]
nature_stores = store_df[~store_df["兜底截止日期"].apply(AnalysisService._is_ecology_deadline)]
return { return {
"status": "success", "status": "success",
"message": "分析报表已生成", "message": "分析报表已生成",
"file_path": output_path, "file_path": output_path,
"download_url": "/api/analysis/download", "download_url": "/api/analysis/download",
"store_count": len(store_df), "ecology_store_count": len(ecology_stores),
"factory_sheets": list(factory_sheets.keys()), "nature_store_count": len(nature_stores),
"factory_rows": sum(len(v) for v in factory_sheets.values()), "ecology_factory_sheets": list(ecology_factory.keys()) if ecology_factory 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)
......
...@@ -515,62 +515,18 @@ class AnalysisService: ...@@ -515,62 +515,18 @@ class AnalysisService:
conn.close() conn.close()
@staticmethod @staticmethod
def build_report(store_df: pd.DataFrame, factory_sheets: dict, def _is_ecology_deadline(deadline_val) -> bool:
start_date: str = None, end_date: str = None) -> str: """兜底截止日期为'25日'的属于生态周期(26日起始),其余为自然月"""
""" if deadline_val is None or (isinstance(deadline_val, float) and pd.isna(deadline_val)):
构建生态系数分析报表。基于模板文件填充数据,保留格式。 return False
s = str(deadline_val).strip()
Args: return "25" in s
store_df: 门店列表(18列新模板)
factory_sheets: 主机厂数据sheet字典
start_date: 产值数据查询开始日期 (yyyy-MM-dd)
end_date: 产值数据查询结束日期 (yyyy-MM-dd)
"""
import shutil
# 查找模板文件
template_path = os.path.join("app", "templates", "输出-问界生态系数-模板.xlsx")
if not os.path.exists(template_path):
raise FileNotFoundError(f"模板文件不存在: {template_path}")
# 确定日期范围(开始日期固定为上月26日)
if start_date and end_date:
date_range_label = f"{start_date} ~ {end_date}"
elif factory_sheets:
main_sheet_name = max(factory_sheets.keys(), key=lambda k: len(factory_sheets[k]))
_, end_date = AnalysisService._parse_date_range(main_sheet_name.strip("()()"))
start_date = AnalysisService._last_month_26()
date_range_label = f"{start_date} ~ {end_date}"
else:
yesterday = (date.today() - timedelta(days=1)).strftime('%Y-%m-%d')
last_month_26 = AnalysisService._last_month_26()
start_date, end_date = last_month_26, yesterday
date_range_label = f"{start_date} ~ {end_date}"
# 查询数据库产值数据(包含门店基础信息:区域、运营负责人等)
# 参考 generate_weekly_comparison.py query_weekly_detail() 的 SQL 逻辑
store_names = [str(n) for n in store_df["门店名"].tolist() if pd.notna(n)]
db_perf = AnalysisService._query_store_performance(store_names, start_date, end_date)
logger.info(f"DB performance + store info fetched for {len(db_perf)} stores "
f"({start_date} ~ {end_date}, first_brand_id={AnalysisService.FIRST_BRAND_ID})")
# 复制模板到输出目录
output_dir = "temp_uploads"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 生成输出文件名(含日期范围)
safe_label = date_range_label.replace(" ", "").replace("~", "-")
output_path = os.path.join(output_dir, f"问界生态系数分析_{safe_label}.xlsx")
shutil.copy2(template_path, output_path)
# 打开模板进行编辑
wb = load_workbook(output_path)
ws = wb["问界生态系数(5.26-6.14)"]
# 读取第4行公式(在清除数据之前),清理外部引用 @staticmethod
def _extract_formulas_from_template(ws):
"""从模板第4行提取公式映射和外部引用列集合"""
formula_map = {} formula_map = {}
skip_external_cols = set() # 引用外部工作簿的列,用Python值替代 skip_external_cols = set()
for col in range(1, 54): for col in range(1, 54):
cell = ws.cell(row=4, column=col) cell = ws.cell(row=4, column=col)
raw = cell.value raw = cell.value
...@@ -582,27 +538,125 @@ class AnalysisService: ...@@ -582,27 +538,125 @@ class AnalysisService:
formula_text = raw.text formula_text = raw.text
else: else:
continue continue
# 清理外部工作簿引用
cleaned = formula_text cleaned = formula_text
# [3]Sheet1 → 门店数据(需要我们在输出中嵌入门店数据sheet) if re.search(r'\[\d+\]', cleaned):
if '[3]' in cleaned or '[1]' in cleaned: # 外部引用([1]Sheet1、[2]阶梯赔付等)无法解析,跳过,由Python计算值替代
# 如果引用 [1]在线表格副本 → 去掉[1](该sheet在输出模板中存在)
cleaned = re.sub(r'\[1\](在线表格副本)', r'\1', cleaned)
if '[3]' in cleaned or '[1]阶梯赔付明细子表' in cleaned:
skip_external_cols.add(col) skip_external_cols.add(col)
continue continue
formula_map[col] = cleaned formula_map[col] = cleaned
return formula_map, skip_external_cols
# 清除数据行(第4行到max_row),保留表头和公式 @staticmethod
def _clear_sheet_data(ws):
"""清除第4行起的所有数据"""
for r in range(4, ws.max_row + 1): for r in range(4, ws.max_row + 1):
for c in range(1, 54): for c in range(1, 54):
ws.cell(row=r, column=c).value = None ws.cell(row=r, column=c).value = None
# 写入新数据 @staticmethod
AnalysisService._write_data_rows(ws, store_df, factory_sheets, db_perf, def _process_one_sheet(ws, store_subset, factory_sheets, start_date, end_date,
start_date, end_date, formula_map, formula_map, skip_external_cols):
skip_external_cols) """对单张sheet写入数据:查DB → 写数据行"""
store_names = [str(n) for n in store_subset["门店名"].tolist() if pd.notna(n)]
if not store_names:
logger.info("No stores for this sheet, skipping DB query")
return
db_perf = AnalysisService._query_store_performance(store_names, start_date, end_date)
logger.info(f"DB fetched {len(db_perf)} stores ({start_date} ~ {end_date})")
AnalysisService._write_data_rows(ws, store_subset, factory_sheets, db_perf,
start_date, end_date, formula_map, skip_external_cols)
@staticmethod
def build_report(store_df: pd.DataFrame,
ecology_factory: dict = None, nature_factory: dict = None,
ecology_start: str = None, ecology_end: str = None,
nature_start: str = None, nature_end: str = None) -> str:
"""
构建生态系数分析报表。
从模板文件读取"模板"sheet,复制出两份:
- Sheet1: 生态数据 — 兜底截止日期为"25日"的门店,使用生态主机厂数据
- Sheet2: 自然月 — 兜底截止日期不是"25日"的门店,使用自然月主机厂数据
"""
import shutil
TEMPLATE_FILE = os.path.join("app", "templates", "输出-问界生态系数-模板.xlsx")
TEMPLATE_SHEET = "模板"
if not os.path.exists(TEMPLATE_FILE):
raise FileNotFoundError(f"模板文件不存在: {TEMPLATE_FILE}")
if ecology_factory is None:
ecology_factory = {}
if nature_factory is None:
nature_factory = {}
ecology_sheet_name = f"生态数据({ecology_start}~{ecology_end})" if ecology_start and ecology_end else "生态数据"
nature_sheet_name = f"自然月({nature_start}~{nature_end})" if nature_start and nature_end else "自然月"
output_dir = "temp_uploads"
os.makedirs(output_dir, exist_ok=True)
safe_label = (ecology_sheet_name + "_" + nature_sheet_name).replace(" ", "").replace("~", "-")[:70]
output_path = os.path.join(output_dir, f"问界生态系数分析_{safe_label}.xlsx")
shutil.copy2(TEMPLATE_FILE, output_path)
wb = load_workbook(output_path)
ws_template = wb[TEMPLATE_SHEET]
# 提取公式(在清除任何数据之前)
formula_map, skip_external_cols = AnalysisService._extract_formulas_from_template(ws_template)
# openpyxl 的 copy_worksheet 不复制条件格式,需手动保存
cf_rules = [(cf.sqref, list(cf.rules)) for cf in ws_template.conditional_formatting]
# 复制两份"模板"sheet
ws_ecology = wb.copy_worksheet(ws_template)
ws_nature = wb.copy_worksheet(ws_template)
ws_ecology.title = ecology_sheet_name
ws_nature.title = nature_sheet_name
# 保留原始"模板"sheet
# 将条件格式复制到两个新 sheet
for sqref, rules in cf_rules:
ws_ecology.conditional_formatting.add(sqref, *rules)
ws_nature.conditional_formatting.add(sqref, *rules)
logger.info(f"Copied {len(cf_rules)} conditional formatting rules to both sheets")
# 清除数据行(保留表头1-3行)
AnalysisService._clear_sheet_data(ws_ecology)
AnalysisService._clear_sheet_data(ws_nature)
logger.info(f"Created sheets: '{ecology_sheet_name}' and '{nature_sheet_name}' from '{TEMPLATE_SHEET}'")
# 按兜底截止日期分组门店:25日→生态,其余→自然月
ecology_mask = store_df["兜底截止日期"].apply(AnalysisService._is_ecology_deadline)
ecology_stores = store_df[ecology_mask]
nature_stores = store_df[~ecology_mask]
logger.info(f"Store split: ecology={len(ecology_stores)} (兜底=25日), "
f"nature={len(nature_stores)} (兜底≠25日), "
f"eco_factory={bool(ecology_factory)}, nat_factory={bool(nature_factory)}, "
f"eco_range={ecology_start}~{ecology_end}, nat_range={nature_start}~{nature_end}")
# 处理生态数据sheet
if len(ecology_stores) > 0 and ecology_factory:
AnalysisService._process_one_sheet(
ws_ecology, ecology_stores, ecology_factory,
ecology_start, ecology_end, formula_map, skip_external_cols)
else:
reason = "no stores" if len(ecology_stores) == 0 else "no factory data"
logger.info(f"Skipping ecology sheet ({reason})")
# 处理自然月sheet
if len(nature_stores) > 0 and nature_factory:
AnalysisService._process_one_sheet(
ws_nature, nature_stores, nature_factory,
nature_start, nature_end, formula_map, skip_external_cols)
else:
reason = "no stores" if len(nature_stores) == 0 else "no factory data"
logger.info(f"Skipping nature sheet ({reason})")
wb.save(output_path) wb.save(output_path)
logger.info(f"Report generated: {output_path}") logger.info(f"Report generated: {output_path}")
...@@ -693,7 +747,7 @@ class AnalysisService: ...@@ -693,7 +747,7 @@ class AnalysisService:
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
# 根据列和值类型设置数字格式 # 根据列和值类型设置数字格式
if isinstance(value, (int, float)): if isinstance(value, (int, float)):
if c in (18, 23, 24, 25, 26, 34, 35, 36): # 触客率/渗透率/转化率 if c in (18, 23, 24, 25, 26, 34, 35, 36, 37, 38, 39): # 触客率/渗透率/转化率/需达标转化率
cell.number_format = '0.00%' cell.number_format = '0.00%'
elif c in (27, 28, 29, 30): # 生态系数 elif c in (27, 28, 29, 30): # 生态系数
cell.number_format = '0.0' cell.number_format = '0.0'
...@@ -785,11 +839,17 @@ class AnalysisService: ...@@ -785,11 +839,17 @@ class AnalysisService:
battery_rate = _safe_float(battery_orders) / d_safe if d_safe > 0 else 0 battery_rate = _safe_float(battery_orders) / d_safe if d_safe > 0 else 0
tire_rate = _safe_float(tire_orders) / d_safe if d_safe > 0 else 0 tire_rate = _safe_float(tire_orders) / d_safe if d_safe > 0 else 0
# ========== 需达标转化率 (AK-AM) ==========
# 直接从门店数据中加载
target_yb = _safe_float(store_row.get("需达标转化率_整车延保"), 0.50)
target_axb = _safe_float(store_row.get("需达标转化率_安心包"), 0.17)
target_battery = _safe_float(store_row.get("需达标转化率_电池"), 0.13)
_style_cell(row_num, 37, target_yb)
_style_cell(row_num, 38, target_axb)
_style_cell(row_num, 39, target_battery)
# ========== 生态系数 (AA-AD) ========== # ========== 生态系数 (AA-AD) ==========
targets = extract_target_rates(store_row) # 使用门店数据中的需达标转化率作为基准
req_yb = targets["整车延保"]
req_axb = targets["安心包"]
req_battery = targets["电池延保"]
def calc_coeff(rate, required): def calc_coeff(rate, required):
if required <= 0: if required <= 0:
...@@ -807,9 +867,9 @@ class AnalysisService: ...@@ -807,9 +867,9 @@ class AnalysisService:
else: else:
return 0.0 return 0.0
yb_coeff = calc_coeff(yb_rate, req_yb) yb_coeff = calc_coeff(yb_rate, target_yb)
axb_coeff = calc_coeff(axb_rate, req_axb) if req_axb > 0 else 1.0 axb_coeff = calc_coeff(axb_rate, target_axb) if target_axb > 0 else 1.0
battery_coeff = calc_coeff(battery_rate, req_battery) if req_battery > 0 else 1.0 battery_coeff = calc_coeff(battery_rate, target_battery) if target_battery > 0 else 1.0
total_score = round(yb_coeff + axb_coeff + battery_coeff, 1) total_score = round(yb_coeff + axb_coeff + battery_coeff, 1)
_style_cell(row_num, 27, yb_coeff) _style_cell(row_num, 27, yb_coeff)
...@@ -831,27 +891,21 @@ class AnalysisService: ...@@ -831,27 +891,21 @@ class AnalysisService:
_style_cell(row_num, 35, round(axb_rate, 4)) _style_cell(row_num, 35, round(axb_rate, 4))
_style_cell(row_num, 36, round(battery_rate, 4)) _style_cell(row_num, 36, round(battery_rate, 4))
# ========== 需达标转化率 (AK-AM) ==========
# 优先使用模板显式数值(已在 extract_target_rates 中处理)
_style_cell(row_num, 37, req_yb)
_style_cell(row_num, 38, req_axb)
_style_cell(row_num, 39, req_battery)
# ========== 是否触发兜底 (AN) ========== # ========== 是否触发兜底 (AN) ==========
triggered = False triggered = False
if req_yb > 0 and yb_rate < req_yb: if target_yb > 0 and yb_rate < target_yb:
triggered = True triggered = True
if req_axb > 0 and axb_rate < req_axb: if target_axb > 0 and axb_rate < target_axb:
triggered = True triggered = True
if req_battery > 0 and battery_rate < req_battery: if target_battery > 0 and battery_rate < target_battery:
triggered = True triggered = True
_style_cell(row_num, 40, "是" if triggered else "否") _style_cell(row_num, 40, "是" if triggered else "否")
# ========== 需达标订单数差额 (AO-AQ) ========== # ========== 需达标订单数差额 (AO-AQ) ==========
d2_safe = max(0, _safe_float(delivery2)) d2_safe = max(0, _safe_float(delivery2))
required_yb_orders = max(0, math.ceil(d2_safe * _safe_float(req_yb, 0))) required_yb_orders = max(0, math.ceil(d2_safe * target_yb))
required_axb_orders = max(0, math.ceil(d2_safe * _safe_float(req_axb, 0))) required_axb_orders = max(0, math.ceil(d2_safe * target_axb))
required_battery_orders = max(0, math.ceil(d2_safe * _safe_float(req_battery, 0))) required_battery_orders = max(0, math.ceil(d2_safe * target_battery))
gap_yb = max(0, required_yb_orders - int(yb_orders)) gap_yb = max(0, required_yb_orders - int(yb_orders))
gap_axb = max(0, required_axb_orders - int(axb_orders)) gap_axb = max(0, required_axb_orders - int(axb_orders))
......
...@@ -383,17 +383,27 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -383,17 +383,27 @@ document.addEventListener('DOMContentLoaded', () => {
document.getElementById('data-analysis-section').style.display = 'block'; document.getElementById('data-analysis-section').style.display = 'block';
document.getElementById('content-title').textContent = '数据分析'; document.getElementById('content-title').textContent = '数据分析';
// 初始化默认日期: 上月26号 至 今天 // 初始化默认日期: 上月26号 ~ 今天
const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const now = new Date(); const now = new Date();
const todayStr = fmt(now); const todayStr = fmt(now);
const lastMonth26 = new Date(now.getFullYear(), now.getMonth()-1, 26); const lastMonth26 = new Date(now.getFullYear(), now.getMonth()-1, 26);
const startStr = fmt(lastMonth26); const startStr = fmt(lastMonth26);
const startInput = document.getElementById('analysis-start-date'); // 本月1号
const endInput = document.getElementById('analysis-end-date'); const firstOfMonth = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
if (startInput && !startInput.value) startInput.value = startStr;
if (endInput && !endInput.value) endInput.value = todayStr; // 生态数据: 上月26号 ~ 今天
const ecoStart = document.getElementById('ecology-start-date');
const ecoEnd = document.getElementById('ecology-end-date');
if (ecoStart && !ecoStart.value) ecoStart.value = startStr;
if (ecoEnd && !ecoEnd.value) ecoEnd.value = todayStr;
// 自然月: 本月1号 ~ 今天
const natStart = document.getElementById('nature-start-date');
const natEnd = document.getElementById('nature-end-date');
if (natStart && !natStart.value) natStart.value = firstOfMonth;
if (natEnd && !natEnd.value) natEnd.value = todayStr;
} }
// 门店列表上传 // 门店列表上传
...@@ -409,15 +419,28 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -409,15 +419,28 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
} }
// 主机厂数据上传 // 生态主机厂数据上传
const factoryDropZone = document.getElementById('factory-drop-zone'); const ecologyDropZone = document.getElementById('ecology-drop-zone');
const factoryFileInput = document.getElementById('factory-file-input'); const ecologyFactoryInput = document.getElementById('ecology-factory-input');
if (factoryDropZone) { if (ecologyDropZone && ecologyFactoryInput) {
factoryDropZone.addEventListener('click', () => factoryFileInput.click()); ecologyDropZone.addEventListener('click', () => ecologyFactoryInput.click());
factoryFileInput.addEventListener('change', () => { ecologyFactoryInput.addEventListener('change', () => {
if (factoryFileInput.files.length > 0) { if (ecologyFactoryInput.files.length > 0) {
document.getElementById('factory-file-name').textContent = '✅ 已选择: ' + factoryFileInput.files[0].name; document.getElementById('ecology-file-name').textContent = '✅ 已选择: ' + ecologyFactoryInput.files[0].name;
document.getElementById('factory-file-name').style.color = '#52c41a'; document.getElementById('ecology-file-name').style.color = '#52c41a';
}
});
}
// 自然月主机厂数据上传
const natureDropZone = document.getElementById('nature-drop-zone');
const natureFactoryInput = document.getElementById('nature-factory-input');
if (natureDropZone && natureFactoryInput) {
natureDropZone.addEventListener('click', () => natureFactoryInput.click());
natureFactoryInput.addEventListener('change', () => {
if (natureFactoryInput.files.length > 0) {
document.getElementById('nature-file-name').textContent = '✅ 已选择: ' + natureFactoryInput.files[0].name;
document.getElementById('nature-file-name').style.color = '#52c41a';
} }
}); });
} }
...@@ -430,10 +453,15 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -430,10 +453,15 @@ document.addEventListener('DOMContentLoaded', () => {
document.getElementById('analysis-error').style.display = 'none'; document.getElementById('analysis-error').style.display = 'none';
const hasStore = storeFileInput && storeFileInput.files.length > 0; const hasStore = storeFileInput && storeFileInput.files.length > 0;
const hasFactory = factoryFileInput && factoryFileInput.files.length > 0; const hasEcology = ecologyFactoryInput && ecologyFactoryInput.files.length > 0;
const hasNature = natureFactoryInput && natureFactoryInput.files.length > 0;
if (!hasStore && !hasFactory) { if (!hasStore) {
alert('请至少上传一个文件(门店列表或主机厂数据)'); alert('请先上传门店列表文件(步骤1)');
return;
}
if (!hasEcology && !hasNature) {
alert('请至少上传一个主机厂数据文件(步骤2或步骤3)');
return; return;
} }
...@@ -443,8 +471,9 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -443,8 +471,9 @@ document.addEventListener('DOMContentLoaded', () => {
try { try {
// 先上传文件 // 先上传文件
const uploadForm = new FormData(); const uploadForm = new FormData();
if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]); uploadForm.append('store_file', storeFileInput.files[0]);
if (hasFactory) uploadForm.append('factory_file', factoryFileInput.files[0]); if (hasEcology) uploadForm.append('ecology_factory_file', ecologyFactoryInput.files[0]);
if (hasNature) uploadForm.append('nature_factory_file', natureFactoryInput.files[0]);
const uploadRes = await fetch('/api/analysis/upload', { const uploadRes = await fetch('/api/analysis/upload', {
method: 'POST', method: 'POST',
...@@ -455,14 +484,18 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -455,14 +484,18 @@ document.addEventListener('DOMContentLoaded', () => {
throw new Error(uploadData.detail || '文件上传失败'); throw new Error(uploadData.detail || '文件上传失败');
} }
// 生成报表 - 携带时间范围参数 // 生成报表 - 携带两组时间范围
btnGenerateReport.textContent = '⏳ 正在分析计算...'; btnGenerateReport.textContent = '⏳ 正在分析计算...';
const genForm = new FormData(); const genForm = new FormData();
const startDate = document.getElementById('analysis-start-date').value; const ecoStart = document.getElementById('ecology-start-date').value;
const endDate = document.getElementById('analysis-end-date').value; const ecoEnd = document.getElementById('ecology-end-date').value;
if (startDate) genForm.append('start_date', startDate); const natStart = document.getElementById('nature-start-date').value;
if (endDate) genForm.append('end_date', endDate); const natEnd = document.getElementById('nature-end-date').value;
if (ecoStart) genForm.append('ecology_start_date', ecoStart);
if (ecoEnd) genForm.append('ecology_end_date', ecoEnd);
if (natStart) genForm.append('nature_start_date', natStart);
if (natEnd) genForm.append('nature_end_date', natEnd);
const genRes = await fetch('/api/analysis/generate', { const genRes = await fetch('/api/analysis/generate', {
method: 'POST', method: 'POST',
...@@ -473,9 +506,8 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -473,9 +506,8 @@ document.addEventListener('DOMContentLoaded', () => {
if (genData.status === 'success') { if (genData.status === 'success') {
document.getElementById('analysis-result').style.display = 'block'; document.getElementById('analysis-result').style.display = 'block';
document.getElementById('analysis-result-info').innerHTML = document.getElementById('analysis-result-info').innerHTML =
`门店数: <strong>${genData.store_count}</strong> 家 | ` + `生态数据门店: <strong>${genData.ecology_store_count}</strong> 家 | ` +
`主机厂数据Sheet数: <strong>${genData.factory_sheets.length}</strong> | ` + `自然月门店: <strong>${genData.nature_store_count}</strong> 家`;
`主机厂数据行数: <strong>${genData.factory_rows}</strong>`;
document.getElementById('btn-download-report').href = genData.download_url; document.getElementById('btn-download-report').href = genData.download_url;
} else { } else {
throw new Error(genData.detail || '报表生成失败'); throw new Error(genData.detail || '报表生成失败');
......
...@@ -17,8 +17,6 @@ ...@@ -17,8 +17,6 @@
<div class="logo">问界运营分析平台</div> <div class="logo">问界运营分析平台</div>
<nav class="nav-links"> <nav class="nav-links">
<div class="nav-item active" data-module="task">任务调度</div> <div class="nav-item active" data-module="task">任务调度</div>
<div class="nav-item" data-module="catalog">数据目录</div>
<div class="nav-item" data-module="upload">数据上传</div>
<div class="nav-item" data-module="analysis">数据分析</div> <div class="nav-item" data-module="analysis">数据分析</div>
</nav> </nav>
<div class="user-info">管理员</div> <div class="user-info">管理员</div>
...@@ -31,12 +29,6 @@ ...@@ -31,12 +29,6 @@
<div class="menu-title">任务管理</div> <div class="menu-title">任务管理</div>
<div class="menu-item active">ODS 同步任务</div> <div class="menu-item active">ODS 同步任务</div>
<div class="menu-item">DWS/DWM/DWA 任务</div> <div class="menu-item">DWS/DWM/DWA 任务</div>
<div class="menu-item">历史任务查询</div>
</div>
<div class="menu-group">
<div class="menu-title">系统配置</div>
<div class="menu-item">同步元数据</div>
<div class="menu-item">调度设置</div>
</div> </div>
</aside> </aside>
...@@ -180,35 +172,35 @@ ...@@ -180,35 +172,35 @@
</div> </div>
</div> </div>
<!-- 步骤2: 上传主机厂数据 --> <!-- 步骤2: 生态主机厂数据(26日周期) -->
<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #e8e8e8;"> <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #e8e8e8;">
<h3 style="margin:0 0 12px; font-size:16px; color:#333;">步骤2: 上传主机厂数据</h3> <h3 style="margin:0 0 12px; font-size:16px; color:#333;">步骤2: 主机厂数据-生态(26日)</h3>
<div id="factory-drop-zone" style="border: 1px dashed #d9d9d9; padding: 20px; text-align: center; border-radius: 4px; cursor: pointer; background: #fff;"> <div id="ecology-drop-zone" style="border: 1px dashed #d9d9d9; padding: 14px; text-align: center; border-radius: 4px; cursor: pointer; background: #fff; margin-bottom: 12px;">
<input type="file" id="factory-file-input" style="display:none;" accept=".xlsx,.xls"> <input type="file" id="ecology-factory-input" style="display:none;" accept=".xlsx,.xls">
<div style="font-size:30px; margin-bottom:8px;">🏭</div> <div style="font-size:24px; margin-bottom:4px;">🏭</div>
<p id="factory-file-name" style="margin:0; font-size:13px; color:#999;">点击选择主机厂数据文件</p> <p id="ecology-file-name" style="margin:0; font-size:12px; color:#999;">点击选择生态主机厂数据</p>
<p style="font-size:11px; color:#faad14; margin:4px 0;" title="Sheet名称需包含时间范围">⚠ Sheet名包含时间范围(如: (5.26-6.21))</p>
<a href="/api/analysis/template/factory" style="font-size:12px; color:#1890ff; text-decoration:none; margin-top:4px; display:inline-block;">
📥 下载主机厂数据模板
</a>
</div> </div>
<div style="display: flex; gap: 8px; align-items: center;">
<input type="date" id="ecology-start-date" style="flex:1; padding: 5px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="开始">
<span style="color:#999;">~</span>
<input type="date" id="ecology-end-date" style="flex:1; padding: 5px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="结束">
</div> </div>
</div> </div>
<!-- 步骤3: 选择时间范围 --> <!-- 步骤3: 自然月主机厂数据(1日周期) -->
<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #e8e8e8; margin-bottom: 20px;"> <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #e8e8e8;">
<h3 style="margin:0 0 12px; font-size:16px; color:#333;">步骤3: 选择时间范围</h3> <h3 style="margin:0 0 12px; font-size:16px; color:#333;">步骤3: 主机厂数据-自然月(1日)</h3>
<div style="display: flex; gap: 20px; align-items: center; flex-wrap: wrap;"> <div id="nature-drop-zone" style="border: 1px dashed #d9d9d9; padding: 14px; text-align: center; border-radius: 4px; cursor: pointer; background: #fff; margin-bottom: 12px;">
<div> <input type="file" id="nature-factory-input" style="display:none;" accept=".xlsx,.xls">
<label style="font-weight: bold; margin-right: 8px;">开始日期:</label> <div style="font-size:24px; margin-bottom:4px;">📅</div>
<input type="date" id="analysis-start-date" style="padding: 6px; border: 1px solid #d9d9d9; border-radius: 4px;"> <p id="nature-file-name" style="margin:0; font-size:12px; color:#999;">点击选择自然月主机厂数据</p>
</div> </div>
<div> <div style="display: flex; gap: 8px; align-items: center;">
<label style="font-weight: bold; margin-right: 8px;">结束日期:</label> <input type="date" id="nature-start-date" style="flex:1; padding: 5px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="开始">
<input type="date" id="analysis-end-date" style="padding: 6px; border: 1px solid #d9d9d9; border-radius: 4px;"> <span style="color:#999;">~</span>
<input type="date" id="nature-end-date" style="flex:1; padding: 5px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;" placeholder="结束">
</div> </div>
</div> </div>
<p style="margin-top: 8px; font-size: 12px; color: #888;">* 默认:上月26号 至 今天。填写日期后用于数据库产值数据查询和输出报表命名。</p>
</div> </div>
<!-- 步骤4: 生成报表 --> <!-- 步骤4: 生成报表 -->
...@@ -216,7 +208,7 @@ ...@@ -216,7 +208,7 @@
<button id="btn-generate-report" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;"> <button id="btn-generate-report" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;">
🚀 开始生成分析报表 🚀 开始生成分析报表
</button> </button>
<p style="font-size:12px; color:#999; margin-top:8px;">根据门店数据与主机厂数据,自动计算生态系数并生成Excel报表</p> <p style="font-size:12px; color:#999; margin-top:8px;">门店按兜底截止日期分组:月底/25日→生态数据sheet,其余→自然月sheet</p>
<p style="font-size:11px; color:#faad14;">📌 使用模板: 输出-问界生态系数-模板.xlsx</p> <p style="font-size:11px; color:#faad14;">📌 使用模板: 输出-问界生态系数-模板.xlsx</p>
</div> </div>
......
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!