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)
......
...@@ -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> </div>
<a href="/api/analysis/template/factory" style="font-size:12px; color:#1890ff; text-decoration:none; margin-top:4px; display:inline-block;"> <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="开始">
</a> <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>
</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!