feat: 企业微信提醒增加“AI智能体”提示
This commit is contained in:
1 parent
f269df7941
commit
26d213c05b
8 files changed
+289
-15
No files matched your search
@@ -4,18 +4,20 @@ backend/app/api/workspace/voucher_check.py
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
批次明细可按 result 与 invoice_no 筛选。
|
||||
批次明细可按 result 与 invoice_no 筛选。企微记录里的 Excel 走本模块下载,不走排程通知人权限。
|
||||
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, request
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import Agent
|
||||
from app.models import Agent, ScheduleRun, VoucherCheckRun
|
||||
from app.services.voucher_check import notify_config_service, query_service
|
||||
|
||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||
@@ -179,6 +181,33 @@ def workspace_voucher_notifications():
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route(
|
||||
"/accounting-voucher-check/schedule-runs/<int:schedule_run_id>/excel",
|
||||
methods=["GET"],
|
||||
)
|
||||
def workspace_voucher_schedule_excel(schedule_run_id: int):
|
||||
"""
|
||||
下载企微发送记录对应的检核结果 Excel。
|
||||
核心逻辑:能看发送记录的人即可下载。只放行已挂到立账凭证批次上的 ScheduleRun,不按排程负责人或通知人拦截。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 该排程记录不是立账凭证批次,或还没有生成 Excel。
|
||||
"""
|
||||
_require_voucher_check_access()
|
||||
engine = VoucherCheckRun.query.filter_by(schedule_run_id=schedule_run_id).first()
|
||||
if engine is None:
|
||||
raise NotFoundError("立账凭证检核批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||
run = ScheduleRun.query.get(schedule_run_id)
|
||||
if run is None or not run.excel_file_data:
|
||||
raise NotFoundError("检核结果 Excel 不存在", code="VOUCHER_CHECK.EXCEL_NOT_FOUND")
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or "voucher_check.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/app/services/integrations/wecom/notify.py
|
||||
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
||||
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
||||
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
||||
文本卡片标题默认加上「AI智能体」来源;密码重置和权限变更保持原标题。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,6 +25,17 @@ _TOKEN_CACHE = {
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
# 企微 textcard 没有发送者栏,用来源前缀让收件人看出是 AI 智能体推送。
|
||||
_AGENT_SOURCE_PREFIX = 'AI智能体 · '
|
||||
_TEXT_CARD_TITLE_LIMIT = 120
|
||||
# 账号与权限通知不是智能体推送,标题不加来源。
|
||||
_NO_AGENT_SOURCE_EVENTS = frozenset({
|
||||
'password_reset',
|
||||
'permission_batch_updated',
|
||||
'permission_request_approved',
|
||||
'permission_request_rejected',
|
||||
})
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
@@ -141,19 +153,54 @@ def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _with_agent_source_title(title: str, *, enabled: bool = True) -> str:
|
||||
"""
|
||||
给企微 textcard 标题加上「AI智能体」来源,并限制在 120 字以内。
|
||||
|
||||
核心逻辑:前缀放在最前,超长时截断业务标题,避免来源被切掉。
|
||||
已带相同前缀时不重复添加。enabled 为 False 时只做长度截断。
|
||||
Args:
|
||||
title: 业务侧传入的卡片标题。
|
||||
enabled: 为 False 时保持原标题,用于密码重置和权限变更。
|
||||
Returns:
|
||||
实际发给企业微信的标题。
|
||||
"""
|
||||
text = (title or '').strip()
|
||||
if not enabled:
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
if text.startswith(_AGENT_SOURCE_PREFIX):
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
return f'{_AGENT_SOURCE_PREFIX}{text}'[:_TEXT_CARD_TITLE_LIMIT]
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
*,
|
||||
with_agent_source: bool = True,
|
||||
) -> dict:
|
||||
"""
|
||||
发送企业微信文本卡片。
|
||||
|
||||
核心逻辑:默认在标题前加上「AI智能体」来源。审计记录仍保存调用方传入的业务标题。
|
||||
Args:
|
||||
wecom_userid: 企业微信 userid。
|
||||
title: 业务标题。
|
||||
description: 卡片正文。
|
||||
jump_url: 点击跳转地址。
|
||||
with_agent_source: 为 False 时标题不加来源。
|
||||
Returns:
|
||||
企业微信 message/send 的 JSON 响应。
|
||||
"""
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'title': _with_agent_source_title(title, enabled=with_agent_source),
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
@@ -200,6 +247,7 @@ def send_wecom_event_message(
|
||||
|
||||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||||
标题在发送时加上「AI智能体」来源;密码重置和权限变更不加。审计 title 保持业务标题。
|
||||
Args:
|
||||
event_type: 通知事件开关名。
|
||||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||||
@@ -239,7 +287,13 @@ def send_wecom_event_message(
|
||||
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)
|
||||
data = send_wecom_textcard_message(
|
||||
target_userid,
|
||||
title,
|
||||
content,
|
||||
final_jump_url,
|
||||
with_agent_source=event_type not in _NO_AGENT_SOURCE_EVENTS,
|
||||
)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/services/voucher_check/notification.py
|
||||
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
||||
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
||||
卡片标题为「销售开票附件缺件」,不写业务方代号和批次号;
|
||||
卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号;
|
||||
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
||||
"""
|
||||
|
||||
@@ -47,7 +47,7 @@ def _missing_type_line(item: dict[str, Any]) -> str:
|
||||
|
||||
def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[str, str]:
|
||||
"""
|
||||
组装销售开票附件缺件 textcard。
|
||||
组装销售开票附件缺件 textcard,标题为「销售开票附件缺件提醒」。
|
||||
核心逻辑:用纯文本而不是 div 着色。企微 description 约 512 字节,
|
||||
颜色标签会挤掉后面的缺件类型。
|
||||
|
||||
@@ -62,7 +62,7 @@ def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[s
|
||||
"请尽快补齐。完整清单见详情里的 Excel。",
|
||||
]
|
||||
)
|
||||
return "销售开票附件缺件", body
|
||||
return "销售开票附件缺件提醒", body
|
||||
|
||||
|
||||
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
||||
|
||||
@@ -3,13 +3,15 @@ backend/tests/test_voucher_check_permissions.py
|
||||
|
||||
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表,但不能触发强制重检、也不能改通知配置。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表并下载企微记录 Excel,但不能触发强制重检、也不能改通知配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask, User, VoucherCheckRun
|
||||
|
||||
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
@@ -176,3 +178,63 @@ def test_voucher_check_notify_config_requires_admin(client, app):
|
||||
)
|
||||
assert put_res.status_code == 403
|
||||
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
|
||||
def test_voucher_check_excel_download_uses_agent_access_not_schedule_notify(client, app):
|
||||
"""企微发送记录的 Excel 按立账凭证访问权下载,不要求是排程负责人或通知人。"""
|
||||
payload = b'voucher-excel'
|
||||
with app.app_context():
|
||||
owner = _create_user(username='vc_excel_owner')
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_excel_viewer'))
|
||||
denied = _create_user(username='vc_excel_denied')
|
||||
task = ScheduleTask(
|
||||
schedule_no='VC-EXCEL-1',
|
||||
name='立账凭证周检',
|
||||
owner_user_id=owner.id,
|
||||
cron_expr='0 6 * * 2',
|
||||
notify_user_ids_json=[],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
schedule_run = ScheduleRun(
|
||||
run_no='RUN-VC-EXCEL-1',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
excel_file_data=payload,
|
||||
excel_file_name='voucher_check.xlsx',
|
||||
excel_file_size=len(payload),
|
||||
)
|
||||
db.session.add(schedule_run)
|
||||
db.session.flush()
|
||||
db.session.add(VoucherCheckRun(
|
||||
id=88001,
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no='RUN-VC-EXCEL-1',
|
||||
profile_code='sales',
|
||||
profile_version='1',
|
||||
profile_snapshot_json={},
|
||||
period_month=date(2026, 9, 1),
|
||||
mode='incremental',
|
||||
status='success',
|
||||
))
|
||||
db.session.commit()
|
||||
schedule_run_id = schedule_run.id
|
||||
granted_id = granted.id
|
||||
denied_id = denied.id
|
||||
|
||||
granted_headers = {'X-User-Id': str(granted_id), 'X-Username': 'vc_excel_viewer'}
|
||||
url = f'/api/workspace/accounting-voucher-check/schedule-runs/{schedule_run_id}/excel'
|
||||
ok_res = client.get(url, headers=granted_headers)
|
||||
# 关键断言:不是排程通知人时,立账凭证授权用户仍能拿到 Excel 正文。
|
||||
assert ok_res.status_code == 200
|
||||
assert ok_res.data == payload
|
||||
|
||||
denied_headers = {'X-User-Id': str(denied_id), 'X-Username': 'vc_excel_denied'}
|
||||
denied_res = client.get(url, headers=denied_headers)
|
||||
assert denied_res.status_code == 403
|
||||
assert _json_error(denied_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
legacy = client.get(f'/api/workspace/schedule-runs/{schedule_run_id}/excel', headers=granted_headers)
|
||||
# 关键断言:旧排程下载口仍只认负责人/通知人,企微记录不能再走这条。
|
||||
assert legacy.status_code == 403
|
||||
assert _json_error(legacy)['code'] == 'AUTH.FORBIDDEN'
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
tests/test_wecom_textcard_source.py
|
||||
|
||||
用途:断言企微 textcard 标题带来源,以及账号类通知不加来源。
|
||||
依赖:app fixture、integrations.wecom.notify。
|
||||
逻辑:直接调用标题函数与发送出口,不经过具体业务模块。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.integrations.wecom.notify import (
|
||||
_with_agent_source_title,
|
||||
send_wecom_event_message,
|
||||
send_wecom_textcard_message,
|
||||
)
|
||||
|
||||
|
||||
def test_agent_source_prefix_stays_when_title_is_truncated():
|
||||
"""超长业务标题截断后,来源前缀仍完整留在最前面。"""
|
||||
title = _with_agent_source_title('缺' * 200)
|
||||
# [断言意图] 前缀不被 120 字上限切掉,业务标题从末尾被截断。
|
||||
assert title.startswith('AI智能体 · ')
|
||||
assert len(title) == 120
|
||||
assert title == f"AI智能体 · {'缺' * 112}"
|
||||
|
||||
|
||||
def test_agent_source_prefix_is_not_repeated():
|
||||
"""已经带来源的标题不再加第二次。"""
|
||||
once = _with_agent_source_title('精益管理培训逾期提醒')
|
||||
twice = _with_agent_source_title(once)
|
||||
# [断言意图] 重复经过发送出口时标题保持单层来源。
|
||||
assert once == 'AI智能体 · 精益管理培训逾期提醒'
|
||||
assert twice == once
|
||||
|
||||
|
||||
def test_textcard_payload_uses_agent_source_title(app, monkeypatch):
|
||||
"""实际发给企业微信的 textcard.title 带来源,调用方传入的仍是业务标题。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_post(_url, params=None, json=None, timeout=None):
|
||||
captured['json'] = json
|
||||
|
||||
class _Resp:
|
||||
def json(self):
|
||||
return {'errcode': 0}
|
||||
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify._get_access_token',
|
||||
lambda: 'token',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify.requests.post',
|
||||
_fake_post,
|
||||
)
|
||||
with app.app_context():
|
||||
app.config['WECOM_AGENT_ID'] = '1000002'
|
||||
send_wecom_textcard_message(
|
||||
'wx-user',
|
||||
'销售开票附件缺件提醒',
|
||||
'正文',
|
||||
'https://example.com/detail',
|
||||
)
|
||||
# [断言意图] 企微载荷标题带来源,正文和按钮保持原样。
|
||||
assert captured['json']['textcard']['title'] == 'AI智能体 · 销售开票附件缺件提醒'
|
||||
assert captured['json']['textcard']['description'] == '正文'
|
||||
assert captured['json']['textcard']['btntxt'] == '查看详情'
|
||||
|
||||
|
||||
def test_account_events_keep_business_title(app, monkeypatch):
|
||||
"""密码重置和权限变更不加来源;业务提醒仍然加上。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_send(_userid, title, _description, _jump_url, *, with_agent_source=True):
|
||||
captured['title'] = title
|
||||
captured['with_agent_source'] = with_agent_source
|
||||
return {'errcode': 0}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify.send_wecom_textcard_message',
|
||||
_fake_send,
|
||||
)
|
||||
with app.app_context():
|
||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
||||
app.config['WECOM_NOTIFY_EVENTS'] = (
|
||||
'password_reset,permission_request_approved,lean_training_overdue'
|
||||
)
|
||||
user = User(
|
||||
username='source-user',
|
||||
email='source@example.com',
|
||||
role='user',
|
||||
wecom_userid='wx-source',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='password_reset',
|
||||
user=user,
|
||||
title='和信AI智能工作台 密码重置',
|
||||
content='请重置密码',
|
||||
jump_url='https://example.com/reset',
|
||||
)
|
||||
# [断言意图] 密码重置不是智能体推送,发送出口关闭来源前缀。
|
||||
assert captured['with_agent_source'] is False
|
||||
assert captured['title'] == '和信AI智能工作台 密码重置'
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_approved',
|
||||
user=user,
|
||||
title='权限申请已通过',
|
||||
content='已通过',
|
||||
)
|
||||
# [断言意图] 权限变更与密码重置同一排除名单。
|
||||
assert captured['with_agent_source'] is False
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='lean_training_overdue',
|
||||
user=user,
|
||||
title='精益管理培训逾期提醒',
|
||||
content='请完成学习',
|
||||
)
|
||||
# [断言意图] 业务提醒仍把来源交给 textcard 出口添加。
|
||||
assert captured['with_agent_source'] is True
|
||||
assert captured['title'] == '精益管理培训逾期提醒'
|
||||
@@ -294,7 +294,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||
po_title, po_body = next((item[1], item[2]) for item in sent if item[0] == "wx-po-recv")
|
||||
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
||||
# 关键断言:卡片面向销售开票附件,不暴露业务方代号和批次号。
|
||||
assert po_title == "销售开票附件缺件"
|
||||
assert po_title == "销售开票附件缺件提醒"
|
||||
assert "2026年8月" in po_body
|
||||
assert "缺 2 份,涉及 1 张发票" in po_body
|
||||
assert "业务方" not in po_body
|
||||
|
||||
@@ -244,7 +244,7 @@ flowchart TD
|
||||
| -------- | ------------------------------------------------------------------------------------------------------- |
|
||||
| 触发 | 本批存在必检文件缺件 |
|
||||
| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 |
|
||||
| 内容 | 标题为「销售开票附件缺件」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示到详情 Excel 补齐。不写业务方代号和批次号 |
|
||||
| 内容 | 标题为「销售开票附件缺件提醒」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示到详情 Excel 补齐。不写业务方代号和批次号 |
|
||||
| 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 |
|
||||
| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 |
|
||||
| 技术失败 | 不作为缺件通知;按排程通知人单独告警 |
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 用途:工作台立账凭证检核任务列表、最近一次检核、批次明细、企微发送记录、通知配置与强制重检 API 客户端。
|
||||
* 依赖:@/shared/api/client、getAuthHeaders。
|
||||
* 逻辑:AccountingVoucherCheckView / DetailView / VoucherCheckNotifyConfigPanel 调用;
|
||||
* 对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。
|
||||
* 对应 /api/workspace/accounting-voucher-check/*,企微记录 Excel 也走该前缀。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
@@ -198,11 +198,15 @@ export function listVoucherCheckNotifications(params?: {
|
||||
|
||||
/**
|
||||
* 下载该排程批次的检核结果 Excel。
|
||||
* 核心逻辑:走立账凭证自己的下载接口,能看企微发送记录就能下,不要求是排程通知人。
|
||||
* @param scheduleRunId - ScheduleRun.id
|
||||
* @param filename - 回退文件名(无 Content-Disposition 时使用)
|
||||
*/
|
||||
export async function downloadVoucherCheckExcel(scheduleRunId: number, filename?: string | null) {
|
||||
const res = await fetch(`/api/workspace/schedule-runs/${scheduleRunId}/excel`, { headers: getAuthHeaders() });
|
||||
const res = await fetch(
|
||||
`/api/workspace/accounting-voucher-check/schedule-runs/${scheduleRunId}/excel`,
|
||||
{ headers: getAuthHeaders() },
|
||||
);
|
||||
if (!res.ok) {
|
||||
throw new Error('excel');
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user