Commit 286a9d53 by 江名洋

feat: 新增问界门店数据分析平台的ETL同步与Excel上传功能

1. 新增源生产数据库配置,支持连接外部业务库进行数据抽取
2. 实现完整的ETL服务层,支持ODS层增量/全量数据同步,新增任务执行历史记录
3. 开发Excel上传解析服务,支持将Excel数据导入ODS表
4. 搭建全套FastAPI接口,涵盖数据上传、ETL任务管理、调度配置、历史查询等功能
5. 更新前端界面,增加任务状态展示、手动触发同步、Excel上传操作模块
6. 补充数据库初始化SQL,新增ETL历史表和同步元数据表
7. 替换原定时任务的模拟逻辑,接入真实的ETL同步流程
8. 新增平台功能测试用例,验证核心业务流程
1 parent 31f3bebe
...@@ -19,6 +19,13 @@ DB_USER=user_jiangmy ...@@ -19,6 +19,13 @@ DB_USER=user_jiangmy
DB_PASSWORD=PYuxMTB1 DB_PASSWORD=PYuxMTB1
DB_NAME=data_analyze DB_NAME=data_analyze
# 源生产数据库 (Source DB)
SOURCE_DB_HOST=192.168.5.23
SOURCE_DB_PORT=3306
SOURCE_DB_USER=user_jiangmy
SOURCE_DB_PASSWORD=VMziLJun
SOURCE_DB_NAME=dj_smartcarlife
# ============================================================================ # ============================================================================
# LLM: 通义千问 (Qwen) # LLM: 通义千问 (Qwen)
# ── 兼容旧变量名 ── # ── 兼容旧变量名 ──
......
No preview for this file type
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
文件名: app/api/endpoints.py 文件名: app/api/endpoints.py
职责: API 接口定义,包括 ETL 任务触发、数据查询、文件上传、模板分析等接口。 职责: 定义 FastAPI 路由接口,处理前端请求并调用 Service 层逻辑。
注意: 不要删除这个注释。 注意: 不要删除这个注释。
""" """
from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Form
from app.services.etl_service import ETLService
from app.services.excel_service import ExcelService
from app.core.scheduler import SchedulerManager
import os
import shutil
router = APIRouter()
# 临时文件存放目录
UPLOAD_DIR = "temp_uploads"
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR)
@router.post("/data/upload")
async def upload_data(
file: UploadFile = File(...),
table_name: str = Form(...)
):
"""上传 Excel 并导入到 ODS 表"""
file_path = os.path.join(UPLOAD_DIR, file.filename)
try:
# 1. 保存临时文件
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# 2. 调用服务导入数据
rows = await ExcelService.upload_to_ods(file_path, table_name)
return {
"status": "success",
"message": f"成功导入 {rows} 行数据到 {table_name}",
"table_name": table_name,
"rows": rows
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
# 清理临时文件
if os.path.exists(file_path):
os.remove(file_path)
@router.get("/etl/status")
async def get_etl_status():
"""获取数据同步状态"""
try:
return await ETLService.get_sync_status()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/etl/history")
async def get_etl_history(
task_id: str = Query(None),
limit: int = Query(10)
):
"""获取执行历史"""
try:
return await ETLService.get_etl_history(task_id=task_id, limit=limit)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/etl/scheduler-config")
async def get_scheduler_config(task_id: str = "sync_ods_data"):
"""获取定时任务配置"""
try:
# 从 SchedulerManager 获取作业信息
job = SchedulerManager._scheduler.get_job(task_id)
if not job:
return {"task_id": task_id, "status": "not_found"}
return {
"task_id": job.id,
"next_run_time": str(job.next_run_time),
"trigger": str(job.trigger),
"status": "active"
}
except Exception as e:
return {"task_id": task_id, "status": "error", "detail": str(e)}
@router.post("/etl/run-ods")
async def run_ods_sync(source_table: str = None):
"""手动触发 ODS 同步"""
try:
results = await ETLService.run_ods_sync(source_table=source_table)
return {"status": "success", "results": results}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
...@@ -21,6 +21,13 @@ class Settings(BaseSettings): ...@@ -21,6 +21,13 @@ class Settings(BaseSettings):
DB_PASSWORD: str = "" DB_PASSWORD: str = ""
DB_NAME: str = "data_analyze" DB_NAME: str = "data_analyze"
# Source MySQL Settings
SOURCE_DB_HOST: str = "127.0.0.1"
SOURCE_DB_PORT: int = 3306
SOURCE_DB_USER: str = "root"
SOURCE_DB_PASSWORD: str = ""
SOURCE_DB_NAME: str = "production"
@property @property
def database_url(self) -> str: def database_url(self) -> str:
"""返回 SQLAlchemy 连接字符串""" """返回 SQLAlchemy 连接字符串"""
......
...@@ -64,9 +64,9 @@ class SchedulerManager: ...@@ -64,9 +64,9 @@ class SchedulerManager:
"""同步 ODS 层数据的定时任务逻辑""" """同步 ODS 层数据的定时任务逻辑"""
logger.info(f"[Scheduler] Start sync_ods_task at {datetime.now()}") logger.info(f"[Scheduler] Start sync_ods_task at {datetime.now()}")
try: try:
# TODO: 调用 app.services.etl_service 中的同步逻辑 from app.services.etl_service import ETLService
await asyncio.sleep(1) # 模拟耗时操作 results = await ETLService.run_ods_sync(task_id="scheduler_ods_sync")
logger.info("[Scheduler] sync_ods_task completed.") logger.info(f"[Scheduler] sync_ods_task completed. Results: {results}")
except Exception as e: except Exception as e:
logger.error(f"[Scheduler] sync_ods_task failed: {e}") logger.error(f"[Scheduler] sync_ods_task failed: {e}")
......
No preview for this file type
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
文件名: app/services/etl_service.py 文件名: app/services/etl_service.py
职责: ETL 业务逻辑,封装对 sql 目录下各类 ETL 脚本的调用及任务状态跟踪。 职责: ETL 业务逻辑,封装对数据库同步任务的执行及任务状态跟踪。
注意: 不要删除这个注释。 注意: 不要删除这个注释。
""" """
import logging
import json
import pymysql
from datetime import datetime
from sqlalchemy import text
from app.db.session import SessionLocal
from app.core.config import settings
logger = logging.getLogger("app.etl")
class ETLService:
# 源表与目标表的映射关系 (源表名, ODS表名, 业务主键, 是否增量)
TABLE_MAPPINGS = [
# --- 维度表 ---
('dj_car_life_service_merchant', 'ods_service_merchant', 'merchant_id', True),
('dj_car_life_shop_merchant_director_config', 'ods_shop_merchant_director_config', 'id', True),
('dj_car_life_merchant_brand_model', 'ods_merchant_brand_model', 'id', True),
('dj_car_life_staff_info', 'ods_staff_info', 'staff_uuid', True),
# --- 产品信息表 ---
('dj_car_life_base_goods', 'ods_base_goods', 'id', True),
('dj_car_life_goods_info', 'ods_goods_info', 'id', True),
('dj_car_life_upgrade_goods', 'ods_upgrade_goods', 'id', True),
('dj_car_life_merchant_goods_info', 'ods_merchant_goods_info', 'id', True),
('dj_car_life_merchant_package_goods_info', 'ods_merchant_package_goods_info', 'id', True),
# --- 日报表 ---
('dj_car_life_staff_daily_report_huawei', 'ods_staff_daily_report_huawei', 'id', True),
('dj_car_life_staff_daily_report', 'ods_staff_daily_report', 'id', True),
('dj_car_life_merchant_daily_report_huawei', 'ods_merchant_daily_report_huawei', 'id', True),
# --- 订单表 ---
('dj_car_life_goods_order', 'ods_goods_order', 'order_code', True),
('dj_car_life_goods_sub_order', 'ods_goods_sub_order', 'id', True),
('dj_car_life_goods_order_customer', 'ods_goods_order_customer', 'id', True),
# --- 目标配置表 ---
('dj_car_life_merchant_deliver_target_config', 'ods_merchant_deliver_target_config','id', True),
('dj_car_life_merchant_output_target_config', 'ods_merchant_output_target_config', 'id', True),
# --- 成交率表 ---
('employee_delivery_deal_rate', 'ods_employee_delivery_deal_rate', 'id', True),
]
@staticmethod
def get_source_conn():
return pymysql.connect(
host=settings.SOURCE_DB_HOST,
port=settings.SOURCE_DB_PORT,
user=settings.SOURCE_DB_USER,
password=settings.SOURCE_DB_PASSWORD,
database=settings.SOURCE_DB_NAME,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
@staticmethod
def get_target_conn():
return pymysql.connect(
host=settings.DB_HOST,
port=settings.DB_PORT,
user=settings.DB_USER,
password=settings.DB_PASSWORD,
database=settings.DB_NAME,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
autocommit=True
)
@classmethod
async def run_ods_sync(cls, source_table_filter: str = None, task_id: str = "auto_ods_sync"):
"""
执行真实的 ODS 层同步任务:从源生产库抽取数据并 Upsert 到目标数仓。
"""
start_time = datetime.now()
db = SessionLocal()
history_id = None
try:
# 1. 记录历史开始
ins_history = text("""
INSERT INTO _etl_history (task_id, task_name, start_time, status, params)
VALUES (:tid, :tname, :start, 'running', :params)
""")
db.execute(ins_history, {
"tid": task_id,
"tname": "ODS同步任务",
"start": start_time,
"params": json.dumps({"filter": source_table_filter})
})
db.commit()
history_id = db.execute(text("SELECT LAST_INSERT_ID()")).scalar()
# 2. 建立连接
source_conn = cls.get_source_conn()
target_conn = cls.get_target_conn()
results = []
total_rows = 0
try:
for src_table, tgt_table, pk, is_incremental in cls.TABLE_MAPPINGS:
if source_table_filter and src_table != source_table_filter:
continue
logger.info(f"[*] Syncing {src_table} -> {tgt_table}...")
# 获取目标表的所有有效字段名
with target_conn.cursor() as cur:
cur.execute(f"SHOW COLUMNS FROM {tgt_table}")
target_columns = [col['Field'] for col in cur.fetchall()]
# 获取上次同步时间
last_sync_time = None
with target_conn.cursor() as cur:
cur.execute("SELECT last_sync_time FROM _sync_meta WHERE source_table=%s", (src_table,))
row = cur.fetchone()
if row:
last_sync_time = row['last_sync_time']
# 从源库拉取数据
query = f"SELECT * FROM {src_table}"
params = []
if is_incremental and last_sync_time:
query += " WHERE updated_date >= %s"
params.append(last_sync_time)
with source_conn.cursor() as cur:
cur.execute(query, params)
rows = cur.fetchall()
if not rows:
results.append({"source": src_table, "target": tgt_table, "rows": 0, "status": "no_data"})
continue
# 过滤字段:只保留目标表中存在的字段,并排除自动更新的 etl_time
all_source_cols = list(rows[0].keys())
cols = [c for c in all_source_cols if c in target_columns and c != 'etl_time']
col_names = ", ".join([f"`{c}`" for c in cols])
placeholders = ", ".join(["%s"] * len(cols))
update_stmt = ", ".join([f"`{c}`=VALUES(`{c}`)" for c in cols if c != pk])
upsert_sql = f"""
INSERT INTO {tgt_table} ({col_names})
VALUES ({placeholders})
ON DUPLICATE KEY UPDATE {update_stmt}
"""
with target_conn.cursor() as cur:
data_tuples = [tuple(row[c] for c in cols) for row in rows]
cur.executemany(upsert_sql, data_tuples)
# 更新元数据
max_updated_date = max([row.get('updated_date', start_time) for row in rows]) if rows else start_time
with target_conn.cursor() as cur:
cur.execute("""
INSERT INTO _sync_meta (source_table, target_table, last_sync_time, last_sync_rows, sync_mode)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
last_sync_time = VALUES(last_sync_time),
last_sync_rows = VALUES(last_sync_rows),
updated_at = NOW()
""", (src_table, tgt_table, max_updated_date, len(rows), "incremental" if is_incremental else "full"))
results.append({"source": src_table, "target": tgt_table, "rows": len(rows), "status": "success"})
total_rows += len(rows)
finally:
source_conn.close()
target_conn.close()
# 3. 更新历史记录
end_time = datetime.now()
db.execute(text("""
UPDATE _etl_history
SET end_time = :end, status = 'success', result_info = :res, rows_affected = :rows
WHERE id = :id
"""), {"end": end_time, "res": json.dumps(results), "rows": total_rows, "id": history_id})
db.commit()
return results
except Exception as e:
logger.error(f"[X] ODS Sync failed: {e}")
if history_id:
db.execute(text("""
UPDATE _etl_history SET end_time = NOW(), status = 'failed', result_info = :err
WHERE id = :id
"""), {"err": str(e), "id": history_id})
db.commit()
raise e
finally:
db.close()
@staticmethod
async def get_etl_history(task_id: str = None, limit: int = 10):
"""获取任务执行历史"""
db = SessionLocal()
try:
query = "SELECT * FROM _etl_history"
if task_id:
query += f" WHERE task_id = '{task_id}'"
query += " ORDER BY start_time DESC LIMIT :limit"
result = db.execute(text(query), {"limit": limit}).fetchall()
return [dict(row._asdict()) for row in result]
finally:
db.close()
@staticmethod
async def get_sync_status():
"""获取所有表的同步状态"""
db = SessionLocal()
try:
query = text("SELECT * FROM _sync_meta")
result = db.execute(query).fetchall()
return [dict(row._asdict()) for row in result]
finally:
db.close()
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
文件名: app/services/excel_service.py 文件名: app/services/excel_service.py
职责: Excel 处理逻辑,支持上传 Excel 转换为数据库表,并实现版本记录功能。 职责: Excel 业务逻辑,负责解析上传的 Excel 文件并将其转换为数据库 ODS 表存储。
注意: 不要删除这个注释。 注意: 不要删除这个注释。
""" """
import pandas as pd
import logging
import pymysql
from app.core.config import settings
logger = logging.getLogger("app.excel")
class ExcelService:
@staticmethod
def get_target_conn():
return pymysql.connect(
host=settings.DB_HOST,
port=settings.DB_PORT,
user=settings.DB_USER,
password=settings.DB_PASSWORD,
database=settings.DB_NAME,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
autocommit=True
)
@classmethod
async def upload_to_ods(cls, file_path: str, table_name: str):
"""
解析 Excel 并导入到指定的 ODS 表,支持 Upsert 覆盖。
"""
try:
# 1. 读取 Excel
df = pd.read_excel(file_path)
# 统一将 NaN 替换为 None,方便数据库写入
df = df.where(pd.notnull(df), None)
if df.empty:
return 0
# 2. 准备 SQL
cols = df.columns.tolist()
col_names = ", ".join([f"`{c}`" for c in cols])
placeholders = ", ".join(["%s"] * len(cols))
# 假设主键是 id,或者根据 table_name 判断。这里统一用 id 排除,或者全部更新
update_stmt = ", ".join([f"`{c}`=VALUES(`{c}`)" for c in cols if c.lower() != 'id'])
upsert_sql = f"""
INSERT INTO {table_name} ({col_names})
VALUES ({placeholders})
ON DUPLICATE KEY UPDATE {update_stmt}
"""
# 3. 写入数据库
conn = cls.get_target_conn()
try:
with conn.cursor() as cur:
data_tuples = [tuple(x) for x in df.values]
cur.executemany(upsert_sql, data_tuples)
logger.info(f"[+] Successfully upserted {len(df)} rows to {table_name}")
return len(df)
finally:
conn.close()
except Exception as e:
logger.error(f"[X] Excel import failed for {table_name}: {e}")
raise e
@staticmethod
async def get_preview(file_path: str, rows: int = 10):
"""获取 Excel 预览数据"""
try:
df = pd.read_excel(file_path).head(rows)
return df.to_dict(orient='records')
except Exception as e:
logger.error(f"[X] Excel preview failed: {e}")
return []
...@@ -24,6 +24,11 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -24,6 +24,11 @@ document.addEventListener('DOMContentLoaded', () => {
// 更新标题 // 更新标题
contentTitle.textContent = item.textContent; contentTitle.textContent = item.textContent;
// 如果点击的是顶部“数据上传”,直接显示上传界面
if (module === 'upload') {
showUploadPage();
}
}); });
}); });
...@@ -34,11 +39,162 @@ document.addEventListener('DOMContentLoaded', () => { ...@@ -34,11 +39,162 @@ document.addEventListener('DOMContentLoaded', () => {
menuItems.forEach(i => i.classList.remove('active')); menuItems.forEach(i => i.classList.remove('active'));
e.target.classList.add('active'); e.target.classList.add('active');
console.log('切换功能点:', e.target.textContent); const menuText = e.target.textContent.trim();
// 此处可以加载具体的功能页面内容 console.log('切换功能点:', menuText);
if (menuText === 'ODS 同步任务') {
loadOdsSyncPage();
} else if (menuText === '数据上传' || menuText === '手动上传数据') {
showUploadPage();
} else {
hideAllSections();
document.getElementById('welcome-message').style.display = 'block';
document.getElementById('content-title').textContent = menuText;
}
}
});
function hideAllSections() {
document.getElementById('task-config-section').style.display = 'none';
document.getElementById('task-history-section').style.display = 'none';
document.getElementById('data-upload-section').style.display = 'none';
document.getElementById('welcome-message').style.display = 'none';
}
function showUploadPage() {
hideAllSections();
document.getElementById('data-upload-section').style.display = 'block';
document.getElementById('content-title').textContent = '数据上传';
}
// 文件上传逻辑
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('excel-file');
dropZone.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', () => {
if (fileInput.files.length > 0) {
dropZone.querySelector('p').textContent = '已选择: ' + fileInput.files[0].name;
}
});
document.getElementById('btn-do-upload').addEventListener('click', async () => {
if (fileInput.files.length === 0) {
alert('请先选择文件');
return;
}
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('table_name', document.getElementById('upload-table-name').value);
const btn = document.getElementById('btn-do-upload');
btn.disabled = true;
btn.textContent = '上传中...';
try {
const res = await fetch('/api/data/upload', {
method: 'POST',
body: formData
});
const data = await res.json();
if (data.status === 'success') {
alert(data.message);
fileInput.value = '';
dropZone.querySelector('p').textContent = '点击或将 Excel 文件拖拽到此处上传';
} else {
alert('上传失败: ' + data.detail);
}
} catch (err) {
alert('上传出错: ' + err);
} finally {
btn.disabled = false;
btn.textContent = '开始上传';
}
});
// 加载 ODS 同步任务页面数据
async function loadOdsSyncPage() {
hideAllSections();
document.getElementById('task-config-section').style.display = 'block';
document.getElementById('task-history-section').style.display = 'block';
document.getElementById('content-title').textContent = 'ODS 同步任务';
// 1. 获取配置
try {
const configRes = await fetch('/api/etl/scheduler-config?task_id=sync_ods_data');
const config = await configRes.json();
document.getElementById('conf-task-id').textContent = config.task_id || '-';
document.getElementById('conf-status').textContent = config.status || '-';
document.getElementById('conf-next-run').textContent = config.next_run_time || '-';
document.getElementById('conf-trigger').textContent = config.trigger || '-';
} catch (err) {
console.error('获取配置失败:', err);
}
// 2. 获取历史
refreshHistory();
}
async function refreshHistory() {
try {
const historyRes = await fetch('/api/etl/history?task_id=sync_ods_data&limit=10');
const history = await historyRes.json();
const tbody = document.getElementById('history-tbody');
tbody.innerHTML = '';
history.forEach(item => {
const tr = document.createElement('tr');
tr.style.borderBottom = '1px solid #f0f0f0';
const duration = item.end_time ? calculateDuration(item.start_time, item.end_time) : '-';
const statusColor = item.status === 'success' ? '#52c41a' : (item.status === 'failed' ? '#f5222d' : '#1890ff');
tr.innerHTML = `
<td style="padding: 12px;">${item.start_time}</td>
<td style="padding: 12px;">${duration}</td>
<td style="padding: 12px; color: ${statusColor}">${item.status}</td>
<td style="padding: 12px;">${item.rows_affected}</td>
<td style="padding: 12px;"><a href="#" onclick="alert('${item.result_info.replace(/'/g, "\\'")}'); return false;">查看</a></td>
`;
tbody.appendChild(tr);
});
} catch (err) {
console.error('获取历史失败:', err);
}
}
// 立即执行按钮
document.getElementById('btn-run-now').addEventListener('click', async () => {
const btn = document.getElementById('btn-run-now');
btn.disabled = true;
btn.textContent = '执行中...';
try {
const res = await fetch('/api/etl/run-ods', { method: 'POST' });
const data = await res.json();
if (data.status === 'success') {
alert('执行成功!');
refreshHistory();
} else {
alert('执行失败: ' + data.detail);
}
} catch (err) {
alert('请求出错: ' + err);
} finally {
btn.disabled = false;
btn.textContent = '立即执行一次';
} }
}); });
function calculateDuration(start, end) {
const s = new Date(start);
const e = new Date(end);
const diff = (e - s) / 1000;
return diff.toFixed(1) + 's';
}
function showSidebarMenu(module) { function showSidebarMenu(module) {
// 实际项目中这里可以根据模块 ID 控制左侧菜单内容的动态切换 // 实际项目中这里可以根据模块 ID 控制左侧菜单内容的动态切换
console.log('切换到模块:', module); console.log('切换到模块:', module);
......
...@@ -45,7 +45,63 @@ ...@@ -45,7 +45,63 @@
<div class="card"> <div class="card">
<h2 id="content-title">任务调度</h2> <h2 id="content-title">任务调度</h2>
<div id="content-body"> <div id="content-body">
<p>欢迎来到问界门店运营数据分析平台。请从左侧选择具体功能进行操作。</p> <!-- 任务配置部分 -->
<div id="task-config-section" style="display:none; margin-bottom: 30px;">
<h3 style="margin-bottom:15px; font-size: 16px; color: #666;">定时任务配置</h3>
<div class="config-grid" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; background: #f8f9fa; padding: 15px; border-radius: 4px;">
<div><strong>任务ID:</strong> <span id="conf-task-id">-</span></div>
<div><strong>状态:</strong> <span id="conf-status">-</span></div>
<div><strong>下次执行:</strong> <span id="conf-next-run">-</span></div>
<div><strong>触发器:</strong> <span id="conf-trigger">-</span></div>
</div>
<div style="margin-top: 15px;">
<button id="btn-run-now" style="padding: 8px 16px; background: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer;">立即执行一次</button>
</div>
</div>
<!-- 历史记录部分 -->
<div id="task-history-section" style="display:none;">
<h3 style="margin-bottom:15px; font-size: 16px; color: #666;">执行历史记录</h3>
<table class="data-table" style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background: #fafafa; border-bottom: 1px solid #f0f0f0;">
<th style="padding: 12px; text-align: left;">开始时间</th>
<th style="padding: 12px; text-align: left;">耗时</th>
<th style="padding: 12px; text-align: left;">状态</th>
<th style="padding: 12px; text-align: left;">影响行数</th>
<th style="padding: 12px; text-align: left;">详情</th>
</tr>
</thead>
<tbody id="history-tbody">
<!-- 数据动态加载 -->
</tbody>
</table>
</div>
<!-- 数据上传部分 -->
<div id="data-upload-section" style="display:none;">
<div style="background: #fff; border: 1px dashed #d9d9d9; padding: 40px; text-align: center; border-radius: 8px;">
<input type="file" id="excel-file" style="display: none;" accept=".xlsx, .xls">
<div id="drop-zone" style="cursor: pointer;">
<div style="font-size: 48px; color: #1890ff; margin-bottom: 10px;">📤</div>
<p>点击或将 Excel 文件拖拽到此处上传</p>
<p style="font-size: 12px; color: #999;">支持 .xlsx, .xls 格式</p>
</div>
</div>
<div style="margin-top: 20px;">
<label>目标表名: </label>
<select id="upload-table-name" style="padding: 5px; width: 300px;">
<option value="ods_staff_daily_report_huawei">员工日报华为表 (ODS)</option>
<option value="ods_goods_order">商品订单主表 (ODS)</option>
<option value="ods_host_plant_delivery">主机厂交付数据 (ODS)</option>
</select>
<button id="btn-do-upload" style="margin-left: 10px; padding: 6px 20px; background: #52c41a; color: white; border: none; border-radius: 4px; cursor: pointer;">开始上传</button>
</div>
</div>
<div id="welcome-message">
<p>欢迎来到问界门店运营数据分析平台。请从左侧选择具体功能进行操作。</p>
</div>
</div> </div>
</div> </div>
</section> </section>
......
...@@ -13,6 +13,7 @@ from fastapi.templating import Jinja2Templates ...@@ -13,6 +13,7 @@ from fastapi.templating import Jinja2Templates
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from app.core.scheduler import SchedulerManager from app.core.scheduler import SchedulerManager
from app.core.config import settings from app.core.config import settings
from app.api.endpoints import router as api_router
# 基础目录 # 基础目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
...@@ -41,6 +42,9 @@ app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "app/static")) ...@@ -41,6 +42,9 @@ app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "app/static"))
# 配置模板引擎 # 配置模板引擎
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates")) templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))
# 注册 API 路由
app.include_router(api_router, prefix="/api")
@app.get("/") @app.get("/")
async def root(request: Request): async def root(request: Request):
"""返回主页面""" """返回主页面"""
......
...@@ -21,6 +21,23 @@ CREATE TABLE IF NOT EXISTS `_sync_meta` ( ...@@ -21,6 +21,23 @@ CREATE TABLE IF NOT EXISTS `_sync_meta` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ETL同步元数据'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ETL同步元数据';
-- ============================================================================ -- ============================================================================
-- 0.1 ETL 执行历史表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `_etl_history` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
`task_id` VARCHAR(128) NOT NULL COMMENT '任务ID(apscheduler id)',
`task_name` VARCHAR(128) DEFAULT NULL COMMENT '任务名称',
`start_time` DATETIME NOT NULL COMMENT '开始时间',
`end_time` DATETIME DEFAULT NULL COMMENT '结束时间',
`status` VARCHAR(16) DEFAULT 'running' COMMENT '状态: running/success/failed',
`params` TEXT DEFAULT NULL COMMENT '执行参数(JSON)',
`result_info` TEXT DEFAULT NULL COMMENT '执行结果/错误信息',
`rows_affected` INT DEFAULT 0 COMMENT '影响行数',
PRIMARY KEY (`id`),
INDEX idx_task_time (task_id, start_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ETL执行历史记录';
-- ============================================================================
-- 1. ODS 层 — 贴源层 -- 1. ODS 层 — 贴源层
-- ============================================================================ -- ============================================================================
......
import requests
import time
BASE_URL = "http://localhost:9500/api"
def test_scheduler_config():
print("[*] Testing scheduler config...")
resp = requests.get(f"{BASE_URL}/etl/scheduler-config?task_id=sync_ods_data")
print(f"Status: {resp.status_code}")
print(f"Response: {resp.json()}")
def test_run_ods_sync():
print("\n[*] Testing manual ODS sync trigger...")
resp = requests.post(f"{BASE_URL}/etl/run-ods")
print(f"Status: {resp.status_code}")
print(f"Response: {resp.json()}")
def test_etl_history():
print("\n[*] Testing ETL history...")
resp = requests.get(f"{BASE_URL}/etl/history?task_id=sync_ods_data")
print(f"Status: {resp.status_code}")
print(f"Response: {resp.json()}")
if __name__ == "__main__":
try:
test_scheduler_config()
test_run_ods_sync()
time.sleep(1) # 等待历史记录写入
test_etl_history()
except Exception as e:
print(f"[X] Test failed: {e}")
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!