Commit 4e070bd1 by 江名洋

feat(analysis): 支持日期范围筛选并丰富门店基础信息

1 parent 3ed058b0
...@@ -131,7 +131,7 @@ async def run_ods_sync(background_tasks: BackgroundTasks, source_table: str = No ...@@ -131,7 +131,7 @@ async def run_ods_sync(background_tasks: BackgroundTasks, source_table: str = No
@router.post("/etl/run-dw") @router.post("/etl/run-dw")
async def run_dw_sync( async def run_dw_sync(
background_tasks: BackgroundTasks, background_tasks: BackgroundTasks,
layer: str = Form(...), layer: str = Form(None),
start_date: str = Form(None), start_date: str = Form(None),
end_date: str = Form(None), end_date: str = Form(None),
full_sync: str = Form(None) full_sync: str = Form(None)
...@@ -140,8 +140,11 @@ async def run_dw_sync( ...@@ -140,8 +140,11 @@ async def run_dw_sync(
- 默认增量同步(最近一天) - 默认增量同步(最近一天)
- full_sync=true 时全量覆盖 - full_sync=true 时全量覆盖
- 指定 start_date/end_date 时按日期范围处理 - 指定 start_date/end_date 时按日期范围处理
- 参数支持 Form 或 Query 方式传递
""" """
try: try:
if not layer:
raise HTTPException(status_code=400, detail="缺少必要参数: layer")
task_id = f"manual_{layer.lower()}_sync" task_id = f"manual_{layer.lower()}_sync"
background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync) background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync)
return { return {
...@@ -153,6 +156,29 @@ async def run_dw_sync( ...@@ -153,6 +156,29 @@ async def run_dw_sync(
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
@router.get("/etl/run-dw")
async def run_dw_sync_get(
background_tasks: BackgroundTasks,
layer: str = Query(...),
start_date: str = Query(None),
end_date: str = Query(None),
full_sync: str = Query(None)
):
"""GET 方式触发 DWS/DWM/DWA 加工 (支持 Query 参数)
- 用法: GET /api/etl/run-dw?layer=DWS&full_sync=true
"""
try:
task_id = f"manual_{layer.lower()}_sync"
background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync)
return {
"status": "success",
"message": f"{layer} 加工任务已在后台启动,请查看执行历史获取进度。"
}
except Exception as e:
logger.error(f"Failed to start background {layer} sync: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ==================== 数据分析接口 ==================== # ==================== 数据分析接口 ====================
@router.get("/analysis/template/{template_type}") @router.get("/analysis/template/{template_type}")
...@@ -228,7 +254,11 @@ async def analysis_upload( ...@@ -228,7 +254,11 @@ async def analysis_upload(
@router.post("/analysis/generate") @router.post("/analysis/generate")
async def analysis_generate(background_tasks: BackgroundTasks): async def analysis_generate(
background_tasks: BackgroundTasks,
start_date: str = Form(None),
end_date: str = Form(None)
):
"""根据已上传的数据生成生态系数分析报表""" """根据已上传的数据生成生态系数分析报表"""
global _analysis_store_file global _analysis_store_file
...@@ -249,7 +279,11 @@ async def analysis_generate(background_tasks: BackgroundTasks): ...@@ -249,7 +279,11 @@ async def analysis_generate(background_tasks: BackgroundTasks):
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) factory_sheets = AnalysisService.read_factory_data(factory_path)
output_path = AnalysisService.build_report(store_df, factory_sheets) output_path = AnalysisService.build_report(
store_df, factory_sheets,
start_date=start_date or None,
end_date=end_date or None
)
return { return {
"status": "success", "status": "success",
......
...@@ -371,6 +371,21 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -371,6 +371,21 @@ document.addEventListener('DOMContentLoaded', () => {
hideAllSections(); hideAllSections();
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号 至 今天
const now = new Date();
const todayStr = now.toISOString().split('T')[0];
// 计算上月26号
const firstOfThisMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const lastDayOfLastMonth = new Date(firstOfThisMonth - 86400000);
const lastMonth26 = new Date(lastDayOfLastMonth.getFullYear(), lastDayOfLastMonth.getMonth(), 26);
const startStr = lastMonth26.toISOString().split('T')[0];
const startInput = document.getElementById('analysis-start-date');
const endInput = document.getElementById('analysis-end-date');
if (startInput && !startInput.value) startInput.value = startStr;
if (endInput && !endInput.value) endInput.value = todayStr;
} }
// 门店列表上传 // 门店列表上传
...@@ -432,10 +447,18 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -432,10 +447,18 @@ document.addEventListener('DOMContentLoaded', () => {
throw new Error(uploadData.detail || '文件上传失败'); throw new Error(uploadData.detail || '文件上传失败');
} }
// 生成报表 // 生成报表 - 携带时间范围参数
btnGenerateReport.textContent = '⏳ 正在分析计算...'; btnGenerateReport.textContent = '⏳ 正在分析计算...';
const genForm = new FormData();
const startDate = document.getElementById('analysis-start-date').value;
const endDate = document.getElementById('analysis-end-date').value;
if (startDate) genForm.append('start_date', startDate);
if (endDate) genForm.append('end_date', endDate);
const genRes = await fetch('/api/analysis/generate', { const genRes = await fetch('/api/analysis/generate', {
method: 'POST' method: 'POST',
body: genForm
}); });
const genData = await genRes.json(); const genData = await genRes.json();
......
...@@ -195,13 +195,29 @@ ...@@ -195,13 +195,29 @@
</div> </div>
</div> </div>
<!-- 步骤3: 生成报表 --> <!-- 步骤3: 选择时间范围 -->
<div style="background: #f8f9fa; padding: 20px; border-radius: 8px; border: 1px solid #e8e8e8; margin-bottom: 20px;">
<h3 style="margin:0 0 12px; font-size:16px; color:#333;">步骤3: 选择时间范围</h3>
<div style="display: flex; gap: 20px; align-items: center; flex-wrap: wrap;">
<div>
<label style="font-weight: bold; margin-right: 8px;">开始日期:</label>
<input type="date" id="analysis-start-date" style="padding: 6px; border: 1px solid #d9d9d9; border-radius: 4px;">
</div>
<div>
<label style="font-weight: bold; margin-right: 8px;">结束日期:</label>
<input type="date" id="analysis-end-date" style="padding: 6px; border: 1px solid #d9d9d9; border-radius: 4px;">
</div>
</div>
<p style="margin-top: 8px; font-size: 12px; color: #888;">* 默认:上月26号 至 今天。填写日期后用于数据库产值数据查询和输出报表命名。</p>
</div>
<!-- 步骤4: 生成报表 -->
<div style="text-align: center; margin: 20px 0;"> <div style="text-align: center; margin: 20px 0;">
<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;">根据门店数据与主机厂数据,自动计算生态系数并生成Excel报表</p>
<p style="font-size:11px; color:#faad14;">📌 表头参考: <a href="/api/analysis/template/output" style="color:#1890ff;">输出样例</a></p> <p style="font-size:11px; color:#faad14;">📌 使用模板: 输出-问界生态系数生态-模板.xlsx</p>
</div> </div>
<!-- 生成结果提示 --> <!-- 生成结果提示 -->
......
16:58:35 ERROR Analysis generate failed: name 'touch' is not defined [endpoints.py:272]
Traceback (most recent call last):
File "D:\work1\data-analyze-webui\app\api\endpoints.py", line 256, in analysis_generate
output_path = AnalysisService.build_report(
store_df, factory_sheets,
start_date=start_date or None,
end_date=end_date or None
)
File "D:\work1\data-analyze-webui\app\services\analysis_service.py", line 493, in build_report
AnalysisService._write_data_rows(ws, store_df, factory_sheets, db_perf,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
start_date, end_date)
^^^^^^^^^^^^^^^^^^^^^
File "D:\work1\data-analyze-webui\app\services\analysis_service.py", line 652, in _write_data_rows
touch_safe = _safe_float(touch, 0)
^^^^^
NameError: name 'touch' is not defined
...@@ -86,3 +86,74 @@ Traceback (most recent call last): ...@@ -86,3 +86,74 @@ Traceback (most recent call last):
raise TypeError(f'Object of type {o.__class__.__name__} ' raise TypeError(f'Object of type {o.__class__.__name__} '
f'is not JSON serializable') f'is not JSON serializable')
TypeError: Object of type datetime is not JSON serializable TypeError: Object of type datetime is not JSON serializable
16:58:33 ERROR Failed to query store info from DB: (1146, "Table 'data_analyze.dj_car_life_scene_merchant_ref' doesn't exist") [analysis_service.py:421]
Traceback (most recent call last):
File "D:\work1\data-analyze-webui\app\services\analysis_service.py", line 399, in _query_store_info
cur.execute(sql, (*store_names,))
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 157, in execute
result = self._query(query)
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
~~~~~~~~~~^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 575, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 826, in _read_query_result
result.read()
~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 1203, in read
first_packet = self.connection._read_packet()
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 782, in _read_packet
packet.raise_for_error()
~~~~~~~~~~~~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\protocol.py", line 219, in raise_for_error
err.raise_mysql_exception(self._data)
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\err.py", line 150, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1146, "Table 'data_analyze.dj_car_life_scene_merchant_ref' doesn't exist")
16:58:35 ERROR Analysis generate failed: name 'touch' is not defined [endpoints.py:272]
Traceback (most recent call last):
File "D:\work1\data-analyze-webui\app\api\endpoints.py", line 256, in analysis_generate
output_path = AnalysisService.build_report(
store_df, factory_sheets,
start_date=start_date or None,
end_date=end_date or None
)
File "D:\work1\data-analyze-webui\app\services\analysis_service.py", line 493, in build_report
AnalysisService._write_data_rows(ws, store_df, factory_sheets, db_perf,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
start_date, end_date)
^^^^^^^^^^^^^^^^^^^^^
File "D:\work1\data-analyze-webui\app\services\analysis_service.py", line 652, in _write_data_rows
touch_safe = _safe_float(touch, 0)
^^^^^
NameError: name 'touch' is not defined
18:16:26 ERROR Failed to query store performance from DB: (1054, "Unknown column 'sence_type' in 'where clause'") [analysis_service.py:354]
Traceback (most recent call last):
File "D:\work1\data-analyze-webui\app\services\analysis_service.py", line 321, in _query_store_performance
cur.execute(sql, params)
~~~~~~~~~~~^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 157, in execute
result = self._query(query)
File "D:\Python313\Lib\site-packages\pymysql\cursors.py", line 328, in _query
conn.query(q)
~~~~~~~~~~^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 575, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 826, in _read_query_result
result.read()
~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 1203, in read
first_packet = self.connection._read_packet()
File "D:\Python313\Lib\site-packages\pymysql\connections.py", line 782, in _read_packet
packet.raise_for_error()
~~~~~~~~~~~~~~~~~~~~~~^^
File "D:\Python313\Lib\site-packages\pymysql\protocol.py", line 219, in raise_for_error
err.raise_mysql_exception(self._data)
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "D:\Python313\Lib\site-packages\pymysql\err.py", line 150, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.OperationalError: (1054, "Unknown column 'sence_type' in 'where clause'")
This diff could not be displayed because it is too large.
...@@ -359,6 +359,60 @@ CREATE TABLE ods_store_config ( ...@@ -359,6 +359,60 @@ CREATE TABLE ods_store_config (
INDEX idx_traffic_grade (traffic_grade) INDEX idx_traffic_grade (traffic_grade)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='店铺配置主数据-ODS'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='店铺配置主数据-ODS';
-- ods_scene_merchant_ref — 场景关联关系表
DROP TABLE IF EXISTS ods_scene_merchant_ref;
CREATE TABLE ods_scene_merchant_ref (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
main_merchant_id BIGINT NOT NULL COMMENT '主关联商户ID',
main_merchant_name VARCHAR(128) DEFAULT NULL COMMENT '主关联商户名称',
sub_merchant_id BIGINT NOT NULL COMMENT '被关联商户ID',
sub_merchant_name VARCHAR(128) DEFAULT NULL COMMENT '被关联商户名称',
scene TINYINT NOT NULL COMMENT '场景值',
main_merchant_type TINYINT DEFAULT NULL COMMENT '主关联商户类型',
sub_merchant_type TINYINT DEFAULT NULL COMMENT '被关联商户类型',
deleted_flag CHAR(1) DEFAULT 'N' COMMENT '删除标记',
created_date DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_date DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
INDEX idx_main_merchant (main_merchant_id),
INDEX idx_sub_merchant (sub_merchant_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='场景关联关系表-ODS';
-- ods_yqmerchant_config — 园区店配置项
DROP TABLE IF EXISTS ods_yqmerchant_config;
CREATE TABLE ods_yqmerchant_config (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
merchant_id BIGINT NOT NULL COMMENT '商户号',
partner_merchant_id BIGINT DEFAULT NULL COMMENT '主服务商商户ID',
partner_merchant_name VARCHAR(128) DEFAULT NULL COMMENT '主服务商商户名称',
business_model TINYINT DEFAULT NULL COMMENT '经营模式 0-园区店 1-驻店',
deleted_flag CHAR(1) DEFAULT 'N' COMMENT '删除标记',
created_date DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_date DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
INDEX idx_merchant_id (merchant_id),
INDEX idx_partner_merchant_id (partner_merchant_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='园区店配置项-ODS';
-- ods_store_info — 门店基础信息汇总表(合并 ods_store_config + ods_service_merchant)
DROP TABLE IF EXISTS ods_store_info;
CREATE TABLE ods_store_info (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
merchant_id BIGINT NOT NULL COMMENT '门店ID',
merchant_name VARCHAR(128) DEFAULT NULL COMMENT '门店名称',
province_name VARCHAR(32) DEFAULT NULL COMMENT '区域(省)',
operation_mode VARCHAR(16) DEFAULT NULL COMMENT '直营与否(直营/非直营)',
area_manager VARCHAR(64) DEFAULT NULL COMMENT '区域运营',
flight_supervisor VARCHAR(128) DEFAULT NULL COMMENT '飞行督导',
online_ops VARCHAR(128) DEFAULT NULL COMMENT '线上运营',
deleted_flag CHAR(1) DEFAULT 'N' COMMENT '删除标记',
created_date DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_date DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
UNIQUE KEY uk_merchant_id (merchant_id),
INDEX idx_name (merchant_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='门店基础信息汇总表-ODS';
-- ods_guarantee_config — 兜底保障配置 -- ods_guarantee_config — 兜底保障配置
DROP TABLE IF EXISTS ods_guarantee_config; DROP TABLE IF EXISTS ods_guarantee_config;
CREATE TABLE ods_guarantee_config ( CREATE TABLE ods_guarantee_config (
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!