Merge branch 'dev' into test
This commit is contained in:
commit
f321e2ddd8
93 files changed
+7562
-9656
No files matched your search
@@ -15,7 +15,7 @@ from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.minio_service import minio_service
|
||||
from app.services.integrations.minio import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -36,7 +36,7 @@ def get_chat_query_preview(chat_log_id: int):
|
||||
if not sql:
|
||||
raise ValidationError('query preview sql is missing')
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
total_count = payload.get('total_count')
|
||||
try:
|
||||
total_count = int(total_count) if total_count is not None else None
|
||||
|
||||
@@ -87,7 +87,7 @@ def chat_completions():
|
||||
role=getattr(user, 'role', None),
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
|
||||
@@ -35,7 +35,7 @@ def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy)
|
||||
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
|
||||
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
|
||||
"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
|
||||
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ def get_oa_employees():
|
||||
page = 1
|
||||
page_size = 20
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
result = OASQLServerService.search_employees(keyword, page, page_size)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
@@ -39,7 +39,7 @@ def resolve_oa_names():
|
||||
sub_ids = request.args.get('subcompany_ids', '').strip()
|
||||
result = {}
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
if dept_ids:
|
||||
for did in dept_ids.split(','):
|
||||
did = did.strip()
|
||||
|
||||
@@ -24,9 +24,9 @@ from flask import Blueprint, request, Response, stream_with_context, jsonify, g,
|
||||
from sqlalchemy import func, desc, or_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.services.integrations.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
|
||||
@@ -27,7 +27,7 @@ def upload_chat_file():
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
|
||||
params = DifyService.get_app_parameters(agent, force_refresh=True)
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
|
||||
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,6 +17,7 @@ from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.jobs import JobType, enqueue
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
@@ -31,7 +32,7 @@ from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hx
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
@@ -543,28 +544,16 @@ def run_file_check():
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
||||
except Exception as exc:
|
||||
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == "running":
|
||||
r.status = "failed"
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
|
||||
enqueue(
|
||||
JobType.FILE_CHECK_RUN,
|
||||
{"task_id": task_id, "schedule_run_id": run_id},
|
||||
domain="file_check",
|
||||
business_ref=str(run_id),
|
||||
message="等待执行文件检核",
|
||||
)
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
@@ -22,7 +22,7 @@ from app.core.errors import (
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.services.integrations.integration_api import IntegrationApiService
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/knowledge_base.py
|
||||
|
||||
用途:知识库 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.kb。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.kb。
|
||||
"""
|
||||
from app.api.kb import knowledge_base_bp
|
||||
|
||||
__all__ = ['knowledge_base_bp']
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule_admin.py
|
||||
|
||||
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
|
||||
"""
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
@@ -14,8 +14,8 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.integrations.wecom.crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
|
||||
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, extract_encrypt_field
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
import re
|
||||
import ast
|
||||
from app.core.errors import (
|
||||
@@ -108,7 +108,7 @@ def submit_leave_workflow():
|
||||
if not form_data.get(key):
|
||||
raise ValidationError(f'{label}不能为空。')
|
||||
try:
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
|
||||
except OALeaveWorkflowError as exc:
|
||||
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
|
||||
@@ -358,7 +358,7 @@ def get_agent_details(id):
|
||||
|
||||
dify_parameters = None
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_schedule.py
|
||||
|
||||
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
|
||||
__all__ = ['workspace_schedule_bp']
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_shipping_notice.py
|
||||
|
||||
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.shipping_notice。
|
||||
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
|
||||
"""
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
__all__ = ['workspace_shipping_notice_bp']
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
backend/app/core/http_context.py
|
||||
|
||||
用途:把 Flask request 读取收口在 core,避免 services 直接依赖 flask.request。
|
||||
依赖:flask.has_request_context / request(仅本模块)。
|
||||
逻辑:API 与 service 需要 Host、Header、客户端 IP 时调用本模块;无请求上下文时返回空值。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def has_http_request() -> bool:
|
||||
"""
|
||||
当前是否处于 HTTP 请求上下文。
|
||||
返回:
|
||||
有请求上下文时 True,Worker / CLI 时 False。
|
||||
"""
|
||||
from flask import has_request_context
|
||||
|
||||
return bool(has_request_context())
|
||||
|
||||
|
||||
def header(name: str, default: str = "") -> str:
|
||||
"""
|
||||
读取请求头;无请求上下文时返回 default。
|
||||
参数:
|
||||
name: Header 名。
|
||||
default: 缺省值。
|
||||
"""
|
||||
if not has_http_request():
|
||||
return default
|
||||
from flask import request
|
||||
|
||||
return str(request.headers.get(name) or default)
|
||||
|
||||
|
||||
def host_url() -> str:
|
||||
"""返回当前请求 host_url(无尾斜杠);无请求时返回空字符串。"""
|
||||
if not has_http_request():
|
||||
return ""
|
||||
from flask import request
|
||||
|
||||
return str(request.host_url or "").rstrip("/")
|
||||
|
||||
|
||||
def remote_addr() -> str:
|
||||
"""返回 request.remote_addr;无请求时返回空字符串。"""
|
||||
if not has_http_request():
|
||||
return ""
|
||||
from flask import request
|
||||
|
||||
return str(request.remote_addr or "").strip()
|
||||
@@ -2,17 +2,44 @@
|
||||
backend/app/jobs/handlers/file_check_run.py
|
||||
|
||||
用途:文件检核异步执行 handler。
|
||||
逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。
|
||||
依赖:schedule.scheduler_service.run_task_now、jobs.queue.finish_job。
|
||||
逻辑:schedule worker 领取 FILE_CHECK_RUN 后,按 payload 中的 task_id / schedule_run_id 执行已创建的 ScheduleRun。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.scheduler_service import run_task_now
|
||||
|
||||
|
||||
@register_handler(JobType.FILE_CHECK_RUN)
|
||||
def run_file_check(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行异步文件检核。"""
|
||||
ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('file_check_run handler pending Wave 4')
|
||||
"""
|
||||
执行已入队的文件检核 ScheduleRun。
|
||||
|
||||
核心逻辑:读取 task/run → 调用 run_task_now(与原 API 后台线程同一入口)→ finish_job。
|
||||
参数:
|
||||
ctx: Worker 上下文。
|
||||
payload: 必须包含 task_id 与 schedule_run_id;可选 job_id。
|
||||
异常:
|
||||
RuntimeError: payload 缺失或任务/运行记录不存在。
|
||||
"""
|
||||
task_id = int(payload.get("task_id") or 0)
|
||||
run_id = int(payload.get("schedule_run_id") or 0)
|
||||
job_id = int(payload.get("job_id") or 0)
|
||||
if not task_id or not run_id:
|
||||
raise RuntimeError("task_id and schedule_run_id are required")
|
||||
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
run = db.session.get(ScheduleRun, run_id)
|
||||
if not task or not run:
|
||||
raise RuntimeError(f"file-check task/run not found task_id={task_id} run_id={run_id}")
|
||||
|
||||
ctx.logger.info("file_check_run start job_id=%s task_id=%s run_id=%s", job_id, task_id, run_id)
|
||||
run_task_now(task, trigger_type="dify_chatflow", triggered_by_user_id=None, run=run)
|
||||
if job_id:
|
||||
finish_job(job_id, result={"task_id": task_id, "schedule_run_id": run_id}, message="文件检核执行完成")
|
||||
@@ -2,17 +2,38 @@
|
||||
backend/app/jobs/handlers/wecom_directory_sync.py
|
||||
|
||||
用途:企微通讯录同步 handler。
|
||||
逻辑:Wave 4 包装 wecom_directory_sync 服务。
|
||||
依赖:wecom_directory_sync.sync_wecom_userids_from_directory、jobs.queue.finish_job。
|
||||
逻辑:schedule worker 领取后按 payload.apply / department_id 执行通讯录回填。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.integrations.wecom.directory_sync import sync_wecom_userids_from_directory
|
||||
|
||||
|
||||
@register_handler(JobType.WECOM_DIRECTORY_SYNC)
|
||||
def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""同步企微通讯录到本地用户/部门。"""
|
||||
ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('wecom_directory_sync handler pending Wave 4')
|
||||
"""
|
||||
从企微通讯录同步 users.wecom_userid。
|
||||
|
||||
核心逻辑:委托 sync_wecom_userids_from_directory;conflicts 时抛错由 Job 层标记失败。
|
||||
参数:
|
||||
ctx: Worker 上下文。
|
||||
payload: apply(bool)、department_id(可选 int)、job_id(可选)。
|
||||
"""
|
||||
apply = bool(payload.get("apply"))
|
||||
raw_dept = payload.get("department_id")
|
||||
department_id = int(raw_dept) if raw_dept not in (None, "") else None
|
||||
job_id = int(payload.get("job_id") or 0)
|
||||
ctx.logger.info(
|
||||
"wecom_directory_sync start job_id=%s apply=%s department_id=%s",
|
||||
job_id,
|
||||
apply,
|
||||
department_id,
|
||||
)
|
||||
summary = sync_wecom_userids_from_directory(apply=apply, department_id=department_id)
|
||||
if job_id:
|
||||
finish_job(job_id, result=summary, message="企微通讯录同步完成")
|
||||
@@ -149,6 +149,13 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
)
|
||||
if job:
|
||||
return _normalize_generic_job(job)
|
||||
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
|
||||
job = claim_next_job(
|
||||
domain=None,
|
||||
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
|
||||
)
|
||||
if job:
|
||||
return _normalize_generic_job(job)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||
}),
|
||||
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
||||
'schedule': frozenset({'schedule_run'}),
|
||||
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
||||
'transfer': frozenset({
|
||||
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||
}),
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.services.admin.training_exam_pdf_service import parse_training_question
|
||||
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
|
||||
from app.services.agent_registry.catalog_loader import get_dify_required_providers
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_admin
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
|
||||
def serialize_agent(agent: Agent) -> dict:
|
||||
|
||||
@@ -14,7 +14,7 @@ from werkzeug.datastructures import FileStorage
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import AgentGuide
|
||||
from app.services.minio_service import minio_service
|
||||
from app.services.integrations.minio import minio_service
|
||||
|
||||
|
||||
GUIDE_USAGE_GENERAL = 'general'
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import AgentGuide, KbDocumentVersion
|
||||
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
|
||||
from app.services.kb.storage import resolve_storage_path
|
||||
from app.services.minio_service import minio_service
|
||||
from app.services.integrations.minio import minio_service
|
||||
from edkb_system.contracts import Block, Context
|
||||
from edkb_system.skills import loader_pdf, ocr
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.core.config.env_persistence import persist_env_settings
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
|
||||
from app.services.auth import wecom_auth_service
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
def serialize_debug_match_user(user: User) -> dict:
|
||||
|
||||
@@ -15,7 +15,7 @@ from app.services.chat.executors.base import (
|
||||
ChatStreamContext,
|
||||
build_dify_inputs_for_context,
|
||||
)
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
|
||||
class DifyChatExecutor(ChatExecutor):
|
||||
|
||||
@@ -16,13 +16,13 @@ from app.services.chat.intent_route_registry import (
|
||||
|
||||
|
||||
def _match(ctx: ChatIntentRouteContext) -> bool:
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
from app.services.integrations.plm.oracle import PLMOracleService
|
||||
|
||||
return PLMOracleService.supports(ctx.query, ctx.agent)
|
||||
|
||||
|
||||
def _stream(ctx: ChatIntentRouteContext):
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
from app.services.integrations.plm.oracle import PLMOracleService
|
||||
|
||||
return PLMOracleService.stream_chat(
|
||||
ctx.query,
|
||||
|
||||
@@ -27,7 +27,7 @@ def _match(ctx: ChatIntentRouteContext) -> bool:
|
||||
|
||||
|
||||
def _stream(ctx: ChatIntentRouteContext):
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
|
||||
return Text2SQLService.stream_chat(
|
||||
ctx.query,
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
|
||||
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
|
||||
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
|
||||
@@ -29,7 +29,7 @@ from app.models import (
|
||||
ContractPaymentNode,
|
||||
User,
|
||||
)
|
||||
from app.services.wecom_notify import (
|
||||
from app.services.integrations.wecom.notify import (
|
||||
send_wecom_event_message,
|
||||
send_wecom_file_message,
|
||||
upload_wecom_temp_media,
|
||||
|
||||
@@ -53,7 +53,7 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
|
||||
return {}
|
||||
try:
|
||||
import oracledb
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
except ImportError:
|
||||
current_app.logger.warning("合同付款预警:Oracle 驱动不可用,按未付款处理")
|
||||
return {}
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
|
||||
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
|
||||
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,8 +14,8 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, QuickQuestion
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.services.integrations.integration_api import IntegrationApiService
|
||||
|
||||
STALE_REASON_KB_UPDATED = 'kb_document_updated'
|
||||
STALE_REASON_KB_DELETED = 'kb_document_deleted'
|
||||
|
||||
@@ -12,7 +12,7 @@ from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
|
||||
|
||||
|
||||
@@ -284,7 +284,7 @@ ORDER BY faj.faj02
|
||||
def _fetch_snapshot_rows(cls, timeout_seconds: int) -> list[dict[str, str]]:
|
||||
"""从 ERP Oracle 拉取固定资产全量快照。"""
|
||||
import oracledb
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
|
||||
username, password, dsn = cls._oracle_credentials()
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
@@ -729,7 +729,7 @@ INSERT INTO fixed_assets (
|
||||
user_context: dict[str, Any] | None = None,
|
||||
) -> tuple[str, list[str], dict[str, Any]]:
|
||||
"""根据用户问句生成本地快照过滤条件。"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
|
||||
clauses: list[str] = []
|
||||
params: list[str] = []
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
backend/app/services/hxops_tool_api.py
|
||||
|
||||
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
|
||||
依赖:Flask current_app / request。
|
||||
依赖:Flask current_app、core.http_context。
|
||||
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, has_request_context, request
|
||||
from flask import current_app
|
||||
|
||||
from app.core.http_context import has_http_request, host_url
|
||||
|
||||
|
||||
def _resolve_config(config: dict | None = None) -> dict:
|
||||
@@ -25,11 +27,11 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
|
||||
|
||||
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
|
||||
|
||||
Args:
|
||||
参数:
|
||||
config: 可选配置字典;缺省时读 current_app.config。
|
||||
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
|
||||
request_host: 可选请求 host_url;缺省且在请求上下文中时取 host_url()。
|
||||
|
||||
Returns:
|
||||
返回:
|
||||
无尾斜杠的根地址,如 http://192.168.100.192:8890。
|
||||
"""
|
||||
cfg = _resolve_config(config)
|
||||
@@ -39,8 +41,8 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
|
||||
return configured
|
||||
|
||||
host = request_host
|
||||
if host is None and has_request_context():
|
||||
host = request.host_url.rstrip("/")
|
||||
if host is None and has_http_request():
|
||||
host = host_url()
|
||||
return host or ""
|
||||
|
||||
|
||||
@@ -50,10 +52,10 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
|
||||
|
||||
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
|
||||
|
||||
Args:
|
||||
参数:
|
||||
config: 可选配置字典;缺省时读 current_app.config。
|
||||
|
||||
Returns:
|
||||
返回:
|
||||
无尾斜杠的根地址,如 https://ai.example.com。
|
||||
"""
|
||||
cfg = _resolve_config(config)
|
||||
@@ -63,7 +65,7 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if has_request_context():
|
||||
return request.host_url.rstrip("/")
|
||||
if has_http_request():
|
||||
return host_url()
|
||||
|
||||
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
|
||||
@@ -1,514 +0,0 @@
|
||||
"""
|
||||
backend/app/services/integration_api.py
|
||||
|
||||
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
|
||||
依赖:Flask request/current_app、requests、Kb* 模型。
|
||||
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from flask import current_app, has_app_context, has_request_context, request
|
||||
|
||||
from app.core.config.settings import Config
|
||||
|
||||
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _request_origin_url() -> str:
|
||||
if not has_request_context():
|
||||
return ""
|
||||
|
||||
forwarded_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip()
|
||||
forwarded_host = (request.headers.get("X-Forwarded-Host") or "").split(",")[0].strip()
|
||||
if forwarded_proto and forwarded_host:
|
||||
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
|
||||
|
||||
origin = str(request.headers.get("Origin") or "").strip().rstrip("/")
|
||||
if origin:
|
||||
return origin
|
||||
|
||||
referer = str(request.headers.get("Referer") or "").strip()
|
||||
if referer:
|
||||
parsed = urlparse(referer)
|
||||
if parsed.scheme and parsed.netloc:
|
||||
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
|
||||
|
||||
return request.host_url.rstrip("/")
|
||||
|
||||
@staticmethod
|
||||
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
|
||||
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
service = KbDifySyncService()
|
||||
if not service.base_url or not service.api_key:
|
||||
return None
|
||||
|
||||
document_payload = service.get_document(
|
||||
dataset_id=str(dataset_id),
|
||||
document_id=str(remote_document_id),
|
||||
)
|
||||
if not isinstance(document_payload, dict):
|
||||
return None
|
||||
|
||||
download_resp = requests.get(
|
||||
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
|
||||
headers=service._headers(),
|
||||
timeout=(5, 15),
|
||||
)
|
||||
if download_resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.info(
|
||||
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
download_resp.status_code,
|
||||
)
|
||||
return None
|
||||
|
||||
download_payload = download_resp.json() if download_resp.content else {}
|
||||
source_url = str((download_payload or {}).get("url") or "").strip()
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
upload_info = (
|
||||
((document_payload.get("data_source_info") or {}).get("upload_file"))
|
||||
if isinstance(document_payload.get("data_source_info"), dict)
|
||||
else {}
|
||||
) or {}
|
||||
source_filename = str(
|
||||
upload_info.get("name")
|
||||
or document_payload.get("name")
|
||||
or ""
|
||||
).strip() or None
|
||||
source_ext = str(
|
||||
upload_info.get("extension")
|
||||
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
|
||||
).strip().lower() or None
|
||||
|
||||
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
|
||||
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
|
||||
|
||||
return {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": expires_at,
|
||||
"version_id": None,
|
||||
"document_id": remote_document_id,
|
||||
}
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id or not row.get("found"):
|
||||
return None
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
return key, normalized
|
||||
|
||||
@staticmethod
|
||||
def _is_loopback_url(url: str) -> bool:
|
||||
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
|
||||
return host in {"127.0.0.1", "localhost", "::1"}
|
||||
|
||||
@staticmethod
|
||||
def get_api_key() -> str:
|
||||
if has_app_context():
|
||||
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
return str(Config.INTEGRATION_API_KEY or "").strip()
|
||||
|
||||
@staticmethod
|
||||
def get_base_url() -> str:
|
||||
mode = "local"
|
||||
if has_app_context():
|
||||
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
|
||||
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
|
||||
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
|
||||
else:
|
||||
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
|
||||
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
|
||||
public_base = ""
|
||||
|
||||
# For server-side lookups, always prefer the explicitly configured
|
||||
# integration service endpoint when present. Falling back to the current
|
||||
# request host would incorrectly call this backend itself.
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if mode != "external":
|
||||
request_origin = IntegrationApiService._request_origin_url()
|
||||
if request_origin:
|
||||
return request_origin
|
||||
if public_base:
|
||||
return public_base
|
||||
if has_request_context():
|
||||
return request.host_url.rstrip("/")
|
||||
|
||||
return configured
|
||||
|
||||
@staticmethod
|
||||
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
|
||||
return (str(dataset_id), str(remote_document_id))
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp_str = payload.get("download_url_expires_at")
|
||||
if exp_str:
|
||||
try:
|
||||
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
|
||||
source_url = payload.get("source_download_url") or ""
|
||||
if "token=" in source_url:
|
||||
try:
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import time
|
||||
qs = parse_qs(urlparse(source_url).query)
|
||||
if 'token' in qs:
|
||||
token = qs['token'][0]
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
exp = payload_data.get('exp', 0)
|
||||
if exp and exp < time.time() + 300:
|
||||
return False # 已过期或即将过期
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
从本地 KbDifySyncRecord 反查可预览下载链接。
|
||||
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
|
||||
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
|
||||
"""
|
||||
if not has_app_context():
|
||||
return None
|
||||
from pathlib import Path
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
|
||||
|
||||
normalized_dataset_id = str(dataset_id or '').strip()
|
||||
normalized_remote_document_id = str(remote_document_id or '').strip()
|
||||
if not normalized_dataset_id or not normalized_remote_document_id:
|
||||
return None
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDifySyncRecord.dataset_id == normalized_dataset_id,
|
||||
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not record or not record.document_version or not record.document_version.document:
|
||||
return None
|
||||
|
||||
version = record.document_version
|
||||
document = version.document
|
||||
|
||||
def _existing(path_value: str | None):
|
||||
if not path_value:
|
||||
return None
|
||||
raw = Path(str(path_value))
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
if candidate.exists() and candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
source_path = _existing(version.source_file_path)
|
||||
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
|
||||
if source_path is None and markdown_path is None:
|
||||
current_app.logger.info(
|
||||
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
|
||||
document.id,
|
||||
version.id,
|
||||
)
|
||||
return None
|
||||
|
||||
base_url = IntegrationApiService._request_origin_url()
|
||||
if not base_url:
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
if explicit:
|
||||
base_url = explicit
|
||||
elif has_request_context():
|
||||
base_url = request.host_url.rstrip('/')
|
||||
else:
|
||||
base_url = ''
|
||||
|
||||
import time
|
||||
import jwt
|
||||
|
||||
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
if not secret:
|
||||
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
|
||||
payload = {
|
||||
'dataset_id': normalized_dataset_id,
|
||||
'remote_document_id': normalized_remote_document_id,
|
||||
'version_id': version.id,
|
||||
'exp': exp
|
||||
}
|
||||
token = jwt.encode(payload, secret, algorithm='HS256')
|
||||
|
||||
if source_path is not None:
|
||||
kind = 'source'
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
else:
|
||||
kind = 'md'
|
||||
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
|
||||
source_filename = f'{stem}.md'
|
||||
source_ext = 'md'
|
||||
|
||||
source_download_url = (
|
||||
f'{base_url}/api/integration/files/{document.id}/download'
|
||||
f'?kind={kind}&version_id={version.id}&token={token}'
|
||||
)
|
||||
|
||||
return {
|
||||
"source_download_url": source_download_url,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": None,
|
||||
"version_id": version.id,
|
||||
"document_id": document.id,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
cached = IntegrationApiService._cache.get(cache_key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
return cached
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
|
||||
url = f"{base_url}/api/integration/dify-file"
|
||||
headers = {"X-Integration-Key": api_key}
|
||||
params = {
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
if isinstance(payload, dict):
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
elif has_app_context():
|
||||
current_app.logger.info(
|
||||
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
resp.status_code,
|
||||
)
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
|
||||
batch_url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
batch_headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
batch_body = {
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
]
|
||||
}
|
||||
try:
|
||||
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
if key == cache_key:
|
||||
return normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
||||
|
||||
# Fallback to local database if remote integration API fails or misses
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[cache_key] = local_result
|
||||
return local_result
|
||||
|
||||
# Last fallback: query Dify document API directly and request a signed download URL.
|
||||
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
|
||||
if dify_result:
|
||||
IntegrationApiService._cache[cache_key] = dify_result
|
||||
return dify_result
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
||||
"""
|
||||
Batch resolve source files by (dataset_id, remote_document_id).
|
||||
Returns a mapping keyed by (dataset_id, remote_document_id).
|
||||
"""
|
||||
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
if not items:
|
||||
return results
|
||||
|
||||
unresolved: List[Dict[str, str]] = []
|
||||
seen = set()
|
||||
|
||||
for item in items:
|
||||
dataset_id = str(item.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(item.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
cached = IntegrationApiService._cache.get(key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
results[key] = cached
|
||||
else:
|
||||
unresolved.append({
|
||||
"dataset_id": dataset_id,
|
||||
"remote_document_id": remote_document_id,
|
||||
})
|
||||
|
||||
if not unresolved:
|
||||
return results
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return results
|
||||
|
||||
url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {"items": unresolved}
|
||||
|
||||
try:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Integration API batch lookup failed: status=%s", resp.status_code
|
||||
)
|
||||
else:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
||||
|
||||
# Fallback to single lookup or local DB for unresolved items
|
||||
for item in unresolved:
|
||||
dataset_id = item["dataset_id"]
|
||||
remote_document_id = item["remote_document_id"]
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in results:
|
||||
continue
|
||||
|
||||
# Check if single lookup was not called already (if it was, it might be cached)
|
||||
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[key] = local_result
|
||||
results[key] = local_result
|
||||
continue
|
||||
|
||||
# As a last resort, try remote single lookup if batch missed it
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if payload:
|
||||
results[key] = payload
|
||||
|
||||
return results
|
||||
@@ -2,16 +2,17 @@
|
||||
backend/app/services/integration_tool_auth.py
|
||||
|
||||
用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。
|
||||
依赖:Flask current_app、core.errors。
|
||||
依赖:Flask current_app、core.errors、core.http_context。
|
||||
逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用;
|
||||
密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, request
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||
from app.core.http_context import header
|
||||
|
||||
|
||||
def require_integration_tool_auth() -> None:
|
||||
@@ -19,7 +20,7 @@ def require_integration_tool_auth() -> None:
|
||||
校验 Tool API 访问权限。
|
||||
核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。
|
||||
|
||||
Raises:
|
||||
异常:
|
||||
ServiceUnavailableError: 服务端未配置密钥。
|
||||
UnauthorizedError: 缺少或错误的凭证。
|
||||
"""
|
||||
@@ -34,9 +35,9 @@ def require_integration_tool_auth() -> None:
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
bearer = header("Authorization").strip()
|
||||
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
integration_key = header("X-Integration-Key").strip()
|
||||
if configured in {api_token, integration_key}:
|
||||
return
|
||||
if not api_token and not integration_key:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,514 @@
|
||||
"""
|
||||
backend/app/services/integrations/integration_api.py
|
||||
|
||||
用途:知识库源文件反查等集成 API 适配。
|
||||
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
|
||||
依赖:Flask current_app、core.http_context、requests、Kb* 模型。
|
||||
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
|
||||
"""
|
||||
from app.services import integration_api # noqa: F401
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
__all__ = ['integration_api']
|
||||
import requests
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
from app.core.config.settings import Config
|
||||
from app.core.http_context import has_http_request, header, host_url
|
||||
|
||||
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _request_origin_url() -> str:
|
||||
if not has_http_request():
|
||||
return ""
|
||||
|
||||
forwarded_proto = header("X-Forwarded-Proto").split(",")[0].strip()
|
||||
forwarded_host = header("X-Forwarded-Host").split(",")[0].strip()
|
||||
if forwarded_proto and forwarded_host:
|
||||
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
|
||||
|
||||
origin = header("Origin").strip().rstrip("/")
|
||||
if origin:
|
||||
return origin
|
||||
|
||||
referer = header("Referer").strip()
|
||||
if referer:
|
||||
parsed = urlparse(referer)
|
||||
if parsed.scheme and parsed.netloc:
|
||||
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
|
||||
|
||||
return host_url()
|
||||
|
||||
@staticmethod
|
||||
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
|
||||
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
service = KbDifySyncService()
|
||||
if not service.base_url or not service.api_key:
|
||||
return None
|
||||
|
||||
document_payload = service.get_document(
|
||||
dataset_id=str(dataset_id),
|
||||
document_id=str(remote_document_id),
|
||||
)
|
||||
if not isinstance(document_payload, dict):
|
||||
return None
|
||||
|
||||
download_resp = requests.get(
|
||||
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
|
||||
headers=service._headers(),
|
||||
timeout=(5, 15),
|
||||
)
|
||||
if download_resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.info(
|
||||
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
download_resp.status_code,
|
||||
)
|
||||
return None
|
||||
|
||||
download_payload = download_resp.json() if download_resp.content else {}
|
||||
source_url = str((download_payload or {}).get("url") or "").strip()
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
upload_info = (
|
||||
((document_payload.get("data_source_info") or {}).get("upload_file"))
|
||||
if isinstance(document_payload.get("data_source_info"), dict)
|
||||
else {}
|
||||
) or {}
|
||||
source_filename = str(
|
||||
upload_info.get("name")
|
||||
or document_payload.get("name")
|
||||
or ""
|
||||
).strip() or None
|
||||
source_ext = str(
|
||||
upload_info.get("extension")
|
||||
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
|
||||
).strip().lower() or None
|
||||
|
||||
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
|
||||
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
|
||||
|
||||
return {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": expires_at,
|
||||
"version_id": None,
|
||||
"document_id": remote_document_id,
|
||||
}
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id or not row.get("found"):
|
||||
return None
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
return key, normalized
|
||||
|
||||
@staticmethod
|
||||
def _is_loopback_url(url: str) -> bool:
|
||||
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
|
||||
return host in {"127.0.0.1", "localhost", "::1"}
|
||||
|
||||
@staticmethod
|
||||
def get_api_key() -> str:
|
||||
if has_app_context():
|
||||
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
return str(Config.INTEGRATION_API_KEY or "").strip()
|
||||
|
||||
@staticmethod
|
||||
def get_base_url() -> str:
|
||||
mode = "local"
|
||||
if has_app_context():
|
||||
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
|
||||
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
|
||||
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
|
||||
else:
|
||||
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
|
||||
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
|
||||
public_base = ""
|
||||
|
||||
# 服务端查询优先使用显式配置的集成服务地址;
|
||||
# 回退到当前请求 host 会错误地打到本后端自身。
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if mode != "external":
|
||||
request_origin = IntegrationApiService._request_origin_url()
|
||||
if request_origin:
|
||||
return request_origin
|
||||
if public_base:
|
||||
return public_base
|
||||
if has_http_request():
|
||||
return host_url()
|
||||
|
||||
return configured
|
||||
|
||||
@staticmethod
|
||||
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
|
||||
return (str(dataset_id), str(remote_document_id))
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp_str = payload.get("download_url_expires_at")
|
||||
if exp_str:
|
||||
try:
|
||||
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
|
||||
source_url = payload.get("source_download_url") or ""
|
||||
if "token=" in source_url:
|
||||
try:
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import time
|
||||
qs = parse_qs(urlparse(source_url).query)
|
||||
if 'token' in qs:
|
||||
token = qs['token'][0]
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
exp = payload_data.get('exp', 0)
|
||||
if exp and exp < time.time() + 300:
|
||||
return False # 已过期或即将过期
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
从本地 KbDifySyncRecord 反查可预览下载链接。
|
||||
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
|
||||
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
|
||||
"""
|
||||
if not has_app_context():
|
||||
return None
|
||||
from pathlib import Path
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
|
||||
|
||||
normalized_dataset_id = str(dataset_id or '').strip()
|
||||
normalized_remote_document_id = str(remote_document_id or '').strip()
|
||||
if not normalized_dataset_id or not normalized_remote_document_id:
|
||||
return None
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDifySyncRecord.dataset_id == normalized_dataset_id,
|
||||
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not record or not record.document_version or not record.document_version.document:
|
||||
return None
|
||||
|
||||
version = record.document_version
|
||||
document = version.document
|
||||
|
||||
def _existing(path_value: str | None):
|
||||
if not path_value:
|
||||
return None
|
||||
raw = Path(str(path_value))
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
if candidate.exists() and candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
source_path = _existing(version.source_file_path)
|
||||
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
|
||||
if source_path is None and markdown_path is None:
|
||||
current_app.logger.info(
|
||||
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
|
||||
document.id,
|
||||
version.id,
|
||||
)
|
||||
return None
|
||||
|
||||
base_url = IntegrationApiService._request_origin_url()
|
||||
if not base_url:
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
if explicit:
|
||||
base_url = explicit
|
||||
elif has_http_request():
|
||||
base_url = host_url()
|
||||
else:
|
||||
base_url = ''
|
||||
|
||||
import time
|
||||
import jwt
|
||||
|
||||
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
if not secret:
|
||||
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
|
||||
payload = {
|
||||
'dataset_id': normalized_dataset_id,
|
||||
'remote_document_id': normalized_remote_document_id,
|
||||
'version_id': version.id,
|
||||
'exp': exp
|
||||
}
|
||||
token = jwt.encode(payload, secret, algorithm='HS256')
|
||||
|
||||
if source_path is not None:
|
||||
kind = 'source'
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
else:
|
||||
kind = 'md'
|
||||
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
|
||||
source_filename = f'{stem}.md'
|
||||
source_ext = 'md'
|
||||
|
||||
source_download_url = (
|
||||
f'{base_url}/api/integration/files/{document.id}/download'
|
||||
f'?kind={kind}&version_id={version.id}&token={token}'
|
||||
)
|
||||
|
||||
return {
|
||||
"source_download_url": source_download_url,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": None,
|
||||
"version_id": version.id,
|
||||
"document_id": document.id,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
cached = IntegrationApiService._cache.get(cache_key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
return cached
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
|
||||
url = f"{base_url}/api/integration/dify-file"
|
||||
headers = {"X-Integration-Key": api_key}
|
||||
params = {
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
if isinstance(payload, dict):
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
elif has_app_context():
|
||||
current_app.logger.info(
|
||||
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
resp.status_code,
|
||||
)
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
|
||||
batch_url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
batch_headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
batch_body = {
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
]
|
||||
}
|
||||
try:
|
||||
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
if key == cache_key:
|
||||
return normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
||||
|
||||
# Fallback to local database if remote integration API fails or misses
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[cache_key] = local_result
|
||||
return local_result
|
||||
|
||||
# 最终兜底:直接查 Dify 文档 API 并请求签名下载 URL。
|
||||
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
|
||||
if dify_result:
|
||||
IntegrationApiService._cache[cache_key] = dify_result
|
||||
return dify_result
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
||||
"""
|
||||
Batch resolve source files by (dataset_id, remote_document_id).
|
||||
Returns a mapping keyed by (dataset_id, remote_document_id).
|
||||
"""
|
||||
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
if not items:
|
||||
return results
|
||||
|
||||
unresolved: List[Dict[str, str]] = []
|
||||
seen = set()
|
||||
|
||||
for item in items:
|
||||
dataset_id = str(item.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(item.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
cached = IntegrationApiService._cache.get(key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
results[key] = cached
|
||||
else:
|
||||
unresolved.append({
|
||||
"dataset_id": dataset_id,
|
||||
"remote_document_id": remote_document_id,
|
||||
})
|
||||
|
||||
if not unresolved:
|
||||
return results
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return results
|
||||
|
||||
url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {"items": unresolved}
|
||||
|
||||
try:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Integration API batch lookup failed: status=%s", resp.status_code
|
||||
)
|
||||
else:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
||||
|
||||
# Fallback to single lookup or local DB for unresolved items
|
||||
for item in unresolved:
|
||||
dataset_id = item["dataset_id"]
|
||||
remote_document_id = item["remote_document_id"]
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in results:
|
||||
continue
|
||||
|
||||
# Check if single lookup was not called already (if it was, it might be cached)
|
||||
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[key] = local_result
|
||||
results[key] = local_result
|
||||
continue
|
||||
|
||||
# As a last resort, try remote single lookup if batch missed it
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if payload:
|
||||
results[key] = payload
|
||||
|
||||
return results
|
||||
@@ -1,8 +1,142 @@
|
||||
"""
|
||||
backend/app/services/integrations/minio.py
|
||||
|
||||
用途:MinIO 对象存储适配。
|
||||
用途:MinIO 对象存储适配(Agent 指南等文件上传/下载)。
|
||||
依赖:minio SDK、app.core.config.settings。
|
||||
逻辑:初始化客户端与 bucket;供 admin/agents、培训指南等模块读写对象。
|
||||
"""
|
||||
from app.services import minio_service # noqa: F401
|
||||
import os
|
||||
import uuid
|
||||
from typing import BinaryIO
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
from werkzeug.utils import secure_filename
|
||||
from app.core.config.settings import config, ACTIVE_ENV_NAME
|
||||
|
||||
__all__ = ['minio_service']
|
||||
cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
class MinioService:
|
||||
def __init__(self):
|
||||
self.client = Minio(
|
||||
cfg.MINIO_ENDPOINT,
|
||||
access_key=cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=cfg.MINIO_SECRET_KEY,
|
||||
secure=cfg.MINIO_SECURE,
|
||||
)
|
||||
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
|
||||
self._ensure_bucket_exists()
|
||||
|
||||
def _ensure_bucket_exists(self):
|
||||
try:
|
||||
if not self.client.bucket_exists(self.bucket_name):
|
||||
self.client.make_bucket(self.bucket_name)
|
||||
# Set bucket policy to public read
|
||||
policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": ["*"]},
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
import json
|
||||
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
|
||||
except Exception as e:
|
||||
# log or print error
|
||||
print(f"MinIO bucket error (or not reachable): {e}")
|
||||
|
||||
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
|
||||
"""
|
||||
Uploads a file to MinIO and returns the generated object name.
|
||||
"""
|
||||
# If MinIO is not running, we could fallback to local storage or raise clear error
|
||||
try:
|
||||
self._ensure_bucket_exists()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ext = os.path.splitext(filename)[1]
|
||||
unique_filename = f"{uuid.uuid4().hex}{ext}"
|
||||
|
||||
try:
|
||||
self.client.put_object(
|
||||
bucket_name=self.bucket_name,
|
||||
object_name=unique_filename,
|
||||
data=file_stream,
|
||||
length=file_size,
|
||||
content_type=content_type
|
||||
)
|
||||
except Exception as e:
|
||||
# For development, if minio is down, let's mock it so UI can continue
|
||||
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
|
||||
|
||||
# fallback to local storage
|
||||
os.makedirs('data/agent-guides', exist_ok=True)
|
||||
local_path = os.path.join('data/agent-guides', unique_filename)
|
||||
file_stream.seek(0)
|
||||
with open(local_path, 'wb') as f:
|
||||
f.write(file_stream.read())
|
||||
|
||||
return unique_filename
|
||||
|
||||
def get_public_url(self, object_name: str) -> str:
|
||||
"""
|
||||
返回同源的指南文件代理地址。
|
||||
|
||||
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
|
||||
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
|
||||
"""
|
||||
return f"/api/agents/guides/files/{object_name}"
|
||||
|
||||
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
|
||||
"""
|
||||
按指定字节范围打开 MinIO 指南对象流。
|
||||
|
||||
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
|
||||
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
|
||||
"""
|
||||
return self.client.get_object(
|
||||
self.bucket_name,
|
||||
object_name,
|
||||
offset=offset,
|
||||
length=length,
|
||||
)
|
||||
|
||||
def stat_file(self, object_name: str):
|
||||
"""
|
||||
获取 MinIO 指南对象元数据。
|
||||
|
||||
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
|
||||
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
|
||||
"""
|
||||
return self.client.stat_object(self.bucket_name, object_name)
|
||||
|
||||
def get_file_bytes(self, object_name: str) -> bytes:
|
||||
"""
|
||||
读取对象的原始字节内容。
|
||||
|
||||
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
|
||||
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
|
||||
"""
|
||||
local_path = os.path.join('data/agent-guides', object_name)
|
||||
if os.path.exists(local_path):
|
||||
with open(local_path, 'rb') as file_obj:
|
||||
return file_obj.read()
|
||||
|
||||
response = self.client.get_object(self.bucket_name, object_name)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
|
||||
def delete_file(self, object_name: str):
|
||||
try:
|
||||
self.client.remove_object(self.bucket_name, object_name)
|
||||
except S3Error as e:
|
||||
print(f"Error deleting file from MinIO: {e}")
|
||||
|
||||
minio_service = MinioService()
|
||||
@@ -1,2 +1,446 @@
|
||||
"""OA 请假 Workflow SOAP 适配(Wave 4 自 oa_leave_workflow.py 迁入)。"""
|
||||
from app.services import oa_leave_workflow # noqa: F401
|
||||
"""
|
||||
backend/app/services/integrations/oa/leave_workflow.py
|
||||
|
||||
用途:OA 请假流程 SOAP 适配(创建/查询请假单)。
|
||||
依赖:requests、SOAP XML、OA WorkflowService、integrations.oa.sqlserver。
|
||||
逻辑:由 HR 请假聊天意图或相关服务调用;组装 WorkflowRequestInfo 并提交 OA。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
|
||||
SOAP_ENV_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
|
||||
SERVICE_NS = 'webservices.services.weaver.com.cn'
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
|
||||
|
||||
NS = {
|
||||
'soapenv': SOAP_ENV_NS,
|
||||
'svc': SERVICE_NS,
|
||||
'wf': WORKFLOW_NS,
|
||||
'xsi': XSI_NS,
|
||||
}
|
||||
|
||||
ET.register_namespace('soapenv', SOAP_ENV_NS)
|
||||
ET.register_namespace('svc', SERVICE_NS)
|
||||
ET.register_namespace('wf', WORKFLOW_NS)
|
||||
ET.register_namespace('xsi', XSI_NS)
|
||||
|
||||
|
||||
class OALeaveWorkflowError(RuntimeError):
|
||||
"""Raised when OA leave workflow submission fails."""
|
||||
|
||||
|
||||
class OALeaveWorkflowService:
|
||||
WORKFLOW_ID = '879'
|
||||
|
||||
# Keep backend leave labels aligned with the chat form options so OA browser
|
||||
# fields always receive the expected showValue instead of a raw code.
|
||||
LEAVE_TYPE_LABELS = {
|
||||
'005': '事假(小时)',
|
||||
'006': '病假(小时)',
|
||||
'007': '丧假(天)',
|
||||
'010': '年假(天)',
|
||||
'021': '因公出差(小时)',
|
||||
'025': '调休假(小时)',
|
||||
'035': '其他假(小时)',
|
||||
'401': '产假(天)',
|
||||
'402': '陪产假(天)',
|
||||
'403': '婚假(天)',
|
||||
'405': '住院病假(小时)',
|
||||
'406': '工伤假(天)',
|
||||
'408': '育儿假(小时)',
|
||||
'ZZ01': '返乡假(小时)',
|
||||
'ZZ04': '事假(经理专用小时)',
|
||||
'ZZ05': '病假(经理专用小时)',
|
||||
'ZZ07': '丧假(经理专用天)',
|
||||
'ZZ08': '产假(经理专用天)',
|
||||
'ZZ09': '陪产假(经理专用天)',
|
||||
'ZZ10': '婚假(经理专用天)',
|
||||
}
|
||||
ERROR_MESSAGES = {
|
||||
'-1': '创建流程失败',
|
||||
'-2': '用户没有流程创建权限',
|
||||
'-3': '创建流程基本信息失败',
|
||||
'-4': '保存表单主表信息失败',
|
||||
'-5': '更新紧急程度失败',
|
||||
'-6': '流程操作者失败',
|
||||
'-7': '流转至下一节点失败',
|
||||
'-8': '节点附加操作失败',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_wsdl_url(cls) -> str:
|
||||
return (
|
||||
current_app.config.get('OA_WORKFLOW_WSDL_URL')
|
||||
or os.getenv('OA_WORKFLOW_WSDL_URL')
|
||||
or 'http://oa.well-trust.com:8888/services/WorkflowService?wsdl'
|
||||
).strip()
|
||||
|
||||
@classmethod
|
||||
def _get_service_url(cls) -> str:
|
||||
wsdl_url = cls._get_wsdl_url()
|
||||
return wsdl_url[:-5] if wsdl_url.lower().endswith('?wsdl') else wsdl_url
|
||||
|
||||
@classmethod
|
||||
def _request_timeout(cls) -> tuple[int, int]:
|
||||
return (5, 25)
|
||||
|
||||
@classmethod
|
||||
def _post_soap(cls, action: str, body_el: ET.Element) -> ET.Element:
|
||||
envelope = ET.Element(f'{{{SOAP_ENV_NS}}}Envelope')
|
||||
ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Header')
|
||||
body = ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Body')
|
||||
body.append(body_el)
|
||||
payload = ET.tostring(envelope, encoding='utf-8', xml_declaration=True)
|
||||
headers = {
|
||||
'Content-Type': 'text/xml; charset=utf-8',
|
||||
'SOAPAction': action,
|
||||
}
|
||||
max_retries = 3
|
||||
last_exc = None
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
response = requests.post(
|
||||
cls._get_service_url(),
|
||||
data=payload,
|
||||
headers=headers,
|
||||
timeout=cls._request_timeout(),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return ET.fromstring(response.text)
|
||||
except requests.RequestException as exc:
|
||||
last_exc = exc
|
||||
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
|
||||
retryable = status_code in (502, 503, 504) if status_code else True
|
||||
if retryable and attempt < max_retries:
|
||||
import time
|
||||
wait = attempt * 2
|
||||
current_app.logger.warning(
|
||||
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
|
||||
attempt, max_retries, status_code, wait, exc,
|
||||
)
|
||||
time.sleep(wait)
|
||||
continue
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
|
||||
except ET.ParseError as exc:
|
||||
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
|
||||
|
||||
@classmethod
|
||||
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
|
||||
|
||||
@classmethod
|
||||
def resolve_agent_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='代理人')
|
||||
|
||||
@classmethod
|
||||
def _resolve_runtime_oa_user(
|
||||
cls,
|
||||
employee_id: str | None,
|
||||
real_name: str | None = None,
|
||||
*,
|
||||
role_label: str,
|
||||
) -> dict[str, str]:
|
||||
employee_id = (employee_id or '').strip()
|
||||
real_name = (real_name or '').strip()
|
||||
if not employee_id:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}工号,无法匹配 OA 用户。')
|
||||
if not real_name:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}姓名,无法匹配 OA 用户。')
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
matched = OASQLServerService.get_employee_by_name_and_workcode(real_name, employee_id)
|
||||
except Exception as exc:
|
||||
raise OALeaveWorkflowError(f'查询{role_label} OA 用户失败:{exc}') from exc
|
||||
|
||||
if not matched:
|
||||
raise OALeaveWorkflowError(f'未找到{role_label} OA 用户:{real_name}({employee_id})。')
|
||||
|
||||
return {
|
||||
'employee_id': matched['employeeId'],
|
||||
'user_id': matched['uid'],
|
||||
'name': matched['name'],
|
||||
'jobtitle': matched.get('jobtitle', ''),
|
||||
'jobtitleName': matched.get('jobtitleName', ''),
|
||||
'departmentid': matched.get('departmentid', ''),
|
||||
'departmentName': matched.get('departmentName', ''),
|
||||
'subcompanyid1': matched.get('subcompanyid1', ''),
|
||||
'subcompanyName': matched.get('subcompanyName', ''),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _pick_browser_field_value(*values: Any) -> str:
|
||||
for value in values:
|
||||
text = ('' if value is None else str(value)).strip()
|
||||
if text:
|
||||
return text
|
||||
return ''
|
||||
|
||||
@classmethod
|
||||
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in0').text = str(workflow_id)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _get_template_request_info(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.getCreateWorkflowRequestInfo'
|
||||
root = cls._post_soap(action, cls._build_get_template_body(workflow_id, oa_user_id))
|
||||
out = root.find('.//svc:out', NS)
|
||||
if out is None or out.attrib.get(f'{{{XSI_NS}}}nil') == 'true' or len(list(out)) == 0:
|
||||
raise OALeaveWorkflowError('OA 未返回建单模板,请确认 workflowId 与 OA userid 是否正确。')
|
||||
return deepcopy(out)
|
||||
|
||||
@classmethod
|
||||
def _find_field(cls, request_info: ET.Element, field_name: str) -> ET.Element | None:
|
||||
for field in request_info.findall('.//wf:WorkflowRequestTableField', NS):
|
||||
if (field.findtext('wf:fieldName', default='', namespaces=NS) or '').strip() == field_name:
|
||||
return field
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _set_field(
|
||||
cls,
|
||||
request_info: ET.Element,
|
||||
field_name: str,
|
||||
*,
|
||||
value: str | None,
|
||||
show_value: str | None = None,
|
||||
) -> None:
|
||||
field = cls._find_field(request_info, field_name)
|
||||
if field is None:
|
||||
current_app.logger.warning('[oa-leave] field not found in template: %s', field_name)
|
||||
return
|
||||
value_node = field.find('wf:fieldValue', NS)
|
||||
if value_node is None:
|
||||
value_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue')
|
||||
value_node.text = '' if value is None else str(value)
|
||||
|
||||
if show_value is not None:
|
||||
show_node = field.find('wf:fieldShowValue', NS)
|
||||
if show_node is None:
|
||||
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
|
||||
show_node.text = str(show_value)
|
||||
|
||||
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
|
||||
if field_html_type == '3':
|
||||
filed_html_node = field.find('wf:filedHtmlShow', NS)
|
||||
if filed_html_node is not None:
|
||||
filed_html_node.text = str(show_value)
|
||||
|
||||
for tag in ['edit', 'view']:
|
||||
node = field.find(f'wf:{tag}', NS)
|
||||
if node is not None:
|
||||
node.text = 'true'
|
||||
else:
|
||||
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
|
||||
node.text = 'true'
|
||||
|
||||
@classmethod
|
||||
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
|
||||
node = parent.find(xpath, NS)
|
||||
if node is not None:
|
||||
node.text = value
|
||||
|
||||
@classmethod
|
||||
def _parse_frontend_datetime(cls, raw: str, field_name: str) -> datetime:
|
||||
text = (raw or '').strip().replace('T', ' ')
|
||||
try:
|
||||
return datetime.strptime(text, '%Y-%m-%d %H:%M')
|
||||
except ValueError as exc:
|
||||
raise OALeaveWorkflowError(f'{field_name} 格式不正确,应为 YYYY-MM-DD HH:MM。') from exc
|
||||
|
||||
@classmethod
|
||||
def _build_request_name(cls, creator_name: str, start_dt: datetime) -> str:
|
||||
return f'请假申请单-{creator_name}-{start_dt.strftime("%Y-%m-%d")}'
|
||||
|
||||
@classmethod
|
||||
def _normalize_duration(cls, value: Any) -> str:
|
||||
try:
|
||||
hours = float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OALeaveWorkflowError('请假时长格式不正确。') from exc
|
||||
if hours <= 0:
|
||||
raise OALeaveWorkflowError('请假时长必须大于 0。')
|
||||
return f'{hours:.2f}'.rstrip('0').rstrip('.')
|
||||
|
||||
@classmethod
|
||||
def build_request_info(cls, form_data: dict[str, Any], current_user: Any) -> tuple[ET.Element, dict[str, str], dict[str, str], dict[str, str]]:
|
||||
filler_name = (
|
||||
form_data.get('fillerName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
filler = cls._resolve_runtime_oa_user(
|
||||
getattr(current_user, 'employee_id', None),
|
||||
filler_name,
|
||||
role_label='填单人'
|
||||
)
|
||||
|
||||
applicant_name = (
|
||||
form_data.get('applicantName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
applicant = cls.resolve_creator_oa_user(
|
||||
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
|
||||
applicant_name,
|
||||
)
|
||||
agent = cls.resolve_agent_oa_user(form_data.get('agentEmployeeId'), form_data.get('agentName'))
|
||||
|
||||
workflow_id = str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID)
|
||||
request_info = cls._get_template_request_info(workflow_id, filler['user_id'])
|
||||
|
||||
start_dt = cls._parse_frontend_datetime(form_data.get('startTime'), '开始时间')
|
||||
end_dt = cls._parse_frontend_datetime(form_data.get('endTime'), '结束时间')
|
||||
if end_dt <= start_dt:
|
||||
raise OALeaveWorkflowError('结束时间必须晚于开始时间。')
|
||||
|
||||
leave_type_code = (form_data.get('leaveType') or '').strip()
|
||||
if not leave_type_code:
|
||||
raise OALeaveWorkflowError('缺少假别编码。')
|
||||
leave_type_label = cls.LEAVE_TYPE_LABELS.get(leave_type_code, leave_type_code)
|
||||
request_name = cls._build_request_name(applicant['name'], start_dt)
|
||||
|
||||
cls._set_text(request_info, 'wf:creatorId', filler['user_id'])
|
||||
cls._set_text(request_info, 'wf:creatorName', filler['name'])
|
||||
cls._set_text(request_info, 'wf:requestLevel', '0')
|
||||
cls._set_text(request_info, 'wf:requestName', request_name)
|
||||
cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id)
|
||||
|
||||
cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name)
|
||||
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'])
|
||||
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'])
|
||||
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
|
||||
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
|
||||
|
||||
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
|
||||
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
|
||||
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
|
||||
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
|
||||
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
|
||||
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
|
||||
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
|
||||
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
|
||||
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
|
||||
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
|
||||
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
|
||||
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
if filler_jobtitle and not filler_jobtitle_name:
|
||||
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
|
||||
if filler_department and not filler_department_name:
|
||||
filler_department_name = OASQLServerService.get_department_name(filler_department)
|
||||
if filler_subcompany and not filler_subcompany_name:
|
||||
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
|
||||
if applicant_jobtitle and not applicant_jobtitle_name:
|
||||
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
|
||||
if applicant_department and not applicant_department_name:
|
||||
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
|
||||
if applicant_subcompany and not applicant_subcompany_name:
|
||||
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
|
||||
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
|
||||
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
|
||||
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
|
||||
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
|
||||
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
|
||||
|
||||
current_app.logger.info(
|
||||
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
|
||||
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
|
||||
filler_department, filler_department_name or filler_department or '暂无',
|
||||
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
|
||||
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
|
||||
applicant_department, applicant_department_name or applicant_department or '暂无',
|
||||
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
|
||||
)
|
||||
|
||||
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'])
|
||||
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
|
||||
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
|
||||
cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label)
|
||||
cls._set_field(request_info, 'jbbh', value=leave_type_code, show_value=leave_type_code)
|
||||
cls._set_field(request_info, 'kssj', value=start_dt.strftime('%Y-%m-%d'), show_value=start_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'kssk', value=start_dt.strftime('%H:%M'), show_value=start_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'jssj', value=end_dt.strftime('%Y-%m-%d'), show_value=end_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'jssk', value=end_dt.strftime('%H:%M'), show_value=end_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'qjsc', value=cls._normalize_duration(form_data.get('durationHours')), show_value=cls._normalize_duration(form_data.get('durationHours')))
|
||||
cls._set_field(request_info, 'sfwgs', value=str(form_data.get('isWorkInjury')), show_value='是' if str(form_data.get('isWorkInjury')) == '0' else '否')
|
||||
cls._set_field(request_info, 'sfwc', value=str(form_data.get('isOutOfOffice')), show_value='是' if str(form_data.get('isOutOfOffice')) == '0' else '否')
|
||||
cls._set_field(request_info, 'bz', value=(form_data.get('remark') or '').strip(), show_value=(form_data.get('remark') or '').strip())
|
||||
|
||||
return request_info, filler, applicant, agent
|
||||
|
||||
@classmethod
|
||||
def _build_create_body(cls, request_info: ET.Element, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}doCreateWorkflowRequest')
|
||||
in0 = deepcopy(request_info)
|
||||
in0.tag = f'{{{SERVICE_NS}}}in0'
|
||||
root.append(in0)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _parse_create_response(cls, root: ET.Element) -> str:
|
||||
out = root.findtext('.//svc:out', default='', namespaces=NS)
|
||||
out = (out or '').strip()
|
||||
if not out:
|
||||
raise OALeaveWorkflowError('OA 未返回单据编号。')
|
||||
if out in cls.ERROR_MESSAGES:
|
||||
raise OALeaveWorkflowError(cls.ERROR_MESSAGES[out])
|
||||
if out.startswith('-'):
|
||||
raise OALeaveWorkflowError(f'OA 创建流程失败,返回码:{out}')
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def serialize_request_xml(cls, request_info: ET.Element) -> str:
|
||||
return ET.tostring(request_info, encoding='unicode')
|
||||
|
||||
@classmethod
|
||||
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
|
||||
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
|
||||
|
||||
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
|
||||
for fn in log_fields:
|
||||
f = cls._find_field(request_info, fn)
|
||||
if f is not None:
|
||||
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
|
||||
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
|
||||
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
|
||||
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
|
||||
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
|
||||
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
|
||||
request_id = cls._parse_create_response(root)
|
||||
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
|
||||
return {
|
||||
'ok': True,
|
||||
'request_id': request_id,
|
||||
'request_name': request_info.findtext('wf:requestName', default='', namespaces=NS),
|
||||
'submitted_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
|
||||
'creator': applicant,
|
||||
'filler': filler,
|
||||
'agent': agent,
|
||||
'workflow_id': str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID),
|
||||
'request_xml': cls.serialize_request_xml(request_info),
|
||||
}
|
||||
@@ -1,2 +1,258 @@
|
||||
"""OA SQL Server 适配(Wave 4 自 oa_sqlserver.py 迁入)。"""
|
||||
from app.services import oa_sqlserver # noqa: F401
|
||||
"""
|
||||
backend/app/services/integrations/oa/sqlserver.py
|
||||
|
||||
用途:封装 OA SQL Server 的员工检索与组织信息查询,供请假代理人/申请人选择等场景复用。
|
||||
依赖:pyodbc、OA ecology 视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
|
||||
逻辑:只读 SQL 查询返回 OA 用户与组织字段;对 OA 多语言包装串在服务层清洗为可展示中文。
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import pyodbc
|
||||
from flask import current_app
|
||||
|
||||
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
|
||||
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
|
||||
)
|
||||
|
||||
class OASQLServerService:
|
||||
@staticmethod
|
||||
def _normalize_oa_text(value) -> str:
|
||||
"""
|
||||
清洗 OA 多语言包装字段。
|
||||
|
||||
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
|
||||
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
|
||||
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
|
||||
|
||||
Args:
|
||||
value: 来自 OA SQL Server 的原始字段值。
|
||||
|
||||
Returns:
|
||||
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
|
||||
if not matched:
|
||||
return text
|
||||
simplified, english, traditional = (
|
||||
segment.strip().strip("`").strip()
|
||||
for segment in matched.groups()
|
||||
)
|
||||
return simplified or english or traditional or text
|
||||
|
||||
@staticmethod
|
||||
def _pick_driver():
|
||||
drivers = pyodbc.drivers()
|
||||
preferred = [
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
]
|
||||
for name in preferred:
|
||||
if name in drivers:
|
||||
return name
|
||||
if not drivers:
|
||||
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
|
||||
return drivers[-1]
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
|
||||
available_drivers = pyodbc.drivers()
|
||||
if driver not in available_drivers:
|
||||
driver = cls._pick_driver()
|
||||
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
|
||||
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
|
||||
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
|
||||
username = os.getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA").strip()
|
||||
password = os.getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA").strip()
|
||||
encrypt = os.getenv("OA_SQLSERVER_ENCRYPT", "no").strip().lower()
|
||||
trust_cert = os.getenv("OA_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
||||
timeout = int(os.getenv("OA_SQLSERVER_TIMEOUT", "10"))
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
)
|
||||
if driver != "SQL Server":
|
||||
conn_str += (
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
return pyodbc.connect(conn_str, timeout=timeout)
|
||||
|
||||
@classmethod
|
||||
def search_employees(cls, keyword: str, page: int, page_size: int):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
offset = (page - 1) * page_size
|
||||
params = []
|
||||
|
||||
# Count total
|
||||
count_sql = "SELECT COUNT(1) FROM userInfo_view WHERE 1=1"
|
||||
if keyword:
|
||||
count_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
like_kw = f"%{keyword}%"
|
||||
params.extend([like_kw, like_kw])
|
||||
|
||||
cursor.execute(count_sql, params)
|
||||
total = cursor.fetchone()[0]
|
||||
|
||||
# Fetch page
|
||||
# Compatible with older SQL Server versions (2008/2012)
|
||||
query_sql = """
|
||||
SELECT id, workcode, lastname, jobtitle, departmentid, subcompanyid1,
|
||||
departmentname, subcompanyname, jobtitlename
|
||||
FROM (
|
||||
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
||||
d.departmentname, s.subcompanyname, j.jobtitlename,
|
||||
ROW_NUMBER() OVER(ORDER BY v.id) as rn
|
||||
FROM userInfo_view v
|
||||
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
||||
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
||||
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
||||
WHERE 1=1
|
||||
"""
|
||||
if keyword:
|
||||
query_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
|
||||
query_sql += """
|
||||
) as T
|
||||
WHERE rn > ? AND rn <= ?
|
||||
"""
|
||||
|
||||
page_params = params + [offset, offset + page_size]
|
||||
cursor.execute(query_sql, page_params)
|
||||
|
||||
items = []
|
||||
for row in cursor.fetchall():
|
||||
items.append({
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": cls._normalize_oa_text(row.lastname),
|
||||
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": cls._normalize_oa_text(row.departmentname),
|
||||
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
||||
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
||||
})
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_employee_by_name_and_workcode(cls, real_name: str, employee_id: str):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
normalized_name = (real_name or "").strip()
|
||||
normalized_employee_id = (employee_id or "").strip()
|
||||
if not normalized_name or not normalized_employee_id:
|
||||
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
|
||||
|
||||
query_sql = """
|
||||
SELECT TOP 1 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
||||
d.departmentname, s.subcompanyname, j.jobtitlename
|
||||
FROM userInfo_view v
|
||||
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
||||
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
||||
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
||||
WHERE v.workcode = ? AND v.lastname = ?
|
||||
ORDER BY v.id
|
||||
"""
|
||||
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
return {
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": cls._normalize_oa_text(row.lastname),
|
||||
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": cls._normalize_oa_text(row.departmentname),
|
||||
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
||||
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_department_name(cls, department_id: str) -> str:
|
||||
if not department_id or not department_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
|
||||
[department_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_subcompany_name(cls, subcompany_id: str) -> str:
|
||||
if not subcompany_id or not subcompany_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
|
||||
[subcompany_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
|
||||
if not jobtitle_id or not jobtitle_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
|
||||
[jobtitle_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -1,2 +1,473 @@
|
||||
"""OA 与企微同步适配(Wave 4 自 oa_wecom_sync.py 迁入)。"""
|
||||
from app.services import oa_wecom_sync # noqa: F401
|
||||
"""
|
||||
backend/app/services/integrations/oa/wecom_sync.py
|
||||
|
||||
用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。
|
||||
依赖:OASQLServerService、SQLAlchemy db、User 模型。
|
||||
逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。
|
||||
"""
|
||||
|
||||
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
|
||||
from app import db
|
||||
|
||||
from app.models import User
|
||||
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
|
||||
|
||||
|
||||
_PREVIEW_LIMIT = 20
|
||||
|
||||
_OA_VIEW = 'userInfo_view'
|
||||
|
||||
_OA_IN_BATCH_SIZE = 500
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _clean_str(value) -> str | None:
|
||||
|
||||
"""
|
||||
|
||||
规范化字符串;空值返回 None。
|
||||
|
||||
@param value: 任意输入
|
||||
|
||||
Returns:
|
||||
|
||||
去首尾空白后的字符串,或 None
|
||||
|
||||
"""
|
||||
|
||||
if value is None:
|
||||
|
||||
return None
|
||||
|
||||
text = str(value).strip()
|
||||
|
||||
return text or None
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def _load_local_users_with_employee_id() -> list[tuple[User, str]]:
|
||||
|
||||
"""
|
||||
|
||||
加载本地含有效工号的用户列表。
|
||||
|
||||
核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。
|
||||
|
||||
Returns:
|
||||
|
||||
(User, employee_id) 元组列表
|
||||
|
||||
"""
|
||||
|
||||
rows: list[tuple[User, str]] = []
|
||||
|
||||
for user in db.session.query(User).filter(User.employee_id.isnot(None)).all():
|
||||
|
||||
employee_id = _clean_str(user.employee_id)
|
||||
|
||||
if not employee_id:
|
||||
|
||||
continue
|
||||
|
||||
rows.append((user, employee_id))
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]:
|
||||
|
||||
"""
|
||||
|
||||
按工号批量查询 OA userInfo_view 中的企微 userid 映射。
|
||||
|
||||
核心逻辑:工号去重后分批 IN 查询,避免全表扫描。
|
||||
|
||||
@param workcodes: 本地 users.employee_id 列表
|
||||
|
||||
Returns:
|
||||
|
||||
每项含 workcode、wecom_userid、name
|
||||
|
||||
Raises:
|
||||
|
||||
RuntimeError: ODBC 连接或查询失败
|
||||
|
||||
"""
|
||||
|
||||
unique_codes: list[str] = []
|
||||
|
||||
seen: set[str] = set()
|
||||
|
||||
for code in workcodes:
|
||||
|
||||
cleaned = _clean_str(code)
|
||||
|
||||
if not cleaned or cleaned in seen:
|
||||
|
||||
continue
|
||||
|
||||
seen.add(cleaned)
|
||||
|
||||
unique_codes.append(cleaned)
|
||||
|
||||
|
||||
|
||||
if not unique_codes:
|
||||
|
||||
return []
|
||||
|
||||
|
||||
|
||||
connection = OASQLServerService._connect()
|
||||
|
||||
cursor = connection.cursor()
|
||||
|
||||
rows: list[dict[str, str | None]] = []
|
||||
|
||||
try:
|
||||
|
||||
for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE):
|
||||
|
||||
batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE]
|
||||
|
||||
placeholders = ','.join('?' for _ in batch)
|
||||
|
||||
cursor.execute(
|
||||
|
||||
f"""
|
||||
|
||||
SELECT id, workcode, lastname
|
||||
|
||||
FROM userInfo_view
|
||||
|
||||
WHERE workcode IN ({placeholders})
|
||||
|
||||
AND id IS NOT NULL
|
||||
|
||||
""",
|
||||
|
||||
batch,
|
||||
|
||||
)
|
||||
|
||||
for row in cursor.fetchall():
|
||||
|
||||
workcode = _clean_str(row.workcode)
|
||||
|
||||
wecom_userid = _clean_str(row.id)
|
||||
|
||||
if not workcode or not wecom_userid:
|
||||
|
||||
continue
|
||||
|
||||
rows.append(
|
||||
|
||||
{
|
||||
|
||||
'workcode': workcode,
|
||||
|
||||
'wecom_userid': wecom_userid,
|
||||
|
||||
'name': _clean_str(row.lastname),
|
||||
|
||||
}
|
||||
|
||||
)
|
||||
|
||||
return rows
|
||||
|
||||
finally:
|
||||
|
||||
try:
|
||||
|
||||
cursor.close()
|
||||
|
||||
finally:
|
||||
|
||||
connection.close()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]:
|
||||
|
||||
"""
|
||||
|
||||
执行 OA 工号 → wecom_userid 同步(本地用户驱动)。
|
||||
|
||||
核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。
|
||||
|
||||
@param apply: True 时提交数据库;存在 conflicts 时不写入
|
||||
|
||||
Returns:
|
||||
|
||||
统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用)
|
||||
|
||||
Raises:
|
||||
|
||||
RuntimeError: OA 未配置、连接失败或 apply 时存在冲突
|
||||
|
||||
"""
|
||||
|
||||
local_users = _load_local_users_with_employee_id()
|
||||
|
||||
workcodes = [employee_id for _, employee_id in local_users]
|
||||
|
||||
oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes)
|
||||
|
||||
|
||||
|
||||
summary: dict[str, Any] = {
|
||||
|
||||
'apply': apply,
|
||||
|
||||
'employee_id_source': f'oa:{_OA_VIEW}.workcode',
|
||||
|
||||
'department_ids': [],
|
||||
|
||||
'local_candidates': len(local_users),
|
||||
|
||||
'wecom_users': 0,
|
||||
|
||||
'wecom_without_employee_id': 0,
|
||||
|
||||
'local_matched': 0,
|
||||
|
||||
'would_update': 0,
|
||||
|
||||
'updated': 0,
|
||||
|
||||
'already_bound': 0,
|
||||
|
||||
'local_missing': 0,
|
||||
|
||||
'conflicts': [],
|
||||
|
||||
'missing_samples': [],
|
||||
|
||||
'pending_updates': [],
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
oa_by_workcode: dict[str, dict[str, str | None]] = {}
|
||||
|
||||
duplicate_workcodes: set[str] = set()
|
||||
|
||||
for row in oa_rows:
|
||||
|
||||
workcode = row['workcode']
|
||||
|
||||
if not workcode:
|
||||
|
||||
continue
|
||||
|
||||
if workcode in oa_by_workcode:
|
||||
|
||||
duplicate_workcodes.add(workcode)
|
||||
|
||||
summary['conflicts'].append(
|
||||
|
||||
{
|
||||
|
||||
'employee_id': workcode,
|
||||
|
||||
'username': '',
|
||||
|
||||
'new_wecom_userid': row['wecom_userid'],
|
||||
|
||||
'reason': 'duplicate_workcode_in_oa',
|
||||
|
||||
}
|
||||
|
||||
)
|
||||
|
||||
continue
|
||||
|
||||
oa_by_workcode[workcode] = row
|
||||
|
||||
|
||||
|
||||
summary['wecom_users'] = len(oa_by_workcode)
|
||||
|
||||
|
||||
|
||||
for local_user, employee_id in local_users:
|
||||
|
||||
if employee_id in duplicate_workcodes:
|
||||
|
||||
continue
|
||||
|
||||
|
||||
|
||||
oa_row = oa_by_workcode.get(employee_id)
|
||||
|
||||
if not oa_row:
|
||||
|
||||
summary['local_missing'] += 1
|
||||
|
||||
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
|
||||
|
||||
summary['missing_samples'].append(
|
||||
|
||||
{
|
||||
|
||||
'employee_id': employee_id,
|
||||
|
||||
'username': local_user.username,
|
||||
|
||||
}
|
||||
|
||||
)
|
||||
|
||||
continue
|
||||
|
||||
|
||||
|
||||
wecom_userid = oa_row['wecom_userid']
|
||||
|
||||
name = oa_row.get('name')
|
||||
|
||||
if not wecom_userid:
|
||||
|
||||
summary['wecom_without_employee_id'] += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
|
||||
summary['local_matched'] += 1
|
||||
|
||||
|
||||
|
||||
if local_user.wecom_userid == wecom_userid:
|
||||
|
||||
summary['already_bound'] += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
|
||||
conflict = None
|
||||
|
||||
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
|
||||
|
||||
conflict = {
|
||||
|
||||
'employee_id': employee_id,
|
||||
|
||||
'username': local_user.username,
|
||||
|
||||
'old_wecom_userid': local_user.wecom_userid,
|
||||
|
||||
'new_wecom_userid': wecom_userid,
|
||||
|
||||
}
|
||||
|
||||
else:
|
||||
|
||||
occupied = (
|
||||
|
||||
db.session.query(User)
|
||||
|
||||
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
|
||||
|
||||
.first()
|
||||
|
||||
)
|
||||
|
||||
if occupied:
|
||||
|
||||
conflict = {
|
||||
|
||||
'employee_id': employee_id,
|
||||
|
||||
'username': local_user.username,
|
||||
|
||||
'new_wecom_userid': wecom_userid,
|
||||
|
||||
'occupied_by_user_id': occupied.id,
|
||||
|
||||
'occupied_by_username': occupied.username,
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
if conflict:
|
||||
|
||||
summary['conflicts'].append(conflict)
|
||||
|
||||
continue
|
||||
|
||||
|
||||
|
||||
summary['would_update'] += 1
|
||||
|
||||
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
|
||||
|
||||
summary['pending_updates'].append(
|
||||
|
||||
{
|
||||
|
||||
'employee_id': employee_id,
|
||||
|
||||
'username': local_user.username,
|
||||
|
||||
'wecom_userid': wecom_userid,
|
||||
|
||||
'name': name,
|
||||
|
||||
}
|
||||
|
||||
)
|
||||
|
||||
if apply:
|
||||
|
||||
local_user.wecom_userid = wecom_userid
|
||||
|
||||
summary['updated'] += 1
|
||||
|
||||
|
||||
|
||||
if summary['conflicts'] and apply:
|
||||
|
||||
db.session.rollback()
|
||||
|
||||
raise RuntimeError('Conflicts detected; resolve manually before apply')
|
||||
|
||||
|
||||
|
||||
if apply and summary['updated'] > 0:
|
||||
|
||||
db.session.commit()
|
||||
|
||||
elif apply:
|
||||
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
|
||||
return summary
|
||||
|
||||
|
||||
@@ -1,2 +1,381 @@
|
||||
"""PLM Oracle 流式查询适配(Wave 4 自 plm_oracle.py 迁入)。"""
|
||||
from app.services import plm_oracle # noqa: F401
|
||||
"""
|
||||
backend/app/services/integrations/plm/oracle.py
|
||||
|
||||
用途:PLM Oracle 物料/SOP 查询与流式聊天快路径。
|
||||
依赖:Flask current_app、Text2SQLService、ChatLog 模型。
|
||||
逻辑:聊天意图路由命中 PLM 时调用;查询 Oracle 并格式化为 SSE 结果。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from html import escape
|
||||
from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ChatLog
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
|
||||
|
||||
class PLMOracleService:
|
||||
_MAX_RESULT_ROWS = 50
|
||||
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
|
||||
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
|
||||
_EXPLICIT_LABEL_PATTERN = re.compile(
|
||||
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_RELATIONAL_SQL = """
|
||||
select *
|
||||
from bi_file endb
|
||||
where endb.revisionguid in (
|
||||
select bb.revisionguid
|
||||
from (
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v,
|
||||
StructureObject_0 str,
|
||||
document_0 doc,
|
||||
bi_file b
|
||||
where v.name in ('RelatedDoc')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = doc.masterfk
|
||||
and doc.latestrevision like '%m%'
|
||||
and b.revisionguid = doc.guid
|
||||
) bb,
|
||||
item_0 i
|
||||
where bb.end1 = i.guid
|
||||
and i.id = :item_id
|
||||
and i.latestrevision like '%m%'
|
||||
)
|
||||
and endb.lastaccesstime is not null
|
||||
"""
|
||||
_FILENAME_SQL = """
|
||||
select *
|
||||
from bi_file
|
||||
where upper(name) like :name_pattern
|
||||
and lastaccesstime is not null
|
||||
order by lastaccesstime desc nulls last
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def supports(cls, query: str, agent) -> bool:
|
||||
_ = agent
|
||||
return bool(cls.extract_material_no(query))
|
||||
|
||||
@classmethod
|
||||
def extract_material_no(cls, query: str) -> str | None:
|
||||
text = str(query or "").strip().upper()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
|
||||
if explicit:
|
||||
return explicit.group(1).strip().upper()
|
||||
|
||||
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
|
||||
if direct_match:
|
||||
return direct_match.group(0).upper()
|
||||
|
||||
for match in cls._MATERIAL_PATTERN.finditer(text):
|
||||
candidate = match.group(0).upper()
|
||||
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _get_connect_kwargs() -> dict:
|
||||
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
|
||||
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
|
||||
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
|
||||
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
|
||||
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
|
||||
|
||||
kwargs = {
|
||||
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
|
||||
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
|
||||
}
|
||||
if dsn:
|
||||
kwargs["dsn"] = dsn
|
||||
return kwargs
|
||||
|
||||
import oracledb
|
||||
|
||||
if service_name:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
|
||||
else:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
|
||||
return kwargs
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
|
||||
|
||||
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
|
||||
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
return oracledb.connect(**cls._get_connect_kwargs())
|
||||
|
||||
@classmethod
|
||||
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(sql, params)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
|
||||
return columns, rows
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
|
||||
try:
|
||||
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
|
||||
if rows:
|
||||
return columns, rows, "relational"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
|
||||
|
||||
columns, rows = cls._execute_query(
|
||||
cls._FILENAME_SQL,
|
||||
name_pattern=f"{material_no.upper()}%",
|
||||
)
|
||||
return columns, rows, "filename_fallback"
|
||||
|
||||
@staticmethod
|
||||
def _format_datetime(value) -> str:
|
||||
if value is None:
|
||||
return "-"
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(value)
|
||||
|
||||
@staticmethod
|
||||
def _format_size(value) -> str:
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
try:
|
||||
size = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return str(value)
|
||||
if size < 1024:
|
||||
return f"{size} B"
|
||||
if size < 1024 * 1024:
|
||||
return f"{size / 1024:.1f} KB"
|
||||
return f"{size / 1024 / 1024:.2f} MB"
|
||||
|
||||
@classmethod
|
||||
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
|
||||
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
|
||||
for value in (storage_id, file_path, file_id):
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
parts.append(text.replace("/", "\\").strip("\\"))
|
||||
return "\\".join(part for part in parts if part)
|
||||
|
||||
@classmethod
|
||||
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
|
||||
def raw(column_name: str):
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return None
|
||||
value = row[idx]
|
||||
return None if value in (None, "") else value
|
||||
|
||||
file_name = str(raw("NAME") or "").strip()
|
||||
if not file_name:
|
||||
return "-"
|
||||
|
||||
storage_id = raw("STORAGEID")
|
||||
file_path = raw("FILEPATH")
|
||||
file_id = str(raw("ID") or "").strip()
|
||||
if not storage_id or file_path is None or not file_id:
|
||||
return escape(file_name)
|
||||
|
||||
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
|
||||
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
|
||||
return f'<a href="{preview_href}">{escape(file_name)}</a>'
|
||||
|
||||
@staticmethod
|
||||
def _escape_markdown_cell(value: str) -> str:
|
||||
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@staticmethod
|
||||
def _escape_html_text(value) -> str:
|
||||
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@classmethod
|
||||
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return "-"
|
||||
value = row[idx]
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
upper_name = column_name.upper()
|
||||
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if upper_name == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
if upper_name == "NAME":
|
||||
return cls._render_file_name(row, index_map)
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
|
||||
parts = [f"记录 {row_no}"]
|
||||
for column_name in cls._SUMMARY_COLUMNS:
|
||||
if column_name.upper() not in index_map:
|
||||
continue
|
||||
rendered = cls._render_column_value(row, column_name, index_map)
|
||||
label = {
|
||||
"NAME": "文件名",
|
||||
"EXTENTIONNAME": "扩展名",
|
||||
"FILETYPE": "文件类型",
|
||||
"FILESIZE": "文件大小",
|
||||
"RELATIVEPATH": "相对路径",
|
||||
"LASTACCESSTIME": "最后访问时间",
|
||||
}.get(column_name.upper(), column_name)
|
||||
if column_name.upper() == "NAME":
|
||||
parts.append(f"{label}: {rendered}")
|
||||
else:
|
||||
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
|
||||
return " | ".join(parts)
|
||||
|
||||
@classmethod
|
||||
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
|
||||
rows_html = []
|
||||
for column_name in columns:
|
||||
rendered_value = cls._render_column_value(row, column_name, index_map)
|
||||
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
|
||||
rows_html.append(
|
||||
"<tr>"
|
||||
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
|
||||
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
|
||||
summary_html = cls._build_record_summary(row, index_map, row_no)
|
||||
return (
|
||||
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
|
||||
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
|
||||
"<div style=\"margin-top:10px;overflow:auto;\">"
|
||||
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
|
||||
"<thead><tr>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
|
||||
"</tr></thead>"
|
||||
f"<tbody>{''.join(rows_html)}</tbody>"
|
||||
"</table>"
|
||||
"</div>"
|
||||
"</details>"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
|
||||
if not rows:
|
||||
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
|
||||
|
||||
overflow = len(rows) > cls._MAX_RESULT_ROWS
|
||||
visible_rows = rows[: cls._MAX_RESULT_ROWS]
|
||||
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
|
||||
|
||||
lines = [
|
||||
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
|
||||
+ ("(仅展示前 50 条)" if overflow else "。"),
|
||||
"",
|
||||
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
|
||||
]
|
||||
for idx, row in enumerate(visible_rows, start=1):
|
||||
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
|
||||
|
||||
if overflow:
|
||||
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
|
||||
return "\n".join(lines)
|
||||
|
||||
@classmethod
|
||||
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
|
||||
material_no = cls.extract_material_no(query)
|
||||
|
||||
try:
|
||||
if not material_no:
|
||||
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
columns, rows, query_mode = cls._query_files(material_no)
|
||||
answer = cls._build_answer(material_no, columns, rows)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=answer,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
payload={
|
||||
"material_no": material_no,
|
||||
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
|
||||
"query_mode": query_mode,
|
||||
},
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.error("Failed to log PLM chat: %s", exc)
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
"event": "message_end",
|
||||
"answer": answer,
|
||||
"replace_answer": True,
|
||||
"chat_log_id": chat_log_id,
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception("[plm-oracle] stream_chat failed query=%s", query)
|
||||
error_data = {
|
||||
"event": "error",
|
||||
"message": str(exc) or "PLM 查询失败",
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,2 +1,97 @@
|
||||
"""企微回调加解密(Wave 4 自 wecom_crypto.py 迁入)。"""
|
||||
from app.services import wecom_crypto # noqa: F401
|
||||
"""
|
||||
backend/app/services/integrations/wecom/crypto.py
|
||||
|
||||
用途:企业微信回调加解密工具(兼容 WXBizMsgCrypt 布局)。
|
||||
依赖:pycryptodome AES。
|
||||
逻辑:user/auth 企微回调验签、解密 Encrypt 字段时调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import random
|
||||
import struct
|
||||
from typing import Optional
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
|
||||
def sha1_hex(parts: list[str]) -> str:
|
||||
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
|
||||
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
|
||||
pad_len = block_size - (len(data) % block_size)
|
||||
return data + bytes([pad_len] * pad_len)
|
||||
|
||||
|
||||
def _pkcs7_unpad(data: bytes) -> bytes:
|
||||
if not data:
|
||||
return data
|
||||
pad_len = data[-1]
|
||||
if pad_len < 1 or pad_len > 32:
|
||||
raise ValueError('invalid pkcs7 padding')
|
||||
if data[-pad_len:] != bytes([pad_len] * pad_len):
|
||||
raise ValueError('invalid pkcs7 padding tail')
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
|
||||
raw = (encoding_aes_key_b64 or '').strip()
|
||||
key = base64.b64decode(raw + '=')
|
||||
if len(key) != 32:
|
||||
raise ValueError('EncodingAESKey must decode to 32 bytes')
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
"""
|
||||
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
|
||||
"""
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
|
||||
msg_bytes = plain_text.encode('utf-8')
|
||||
pack = (
|
||||
random_bytes
|
||||
+ struct.pack('>I', len(msg_bytes))
|
||||
+ msg_bytes
|
||||
+ corp_id.encode('utf-8')
|
||||
)
|
||||
padded = _pkcs7_pad(pack, 32)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
encrypted = cipher.encrypt(padded)
|
||||
return base64.b64encode(encrypted).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
cipher_bytes = base64.b64decode(cipher_b64)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
plain_padded = cipher.decrypt(cipher_bytes)
|
||||
plain = _pkcs7_unpad(plain_padded)
|
||||
content = plain[16:]
|
||||
if len(content) < 4:
|
||||
raise ValueError('decrypted payload too short')
|
||||
xml_len = struct.unpack('>I', content[:4])[0]
|
||||
xml_bytes = content[4:4 + xml_len]
|
||||
tail = content[4 + xml_len:]
|
||||
if tail.decode('utf-8', errors='strict') != corp_id:
|
||||
raise ValueError('corp_id mismatch after decrypt')
|
||||
return xml_bytes.decode('utf-8')
|
||||
|
||||
|
||||
def extract_encrypt_field(xml_body: str) -> Optional[str]:
|
||||
if not xml_body:
|
||||
return None
|
||||
import re
|
||||
|
||||
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
|
||||
if m2:
|
||||
return m2.group(1).strip()
|
||||
return None
|
||||
@@ -1,2 +1,244 @@
|
||||
"""企微通讯录同步(Wave 4 自 wecom_directory_sync.py 迁入)。"""
|
||||
from app.services import wecom_directory_sync # noqa: F401
|
||||
"""
|
||||
backend/app/services/integrations/wecom/directory_sync.py
|
||||
|
||||
用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。
|
||||
依赖:Flask current_app、SQLAlchemy db、wecom.notify._get_access_token、User 模型。
|
||||
逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.integrations.wecom.notify import _get_access_token
|
||||
|
||||
_PREVIEW_LIMIT = 20
|
||||
|
||||
|
||||
def _clean_str(value) -> str | None:
|
||||
"""裁剪字符串类取值;空串视为 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None:
|
||||
"""
|
||||
从企微成员 extattr.attrs 中读取指定扩展字段。
|
||||
@param wecom_user: user/list 返回的成员 dict
|
||||
@param key: 扩展属性名
|
||||
Returns:
|
||||
字段文本或 None
|
||||
"""
|
||||
extattr = wecom_user.get('extattr') or {}
|
||||
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
|
||||
if not isinstance(attrs, list):
|
||||
return None
|
||||
for attr in attrs:
|
||||
if not isinstance(attr, dict):
|
||||
continue
|
||||
if _clean_str(attr.get('name')) != key:
|
||||
continue
|
||||
raw = attr.get('value')
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
||||
return _clean_str(raw)
|
||||
return None
|
||||
|
||||
|
||||
def extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None:
|
||||
"""
|
||||
按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。
|
||||
核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。
|
||||
"""
|
||||
userid = _clean_str(wecom_user.get('userid'))
|
||||
source = _clean_str(employee_id_source) or 'userid'
|
||||
if source == 'userid':
|
||||
return userid
|
||||
if source.startswith('extattr:'):
|
||||
return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1])
|
||||
return _clean_str(wecom_user.get(source))
|
||||
|
||||
|
||||
def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取企业微信部门列表。
|
||||
Raises:
|
||||
RuntimeError: API 失败
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/department/list',
|
||||
params={'access_token': access_token},
|
||||
timeout=15,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'department/list failed: {data}')
|
||||
departments = data.get('department') or []
|
||||
if not isinstance(departments, list):
|
||||
return []
|
||||
return [item for item in departments if isinstance(item, dict)]
|
||||
|
||||
|
||||
def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取指定部门(含子部门)成员简要列表。
|
||||
@param department_id: 企微部门 ID
|
||||
Returns:
|
||||
user/list 返回的 userlist
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/list',
|
||||
params={
|
||||
'access_token': access_token,
|
||||
'department_id': department_id,
|
||||
'fetch_child': 1,
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'user/list failed department_id={department_id}: {data}')
|
||||
userlist = data.get('userlist') or []
|
||||
if not isinstance(userlist, list):
|
||||
return []
|
||||
return [item for item in userlist if isinstance(item, dict)]
|
||||
|
||||
|
||||
def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
汇总多个部门成员,按 wecom_userid 去重。
|
||||
Returns:
|
||||
key=userid, value=成员 dict
|
||||
"""
|
||||
merged: dict[str, dict[str, Any]] = {}
|
||||
for dept_id in department_ids:
|
||||
for user in fetch_wecom_users_in_department(access_token, dept_id):
|
||||
userid = _clean_str(user.get('userid'))
|
||||
if userid:
|
||||
merged[userid] = user
|
||||
return merged
|
||||
|
||||
|
||||
def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
执行工号 → wecom_userid 同步。
|
||||
核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。
|
||||
@param apply: True 时提交数据库;存在 conflicts 时不写入
|
||||
@param department_id: 指定根部门 ID;None 时使用全部部门
|
||||
Returns:
|
||||
统计摘要 dict(含 conflicts、pending_updates 预览)
|
||||
"""
|
||||
if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'):
|
||||
raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured')
|
||||
|
||||
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
token = _get_access_token()
|
||||
|
||||
if department_id is not None:
|
||||
department_ids = [department_id]
|
||||
else:
|
||||
departments = fetch_wecom_departments(token)
|
||||
department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None]
|
||||
if not department_ids:
|
||||
department_ids = [1]
|
||||
|
||||
wecom_users = collect_wecom_users(token, department_ids)
|
||||
summary: dict[str, Any] = {
|
||||
'apply': apply,
|
||||
'employee_id_source': employee_id_source,
|
||||
'department_ids': department_ids,
|
||||
'wecom_users': len(wecom_users),
|
||||
'wecom_without_employee_id': 0,
|
||||
'local_matched': 0,
|
||||
'would_update': 0,
|
||||
'updated': 0,
|
||||
'already_bound': 0,
|
||||
'local_missing': 0,
|
||||
'conflicts': [],
|
||||
'missing_samples': [],
|
||||
'pending_updates': [],
|
||||
}
|
||||
|
||||
for wecom_user in wecom_users.values():
|
||||
wecom_userid = _clean_str(wecom_user.get('userid'))
|
||||
wecom_unionid = _clean_str(wecom_user.get('unionid'))
|
||||
employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source)
|
||||
if not employee_id:
|
||||
summary['wecom_without_employee_id'] += 1
|
||||
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
|
||||
summary['missing_samples'].append(
|
||||
{'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))}
|
||||
)
|
||||
continue
|
||||
|
||||
local_user = db.session.query(User).filter(User.employee_id == employee_id).first()
|
||||
if not local_user:
|
||||
summary['local_missing'] += 1
|
||||
continue
|
||||
|
||||
summary['local_matched'] += 1
|
||||
|
||||
if local_user.wecom_userid == wecom_userid:
|
||||
summary['already_bound'] += 1
|
||||
continue
|
||||
|
||||
conflict = None
|
||||
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'old_wecom_userid': local_user.wecom_userid,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
}
|
||||
else:
|
||||
occupied = (
|
||||
db.session.query(User)
|
||||
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
|
||||
.first()
|
||||
)
|
||||
if occupied:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
'occupied_by_user_id': occupied.id,
|
||||
'occupied_by_username': occupied.username,
|
||||
}
|
||||
|
||||
if conflict:
|
||||
summary['conflicts'].append(conflict)
|
||||
continue
|
||||
|
||||
summary['would_update'] += 1
|
||||
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
|
||||
summary['pending_updates'].append(
|
||||
{
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'wecom_userid': wecom_userid,
|
||||
'name': _clean_str(wecom_user.get('name')),
|
||||
}
|
||||
)
|
||||
if apply:
|
||||
local_user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
local_user.wecom_unionid = wecom_unionid
|
||||
summary['updated'] += 1
|
||||
|
||||
if summary['conflicts'] and apply:
|
||||
db.session.rollback()
|
||||
raise RuntimeError('Conflicts detected; resolve manually before apply')
|
||||
|
||||
if apply and summary['updated'] > 0:
|
||||
db.session.commit()
|
||||
elif apply:
|
||||
db.session.rollback()
|
||||
|
||||
return summary
|
||||
@@ -1,2 +1,264 @@
|
||||
"""企微消息通知(Wave 4 自 wecom_notify.py 迁入)。"""
|
||||
from app.services import wecom_notify # noqa: F401
|
||||
"""
|
||||
backend/app/services/integrations/wecom/notify.py
|
||||
|
||||
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
||||
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
||||
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from io import BytesIO
|
||||
from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User, WecomNotifyAudit
|
||||
|
||||
|
||||
_TOKEN_CACHE = {
|
||||
'token': None,
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
if isinstance(raw, str):
|
||||
return {x.strip() for x in raw.split(',') if x.strip()}
|
||||
if isinstance(raw, (list, tuple, set)):
|
||||
return {str(x).strip() for x in raw if str(x).strip()}
|
||||
return set()
|
||||
|
||||
|
||||
def _get_notify_base_url() -> str:
|
||||
"""
|
||||
解析企微 textcard 跳转基地址(用户点击入口,须为浏览器可访问的 HTTPS 公网域名)。
|
||||
核心逻辑:优先 WECOM_PUBLIC_BASE_URL,其次 HXOPS_PUBLIC_BASE_URL;
|
||||
WECOM_NOTIFY_BASE_URL 仅作历史内网/端口兼容兜底。
|
||||
Returns:
|
||||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||||
"""
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'HXOPS_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
raw = current_app.config.get(key)
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
return raw.strip().rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||||
base = _get_notify_base_url()
|
||||
if not base:
|
||||
return ''
|
||||
base = base.rstrip('/')
|
||||
if not path.startswith('/'):
|
||||
path = f'/{path}'
|
||||
merged = {'wecom_trace': trace_id}
|
||||
if params:
|
||||
merged.update({k: v for k, v in params.items() if v is not None})
|
||||
return f'{base}{path}?{urlencode(merged)}'
|
||||
|
||||
|
||||
def _get_access_token() -> str:
|
||||
now = datetime.utcnow()
|
||||
token = _TOKEN_CACHE.get('token')
|
||||
expires_at = _TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and now < expires_at:
|
||||
return token
|
||||
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
|
||||
params={'corpid': corp_id, 'corpsecret': secret},
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
|
||||
|
||||
_TOKEN_CACHE['token'] = data['access_token']
|
||||
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
|
||||
|
||||
def _create_audit(
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
trace_id: str,
|
||||
) -> WecomNotifyAudit:
|
||||
audit = WecomNotifyAudit(
|
||||
event_type=event_type,
|
||||
status='failed',
|
||||
trace_id=trace_id,
|
||||
user_id=user.id if user else None,
|
||||
username=user.username if user else None,
|
||||
wecom_userid=user.wecom_userid if user else None,
|
||||
title=title,
|
||||
content=content,
|
||||
)
|
||||
db.session.add(audit)
|
||||
return audit
|
||||
|
||||
|
||||
def upload_wecom_temp_media(file_data: bytes, filename: str) -> str:
|
||||
token = _get_access_token()
|
||||
url = (
|
||||
f'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
|
||||
f'?access_token={token}&type=file'
|
||||
)
|
||||
resp = requests.post(
|
||||
url,
|
||||
files={'media': (filename, BytesIO(file_data), 'application/octet-stream')},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode', 0) != 0 or not data.get('media_id'):
|
||||
raise RuntimeError(f"WeCom media upload failed: {data}")
|
||||
return data['media_id']
|
||||
|
||||
|
||||
def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'file',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'file': {'media_id': media_id},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _append_query_param(url: str, key: str, value: str) -> str:
|
||||
"""
|
||||
向 URL 追加单个 query 参数,保留已有参数。
|
||||
@param url: 原始 URL
|
||||
@param key: 参数名
|
||||
@param value: 参数值
|
||||
Returns:
|
||||
追加参数后的 URL
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
pairs = parse_qsl(parsed.query, keep_blank_values=True)
|
||||
pairs.append((key, value))
|
||||
return urlunparse(parsed._replace(query=urlencode(pairs)))
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
jump_url: str | None = None,
|
||||
wecom_userid: str | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
|
||||
|
||||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||||
Args:
|
||||
event_type: 通知事件开关名。
|
||||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||||
title: 卡片标题。
|
||||
content: 卡片正文。
|
||||
jump_path: 站内跳转路径。
|
||||
jump_params: 跳转查询参数。
|
||||
jump_url: 若传入则覆盖默认拼接的跳转地址。
|
||||
wecom_userid: 可选,显式指定企微 touser;空则回退 user.wecom_userid。
|
||||
Returns:
|
||||
含 ok / trace_id 的发送结果字典。
|
||||
"""
|
||||
trace_id = uuid.uuid4().hex
|
||||
audit = _create_audit(event_type, user, title, content, trace_id)
|
||||
target_userid = str(wecom_userid or (user.wecom_userid if user else "") or "").strip()
|
||||
if target_userid:
|
||||
audit.wecom_userid = target_userid
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
audit.error_code = 'NOTIFY_DISABLED'
|
||||
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
|
||||
|
||||
if event_type not in _get_enabled_events():
|
||||
audit.error_code = 'EVENT_DISABLED'
|
||||
audit.error_message = f'event {event_type} disabled'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
|
||||
|
||||
if not target_userid:
|
||||
audit.error_code = 'WECOM_USER_UNBOUND'
|
||||
audit.error_message = 'user has no wecom_userid'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||||
|
||||
try:
|
||||
if jump_url:
|
||||
final_jump_url = _append_query_param(jump_url, 'wecom_trace', trace_id)
|
||||
else:
|
||||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = final_jump_url
|
||||
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
audit.error_code = str(data.get('errcode'))
|
||||
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
|
||||
except Exception as exc:
|
||||
audit.error_code = 'EXCEPTION'
|
||||
audit.error_message = str(exc)[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
|
||||
|
||||
|
||||
def mark_wecom_message_opened(trace_id: str) -> bool:
|
||||
if not trace_id:
|
||||
return False
|
||||
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
|
||||
if not row:
|
||||
return False
|
||||
if not row.opened_at:
|
||||
row.opened_at = datetime.utcnow()
|
||||
return True
|
||||
@@ -7,8 +7,8 @@ backend/app/services/lean_training_push_service.py
|
||||
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
|
||||
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
|
||||
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
|
||||
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护),
|
||||
再对各任务推进一批推送。
|
||||
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
|
||||
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -51,7 +51,9 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
|
||||
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完;
|
||||
- 配置中新增上传、尚未冻结进模板列表的视频按上传时间倒序自动追加到列表末尾:
|
||||
HR 事后手动勾选补推的进度经游标继承持续生效,每周自动计划从断点继续向后推;
|
||||
追加只发生在末尾,已推送前缀与游标不变,推过的视频绝不重复推。
|
||||
追加只发生在末尾,已推送前缀与游标不变,推过的视频绝不重复推;
|
||||
- 视频库已全部推完且配置无新增视频时**暂停滚动**:不再创建内容重复的新一期任务
|
||||
(对应"全部视频推送完成后暂停,不再重复推送"规则);新视频上传后下周一自动恢复创建。
|
||||
"""
|
||||
week_start, due_at = _current_week_bounds(now)
|
||||
week_key = week_start.isoformat()
|
||||
@@ -65,8 +67,21 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
|
||||
).scalars().first()
|
||||
if not template:
|
||||
return None
|
||||
# [RULE] 视频库已全部推完且配置无新增视频时暂停滚动:不再创建内容重复的新一期任务。
|
||||
# 若继续创建,新一期只会继承同一份已推完的清单,学员端每期显示完全相同的视频、
|
||||
# 也无可推送的新内容(对应"全部视频推送完成后暂停,不再重复推送"规则);
|
||||
# 配置上传新视频后,下周一滚动自动恢复创建并只推新视频。
|
||||
template_video_ids = list(template.video_resource_ids or [])
|
||||
if template.pushed_video_count >= len(template_video_ids):
|
||||
template_frozen_ids = {int(resource_id) for resource_id in template_video_ids}
|
||||
has_new_config_videos = any(
|
||||
resource.id not in template_frozen_ids
|
||||
for resource in _config_video_resource_ids(template.config)
|
||||
)
|
||||
if not has_new_config_videos:
|
||||
return None
|
||||
# [STEP 1] 复制最近一期配置滚动创建当周任务(视频列表沿用冻结顺序,游标继承已推送进度避免重复推送)
|
||||
video_resource_ids = list(template.video_resource_ids or [])
|
||||
video_resource_ids = template_video_ids
|
||||
# [RULE] 自动追加配置新增视频(上传时间倒序、只追加到末尾):前缀与游标保持对齐,断点续推不重推
|
||||
frozen_ids = {int(resource_id) for resource_id in video_resource_ids}
|
||||
video_resource_ids.extend(
|
||||
|
||||
@@ -20,7 +20,7 @@ from app.services.lean_training_service import (
|
||||
resolve_lean_training_jump_agent_id,
|
||||
target_user_ids_for_task,
|
||||
)
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ from app.models import (
|
||||
TrainingConfigResource,
|
||||
User,
|
||||
)
|
||||
from app.services.minio_service import minio_service
|
||||
from app.services.integrations.minio import minio_service
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
||||
|
||||
LEAN_TRAINING_TYPE = "lean_management"
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
import os
|
||||
import uuid
|
||||
from typing import BinaryIO
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
from werkzeug.utils import secure_filename
|
||||
from app.core.config.settings import config, ACTIVE_ENV_NAME
|
||||
|
||||
cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
class MinioService:
|
||||
def __init__(self):
|
||||
self.client = Minio(
|
||||
cfg.MINIO_ENDPOINT,
|
||||
access_key=cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=cfg.MINIO_SECRET_KEY,
|
||||
secure=cfg.MINIO_SECURE,
|
||||
)
|
||||
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
|
||||
self._ensure_bucket_exists()
|
||||
|
||||
def _ensure_bucket_exists(self):
|
||||
try:
|
||||
if not self.client.bucket_exists(self.bucket_name):
|
||||
self.client.make_bucket(self.bucket_name)
|
||||
# Set bucket policy to public read
|
||||
policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": ["*"]},
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
import json
|
||||
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
|
||||
except Exception as e:
|
||||
# log or print error
|
||||
print(f"MinIO bucket error (or not reachable): {e}")
|
||||
|
||||
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
|
||||
"""
|
||||
Uploads a file to MinIO and returns the generated object name.
|
||||
"""
|
||||
# If MinIO is not running, we could fallback to local storage or raise clear error
|
||||
try:
|
||||
self._ensure_bucket_exists()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ext = os.path.splitext(filename)[1]
|
||||
unique_filename = f"{uuid.uuid4().hex}{ext}"
|
||||
|
||||
try:
|
||||
self.client.put_object(
|
||||
bucket_name=self.bucket_name,
|
||||
object_name=unique_filename,
|
||||
data=file_stream,
|
||||
length=file_size,
|
||||
content_type=content_type
|
||||
)
|
||||
except Exception as e:
|
||||
# For development, if minio is down, let's mock it so UI can continue
|
||||
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
|
||||
|
||||
# fallback to local storage
|
||||
os.makedirs('data/agent-guides', exist_ok=True)
|
||||
local_path = os.path.join('data/agent-guides', unique_filename)
|
||||
file_stream.seek(0)
|
||||
with open(local_path, 'wb') as f:
|
||||
f.write(file_stream.read())
|
||||
|
||||
return unique_filename
|
||||
|
||||
def get_public_url(self, object_name: str) -> str:
|
||||
"""
|
||||
返回同源的指南文件代理地址。
|
||||
|
||||
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
|
||||
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
|
||||
"""
|
||||
return f"/api/agents/guides/files/{object_name}"
|
||||
|
||||
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
|
||||
"""
|
||||
按指定字节范围打开 MinIO 指南对象流。
|
||||
|
||||
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
|
||||
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
|
||||
"""
|
||||
return self.client.get_object(
|
||||
self.bucket_name,
|
||||
object_name,
|
||||
offset=offset,
|
||||
length=length,
|
||||
)
|
||||
|
||||
def stat_file(self, object_name: str):
|
||||
"""
|
||||
获取 MinIO 指南对象元数据。
|
||||
|
||||
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
|
||||
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
|
||||
"""
|
||||
return self.client.stat_object(self.bucket_name, object_name)
|
||||
|
||||
def get_file_bytes(self, object_name: str) -> bytes:
|
||||
"""
|
||||
读取对象的原始字节内容。
|
||||
|
||||
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
|
||||
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
|
||||
"""
|
||||
local_path = os.path.join('data/agent-guides', object_name)
|
||||
if os.path.exists(local_path):
|
||||
with open(local_path, 'rb') as file_obj:
|
||||
return file_obj.read()
|
||||
|
||||
response = self.client.get_object(self.bucket_name, object_name)
|
||||
try:
|
||||
return response.read()
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
|
||||
def delete_file(self, object_name: str):
|
||||
try:
|
||||
self.client.remove_object(self.bucket_name, object_name)
|
||||
except S3Error as e:
|
||||
print(f"Error deleting file from MinIO: {e}")
|
||||
|
||||
minio_service = MinioService()
|
||||
@@ -1,439 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
|
||||
SOAP_ENV_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
|
||||
SERVICE_NS = 'webservices.services.weaver.com.cn'
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
|
||||
|
||||
NS = {
|
||||
'soapenv': SOAP_ENV_NS,
|
||||
'svc': SERVICE_NS,
|
||||
'wf': WORKFLOW_NS,
|
||||
'xsi': XSI_NS,
|
||||
}
|
||||
|
||||
ET.register_namespace('soapenv', SOAP_ENV_NS)
|
||||
ET.register_namespace('svc', SERVICE_NS)
|
||||
ET.register_namespace('wf', WORKFLOW_NS)
|
||||
ET.register_namespace('xsi', XSI_NS)
|
||||
|
||||
|
||||
class OALeaveWorkflowError(RuntimeError):
|
||||
"""Raised when OA leave workflow submission fails."""
|
||||
|
||||
|
||||
class OALeaveWorkflowService:
|
||||
WORKFLOW_ID = '879'
|
||||
|
||||
# Keep backend leave labels aligned with the chat form options so OA browser
|
||||
# fields always receive the expected showValue instead of a raw code.
|
||||
LEAVE_TYPE_LABELS = {
|
||||
'005': '事假(小时)',
|
||||
'006': '病假(小时)',
|
||||
'007': '丧假(天)',
|
||||
'010': '年假(天)',
|
||||
'021': '因公出差(小时)',
|
||||
'025': '调休假(小时)',
|
||||
'035': '其他假(小时)',
|
||||
'401': '产假(天)',
|
||||
'402': '陪产假(天)',
|
||||
'403': '婚假(天)',
|
||||
'405': '住院病假(小时)',
|
||||
'406': '工伤假(天)',
|
||||
'408': '育儿假(小时)',
|
||||
'ZZ01': '返乡假(小时)',
|
||||
'ZZ04': '事假(经理专用小时)',
|
||||
'ZZ05': '病假(经理专用小时)',
|
||||
'ZZ07': '丧假(经理专用天)',
|
||||
'ZZ08': '产假(经理专用天)',
|
||||
'ZZ09': '陪产假(经理专用天)',
|
||||
'ZZ10': '婚假(经理专用天)',
|
||||
}
|
||||
ERROR_MESSAGES = {
|
||||
'-1': '创建流程失败',
|
||||
'-2': '用户没有流程创建权限',
|
||||
'-3': '创建流程基本信息失败',
|
||||
'-4': '保存表单主表信息失败',
|
||||
'-5': '更新紧急程度失败',
|
||||
'-6': '流程操作者失败',
|
||||
'-7': '流转至下一节点失败',
|
||||
'-8': '节点附加操作失败',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_wsdl_url(cls) -> str:
|
||||
return (
|
||||
current_app.config.get('OA_WORKFLOW_WSDL_URL')
|
||||
or os.getenv('OA_WORKFLOW_WSDL_URL')
|
||||
or 'http://oa.well-trust.com:8888/services/WorkflowService?wsdl'
|
||||
).strip()
|
||||
|
||||
@classmethod
|
||||
def _get_service_url(cls) -> str:
|
||||
wsdl_url = cls._get_wsdl_url()
|
||||
return wsdl_url[:-5] if wsdl_url.lower().endswith('?wsdl') else wsdl_url
|
||||
|
||||
@classmethod
|
||||
def _request_timeout(cls) -> tuple[int, int]:
|
||||
return (5, 25)
|
||||
|
||||
@classmethod
|
||||
def _post_soap(cls, action: str, body_el: ET.Element) -> ET.Element:
|
||||
envelope = ET.Element(f'{{{SOAP_ENV_NS}}}Envelope')
|
||||
ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Header')
|
||||
body = ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Body')
|
||||
body.append(body_el)
|
||||
payload = ET.tostring(envelope, encoding='utf-8', xml_declaration=True)
|
||||
headers = {
|
||||
'Content-Type': 'text/xml; charset=utf-8',
|
||||
'SOAPAction': action,
|
||||
}
|
||||
max_retries = 3
|
||||
last_exc = None
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
response = requests.post(
|
||||
cls._get_service_url(),
|
||||
data=payload,
|
||||
headers=headers,
|
||||
timeout=cls._request_timeout(),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return ET.fromstring(response.text)
|
||||
except requests.RequestException as exc:
|
||||
last_exc = exc
|
||||
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
|
||||
retryable = status_code in (502, 503, 504) if status_code else True
|
||||
if retryable and attempt < max_retries:
|
||||
import time
|
||||
wait = attempt * 2
|
||||
current_app.logger.warning(
|
||||
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
|
||||
attempt, max_retries, status_code, wait, exc,
|
||||
)
|
||||
time.sleep(wait)
|
||||
continue
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
|
||||
except ET.ParseError as exc:
|
||||
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
|
||||
|
||||
@classmethod
|
||||
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
|
||||
|
||||
@classmethod
|
||||
def resolve_agent_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='代理人')
|
||||
|
||||
@classmethod
|
||||
def _resolve_runtime_oa_user(
|
||||
cls,
|
||||
employee_id: str | None,
|
||||
real_name: str | None = None,
|
||||
*,
|
||||
role_label: str,
|
||||
) -> dict[str, str]:
|
||||
employee_id = (employee_id or '').strip()
|
||||
real_name = (real_name or '').strip()
|
||||
if not employee_id:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}工号,无法匹配 OA 用户。')
|
||||
if not real_name:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}姓名,无法匹配 OA 用户。')
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
matched = OASQLServerService.get_employee_by_name_and_workcode(real_name, employee_id)
|
||||
except Exception as exc:
|
||||
raise OALeaveWorkflowError(f'查询{role_label} OA 用户失败:{exc}') from exc
|
||||
|
||||
if not matched:
|
||||
raise OALeaveWorkflowError(f'未找到{role_label} OA 用户:{real_name}({employee_id})。')
|
||||
|
||||
return {
|
||||
'employee_id': matched['employeeId'],
|
||||
'user_id': matched['uid'],
|
||||
'name': matched['name'],
|
||||
'jobtitle': matched.get('jobtitle', ''),
|
||||
'jobtitleName': matched.get('jobtitleName', ''),
|
||||
'departmentid': matched.get('departmentid', ''),
|
||||
'departmentName': matched.get('departmentName', ''),
|
||||
'subcompanyid1': matched.get('subcompanyid1', ''),
|
||||
'subcompanyName': matched.get('subcompanyName', ''),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _pick_browser_field_value(*values: Any) -> str:
|
||||
for value in values:
|
||||
text = ('' if value is None else str(value)).strip()
|
||||
if text:
|
||||
return text
|
||||
return ''
|
||||
|
||||
@classmethod
|
||||
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in0').text = str(workflow_id)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _get_template_request_info(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.getCreateWorkflowRequestInfo'
|
||||
root = cls._post_soap(action, cls._build_get_template_body(workflow_id, oa_user_id))
|
||||
out = root.find('.//svc:out', NS)
|
||||
if out is None or out.attrib.get(f'{{{XSI_NS}}}nil') == 'true' or len(list(out)) == 0:
|
||||
raise OALeaveWorkflowError('OA 未返回建单模板,请确认 workflowId 与 OA userid 是否正确。')
|
||||
return deepcopy(out)
|
||||
|
||||
@classmethod
|
||||
def _find_field(cls, request_info: ET.Element, field_name: str) -> ET.Element | None:
|
||||
for field in request_info.findall('.//wf:WorkflowRequestTableField', NS):
|
||||
if (field.findtext('wf:fieldName', default='', namespaces=NS) or '').strip() == field_name:
|
||||
return field
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _set_field(
|
||||
cls,
|
||||
request_info: ET.Element,
|
||||
field_name: str,
|
||||
*,
|
||||
value: str | None,
|
||||
show_value: str | None = None,
|
||||
) -> None:
|
||||
field = cls._find_field(request_info, field_name)
|
||||
if field is None:
|
||||
current_app.logger.warning('[oa-leave] field not found in template: %s', field_name)
|
||||
return
|
||||
value_node = field.find('wf:fieldValue', NS)
|
||||
if value_node is None:
|
||||
value_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue')
|
||||
value_node.text = '' if value is None else str(value)
|
||||
|
||||
if show_value is not None:
|
||||
show_node = field.find('wf:fieldShowValue', NS)
|
||||
if show_node is None:
|
||||
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
|
||||
show_node.text = str(show_value)
|
||||
|
||||
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
|
||||
if field_html_type == '3':
|
||||
filed_html_node = field.find('wf:filedHtmlShow', NS)
|
||||
if filed_html_node is not None:
|
||||
filed_html_node.text = str(show_value)
|
||||
|
||||
for tag in ['edit', 'view']:
|
||||
node = field.find(f'wf:{tag}', NS)
|
||||
if node is not None:
|
||||
node.text = 'true'
|
||||
else:
|
||||
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
|
||||
node.text = 'true'
|
||||
|
||||
@classmethod
|
||||
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
|
||||
node = parent.find(xpath, NS)
|
||||
if node is not None:
|
||||
node.text = value
|
||||
|
||||
@classmethod
|
||||
def _parse_frontend_datetime(cls, raw: str, field_name: str) -> datetime:
|
||||
text = (raw or '').strip().replace('T', ' ')
|
||||
try:
|
||||
return datetime.strptime(text, '%Y-%m-%d %H:%M')
|
||||
except ValueError as exc:
|
||||
raise OALeaveWorkflowError(f'{field_name} 格式不正确,应为 YYYY-MM-DD HH:MM。') from exc
|
||||
|
||||
@classmethod
|
||||
def _build_request_name(cls, creator_name: str, start_dt: datetime) -> str:
|
||||
return f'请假申请单-{creator_name}-{start_dt.strftime("%Y-%m-%d")}'
|
||||
|
||||
@classmethod
|
||||
def _normalize_duration(cls, value: Any) -> str:
|
||||
try:
|
||||
hours = float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OALeaveWorkflowError('请假时长格式不正确。') from exc
|
||||
if hours <= 0:
|
||||
raise OALeaveWorkflowError('请假时长必须大于 0。')
|
||||
return f'{hours:.2f}'.rstrip('0').rstrip('.')
|
||||
|
||||
@classmethod
|
||||
def build_request_info(cls, form_data: dict[str, Any], current_user: Any) -> tuple[ET.Element, dict[str, str], dict[str, str], dict[str, str]]:
|
||||
filler_name = (
|
||||
form_data.get('fillerName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
filler = cls._resolve_runtime_oa_user(
|
||||
getattr(current_user, 'employee_id', None),
|
||||
filler_name,
|
||||
role_label='填单人'
|
||||
)
|
||||
|
||||
applicant_name = (
|
||||
form_data.get('applicantName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
applicant = cls.resolve_creator_oa_user(
|
||||
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
|
||||
applicant_name,
|
||||
)
|
||||
agent = cls.resolve_agent_oa_user(form_data.get('agentEmployeeId'), form_data.get('agentName'))
|
||||
|
||||
workflow_id = str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID)
|
||||
request_info = cls._get_template_request_info(workflow_id, filler['user_id'])
|
||||
|
||||
start_dt = cls._parse_frontend_datetime(form_data.get('startTime'), '开始时间')
|
||||
end_dt = cls._parse_frontend_datetime(form_data.get('endTime'), '结束时间')
|
||||
if end_dt <= start_dt:
|
||||
raise OALeaveWorkflowError('结束时间必须晚于开始时间。')
|
||||
|
||||
leave_type_code = (form_data.get('leaveType') or '').strip()
|
||||
if not leave_type_code:
|
||||
raise OALeaveWorkflowError('缺少假别编码。')
|
||||
leave_type_label = cls.LEAVE_TYPE_LABELS.get(leave_type_code, leave_type_code)
|
||||
request_name = cls._build_request_name(applicant['name'], start_dt)
|
||||
|
||||
cls._set_text(request_info, 'wf:creatorId', filler['user_id'])
|
||||
cls._set_text(request_info, 'wf:creatorName', filler['name'])
|
||||
cls._set_text(request_info, 'wf:requestLevel', '0')
|
||||
cls._set_text(request_info, 'wf:requestName', request_name)
|
||||
cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id)
|
||||
|
||||
cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name)
|
||||
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'])
|
||||
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'])
|
||||
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
|
||||
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
|
||||
|
||||
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
|
||||
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
|
||||
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
|
||||
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
|
||||
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
|
||||
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
|
||||
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
|
||||
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
|
||||
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
|
||||
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
|
||||
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
|
||||
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
if filler_jobtitle and not filler_jobtitle_name:
|
||||
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
|
||||
if filler_department and not filler_department_name:
|
||||
filler_department_name = OASQLServerService.get_department_name(filler_department)
|
||||
if filler_subcompany and not filler_subcompany_name:
|
||||
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
|
||||
if applicant_jobtitle and not applicant_jobtitle_name:
|
||||
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
|
||||
if applicant_department and not applicant_department_name:
|
||||
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
|
||||
if applicant_subcompany and not applicant_subcompany_name:
|
||||
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
|
||||
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
|
||||
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
|
||||
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
|
||||
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
|
||||
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
|
||||
|
||||
current_app.logger.info(
|
||||
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
|
||||
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
|
||||
filler_department, filler_department_name or filler_department or '暂无',
|
||||
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
|
||||
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
|
||||
applicant_department, applicant_department_name or applicant_department or '暂无',
|
||||
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
|
||||
)
|
||||
|
||||
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'])
|
||||
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
|
||||
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
|
||||
cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label)
|
||||
cls._set_field(request_info, 'jbbh', value=leave_type_code, show_value=leave_type_code)
|
||||
cls._set_field(request_info, 'kssj', value=start_dt.strftime('%Y-%m-%d'), show_value=start_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'kssk', value=start_dt.strftime('%H:%M'), show_value=start_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'jssj', value=end_dt.strftime('%Y-%m-%d'), show_value=end_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'jssk', value=end_dt.strftime('%H:%M'), show_value=end_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'qjsc', value=cls._normalize_duration(form_data.get('durationHours')), show_value=cls._normalize_duration(form_data.get('durationHours')))
|
||||
cls._set_field(request_info, 'sfwgs', value=str(form_data.get('isWorkInjury')), show_value='是' if str(form_data.get('isWorkInjury')) == '0' else '否')
|
||||
cls._set_field(request_info, 'sfwc', value=str(form_data.get('isOutOfOffice')), show_value='是' if str(form_data.get('isOutOfOffice')) == '0' else '否')
|
||||
cls._set_field(request_info, 'bz', value=(form_data.get('remark') or '').strip(), show_value=(form_data.get('remark') or '').strip())
|
||||
|
||||
return request_info, filler, applicant, agent
|
||||
|
||||
@classmethod
|
||||
def _build_create_body(cls, request_info: ET.Element, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}doCreateWorkflowRequest')
|
||||
in0 = deepcopy(request_info)
|
||||
in0.tag = f'{{{SERVICE_NS}}}in0'
|
||||
root.append(in0)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _parse_create_response(cls, root: ET.Element) -> str:
|
||||
out = root.findtext('.//svc:out', default='', namespaces=NS)
|
||||
out = (out or '').strip()
|
||||
if not out:
|
||||
raise OALeaveWorkflowError('OA 未返回单据编号。')
|
||||
if out in cls.ERROR_MESSAGES:
|
||||
raise OALeaveWorkflowError(cls.ERROR_MESSAGES[out])
|
||||
if out.startswith('-'):
|
||||
raise OALeaveWorkflowError(f'OA 创建流程失败,返回码:{out}')
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def serialize_request_xml(cls, request_info: ET.Element) -> str:
|
||||
return ET.tostring(request_info, encoding='unicode')
|
||||
|
||||
@classmethod
|
||||
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
|
||||
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
|
||||
|
||||
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
|
||||
for fn in log_fields:
|
||||
f = cls._find_field(request_info, fn)
|
||||
if f is not None:
|
||||
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
|
||||
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
|
||||
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
|
||||
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
|
||||
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
|
||||
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
|
||||
request_id = cls._parse_create_response(root)
|
||||
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
|
||||
return {
|
||||
'ok': True,
|
||||
'request_id': request_id,
|
||||
'request_name': request_info.findtext('wf:requestName', default='', namespaces=NS),
|
||||
'submitted_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
|
||||
'creator': applicant,
|
||||
'filler': filler,
|
||||
'agent': agent,
|
||||
'workflow_id': str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID),
|
||||
'request_xml': cls.serialize_request_xml(request_info),
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
"""
|
||||
backend/app/services/oa_sqlserver.py
|
||||
|
||||
用途:封装 OA SQL Server 的员工检索与组织信息查询能力,供请假代理人/申请人选择等场景复用。
|
||||
依赖:pyodbc、OA ecology 数据库视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
|
||||
逻辑:通过只读 SQL 查询返回 OA 用户与组织字段;对于 OA 中夹带的多语言包装串,统一在服务层清洗成可直接展示的中文文本。
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import pyodbc
|
||||
from flask import current_app
|
||||
|
||||
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
|
||||
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
|
||||
)
|
||||
|
||||
class OASQLServerService:
|
||||
@staticmethod
|
||||
def _normalize_oa_text(value) -> str:
|
||||
"""
|
||||
清洗 OA 多语言包装字段。
|
||||
|
||||
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
|
||||
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
|
||||
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
|
||||
|
||||
Args:
|
||||
value: 来自 OA SQL Server 的原始字段值。
|
||||
|
||||
Returns:
|
||||
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
|
||||
if not matched:
|
||||
return text
|
||||
simplified, english, traditional = (
|
||||
segment.strip().strip("`").strip()
|
||||
for segment in matched.groups()
|
||||
)
|
||||
return simplified or english or traditional or text
|
||||
|
||||
@staticmethod
|
||||
def _pick_driver():
|
||||
drivers = pyodbc.drivers()
|
||||
preferred = [
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
]
|
||||
for name in preferred:
|
||||
if name in drivers:
|
||||
return name
|
||||
if not drivers:
|
||||
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
|
||||
return drivers[-1]
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
|
||||
available_drivers = pyodbc.drivers()
|
||||
if driver not in available_drivers:
|
||||
driver = cls._pick_driver()
|
||||
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
|
||||
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
|
||||
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
|
||||
username = os.getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA").strip()
|
||||
password = os.getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA").strip()
|
||||
encrypt = os.getenv("OA_SQLSERVER_ENCRYPT", "no").strip().lower()
|
||||
trust_cert = os.getenv("OA_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
||||
timeout = int(os.getenv("OA_SQLSERVER_TIMEOUT", "10"))
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
)
|
||||
if driver != "SQL Server":
|
||||
conn_str += (
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
return pyodbc.connect(conn_str, timeout=timeout)
|
||||
|
||||
@classmethod
|
||||
def search_employees(cls, keyword: str, page: int, page_size: int):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
offset = (page - 1) * page_size
|
||||
params = []
|
||||
|
||||
# Count total
|
||||
count_sql = "SELECT COUNT(1) FROM userInfo_view WHERE 1=1"
|
||||
if keyword:
|
||||
count_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
like_kw = f"%{keyword}%"
|
||||
params.extend([like_kw, like_kw])
|
||||
|
||||
cursor.execute(count_sql, params)
|
||||
total = cursor.fetchone()[0]
|
||||
|
||||
# Fetch page
|
||||
# Compatible with older SQL Server versions (2008/2012)
|
||||
query_sql = """
|
||||
SELECT id, workcode, lastname, jobtitle, departmentid, subcompanyid1,
|
||||
departmentname, subcompanyname, jobtitlename
|
||||
FROM (
|
||||
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
||||
d.departmentname, s.subcompanyname, j.jobtitlename,
|
||||
ROW_NUMBER() OVER(ORDER BY v.id) as rn
|
||||
FROM userInfo_view v
|
||||
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
||||
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
||||
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
||||
WHERE 1=1
|
||||
"""
|
||||
if keyword:
|
||||
query_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
|
||||
query_sql += """
|
||||
) as T
|
||||
WHERE rn > ? AND rn <= ?
|
||||
"""
|
||||
|
||||
page_params = params + [offset, offset + page_size]
|
||||
cursor.execute(query_sql, page_params)
|
||||
|
||||
items = []
|
||||
for row in cursor.fetchall():
|
||||
items.append({
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": cls._normalize_oa_text(row.lastname),
|
||||
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": cls._normalize_oa_text(row.departmentname),
|
||||
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
||||
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
||||
})
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_employee_by_name_and_workcode(cls, real_name: str, employee_id: str):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
normalized_name = (real_name or "").strip()
|
||||
normalized_employee_id = (employee_id or "").strip()
|
||||
if not normalized_name or not normalized_employee_id:
|
||||
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
|
||||
|
||||
query_sql = """
|
||||
SELECT TOP 1 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
||||
d.departmentname, s.subcompanyname, j.jobtitlename
|
||||
FROM userInfo_view v
|
||||
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
||||
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
||||
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
||||
WHERE v.workcode = ? AND v.lastname = ?
|
||||
ORDER BY v.id
|
||||
"""
|
||||
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
return {
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": cls._normalize_oa_text(row.lastname),
|
||||
"jobtitle": cls._normalize_oa_text(row.jobtitle),
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": cls._normalize_oa_text(row.departmentname),
|
||||
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
|
||||
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_department_name(cls, department_id: str) -> str:
|
||||
if not department_id or not department_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
|
||||
[department_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_subcompany_name(cls, subcompany_id: str) -> str:
|
||||
if not subcompany_id or not subcompany_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
|
||||
[subcompany_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
|
||||
if not jobtitle_id or not jobtitle_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
|
||||
[jobtitle_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -1,240 +0,0 @@
|
||||
"""
|
||||
backend/app/services/oa_wecom_sync.py
|
||||
|
||||
用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。
|
||||
依赖:OASQLServerService、SQLAlchemy db、User 模型。
|
||||
逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
|
||||
_PREVIEW_LIMIT = 20
|
||||
_OA_VIEW = 'userInfo_view'
|
||||
_OA_IN_BATCH_SIZE = 500
|
||||
|
||||
|
||||
def _clean_str(value) -> str | None:
|
||||
"""
|
||||
规范化字符串;空值返回 None。
|
||||
@param value: 任意输入
|
||||
Returns:
|
||||
去首尾空白后的字符串,或 None
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _load_local_users_with_employee_id() -> list[tuple[User, str]]:
|
||||
"""
|
||||
加载本地含有效工号的用户列表。
|
||||
核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。
|
||||
Returns:
|
||||
(User, employee_id) 元组列表
|
||||
"""
|
||||
rows: list[tuple[User, str]] = []
|
||||
for user in db.session.query(User).filter(User.employee_id.isnot(None)).all():
|
||||
employee_id = _clean_str(user.employee_id)
|
||||
if not employee_id:
|
||||
continue
|
||||
rows.append((user, employee_id))
|
||||
return rows
|
||||
|
||||
|
||||
def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]:
|
||||
"""
|
||||
按工号批量查询 OA userInfo_view 中的企微 userid 映射。
|
||||
核心逻辑:工号去重后分批 IN 查询,避免全表扫描。
|
||||
@param workcodes: 本地 users.employee_id 列表
|
||||
Returns:
|
||||
每项含 workcode、wecom_userid、name
|
||||
Raises:
|
||||
RuntimeError: ODBC 连接或查询失败
|
||||
"""
|
||||
unique_codes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for code in workcodes:
|
||||
cleaned = _clean_str(code)
|
||||
if not cleaned or cleaned in seen:
|
||||
continue
|
||||
seen.add(cleaned)
|
||||
unique_codes.append(cleaned)
|
||||
|
||||
if not unique_codes:
|
||||
return []
|
||||
|
||||
connection = OASQLServerService._connect()
|
||||
cursor = connection.cursor()
|
||||
rows: list[dict[str, str | None]] = []
|
||||
try:
|
||||
for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE):
|
||||
batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE]
|
||||
placeholders = ','.join('?' for _ in batch)
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT id, workcode, lastname
|
||||
FROM userInfo_view
|
||||
WHERE workcode IN ({placeholders})
|
||||
AND id IS NOT NULL
|
||||
""",
|
||||
batch,
|
||||
)
|
||||
for row in cursor.fetchall():
|
||||
workcode = _clean_str(row.workcode)
|
||||
wecom_userid = _clean_str(row.id)
|
||||
if not workcode or not wecom_userid:
|
||||
continue
|
||||
rows.append(
|
||||
{
|
||||
'workcode': workcode,
|
||||
'wecom_userid': wecom_userid,
|
||||
'name': _clean_str(row.lastname),
|
||||
}
|
||||
)
|
||||
return rows
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]:
|
||||
"""
|
||||
执行 OA 工号 → wecom_userid 同步(本地用户驱动)。
|
||||
核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。
|
||||
@param apply: True 时提交数据库;存在 conflicts 时不写入
|
||||
Returns:
|
||||
统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用)
|
||||
Raises:
|
||||
RuntimeError: OA 未配置、连接失败或 apply 时存在冲突
|
||||
"""
|
||||
local_users = _load_local_users_with_employee_id()
|
||||
workcodes = [employee_id for _, employee_id in local_users]
|
||||
oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes)
|
||||
|
||||
summary: dict[str, Any] = {
|
||||
'apply': apply,
|
||||
'employee_id_source': f'oa:{_OA_VIEW}.workcode',
|
||||
'department_ids': [],
|
||||
'local_candidates': len(local_users),
|
||||
'wecom_users': 0,
|
||||
'wecom_without_employee_id': 0,
|
||||
'local_matched': 0,
|
||||
'would_update': 0,
|
||||
'updated': 0,
|
||||
'already_bound': 0,
|
||||
'local_missing': 0,
|
||||
'conflicts': [],
|
||||
'missing_samples': [],
|
||||
'pending_updates': [],
|
||||
}
|
||||
|
||||
oa_by_workcode: dict[str, dict[str, str | None]] = {}
|
||||
duplicate_workcodes: set[str] = set()
|
||||
for row in oa_rows:
|
||||
workcode = row['workcode']
|
||||
if not workcode:
|
||||
continue
|
||||
if workcode in oa_by_workcode:
|
||||
duplicate_workcodes.add(workcode)
|
||||
summary['conflicts'].append(
|
||||
{
|
||||
'employee_id': workcode,
|
||||
'username': '',
|
||||
'new_wecom_userid': row['wecom_userid'],
|
||||
'reason': 'duplicate_workcode_in_oa',
|
||||
}
|
||||
)
|
||||
continue
|
||||
oa_by_workcode[workcode] = row
|
||||
|
||||
summary['wecom_users'] = len(oa_by_workcode)
|
||||
|
||||
for local_user, employee_id in local_users:
|
||||
if employee_id in duplicate_workcodes:
|
||||
continue
|
||||
|
||||
oa_row = oa_by_workcode.get(employee_id)
|
||||
if not oa_row:
|
||||
summary['local_missing'] += 1
|
||||
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
|
||||
summary['missing_samples'].append(
|
||||
{
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
wecom_userid = oa_row['wecom_userid']
|
||||
name = oa_row.get('name')
|
||||
if not wecom_userid:
|
||||
summary['wecom_without_employee_id'] += 1
|
||||
continue
|
||||
|
||||
summary['local_matched'] += 1
|
||||
|
||||
if local_user.wecom_userid == wecom_userid:
|
||||
summary['already_bound'] += 1
|
||||
continue
|
||||
|
||||
conflict = None
|
||||
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'old_wecom_userid': local_user.wecom_userid,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
}
|
||||
else:
|
||||
occupied = (
|
||||
db.session.query(User)
|
||||
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
|
||||
.first()
|
||||
)
|
||||
if occupied:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
'occupied_by_user_id': occupied.id,
|
||||
'occupied_by_username': occupied.username,
|
||||
}
|
||||
|
||||
if conflict:
|
||||
summary['conflicts'].append(conflict)
|
||||
continue
|
||||
|
||||
summary['would_update'] += 1
|
||||
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
|
||||
summary['pending_updates'].append(
|
||||
{
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'wecom_userid': wecom_userid,
|
||||
'name': name,
|
||||
}
|
||||
)
|
||||
if apply:
|
||||
local_user.wecom_userid = wecom_userid
|
||||
summary['updated'] += 1
|
||||
|
||||
if summary['conflicts'] and apply:
|
||||
db.session.rollback()
|
||||
raise RuntimeError('Conflicts detected; resolve manually before apply')
|
||||
|
||||
if apply and summary['updated'] > 0:
|
||||
db.session.commit()
|
||||
elif apply:
|
||||
db.session.rollback()
|
||||
|
||||
return summary
|
||||
|
||||
@@ -1,374 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from html import escape
|
||||
from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ChatLog
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
|
||||
class PLMOracleService:
|
||||
_MAX_RESULT_ROWS = 50
|
||||
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
|
||||
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
|
||||
_EXPLICIT_LABEL_PATTERN = re.compile(
|
||||
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_RELATIONAL_SQL = """
|
||||
select *
|
||||
from bi_file endb
|
||||
where endb.revisionguid in (
|
||||
select bb.revisionguid
|
||||
from (
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v,
|
||||
StructureObject_0 str,
|
||||
document_0 doc,
|
||||
bi_file b
|
||||
where v.name in ('RelatedDoc')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = doc.masterfk
|
||||
and doc.latestrevision like '%m%'
|
||||
and b.revisionguid = doc.guid
|
||||
) bb,
|
||||
item_0 i
|
||||
where bb.end1 = i.guid
|
||||
and i.id = :item_id
|
||||
and i.latestrevision like '%m%'
|
||||
)
|
||||
and endb.lastaccesstime is not null
|
||||
"""
|
||||
_FILENAME_SQL = """
|
||||
select *
|
||||
from bi_file
|
||||
where upper(name) like :name_pattern
|
||||
and lastaccesstime is not null
|
||||
order by lastaccesstime desc nulls last
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def supports(cls, query: str, agent) -> bool:
|
||||
_ = agent
|
||||
return bool(cls.extract_material_no(query))
|
||||
|
||||
@classmethod
|
||||
def extract_material_no(cls, query: str) -> str | None:
|
||||
text = str(query or "").strip().upper()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
|
||||
if explicit:
|
||||
return explicit.group(1).strip().upper()
|
||||
|
||||
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
|
||||
if direct_match:
|
||||
return direct_match.group(0).upper()
|
||||
|
||||
for match in cls._MATERIAL_PATTERN.finditer(text):
|
||||
candidate = match.group(0).upper()
|
||||
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _get_connect_kwargs() -> dict:
|
||||
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
|
||||
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
|
||||
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
|
||||
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
|
||||
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
|
||||
|
||||
kwargs = {
|
||||
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
|
||||
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
|
||||
}
|
||||
if dsn:
|
||||
kwargs["dsn"] = dsn
|
||||
return kwargs
|
||||
|
||||
import oracledb
|
||||
|
||||
if service_name:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
|
||||
else:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
|
||||
return kwargs
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
|
||||
|
||||
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
|
||||
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
return oracledb.connect(**cls._get_connect_kwargs())
|
||||
|
||||
@classmethod
|
||||
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(sql, params)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
|
||||
return columns, rows
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
|
||||
try:
|
||||
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
|
||||
if rows:
|
||||
return columns, rows, "relational"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
|
||||
|
||||
columns, rows = cls._execute_query(
|
||||
cls._FILENAME_SQL,
|
||||
name_pattern=f"{material_no.upper()}%",
|
||||
)
|
||||
return columns, rows, "filename_fallback"
|
||||
|
||||
@staticmethod
|
||||
def _format_datetime(value) -> str:
|
||||
if value is None:
|
||||
return "-"
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(value)
|
||||
|
||||
@staticmethod
|
||||
def _format_size(value) -> str:
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
try:
|
||||
size = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return str(value)
|
||||
if size < 1024:
|
||||
return f"{size} B"
|
||||
if size < 1024 * 1024:
|
||||
return f"{size / 1024:.1f} KB"
|
||||
return f"{size / 1024 / 1024:.2f} MB"
|
||||
|
||||
@classmethod
|
||||
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
|
||||
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
|
||||
for value in (storage_id, file_path, file_id):
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
parts.append(text.replace("/", "\\").strip("\\"))
|
||||
return "\\".join(part for part in parts if part)
|
||||
|
||||
@classmethod
|
||||
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
|
||||
def raw(column_name: str):
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return None
|
||||
value = row[idx]
|
||||
return None if value in (None, "") else value
|
||||
|
||||
file_name = str(raw("NAME") or "").strip()
|
||||
if not file_name:
|
||||
return "-"
|
||||
|
||||
storage_id = raw("STORAGEID")
|
||||
file_path = raw("FILEPATH")
|
||||
file_id = str(raw("ID") or "").strip()
|
||||
if not storage_id or file_path is None or not file_id:
|
||||
return escape(file_name)
|
||||
|
||||
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
|
||||
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
|
||||
return f'<a href="{preview_href}">{escape(file_name)}</a>'
|
||||
|
||||
@staticmethod
|
||||
def _escape_markdown_cell(value: str) -> str:
|
||||
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@staticmethod
|
||||
def _escape_html_text(value) -> str:
|
||||
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@classmethod
|
||||
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return "-"
|
||||
value = row[idx]
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
upper_name = column_name.upper()
|
||||
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if upper_name == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
if upper_name == "NAME":
|
||||
return cls._render_file_name(row, index_map)
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
|
||||
parts = [f"记录 {row_no}"]
|
||||
for column_name in cls._SUMMARY_COLUMNS:
|
||||
if column_name.upper() not in index_map:
|
||||
continue
|
||||
rendered = cls._render_column_value(row, column_name, index_map)
|
||||
label = {
|
||||
"NAME": "文件名",
|
||||
"EXTENTIONNAME": "扩展名",
|
||||
"FILETYPE": "文件类型",
|
||||
"FILESIZE": "文件大小",
|
||||
"RELATIVEPATH": "相对路径",
|
||||
"LASTACCESSTIME": "最后访问时间",
|
||||
}.get(column_name.upper(), column_name)
|
||||
if column_name.upper() == "NAME":
|
||||
parts.append(f"{label}: {rendered}")
|
||||
else:
|
||||
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
|
||||
return " | ".join(parts)
|
||||
|
||||
@classmethod
|
||||
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
|
||||
rows_html = []
|
||||
for column_name in columns:
|
||||
rendered_value = cls._render_column_value(row, column_name, index_map)
|
||||
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
|
||||
rows_html.append(
|
||||
"<tr>"
|
||||
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
|
||||
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
|
||||
summary_html = cls._build_record_summary(row, index_map, row_no)
|
||||
return (
|
||||
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
|
||||
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
|
||||
"<div style=\"margin-top:10px;overflow:auto;\">"
|
||||
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
|
||||
"<thead><tr>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
|
||||
"</tr></thead>"
|
||||
f"<tbody>{''.join(rows_html)}</tbody>"
|
||||
"</table>"
|
||||
"</div>"
|
||||
"</details>"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
|
||||
if not rows:
|
||||
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
|
||||
|
||||
overflow = len(rows) > cls._MAX_RESULT_ROWS
|
||||
visible_rows = rows[: cls._MAX_RESULT_ROWS]
|
||||
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
|
||||
|
||||
lines = [
|
||||
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
|
||||
+ ("(仅展示前 50 条)" if overflow else "。"),
|
||||
"",
|
||||
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
|
||||
]
|
||||
for idx, row in enumerate(visible_rows, start=1):
|
||||
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
|
||||
|
||||
if overflow:
|
||||
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
|
||||
return "\n".join(lines)
|
||||
|
||||
@classmethod
|
||||
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
|
||||
material_no = cls.extract_material_no(query)
|
||||
|
||||
try:
|
||||
if not material_no:
|
||||
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
columns, rows, query_mode = cls._query_files(material_no)
|
||||
answer = cls._build_answer(material_no, columns, rows)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=answer,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
payload={
|
||||
"material_no": material_no,
|
||||
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
|
||||
"query_mode": query_mode,
|
||||
},
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.error("Failed to log PLM chat: %s", exc)
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
"event": "message_end",
|
||||
"answer": answer,
|
||||
"replace_answer": True,
|
||||
"chat_log_id": chat_log_id,
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception("[plm-oracle] stream_chat failed query=%s", query)
|
||||
error_data = {
|
||||
"event": "error",
|
||||
"message": str(exc) or "PLM 查询失败",
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
@@ -18,7 +18,7 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.models import Agent
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
|
||||
MAX_FINDINGS = 20
|
||||
|
||||
@@ -149,7 +149,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
|
||||
则跳过以免与领域缺件/失败告警重复。
|
||||
"""
|
||||
from app.services.wecom_notify import (
|
||||
from app.services.integrations.wecom.notify import (
|
||||
upload_wecom_temp_media,
|
||||
send_wecom_file_message,
|
||||
send_wecom_textcard_message,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/fulfillment_audit.py
|
||||
|
||||
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError、db.session。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id、core.http_context、AppError、db.session。
|
||||
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用;
|
||||
默认 strict=True;审计写入包在 SAVEPOINT 内,失败不污染外层业务事务;
|
||||
strict=False 时仅记日志(门禁路径用,禁止审计打断匹配等业务结果);
|
||||
@@ -37,10 +37,11 @@ def _client_request_context() -> tuple[str | None, str | None]:
|
||||
核心逻辑:优先 X-Forwarded-For 首段;无请求上下文时返回 (None, None)。
|
||||
"""
|
||||
try:
|
||||
from flask import request
|
||||
forwarded = str(request.headers.get('X-Forwarded-For') or '').split(',')[0].strip()
|
||||
ip = forwarded or str(request.remote_addr or '').strip() or None
|
||||
ua = str(request.headers.get('User-Agent') or '').strip() or None
|
||||
from app.core.http_context import header, remote_addr
|
||||
|
||||
forwarded = header('X-Forwarded-For').split(',')[0].strip()
|
||||
ip = forwarded or remote_addr() or None
|
||||
ua = header('User-Agent').strip() or None
|
||||
return ip, ua
|
||||
except RuntimeError:
|
||||
return None, None
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/i18n.py
|
||||
|
||||
用途:维护发货通知链路的多语言文案与语言解析工具。
|
||||
依赖:Flask request 上下文、模块内 `_MESSAGES` 文案字典。
|
||||
依赖:core.http_context、模块内 `_MESSAGES` 文案字典。
|
||||
逻辑:由 parse_summary、field_alignment_summary、workflow 提示文案等上游模块调用本文件输出用户可读消息。
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import has_request_context, request
|
||||
from app.core.http_context import has_http_request, header
|
||||
|
||||
SUPPORTED_LANGS = ("zh", "en", "th")
|
||||
|
||||
@@ -422,11 +422,11 @@ def resolve_lang(payload: dict[str, Any] | None = None) -> str:
|
||||
if val:
|
||||
return normalize_lang(val)
|
||||
|
||||
if has_request_context():
|
||||
hdr = str(request.headers.get("X-Lang") or "").strip()
|
||||
if has_http_request():
|
||||
hdr = header("X-Lang").strip()
|
||||
if hdr:
|
||||
return normalize_lang(hdr)
|
||||
accept = str(request.headers.get("Accept-Language") or "").strip()
|
||||
accept = header("Accept-Language").strip()
|
||||
if accept:
|
||||
return normalize_lang(accept.split(",")[0].strip())
|
||||
return "zh"
|
||||
|
||||
@@ -24,7 +24,7 @@ from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, ShippingOrderReviewCase, ShippingOrderReviewSuggestion
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
|
||||
@@ -8,7 +8,7 @@ from app import db
|
||||
from app.models import ShippingReceiptNotificationDelivery, ShippingReceiptReportFile, User
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.wecom_notify import send_wecom_file_message, send_wecom_textcard_message, upload_wecom_temp_media
|
||||
from app.services.integrations.wecom.notify import send_wecom_file_message, send_wecom_textcard_message, upload_wecom_temp_media
|
||||
|
||||
|
||||
def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]:
|
||||
|
||||
@@ -367,7 +367,7 @@ def _release_alert_send_lock(*, previous_state: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def _send_alert_to_recipients(*, title: str, content: str) -> bool:
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
recipients = _alert_recipients()
|
||||
if not recipients:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,7 +21,7 @@ from app.core.errors import ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import Agent, TrainingRecord, User
|
||||
from app.services.training_config_service import get_published_config
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
TRAINING_STAGES = {"video", "summary", "exam", "result"}
|
||||
TRAINING_TYPES = {"onboarding", "safety"}
|
||||
|
||||
@@ -130,7 +130,7 @@ def open_erp_connection(config: VoucherCheckEngineConfig):
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
) from exc
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
from app.services.integrations.text2sql import Text2SQLService
|
||||
|
||||
try:
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
|
||||
@@ -167,7 +167,7 @@ def send_batch_missing_summary(
|
||||
summary=summary,
|
||||
)
|
||||
|
||||
from app.services.wecom_notify import (
|
||||
from app.services.integrations.wecom.notify import (
|
||||
_build_jump_url,
|
||||
_create_audit,
|
||||
send_wecom_textcard_message,
|
||||
@@ -253,7 +253,7 @@ def send_failure_alert(
|
||||
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
|
||||
return
|
||||
|
||||
from app.services.wecom_notify import (
|
||||
from app.services.integrations.wecom.notify import (
|
||||
_build_jump_url,
|
||||
_create_audit,
|
||||
send_wecom_textcard_message,
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
"""
|
||||
WeCom (企业微信) callback crypto helpers — compatible with WXBizMsgCrypt layout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import random
|
||||
import struct
|
||||
from typing import Optional
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
|
||||
def sha1_hex(parts: list[str]) -> str:
|
||||
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
|
||||
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
|
||||
pad_len = block_size - (len(data) % block_size)
|
||||
return data + bytes([pad_len] * pad_len)
|
||||
|
||||
|
||||
def _pkcs7_unpad(data: bytes) -> bytes:
|
||||
if not data:
|
||||
return data
|
||||
pad_len = data[-1]
|
||||
if pad_len < 1 or pad_len > 32:
|
||||
raise ValueError('invalid pkcs7 padding')
|
||||
if data[-pad_len:] != bytes([pad_len] * pad_len):
|
||||
raise ValueError('invalid pkcs7 padding tail')
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
|
||||
raw = (encoding_aes_key_b64 or '').strip()
|
||||
key = base64.b64decode(raw + '=')
|
||||
if len(key) != 32:
|
||||
raise ValueError('EncodingAESKey must decode to 32 bytes')
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
"""
|
||||
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
|
||||
"""
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
|
||||
msg_bytes = plain_text.encode('utf-8')
|
||||
pack = (
|
||||
random_bytes
|
||||
+ struct.pack('>I', len(msg_bytes))
|
||||
+ msg_bytes
|
||||
+ corp_id.encode('utf-8')
|
||||
)
|
||||
padded = _pkcs7_pad(pack, 32)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
encrypted = cipher.encrypt(padded)
|
||||
return base64.b64encode(encrypted).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
cipher_bytes = base64.b64decode(cipher_b64)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
plain_padded = cipher.decrypt(cipher_bytes)
|
||||
plain = _pkcs7_unpad(plain_padded)
|
||||
content = plain[16:]
|
||||
if len(content) < 4:
|
||||
raise ValueError('decrypted payload too short')
|
||||
xml_len = struct.unpack('>I', content[:4])[0]
|
||||
xml_bytes = content[4:4 + xml_len]
|
||||
tail = content[4 + xml_len:]
|
||||
if tail.decode('utf-8', errors='strict') != corp_id:
|
||||
raise ValueError('corp_id mismatch after decrypt')
|
||||
return xml_bytes.decode('utf-8')
|
||||
|
||||
|
||||
def extract_encrypt_field(xml_body: str) -> Optional[str]:
|
||||
if not xml_body:
|
||||
return None
|
||||
import re
|
||||
|
||||
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
|
||||
if m2:
|
||||
return m2.group(1).strip()
|
||||
return None
|
||||
@@ -1,244 +0,0 @@
|
||||
"""
|
||||
backend/app/services/wecom_directory_sync.py
|
||||
|
||||
用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。
|
||||
依赖:Flask current_app、SQLAlchemy db、wecom_notify._get_access_token、User 模型。
|
||||
逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.wecom_notify import _get_access_token
|
||||
|
||||
_PREVIEW_LIMIT = 20
|
||||
|
||||
|
||||
def _clean_str(value) -> str | None:
|
||||
"""Trim string-like values; empty strings become None."""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None:
|
||||
"""
|
||||
从企微成员 extattr.attrs 中读取指定扩展字段。
|
||||
@param wecom_user: user/list 返回的成员 dict
|
||||
@param key: 扩展属性名
|
||||
Returns:
|
||||
字段文本或 None
|
||||
"""
|
||||
extattr = wecom_user.get('extattr') or {}
|
||||
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
|
||||
if not isinstance(attrs, list):
|
||||
return None
|
||||
for attr in attrs:
|
||||
if not isinstance(attr, dict):
|
||||
continue
|
||||
if _clean_str(attr.get('name')) != key:
|
||||
continue
|
||||
raw = attr.get('value')
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
||||
return _clean_str(raw)
|
||||
return None
|
||||
|
||||
|
||||
def extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None:
|
||||
"""
|
||||
按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。
|
||||
核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。
|
||||
"""
|
||||
userid = _clean_str(wecom_user.get('userid'))
|
||||
source = _clean_str(employee_id_source) or 'userid'
|
||||
if source == 'userid':
|
||||
return userid
|
||||
if source.startswith('extattr:'):
|
||||
return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1])
|
||||
return _clean_str(wecom_user.get(source))
|
||||
|
||||
|
||||
def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取企业微信部门列表。
|
||||
Raises:
|
||||
RuntimeError: API 失败
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/department/list',
|
||||
params={'access_token': access_token},
|
||||
timeout=15,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'department/list failed: {data}')
|
||||
departments = data.get('department') or []
|
||||
if not isinstance(departments, list):
|
||||
return []
|
||||
return [item for item in departments if isinstance(item, dict)]
|
||||
|
||||
|
||||
def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取指定部门(含子部门)成员简要列表。
|
||||
@param department_id: 企微部门 ID
|
||||
Returns:
|
||||
user/list 返回的 userlist
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/list',
|
||||
params={
|
||||
'access_token': access_token,
|
||||
'department_id': department_id,
|
||||
'fetch_child': 1,
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'user/list failed department_id={department_id}: {data}')
|
||||
userlist = data.get('userlist') or []
|
||||
if not isinstance(userlist, list):
|
||||
return []
|
||||
return [item for item in userlist if isinstance(item, dict)]
|
||||
|
||||
|
||||
def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
汇总多个部门成员,按 wecom_userid 去重。
|
||||
Returns:
|
||||
key=userid, value=成员 dict
|
||||
"""
|
||||
merged: dict[str, dict[str, Any]] = {}
|
||||
for dept_id in department_ids:
|
||||
for user in fetch_wecom_users_in_department(access_token, dept_id):
|
||||
userid = _clean_str(user.get('userid'))
|
||||
if userid:
|
||||
merged[userid] = user
|
||||
return merged
|
||||
|
||||
|
||||
def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
执行工号 → wecom_userid 同步。
|
||||
核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。
|
||||
@param apply: True 时提交数据库;存在 conflicts 时不写入
|
||||
@param department_id: 指定根部门 ID;None 时使用全部部门
|
||||
Returns:
|
||||
统计摘要 dict(含 conflicts、pending_updates 预览)
|
||||
"""
|
||||
if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'):
|
||||
raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured')
|
||||
|
||||
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
token = _get_access_token()
|
||||
|
||||
if department_id is not None:
|
||||
department_ids = [department_id]
|
||||
else:
|
||||
departments = fetch_wecom_departments(token)
|
||||
department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None]
|
||||
if not department_ids:
|
||||
department_ids = [1]
|
||||
|
||||
wecom_users = collect_wecom_users(token, department_ids)
|
||||
summary: dict[str, Any] = {
|
||||
'apply': apply,
|
||||
'employee_id_source': employee_id_source,
|
||||
'department_ids': department_ids,
|
||||
'wecom_users': len(wecom_users),
|
||||
'wecom_without_employee_id': 0,
|
||||
'local_matched': 0,
|
||||
'would_update': 0,
|
||||
'updated': 0,
|
||||
'already_bound': 0,
|
||||
'local_missing': 0,
|
||||
'conflicts': [],
|
||||
'missing_samples': [],
|
||||
'pending_updates': [],
|
||||
}
|
||||
|
||||
for wecom_user in wecom_users.values():
|
||||
wecom_userid = _clean_str(wecom_user.get('userid'))
|
||||
wecom_unionid = _clean_str(wecom_user.get('unionid'))
|
||||
employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source)
|
||||
if not employee_id:
|
||||
summary['wecom_without_employee_id'] += 1
|
||||
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
|
||||
summary['missing_samples'].append(
|
||||
{'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))}
|
||||
)
|
||||
continue
|
||||
|
||||
local_user = db.session.query(User).filter(User.employee_id == employee_id).first()
|
||||
if not local_user:
|
||||
summary['local_missing'] += 1
|
||||
continue
|
||||
|
||||
summary['local_matched'] += 1
|
||||
|
||||
if local_user.wecom_userid == wecom_userid:
|
||||
summary['already_bound'] += 1
|
||||
continue
|
||||
|
||||
conflict = None
|
||||
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'old_wecom_userid': local_user.wecom_userid,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
}
|
||||
else:
|
||||
occupied = (
|
||||
db.session.query(User)
|
||||
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
|
||||
.first()
|
||||
)
|
||||
if occupied:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
'occupied_by_user_id': occupied.id,
|
||||
'occupied_by_username': occupied.username,
|
||||
}
|
||||
|
||||
if conflict:
|
||||
summary['conflicts'].append(conflict)
|
||||
continue
|
||||
|
||||
summary['would_update'] += 1
|
||||
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
|
||||
summary['pending_updates'].append(
|
||||
{
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'wecom_userid': wecom_userid,
|
||||
'name': _clean_str(wecom_user.get('name')),
|
||||
}
|
||||
)
|
||||
if apply:
|
||||
local_user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
local_user.wecom_unionid = wecom_unionid
|
||||
summary['updated'] += 1
|
||||
|
||||
if summary['conflicts'] and apply:
|
||||
db.session.rollback()
|
||||
raise RuntimeError('Conflicts detected; resolve manually before apply')
|
||||
|
||||
if apply and summary['updated'] > 0:
|
||||
db.session.commit()
|
||||
elif apply:
|
||||
db.session.rollback()
|
||||
|
||||
return summary
|
||||
@@ -1,257 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from io import BytesIO
|
||||
from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User, WecomNotifyAudit
|
||||
|
||||
|
||||
_TOKEN_CACHE = {
|
||||
'token': None,
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
if isinstance(raw, str):
|
||||
return {x.strip() for x in raw.split(',') if x.strip()}
|
||||
if isinstance(raw, (list, tuple, set)):
|
||||
return {str(x).strip() for x in raw if str(x).strip()}
|
||||
return set()
|
||||
|
||||
|
||||
def _get_notify_base_url() -> str:
|
||||
"""
|
||||
解析企微 textcard 跳转基地址(用户点击入口,须为浏览器可访问的 HTTPS 公网域名)。
|
||||
核心逻辑:优先 WECOM_PUBLIC_BASE_URL,其次 HXOPS_PUBLIC_BASE_URL;
|
||||
WECOM_NOTIFY_BASE_URL 仅作历史内网/端口兼容兜底。
|
||||
Returns:
|
||||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||||
"""
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'HXOPS_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
raw = current_app.config.get(key)
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
return raw.strip().rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||||
base = _get_notify_base_url()
|
||||
if not base:
|
||||
return ''
|
||||
base = base.rstrip('/')
|
||||
if not path.startswith('/'):
|
||||
path = f'/{path}'
|
||||
merged = {'wecom_trace': trace_id}
|
||||
if params:
|
||||
merged.update({k: v for k, v in params.items() if v is not None})
|
||||
return f'{base}{path}?{urlencode(merged)}'
|
||||
|
||||
|
||||
def _get_access_token() -> str:
|
||||
now = datetime.utcnow()
|
||||
token = _TOKEN_CACHE.get('token')
|
||||
expires_at = _TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and now < expires_at:
|
||||
return token
|
||||
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
|
||||
params={'corpid': corp_id, 'corpsecret': secret},
|
||||
timeout=8,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
|
||||
|
||||
_TOKEN_CACHE['token'] = data['access_token']
|
||||
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
|
||||
|
||||
def _create_audit(
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
trace_id: str,
|
||||
) -> WecomNotifyAudit:
|
||||
audit = WecomNotifyAudit(
|
||||
event_type=event_type,
|
||||
status='failed',
|
||||
trace_id=trace_id,
|
||||
user_id=user.id if user else None,
|
||||
username=user.username if user else None,
|
||||
wecom_userid=user.wecom_userid if user else None,
|
||||
title=title,
|
||||
content=content,
|
||||
)
|
||||
db.session.add(audit)
|
||||
return audit
|
||||
|
||||
|
||||
def upload_wecom_temp_media(file_data: bytes, filename: str) -> str:
|
||||
token = _get_access_token()
|
||||
url = (
|
||||
f'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
|
||||
f'?access_token={token}&type=file'
|
||||
)
|
||||
resp = requests.post(
|
||||
url,
|
||||
files={'media': (filename, BytesIO(file_data), 'application/octet-stream')},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode', 0) != 0 or not data.get('media_id'):
|
||||
raise RuntimeError(f"WeCom media upload failed: {data}")
|
||||
return data['media_id']
|
||||
|
||||
|
||||
def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'file',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'file': {'media_id': media_id},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _append_query_param(url: str, key: str, value: str) -> str:
|
||||
"""
|
||||
向 URL 追加单个 query 参数,保留已有参数。
|
||||
@param url: 原始 URL
|
||||
@param key: 参数名
|
||||
@param value: 参数值
|
||||
Returns:
|
||||
追加参数后的 URL
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
pairs = parse_qsl(parsed.query, keep_blank_values=True)
|
||||
pairs.append((key, value))
|
||||
return urlunparse(parsed._replace(query=urlencode(pairs)))
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
jump_url: str | None = None,
|
||||
wecom_userid: str | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
|
||||
|
||||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||||
Args:
|
||||
event_type: 通知事件开关名。
|
||||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||||
title: 卡片标题。
|
||||
content: 卡片正文。
|
||||
jump_path: 站内跳转路径。
|
||||
jump_params: 跳转查询参数。
|
||||
jump_url: 若传入则覆盖默认拼接的跳转地址。
|
||||
wecom_userid: 可选,显式指定企微 touser;空则回退 user.wecom_userid。
|
||||
Returns:
|
||||
含 ok / trace_id 的发送结果字典。
|
||||
"""
|
||||
trace_id = uuid.uuid4().hex
|
||||
audit = _create_audit(event_type, user, title, content, trace_id)
|
||||
target_userid = str(wecom_userid or (user.wecom_userid if user else "") or "").strip()
|
||||
if target_userid:
|
||||
audit.wecom_userid = target_userid
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
audit.error_code = 'NOTIFY_DISABLED'
|
||||
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
|
||||
|
||||
if event_type not in _get_enabled_events():
|
||||
audit.error_code = 'EVENT_DISABLED'
|
||||
audit.error_message = f'event {event_type} disabled'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
|
||||
|
||||
if not target_userid:
|
||||
audit.error_code = 'WECOM_USER_UNBOUND'
|
||||
audit.error_message = 'user has no wecom_userid'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||||
|
||||
try:
|
||||
if jump_url:
|
||||
final_jump_url = _append_query_param(jump_url, 'wecom_trace', trace_id)
|
||||
else:
|
||||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = final_jump_url
|
||||
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
audit.error_code = str(data.get('errcode'))
|
||||
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
|
||||
except Exception as exc:
|
||||
audit.error_code = 'EXCEPTION'
|
||||
audit.error_message = str(exc)[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
|
||||
|
||||
|
||||
def mark_wecom_message_opened(trace_id: str) -> bool:
|
||||
if not trace_id:
|
||||
return False
|
||||
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
|
||||
if not row:
|
||||
return False
|
||||
if not row.opened_at:
|
||||
row.opened_at = datetime.utcnow()
|
||||
return True
|
||||
@@ -4,13 +4,13 @@ backend/scripts/sync_wecom_userid_by_employee_id.py
|
||||
|
||||
用途:从企业微信通讯录拉取成员,按工号(employee_id)回填本地 users.wecom_userid。
|
||||
依赖:app.create_app、wecom_directory_sync.sync_wecom_userids_from_directory。
|
||||
逻辑:运维 CLI;默认 dry-run,--apply 才写库。
|
||||
逻辑:运维 CLI;默认 dry-run,--apply 才写库。--enqueue 只入队,由 schedule worker 执行。
|
||||
|
||||
Usage:
|
||||
cd backend
|
||||
python scripts/sync_wecom_userid_by_employee_id.py
|
||||
python scripts/sync_wecom_userid_by_employee_id.py --apply
|
||||
python scripts/sync_wecom_userid_by_employee_id.py --apply --department-id 1
|
||||
python scripts/sync_wecom_userid_by_employee_id.py --apply --enqueue
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,25 +26,36 @@ 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_directory_sync import sync_wecom_userids_from_directory # noqa: E402
|
||||
from app.jobs import JobType, enqueue # noqa: E402
|
||||
from app.services.integrations.wecom.directory_sync import sync_wecom_userids_from_directory # noqa: E402
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 入口:解析参数并打印同步摘要 JSON。"""
|
||||
"""CLI 入口:解析参数并打印同步摘要 JSON;--enqueue 时只返回 job_id。"""
|
||||
parser = argparse.ArgumentParser(description='Sync User.wecom_userid from WeCom directory by employee_id.')
|
||||
parser.add_argument('--apply', action='store_true', help='Persist changes (default: dry-run).')
|
||||
parser.add_argument('--department-id', type=int, default=None, help='Root department id (default: all departments).')
|
||||
parser.add_argument('--enqueue', action='store_true', help='Enqueue WECOM_DIRECTORY_SYNC instead of running inline.')
|
||||
args = parser.parse_args()
|
||||
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
with app.app_context():
|
||||
if args.enqueue:
|
||||
job_id = enqueue(
|
||||
JobType.WECOM_DIRECTORY_SYNC,
|
||||
{"apply": bool(args.apply), "department_id": args.department_id},
|
||||
domain="wecom",
|
||||
business_ref=f"directory-sync:{args.department_id or 'all'}",
|
||||
message="等待同步企微通讯录",
|
||||
)
|
||||
print(json.dumps({"enqueued": True, "job_id": job_id}, ensure_ascii=False))
|
||||
return 0
|
||||
summary = sync_wecom_userids_from_directory(apply=args.apply, department_id=args.department_id)
|
||||
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if summary.get('conflicts'):
|
||||
print('\nConflicts detected; resolve manually before --apply.', file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if summary.get('conflicts'):
|
||||
print('\nConflicts detected; resolve manually before --apply.', file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -104,7 +104,7 @@ def test_try_fast_route_hr_leave_when_route_declared(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -136,11 +136,11 @@ def test_try_fast_route_text2sql_for_erp_kb(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.text2sql.Text2SQLService.stream_chat',
|
||||
'app.services.integrations.text2sql.Text2SQLService.stream_chat',
|
||||
classmethod(lambda cls, *args, **kwargs: iter(['data: {"event":"message"}\n\n'])),
|
||||
)
|
||||
|
||||
@@ -172,7 +172,7 @@ def test_try_fast_route_returns_none_for_generic_query(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
@@ -200,7 +200,7 @@ def test_try_fast_route_plm_skips_when_attachments_present(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: True),
|
||||
)
|
||||
|
||||
@@ -227,7 +227,7 @@ def test_try_fast_route_skips_hr_when_route_not_declared(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
@@ -254,7 +254,7 @@ def test_try_fast_route_skips_text2sql_without_route(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import pytest
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent, ChatLog, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -13,7 +13,7 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.services.file_check import FileCheckService
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ def _mock_stream_response(monkeypatch, *, status_code: int = 200, lines: list[by
|
||||
calls["count"] += 1
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
return calls
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ def test_workflow_streaming_503_retries_then_success(monkeypatch):
|
||||
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
|
||||
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||
|
||||
@@ -199,7 +199,7 @@ def test_workflow_streaming_401_does_not_retry(monkeypatch):
|
||||
resp.status_code = 401
|
||||
raise requests.HTTPError(response=resp)
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
|
||||
with pytest.raises(requests.HTTPError):
|
||||
DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||
@@ -353,7 +353,7 @@ def test_dedupe_exact_doubled_text_fixes_historical_records():
|
||||
def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
|
||||
"""连接超时的 error SSE 必须携带持久化主键,供领域 Handler 回写失败状态。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.dify.requests.post",
|
||||
"app.services.integrations.dify.requests.post",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(requests.exceptions.ConnectTimeout("connect timed out")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -402,7 +402,7 @@ def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeyp
|
||||
yield _sse_lines({"event": "message", "answer": "partial answer"})[0]
|
||||
raise requests.exceptions.ReadTimeout("read timed out")
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
||||
monkeypatch.setattr(
|
||||
DifyService,
|
||||
"_persist_stream_chat_record",
|
||||
|
||||
@@ -297,7 +297,10 @@ def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
@@ -382,7 +385,10 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -619,7 +625,10 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
@@ -1224,18 +1233,13 @@ def test_file_check_tool_excel_download_uses_signed_token(app, client):
|
||||
|
||||
|
||||
def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
|
||||
started_threads = []
|
||||
enqueued = []
|
||||
|
||||
class _Thread:
|
||||
def __init__(self, *, target, daemon, name):
|
||||
self.target = target
|
||||
self.daemon = daemon
|
||||
self.name = name
|
||||
def _enqueue(*args, **kwargs):
|
||||
enqueued.append({"args": args, "kwargs": kwargs})
|
||||
return 1
|
||||
|
||||
def start(self):
|
||||
started_threads.append(self.name)
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -1254,7 +1258,7 @@ def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeyp
|
||||
assert data['ok'] is True
|
||||
assert data['run']['task_id'] == task_id
|
||||
assert data['run']['status'] == 'running'
|
||||
assert started_threads == [f"file-check-run-{data['run']['run_id']}"]
|
||||
assert enqueued and enqueued[0]['kwargs'].get('domain') == 'file_check'
|
||||
|
||||
|
||||
def test_serialize_file_judgement_reads_file_key():
|
||||
@@ -1816,7 +1820,10 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -1860,7 +1867,7 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
|
||||
) == run_id
|
||||
|
||||
chat_log_id = None
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-registry-001'},
|
||||
@@ -1998,7 +2005,10 @@ def _stub_file_check_thread(monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
|
||||
def _file_check_agent_proxy(task_id: int):
|
||||
@@ -2049,7 +2059,7 @@ def test_chat_tool_runs_tool_first_then_chat_log(app, client, monkeypatch):
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
@@ -2094,7 +2104,7 @@ def test_chat_tool_runs_chat_log_first_then_tool(app, client, monkeypatch):
|
||||
admin_id = admin.id
|
||||
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
@@ -2219,7 +2229,7 @@ def test_chat_tool_runs_same_message_does_not_cross_runs(app, client, monkeypatc
|
||||
run_b = res_b.get_json()['run']['run_id']
|
||||
assert run_b == run_a
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result_b = DifyService._persist_stream_chat_record(
|
||||
@@ -2279,7 +2289,7 @@ def test_chat_tool_runs_without_turn_id_same_message_skips_ambiguous_bind(app, c
|
||||
from app.models import ChatToolRun
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from types import SimpleNamespace
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService
|
||||
from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService
|
||||
|
||||
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
|
||||
+211
-106
@@ -1,106 +1,211 @@
|
||||
"""Tests for OA userInfo_view → wecom_userid sync."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import User
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oa_rows_for_local_user():
|
||||
return [
|
||||
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},
|
||||
]
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='26030025',
|
||||
email='26030025@test.local',
|
||||
employee_id='26030025',
|
||||
real_name='sophie',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=oa_rows_for_local_user,
|
||||
) as fetch_mock:
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
fetch_mock.assert_called_once_with(['26030025'])
|
||||
assert summary['local_candidates'] == 1
|
||||
assert summary['wecom_users'] == 1
|
||||
assert summary['local_matched'] == 1
|
||||
assert summary['would_update'] == 1
|
||||
assert summary['local_missing'] == 0
|
||||
assert summary['pending_updates'][0]['wecom_userid'] == '21784'
|
||||
|
||||
db.session.refresh(user)
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='26030025',
|
||||
email='26030025@test.local',
|
||||
employee_id='26030025',
|
||||
real_name='sophie',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=oa_rows_for_local_user,
|
||||
):
|
||||
summary = sync_wecom_userids_from_oa(apply=True)
|
||||
|
||||
assert summary['updated'] == 1
|
||||
db.session.refresh(user)
|
||||
assert user.wecom_userid == '21784'
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='missing_oa',
|
||||
email='missing_oa@test.local',
|
||||
employee_id='99999999',
|
||||
real_name='missing',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=[],
|
||||
) as fetch_mock:
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
fetch_mock.assert_called_once_with(['99999999'])
|
||||
assert summary['local_candidates'] == 1
|
||||
assert summary['wecom_users'] == 0
|
||||
assert summary['local_matched'] == 0
|
||||
assert summary['local_missing'] == 1
|
||||
|
||||
"""Tests for OA userInfo_view → wecom_userid sync."""
|
||||
|
||||
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
|
||||
from app.models import User
|
||||
|
||||
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
def oa_rows_for_local_user():
|
||||
|
||||
return [
|
||||
|
||||
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},
|
||||
|
||||
]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='26030025',
|
||||
|
||||
email='26030025@test.local',
|
||||
|
||||
employee_id='26030025',
|
||||
|
||||
real_name='sophie',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=oa_rows_for_local_user,
|
||||
|
||||
) as fetch_mock:
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
|
||||
|
||||
fetch_mock.assert_called_once_with(['26030025'])
|
||||
|
||||
assert summary['local_candidates'] == 1
|
||||
|
||||
assert summary['wecom_users'] == 1
|
||||
|
||||
assert summary['local_matched'] == 1
|
||||
|
||||
assert summary['would_update'] == 1
|
||||
|
||||
assert summary['local_missing'] == 0
|
||||
|
||||
assert summary['pending_updates'][0]['wecom_userid'] == '21784'
|
||||
|
||||
|
||||
|
||||
db.session.refresh(user)
|
||||
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='26030025',
|
||||
|
||||
email='26030025@test.local',
|
||||
|
||||
employee_id='26030025',
|
||||
|
||||
real_name='sophie',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=oa_rows_for_local_user,
|
||||
|
||||
):
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=True)
|
||||
|
||||
|
||||
|
||||
assert summary['updated'] == 1
|
||||
|
||||
db.session.refresh(user)
|
||||
|
||||
assert user.wecom_userid == '21784'
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='missing_oa',
|
||||
|
||||
email='missing_oa@test.local',
|
||||
|
||||
employee_id='99999999',
|
||||
|
||||
real_name='missing',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=[],
|
||||
|
||||
) as fetch_mock:
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
|
||||
|
||||
fetch_mock.assert_called_once_with(['99999999'])
|
||||
|
||||
assert summary['local_candidates'] == 1
|
||||
|
||||
assert summary['wecom_users'] == 0
|
||||
|
||||
assert summary['local_matched'] == 0
|
||||
|
||||
assert summary['local_missing'] == 1
|
||||
|
||||
|
||||
@@ -360,7 +360,7 @@ def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app)
|
||||
|
||||
def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
|
||||
"""textcard 跳转应优先 HTTPS 公网域名,而非内网/端口 WECOM_NOTIFY_BASE_URL。"""
|
||||
from app.services.wecom_notify import _get_notify_base_url
|
||||
from app.services.integrations.wecom.notify import _get_notify_base_url
|
||||
|
||||
with app.app_context():
|
||||
app.config["WECOM_NOTIFY_BASE_URL"] = "http://ait.well-trust.com:8890/"
|
||||
@@ -371,7 +371,7 @@ def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
|
||||
|
||||
def test_get_notify_base_url_falls_back_to_hxops_public_base_url(app):
|
||||
"""未配置 WECOM_PUBLIC 时应回退 HXOPS_PUBLIC_BASE_URL,而非 WECOM_NOTIFY_BASE_URL。"""
|
||||
from app.services.wecom_notify import _get_notify_base_url
|
||||
from app.services.integrations.wecom.notify import _get_notify_base_url
|
||||
|
||||
with app.app_context():
|
||||
app.config["WECOM_PUBLIC_BASE_URL"] = ""
|
||||
@@ -394,19 +394,19 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
|
||||
return {"errcode": 0}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify.send_wecom_textcard_message",
|
||||
"app.services.integrations.wecom.notify.send_wecom_textcard_message",
|
||||
_fake_send_textcard,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify._get_enabled_events",
|
||||
"app.services.integrations.wecom.notify._get_enabled_events",
|
||||
lambda: {"schedule_completed"},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify.upload_wecom_temp_media",
|
||||
"app.services.integrations.wecom.notify.upload_wecom_temp_media",
|
||||
lambda _data, filename: media_uploads.append(filename) or f"media-{len(media_uploads)}",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify.send_wecom_file_message",
|
||||
"app.services.integrations.wecom.notify.send_wecom_file_message",
|
||||
lambda _userid, media_id: file_sends.append(media_id) or {"errcode": 0},
|
||||
)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import pytest
|
||||
from flask import Flask
|
||||
from app import create_app, db
|
||||
from app.models import ChatLog, Agent, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
import json
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -394,7 +394,7 @@ def test_chat_completions_stream_success(client, mocker, mock_agent_query):
|
||||
mock_post.return_value.__enter__.return_value = mock_response
|
||||
|
||||
# Mock DB logging
|
||||
mocker.patch('app.services.dify.DifyService._log_chat')
|
||||
mocker.patch('app.services.integrations.dify.DifyService._log_chat')
|
||||
|
||||
# Setup decorator mocks
|
||||
mock_user = User(id=1, username="test_user")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import base64
|
||||
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
|
||||
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
|
||||
|
||||
|
||||
def test_wecom_aes_roundtrip():
|
||||
|
||||
@@ -24,7 +24,7 @@ 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
|
||||
from app.services.integrations.wecom.notify import _get_access_token # noqa: E402
|
||||
|
||||
|
||||
def _get_userid_by_mobile(mobile: str) -> dict[str, Any]:
|
||||
|
||||
@@ -25,7 +25,7 @@ if str(BACKEND_ROOT) not in sys.path:
|
||||
|
||||
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
|
||||
from app.services.integrations.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]:
|
||||
|
||||
@@ -186,14 +186,14 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||
sent.append((wecom_userid, title, description))
|
||||
return {"errcode": 0}
|
||||
|
||||
monkeypatch.setattr("app.services.wecom_notify.send_wecom_textcard_message", _fake_send)
|
||||
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
|
||||
monkeypatch.setattr(
|
||||
"app.services.wecom_notify._create_audit",
|
||||
"app.services.integrations.wecom.notify._create_audit",
|
||||
lambda *args, **kwargs: SimpleNamespace(
|
||||
jump_url=None, status=None, error_code=None, error_message=None
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr("app.services.wecom_notify._build_jump_url", lambda *args, **kwargs: "https://jump")
|
||||
monkeypatch.setattr("app.services.integrations.wecom.notify._build_jump_url", lambda *args, **kwargs: "https://jump")
|
||||
|
||||
with app.app_context():
|
||||
app.config["WECOM_NOTIFY_ENABLED"] = True
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
| 5 | 指定培训视频:按计划分批推送并标注周次 | 视频按冻结顺序每周推 N 个;已推送视频带「第X周 MM-DD至MM-DD」标签;推过的视频不重复推,直至全部视频推完 |
|
||||
| 6 | 推送过的视频默认勾选且不能取消勾选 | 已推送前缀(游标内)视频 checkbox 禁用,取消勾选请求被忽略 |
|
||||
| 7 | 【发布周任务】仅首次自动推首批 | 新建任务继承历史推送游标,仅当继承后游标为 0(无可继承进度)时按冻结顺序自动推首批 N 个;失败可用【立即新增任务补推】补发/增推 |
|
||||
| 8 | 定时脚本自动更新推送 | 平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(继承游标并自动追加配置新增视频)并推送下一批,无需人工维护 |
|
||||
| 8 | 定时脚本自动更新推送 | 平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(继承游标并自动追加配置新增视频)并推送下一批,无需人工维护;视频库全部推完且配置无新增视频时**暂停滚动**,不创建内容重复的新一期任务,新视频上传后自动恢复 |
|
||||
| 9 | 消息推送规则(企微) | 任务发布即通知;每批推送成功立即通知;已延期(过截止未提交)人员在每批推送成功后立即收到延期提醒 |
|
||||
|
||||
---
|
||||
@@ -65,7 +65,7 @@
|
||||
|
||||
- 两个默认排程由 `ensure_default_lean_training_schedule()` 应用启动时幂等创建([lean_training_schedule_seed.py](../../../backend/app/services/lean_training_schedule_seed.py)),管理员可在排程中心停用或调整。
|
||||
- 每周一 09:00 执行流程(`run_lean_training_video_push`):
|
||||
1. `ensure_current_week_task`:当周任务不存在时,以“严格早于当周”的最近一期已发布任务为模板自动创建(复制视频冻结列表、每周数量、受训对象,**游标继承**最近一期进度),并把配置中新增上传、尚未冻结的视频按上传时间倒序**自动追加到冻结列表末尾**(前缀与游标不变,每周自动计划从断点继续推新视频),状态直接为已发布,并立即发送任务发布通知;
|
||||
1. `ensure_current_week_task`:当周任务不存在时,以“严格早于当周”的最近一期已发布任务为模板自动创建(复制视频冻结列表、每周数量、受训对象,**游标继承**最近一期进度),并把配置中新增上传、尚未冻结的视频按上传时间倒序**自动追加到冻结列表末尾**(前缀与游标不变,每周自动计划从断点继续推新视频),状态直接为已发布,并立即发送任务发布通知;模板视频已全部推完且配置无新增视频时暂停滚动(不创建新一期,返回 None),待新视频上传后自动恢复;
|
||||
2. `push_lean_training_videos(trigger="schedule")`:按游标推下一批 N 个视频并发企微通知,写推送日志;
|
||||
3. 批次推送成功后立即对"已延期"人员发送延期提醒(见 §4)。
|
||||
- 系统内尚无任何已发布任务模板时排程无事可做,等待管理员首次手动发布。
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训配置管理 | 已实现 | `TrainingConfigResource` 增加 `training_level`;管理端按公司级、部门级、班组级卡片独立增删资料;知识库候选仅允许“员工培训”分组内未删除文档的当前版本;员工端按 `safetyStage` 动态展示当前级别资料;培训资料区直接上传的视频列表超过 3 条时默认收起(仅展示前 3 条),底部可展开查看全部/收起,切换培训类型恢复收起、上传新视频后自动展开 |
|
||||
| 精益培训对象化任务与提醒 | 已实现 | HR 按系统角色或指定用户(并集)发布精益周任务;任务、看板和提醒只处理冻结对象,首次发布与定向催学均复用企微提醒审计幂等去重。学员端“精益管理”按时间树展示全部已发布任务(按任务周期倒序、最新在上),每期任务带状态徽章(进行中/已延期/已完成,由服务端按截止时间与完成记录判定)、任务周期区间与视频缩略图(点击弹窗播放,须播放到结尾才判定观看完成并由服务端持久化,提前关闭或拖拽跳过不计);提交学习感悟前校验:未观看全部已推送视频或感悟字数不达标时拦截并友好提示;任务"已完成"仅在感悟提交后落定。 |
|
||||
| 精益周任务规则化推送 | 已实现 | 任务周(周一)与截止时间默认按当周计算且**支持修改**(可指定任意自然周与截止时刻,须为周一且截止不早于所选周周一;修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务);培训视频列表分页展示(4 条/页),已推送视频默认勾选、不可取消并带"第X周 MM-DD至MM-DD"周次标签,推过的视频不重复推直至全部推完(跨任务按已推送前缀并集去重,手动新建下一期任务同样继承历史推送游标、绝不从 0 重推首批);【发布周任务】对所选周任务发布并仅当继承游标为 0 时自动推首批,【立即新增任务补推】按游标对所选周任务增推(点击时若表单勾选/规则与已保存任务不一致,自动先保存再推送,避免按旧冻结清单推送误报全部推完);平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(模板取严格早于当周的最近一期,游标继承进度,并自动追加配置新增视频到冻结列表末尾,前缀与游标不变、从断点只推新视频)并推送下一批,无需人工维护;每批推送成功后立即向受训人员发送企微通知,并对"已延期"(过截止未提交)人员立即发送延期提醒(event_key 幂等防重);学员端任务期号统一采用后端 week_index 口径。规则手册见 [docs/features/training/精益管理周任务规则手册.md](features/training/精益管理周任务规则手册.md) |
|
||||
| 精益周任务规则化推送 | 已实现 | 任务周(周一)与截止时间默认按当周计算且**支持修改**(可指定任意自然周与截止时刻,须为周一且截止不早于所选周周一;修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务);培训视频列表分页展示(4 条/页),已推送视频默认勾选、不可取消并带"第X周 MM-DD至MM-DD"周次标签,推过的视频不重复推直至全部推完(跨任务按已推送前缀并集去重,手动新建下一期任务同样继承历史推送游标、绝不从 0 重推首批);【发布周任务】对所选周任务发布并仅当继承游标为 0 时自动推首批,【立即新增任务补推】按游标对所选周任务增推(点击时若表单勾选/规则与已保存任务不一致,自动先保存再推送,避免按旧冻结清单推送误报全部推完);平台排程每周一 09:00(Asia/Shanghai)自动滚动创建当周任务(模板取严格早于当周的最近一期,游标继承进度,并自动追加配置新增视频到冻结列表末尾,前缀与游标不变、从断点只推新视频;视频库全部推完且无新增视频时暂停滚动、不再创建内容重复的新一期,新视频上传后自动恢复)并推送下一批,无需人工维护;每批推送成功后立即向受训人员发送企微通知,并对"已延期"(过截止未提交)人员立即发送延期提醒(event_key 幂等防重);学员端任务期号统一采用后端 week_index 口径。规则手册见 [docs/features/training/精益管理周任务规则手册.md](features/training/精益管理周任务规则手册.md) |
|
||||
| 培训分享入口 | 前端已实现 | 员工培训页培训类型页签行右侧新增分享按钮,仅具备 `training_hr_manage`(培训管理)权限的用户可见;点击弹出分享弹窗,支持复制链接或下载二维码,链接指向 `/chat/<agentId>?training_type=<当前培训类型>` 深链,接收者点击或扫码后在登录页登录,登录成功自动回跳员工培训页并定位到对应培训类型(如“出国规章培训”);文案覆盖 zh-CN/zh-TW/en/th 四语言 |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见[docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
**合并前自检**:`pytest backend/tests` 通过;改表结构须配套 Alembic 迁移;对外 URL 保持不变。
|
||||
|
||||
**当前进度**:Wave 1 基础设施已完成(`register_blueprints`、`extensions.py`、`core/*` 权威实现、根 shim 已删除、`AppError` envelope 统一、Tool API 保留 Dify 格式);Wave 3 已完成(`admin/`、`kb/`、`user/`、`chat/` 均已迁包;用户认证按本地密码、Casdoor、企微与密码重置拆分,共享认证操作收口至 `auth_support.py`;Chat 的 SSE、会话、预览、上传与反馈均已按职责拆分);Wave 4 的排程迁出 Web 已完成(手动/Cron 统一入 `jobs`,由 `hxops-schedule-worker` 独立执行)。
|
||||
**当前进度**:Wave 1–3 已完成;Wave 4 已完成(排程迁出 Web;`integrations/` 真迁移;根路径兼容 shim 已删除;`FILE_CHECK_RUN` / `WECOM_DIRECTORY_SYNC` 由 schedule worker 执行;`services/` 不再直接 `import flask.request`,HTTP 读取收口到 `core/http_context.py`)。残留:固资快照线程仍在 Web 进程(另行治理)。
|
||||
|
||||
---
|
||||
|
||||
@@ -514,9 +514,9 @@ from app.models import User, Agent # Wave 1 后仍保持此入口
|
||||
```text
|
||||
Wave 0 骨架建立 ✅ 目录 + 占位(行为不变)
|
||||
Wave 1 基础设施 ✅ register_blueprints / extensions / core / AppError / models
|
||||
Wave 2 任务层 jobs/ 接 KB worker
|
||||
Wave 2 任务层 ✅ jobs/ 接 KB / shipping / schedule 等 worker
|
||||
Wave 3 拆 god 文件 admin ✅ → user ✅ → chat ✅ → kb ✅
|
||||
Wave 4 集成收敛 scheduler ✅ 迁出 web;integrations/ 真迁移待完成
|
||||
Wave 4 集成收敛 ✅ scheduler 迁出 web;integrations/ 真迁移;根路径 shim 已删除;file-check / 企微通讯录入队
|
||||
```
|
||||
|
||||
### 9.1 Wave 1 任务清单
|
||||
@@ -545,8 +545,8 @@ Wave 4 集成收敛 scheduler ✅ 迁出 web;integrations/ 真迁移
|
||||
|
||||
- [ ] 无 >800 行业务源文件(`edkb_system/` 除外)
|
||||
- [x] API 统一 `AppError`(Tool API 除外,见 `docs/convention/error_handling.md` §2.5)
|
||||
- [ ] `services/` 无 `flask.request`
|
||||
- [ ] 后台任务统一经 `jobs/`
|
||||
- [x] `services/` 无 `flask.request`(HTTP 头/Host 经 `app.core.http_context`)
|
||||
- [x] 后台任务统一经 `jobs/`(file-check、企微通讯录同步已入队;固资快照线程另行治理)
|
||||
- [x] web 进程无 scheduler thread(排程由 `hxops-schedule-worker` 执行;固资快照线程另行治理)
|
||||
|
||||
---
|
||||
|
||||
@@ -9,7 +9,7 @@ sys.path.append(os.path.join(os.getcwd(), 'backend'))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
app = create_app()
|
||||
|
||||
|
||||
Reference in new issue
Block a user