Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-05-27 16:46:36 +08:00
commit d3fa1cc243
70 files changed
+7071 -4371

No files matched your search

+6
View File
@@ -8,6 +8,7 @@ from flask import Blueprint, jsonify, request
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import _run_generic_check_job
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
internal_jobs_bp = Blueprint('internal_jobs', __name__)
@@ -47,6 +48,10 @@ def run_internal_job(name: str):
db.session.add(run)
db.session.commit()
if not run.dify_execution_snapshot:
capture_dify_execution_snapshot(run, task)
db.session.commit()
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
except Exception as exc:
@@ -68,6 +73,7 @@ def run_internal_job(name: str):
run.finished_at = datetime.utcnow()
if run.started_at and run.finished_at:
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
return jsonify({
+3 -2
View File
@@ -1036,10 +1036,11 @@ def delete_document(document_id: int):
if not document or document.is_deleted:
return jsonify({'error': 'Knowledge base document not found'}), 404
delete_result = None
try:
delete_result = delete_document_from_dify(document.id)
except Exception as exc:
return jsonify({'error': f'删除 Dify 远端文档失败:{exc}'}), 400
except Exception:
pass
document.is_deleted = True
document.updated_by_id = getattr(current_user, 'id', None)
+19
View File
@@ -62,6 +62,7 @@ def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
"headers": cfg_model.api_headers or {},
"body_template": cfg_model.api_body_template or "",
},
"dify_system_prompt": cfg_model.dify_system_prompt or "",
}
@@ -206,6 +207,10 @@ def test_schedule_run(task_id: int):
db.session.add(run)
db.session.commit()
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
capture_dify_execution_snapshot(run, task)
db.session.commit()
if not cfg.fetch_sql:
run.status = 'success'
run.finished_at = datetime.utcnow()
@@ -289,6 +294,7 @@ def test_schedule_run(task_id: int):
fetch_sql=test_sql,
max_rows=limit,
pre_dify_fn=test_pre_dify,
dify_system_prompt=cfg.dify_system_prompt,
)
duration_ms = int((_time.time() - start_ts) * 1000)
@@ -363,6 +369,7 @@ def test_schedule_run(task_id: int):
"errors": errors,
"step_logs": step_logs,
"dify_agent_id": dify_agent_id,
"dify_execution_snapshot": run.dify_execution_snapshot,
})
except Exception as e:
duration_ms = int((_time.time() - start_ts) * 1000)
@@ -510,6 +517,11 @@ def post_schedule():
config_data = data.get('config')
if config_data:
upsert_schedule_task_config(task.id, config_data)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
return jsonify(serialize_task(task)), 201
@@ -541,6 +553,13 @@ def patch_schedule(task_id: int):
upsert_schedule_task_config(task_id, config_data)
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
return jsonify(serialize_task(task))
+5 -1
View File
@@ -39,7 +39,7 @@ def _load_environment_files() -> str:
env_file = _ROOT_DIR / f'.env.{env_name}'
if env_file.exists():
load_dotenv(env_file, override=False)
load_dotenv(env_file, override=True)
if env_name == 'dev':
local_file = _ROOT_DIR / '.env.local'
@@ -64,6 +64,10 @@ class Config:
'pool_recycle': 3600,
'pool_pre_ping': True,
}
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', 'sync').strip().lower()
# Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
+2
View File
@@ -613,6 +613,7 @@ class ScheduleTaskConfig(Base):
api_method: Mapped[str] = mapped_column(String(16), default='POST')
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
dify_system_prompt: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
@@ -644,6 +645,7 @@ class ScheduleRun(Base):
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
dify_execution_snapshot: Mapped[Optional[dict]] = mapped_column(JSON)
error_message: Mapped[Optional[str]] = mapped_column(Text)
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
@@ -17,7 +17,10 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
- worker: 仅保留 queued,等待独立 worker 轮询;
- manual: 保留 queued,等待管理台手动执行。
"""
mode = str(current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')).strip().lower()
mode = str(
current_app.config.get('TASK_EXECUTION_MODE')
or current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')
).strip().lower()
job = db.session.get(KbJob, job_id)
if not job:
@@ -32,7 +35,7 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
return run_path_upload_job(job_id)
return False, f'unsupported_sync_job:{job.job_type}'
if mode == 'worker':
if mode in ('worker', 'rq'):
return True, 'queued_for_worker'
return True, 'queued_manual'
@@ -258,6 +258,7 @@ def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExec
log_prefix=cfg.log_prefix,
fetch_sql=cfg.fetch_sql,
pre_dify_fn=pre_dify_fn,
dify_system_prompt=cfg.dify_system_prompt,
)
@@ -0,0 +1,40 @@
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import Agent, ScheduleRun, ScheduleTask
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
def build_dify_execution_snapshot(task: ScheduleTask) -> dict[str, Any]:
"""Capture Dify agent + system prompt used at execution time for audit."""
captured_at = datetime.utcnow().isoformat() + "Z"
if not task.dify_agent_id:
return {
"dify_enabled": False,
"dify_agent_id": None,
"dify_agent_name": None,
"dify_app_id": None,
"dify_system_prompt": "",
"captured_at": captured_at,
}
cfg = get_schedule_sql_config_by_task_id(task.id)
prompt = str(cfg.dify_system_prompt if cfg else "").strip()
agent = db.session.get(Agent, task.dify_agent_id)
return {
"dify_enabled": True,
"dify_agent_id": task.dify_agent_id,
"dify_agent_name": getattr(agent, "name", None) if agent else None,
"dify_app_id": getattr(agent, "dify_app_id", None) if agent else None,
"dify_system_prompt": prompt,
"captured_at": captured_at,
}
def capture_dify_execution_snapshot(run: ScheduleRun, task: ScheduleTask) -> dict[str, Any]:
snapshot = build_dify_execution_snapshot(task)
run.dify_execution_snapshot = snapshot
return snapshot
+25 -9
View File
@@ -80,7 +80,16 @@ def export_schedule_result_excel(
if not headers:
return None, None, 0
rows: list[dict[str, Any]] = []
wb = Workbook()
ws = wb.active
ws.title = "result"
ws.append([header_labels.get(k, k) for k in headers])
detail_key_set = set(all_detail_headers)
merge_keys = [k for k in headers if k not in detail_key_set]
col_index_map = {k: idx + 1 for idx, k in enumerate(headers)}
current_excel_row = 2 # header is row 1
for row in details:
if not isinstance(row, dict):
continue
@@ -98,23 +107,30 @@ def export_schedule_result_excel(
base_row[key] = _flatten_value(v)
detail_rows = row.get("_detail_rows")
group_rows: list[dict[str, Any]] = []
if all_detail_headers and isinstance(detail_rows, list) and detail_rows:
for dr in detail_rows:
flat = dict(base_row)
if isinstance(dr, dict):
for dk in all_detail_headers:
flat[dk] = dr.get(dk, "")
rows.append(flat)
group_rows.append(flat)
else:
rows.append(base_row)
group_rows.append(base_row)
wb = Workbook()
ws = wb.active
ws.title = "result"
ws.append([header_labels.get(k, k) for k in headers])
for out_row in group_rows:
ws.append([out_row.get(k, "") for k in headers])
for row in rows:
ws.append([row.get(k, "") for k in headers])
group_size = len(group_rows)
if group_size > 1:
start_row = current_excel_row
end_row = current_excel_row + group_size - 1
for key in merge_keys:
col = col_index_map.get(key)
if not col:
continue
ws.merge_cells(start_row=start_row, start_column=col, end_row=end_row, end_column=col)
current_excel_row += group_size
buf = io.BytesIO()
wb.save(buf)
@@ -54,6 +54,7 @@ def serialize_run(run: ScheduleRun) -> dict:
'api_response_json': run.api_response_json,
'response_summary_json': run.response_summary_json,
'step_logs': run.step_logs,
'dify_execution_snapshot': run.dify_execution_snapshot,
'error_message': run.error_message,
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
@@ -14,6 +14,7 @@ from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
_worker_started = False
_worker_lock = threading.Lock()
@@ -248,6 +249,9 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
db.session.add(run)
db.session.commit()
capture_dify_execution_snapshot(run, task)
db.session.commit()
if task.cron_expr and trigger_type == "cron":
try:
iter = croniter(task.cron_expr, datetime.utcnow())
@@ -94,6 +94,7 @@ class ScheduleSqlConfig:
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
data_source_type: str = "database"
dify_system_prompt: str = ""
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
@@ -153,6 +154,7 @@ def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
data_source=ds,
external_api=ext,
data_source_type=str(task.data_source_type if task else "database"),
dify_system_prompt=str(cfg_model.dify_system_prompt or ""),
)
@@ -233,6 +235,8 @@ def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleS
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
elif k == "header_labels":
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
elif k == "dify_system_prompt":
setattr(cfg_model, k, str(v) if v is not None else None)
db.session.commit()
db.session.refresh(cfg_model)
+27 -3
View File
@@ -117,6 +117,17 @@ def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
return s[:max_len] + f"...[truncated, total {len(s)} chars]"
def _serialize_dify_inputs_for_log(inputs: dict[str, Any]) -> dict[str, Any]:
"""Log Dify request inputs; keep system_prompt intact for audit."""
out: dict[str, Any] = {}
for k, v in inputs.items():
if k == "system_prompt":
out[k] = str(v)
else:
out[k] = _truncate_str(str(v), 500)
return out
def _run_check_job_loop(
*,
conn_str: str,
@@ -134,6 +145,7 @@ def _run_check_job_loop(
fetch_sql: str = "",
max_rows: int = 0,
pre_dify_fn: PreDifyFunc | None = None,
dify_system_prompt: str = "",
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]:
from app.services.schedule.scheduler_service import is_run_cancelled
@@ -218,6 +230,9 @@ def _run_check_job_loop(
"record": record_text,
"attachment_url": attachment_url,
}
prompt = str(dify_system_prompt or "").strip()
if prompt:
dify_inputs["system_prompt"] = prompt
t_dify = _ts()
try:
dify_res = DifyService.run_workflow_streaming(
@@ -228,7 +243,10 @@ def _run_check_job_loop(
)
except Exception as dify_exc:
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"error": str(dify_exc),
}))
raise
@@ -243,7 +261,10 @@ def _run_check_job_loop(
dify_message = f"Dify执行失败:{err_detail}"
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": _truncate_str(str(dify_res)),
"workflow_run_id": workflow_run_id,
}))
@@ -271,7 +292,10 @@ def _run_check_job_loop(
dify_ok = True
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
"request": {"inputs": {k: _truncate_str(str(v), 500) for k, v in dify_inputs.items()}, "agent_id": getattr(agent, "id", None)},
"request": {
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
"agent_id": getattr(agent, "id", None),
},
"response": {
"status": dify_status,
"dify_result": dify_result,
Binary file not shown.
@@ -0,0 +1,25 @@
"""add_dify_system_prompt_to_schedule_configs
Revision ID: d2e3f4a5b6c7
Revises: c1d2e3f4a5b6
Create Date: 2026-05-25
"""
from alembic import op
import sqlalchemy as sa
revision = 'd2e3f4a5b6c7'
down_revision = 'c1d2e3f4a5b6'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
batch_op.add_column(sa.Column('dify_system_prompt', sa.Text(), nullable=True))
def downgrade():
with op.batch_alter_table('schedule_task_configs', schema=None) as batch_op:
batch_op.drop_column('dify_system_prompt')
@@ -0,0 +1,25 @@
"""add_dify_execution_snapshot_to_schedule_runs
Revision ID: e3f4a5b6c7d8
Revises: d2e3f4a5b6c7
Create Date: 2026-05-25
"""
from alembic import op
import sqlalchemy as sa
revision = 'e3f4a5b6c7d8'
down_revision = 'd2e3f4a5b6c7'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
batch_op.add_column(sa.Column('dify_execution_snapshot', sa.JSON(), nullable=True))
def downgrade():
with op.batch_alter_table('schedule_runs', schema=None) as batch_op:
batch_op.drop_column('dify_execution_snapshot')
@@ -0,0 +1,102 @@
from __future__ import annotations
"""
WeCom mobile -> userid diagnostic script.
Usage:
cd backend
WECOM_DIAGNOSTIC_MOBILE=13800138000 .\\venv\\Scripts\\python.exe tests\\test_wecom_get_userid_by_mobile.py
Optional:
WECOM_DIAGNOSTIC_VERIFY_USER_GET=1 After getuserid, call user/get for the returned userid.
"""
import json
import os
import sys
from pathlib import Path
from typing import Any
import requests
BACKEND_ROOT = Path(__file__).resolve().parents[1]
if str(BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(BACKEND_ROOT))
from app import create_app # noqa: E402
from app.services.wecom_notify import _get_access_token # noqa: E402
def _get_userid_by_mobile(mobile: str) -> dict[str, Any]:
token = _get_access_token()
resp = requests.post(
"https://qyapi.weixin.qq.com/cgi-bin/user/getuserid",
params={"access_token": token},
json={"mobile": mobile},
timeout=8,
)
return {"http_status": resp.status_code, "response": resp.json()}
def _user_get(userid: str) -> dict[str, Any]:
token = _get_access_token()
resp = requests.get(
"https://qyapi.weixin.qq.com/cgi-bin/user/get",
params={"access_token": token, "userid": userid},
timeout=8,
)
return {"http_status": resp.status_code, "response": resp.json()}
def main() -> int:
mobile = os.getenv("WECOM_DIAGNOSTIC_MOBILE", "").strip()
if not mobile:
print("Missing WECOM_DIAGNOSTIC_MOBILE", file=sys.stderr)
return 2
app = create_app("development")
with app.app_context():
if not app.config.get("WECOM_CORP_ID") or not app.config.get("WECOM_SECRET"):
print("WECOM_CORP_ID / WECOM_SECRET is not configured", file=sys.stderr)
return 2
if not app.config.get("WECOM_AGENT_ID"):
print("WECOM_AGENT_ID is not configured", file=sys.stderr)
return 2
data = _get_userid_by_mobile(mobile)
print(json.dumps({"mobile": mobile, "getuserid": data}, ensure_ascii=False, indent=2))
resp = data["response"] or {}
if resp.get("errcode") != 0:
print(
f"user/getuserid failed for mobile={mobile}: {resp}",
file=sys.stderr,
)
return 1
userid = str(resp.get("userid") or "").strip()
if not userid:
print(
f"user/getuserid succeeded but userid is empty for mobile={mobile}: {resp}",
file=sys.stderr,
)
return 1
if os.getenv("WECOM_DIAGNOSTIC_VERIFY_USER_GET", "1") == "1":
user_get = _user_get(userid)
print(json.dumps({"user_get": user_get}, ensure_ascii=False, indent=2))
ug = user_get["response"] or {}
if ug.get("errcode") != 0:
print(
f"user/get failed for userid={userid}: {ug}",
file=sys.stderr,
)
return 1
print("OK")
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,133 @@
from __future__ import annotations
"""
WeCom userid diagnostic script.
Usage:
cd backend
WECOM_DIAGNOSTIC_TARGET=sophie .\\venv\\Scripts\\python.exe tests\\test_wecom_userid_diagnostic.py
Optional:
WECOM_DIAGNOSTIC_SEND=1 Also try sending a minimal textcard message
"""
import json
import os
import sys
from pathlib import Path
from typing import Any
from sqlalchemy import or_
BACKEND_ROOT = Path(__file__).resolve().parents[1]
if str(BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(BACKEND_ROOT))
from app import create_app, db # noqa: E402
from app.models import User # noqa: E402
from app.services.wecom_notify import _get_access_token, send_wecom_textcard_message # noqa: E402
def _resolve_target_userid(app, target: str) -> tuple[str, dict[str, Any] | None]:
target = (target or "").strip()
if not target:
raise ValueError("WECOM_DIAGNOSTIC_TARGET is empty")
with app.app_context():
query = db.session.query(User).filter(
or_(
User.username == target,
User.real_name == target,
User.employee_id == target,
User.employee_id == target if target.isdigit() else False,
)
)
user = query.first()
if not user:
# Allow direct WeCom userid input
return target, None
snapshot = {
"id": user.id,
"username": user.username,
"real_name": user.real_name,
"employee_id": user.employee_id,
"wecom_userid": user.wecom_userid,
"wecom_unionid": user.wecom_unionid,
"department": user.department,
"status": user.status,
}
if not user.wecom_userid:
raise RuntimeError(f"Matched DB user {user.username} but wecom_userid is empty")
return str(user.wecom_userid).strip(), snapshot
def _wecom_user_get(userid: str) -> dict[str, Any]:
token = _get_access_token()
import requests
resp = requests.get(
"https://qyapi.weixin.qq.com/cgi-bin/user/get",
params={"access_token": token, "userid": userid},
timeout=8,
)
return {"http_status": resp.status_code, "response": resp.json()}
def main() -> int:
target = os.getenv("WECOM_DIAGNOSTIC_TARGET", "").strip()
if not target:
print("Missing WECOM_DIAGNOSTIC_TARGET", file=sys.stderr)
return 2
app = create_app("development")
with app.app_context():
if not app.config.get("WECOM_CORP_ID") or not app.config.get("WECOM_SECRET"):
print("WECOM_CORP_ID / WECOM_SECRET is not configured", file=sys.stderr)
return 2
if not app.config.get("WECOM_AGENT_ID"):
print("WECOM_AGENT_ID is not configured", file=sys.stderr)
return 2
userid, matched_user = _resolve_target_userid(app, target)
print(json.dumps({
"target": target,
"resolved_userid": userid,
"matched_user": matched_user,
}, ensure_ascii=False, indent=2))
user_get = _wecom_user_get(userid)
print(json.dumps({"user_get": user_get}, ensure_ascii=False, indent=2))
user_get_resp = user_get["response"] or {}
if user_get_resp.get("errcode") != 0:
print(
f"user/get failed for userid={userid}: {user_get_resp}. "
f"This usually means the userid is invalid or the app has no access to that user.",
file=sys.stderr,
)
return 1
if os.getenv("WECOM_DIAGNOSTIC_SEND", "0") == "1":
send_resp = send_wecom_textcard_message(
userid,
title="WeCom userid diagnostic",
description=f"userid={userid}",
jump_url="",
)
print(json.dumps({"send_response": send_resp}, ensure_ascii=False, indent=2))
if send_resp.get("errcode") != 0:
print(
f"message/send failed for userid={userid}: {send_resp}. "
f"If user/get passed, the userid is valid and the issue is likely app scope or agent permissions.",
file=sys.stderr,
)
return 1
print("OK")
return 0
if __name__ == "__main__":
raise SystemExit(main())