Commit bcd74913 by 江名洋

feat(harmony): 添加鸿蒙子品牌分析接口及修复时区与调度配置

1 parent e2aa8c94
...@@ -874,6 +874,109 @@ async def harmony_download(file: str = Query(None)): ...@@ -874,6 +874,109 @@ async def harmony_download(file: str = Query(None)):
) )
# ==================== 鸿蒙子品牌分析接口 ====================
_sub_brand_file = None
@router.get("/harmony/sub-brand/template/{template_type}")
async def download_sub_brand_template(template_type: str):
"""下载鸿蒙子品牌分析模板文件"""
prefix_map = {
"output": "输出模板-鸿蒙子品牌-模板",
}
prefix = prefix_map.get(template_type)
if not prefix:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: output")
try:
file_path = _find_latest_template(prefix)
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"未找到类型为 {template_type} 的模板文件")
filename = os.path.basename(file_path)
return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@router.post("/harmony/sub-brand/upload")
async def sub_brand_upload(
data_file: UploadFile = File(...),
start_date: str = Form(None),
end_date: str = Form(None),
):
"""上传鸿蒙子品牌数据文件"""
global _sub_brand_file
if not data_file or not data_file.filename:
raise HTTPException(status_code=400, detail="请上传子品牌数据文件")
fname = _build_dated_filename(data_file.filename, "hm_sub_brand", start_date, end_date)
file_path = _date_path(fname, category="harmony")
with open(file_path, "wb") as f:
shutil.copyfileobj(data_file.file, f)
_sub_brand_file = file_path
return {"status": "success", "message": f"子品牌数据已上传: {data_file.filename}"}
@router.post("/harmony/sub-brand/generate")
async def sub_brand_generate(
start_date: str = Form(None),
end_date: str = Form(None),
):
"""根据上传的子品牌数据生成鸿蒙子品牌分析报表"""
global _sub_brand_file
if not _sub_brand_file or not os.path.exists(_sub_brand_file):
raise HTTPException(status_code=400, detail="请先上传子品牌数据文件")
try:
output_path = HarmonyAnalysisService.build_sub_brand_report(
_sub_brand_file,
start_date=start_date,
end_date=end_date,
)
return {
"status": "success",
"message": "鸿蒙子品牌分析报表已生成",
"file_path": output_path,
"download_url": f"api/harmony/sub-brand/download?file={os.path.basename(output_path)}",
}
except Exception as e:
logger.error(f"Sub-brand analysis generate failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")
@router.get("/harmony/sub-brand/download")
async def sub_brand_download(file: str = Query(None)):
"""下载鸿蒙子品牌分析报表"""
if file:
file_path = _find_file(file)
if not file_path:
raise HTTPException(status_code=404, detail="指定的报表文件不存在")
return FileResponse(
file_path, filename=file,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
output_files = sorted(
[os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
for f in fs if f.startswith("鸿蒙子品牌分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(f),
reverse=True
)
if not output_files:
raise HTTPException(status_code=404, detail="未找到鸿蒙子品牌分析报表,请先生成")
file_path = output_files[0]
return FileResponse(
file_path,
filename=os.path.basename(file_path),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
# ==================== 策略效果盯防接口 ==================== # ==================== 策略效果盯防接口 ====================
@router.get("/strategy/options") @router.get("/strategy/options")
......
...@@ -36,8 +36,8 @@ class Settings(BaseSettings): ...@@ -36,8 +36,8 @@ class Settings(BaseSettings):
@property @property
def database_url(self) -> str: def database_url(self) -> str:
"""返回 SQLAlchemy 连接字符串""" """返回 SQLAlchemy 连接字符串(session timezone 设为 UTC+8)"""
return f"mysql+pymysql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}?charset=utf8mb4" return f"mysql+pymysql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}?charset=utf8mb4&init_command=SET time_zone='%2B08:00'"
# LLM Settings (Qwen) # LLM Settings (Qwen)
LLM_QWEN_MODEL: str = "qwen3.7-plus" LLM_QWEN_MODEL: str = "qwen3.7-plus"
......
...@@ -31,28 +31,30 @@ class SchedulerManager: ...@@ -31,28 +31,30 @@ class SchedulerManager:
if cls._scheduler is None: if cls._scheduler is None:
cls._scheduler = AsyncIOScheduler() cls._scheduler = AsyncIOScheduler()
# 1. ODS 同步任务 (每 30 分钟执行一次,带 3s 抖动,模仿用户参考) # 1. ODS 同步任务 (每 3 小时执行一次,带 3s 抖动)
# start_date 设为启动后 30s,避免等 3 小时才首次执行
first_run = datetime.now() + timedelta(seconds=30)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.sync_ods_task, cls.sync_ods_task,
IntervalTrigger(minutes=180, jitter=3), IntervalTrigger(minutes=180, jitter=3, start_date=first_run),
id="sync_ods_data", id="sync_ods_data",
max_instances=1, max_instances=1,
replace_existing=True replace_existing=True
) )
# 2. 策略效果分析任务 (每 2 小时执行一次) # 2. 策略效果分析任务 (每 2 小时执行一次,启动后 60s 首次执行)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.sync_strategy_analysis, cls.sync_strategy_analysis,
IntervalTrigger(hours=2), IntervalTrigger(hours=2, start_date=first_run),
id="sync_strategy_analysis", id="sync_strategy_analysis",
max_instances=1, max_instances=1,
replace_existing=True, replace_existing=True,
) )
# 3. 盯防数据自动刷新 (每 1 小时扫描超过 4 小时未刷新的盯防数据) # 3. 盯防数据自动刷新 (每 1 小时扫描超过 4 小时未刷新的盯防数据,启动后 60s 首次执行)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.auto_refresh_strategy_monitoring, cls.auto_refresh_strategy_monitoring,
IntervalTrigger(hours=1, jitter=120), IntervalTrigger(hours=1, jitter=120, start_date=first_run),
id="auto_refresh_strategy_monitoring", id="auto_refresh_strategy_monitoring",
max_instances=1, max_instances=1,
replace_existing=True, replace_existing=True,
......
...@@ -67,7 +67,8 @@ class ETLService: ...@@ -67,7 +67,8 @@ class ETLService:
charset='utf8mb4', charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor, cursorclass=pymysql.cursors.DictCursor,
connect_timeout=10, connect_timeout=10,
read_timeout=300 read_timeout=300,
init_command="SET time_zone='+08:00'"
) )
@staticmethod @staticmethod
...@@ -82,7 +83,8 @@ class ETLService: ...@@ -82,7 +83,8 @@ class ETLService:
cursorclass=pymysql.cursors.DictCursor, cursorclass=pymysql.cursors.DictCursor,
autocommit=True, autocommit=True,
connect_timeout=10, connect_timeout=10,
read_timeout=300 read_timeout=300,
init_command="SET time_zone='+08:00'"
) )
@classmethod @classmethod
...@@ -271,17 +273,33 @@ class ETLService: ...@@ -271,17 +273,33 @@ class ETLService:
except Exception as e: except Exception as e:
logger.error(f"[X] ODS Sync failed for task_id={task_id}: {e}", exc_info=True) logger.error(f"[X] ODS Sync failed for task_id={task_id}: {e}", exc_info=True)
if history_id: # 使用独立连接(pymysql)更新历史记录,避免 db 会话已损坏时更新失败
db.execute(text(""" cls._safe_update_history_failed(history_id, str(e))
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 raise e
finally: finally:
db.close() db.close()
@staticmethod @staticmethod
def _safe_update_history_failed(history_id: int, error_msg: str):
"""使用独立 pymysql 连接更新 _etl_history 失败状态,避免 SQLAlchemy session 已损坏时更新失败"""
if not history_id:
return
conn = None
try:
conn = ETLService.get_target_conn()
with conn.cursor() as cur:
cur.execute(
"UPDATE _etl_history SET end_time = NOW(), status = 'failed', result_info = %s WHERE id = %s",
(error_msg[:2000], history_id) # 截断超长错误信息
)
conn.commit()
except Exception as update_err:
logger.error(f"[X] Failed to update ETL history (id={history_id}) to 'failed': {update_err}")
finally:
if conn:
conn.close()
@staticmethod
def _populate_ods_store_config(): def _populate_ods_store_config():
""" """
从 ods_service_merchant 填充 ods_store_config 中缺失的门店基础信息, 从 ods_service_merchant 填充 ods_store_config 中缺失的门店基础信息,
...@@ -521,12 +539,7 @@ class ETLService: ...@@ -521,12 +539,7 @@ class ETLService:
except Exception as e: except Exception as e:
logger.error(f"[X] {layer} Sync failed for task_id={task_id}: {e}", exc_info=True) logger.error(f"[X] {layer} Sync failed for task_id={task_id}: {e}", exc_info=True)
if history_id: cls._safe_update_history_failed(history_id, str(e))
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 raise e
finally: finally:
db.close() db.close()
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!