191 lines
6.9 KiB
Python
191 lines
6.9 KiB
Python
"""
|
|
backend/app/services/feedback_notify.py
|
|
|
|
用途:将用户新提交的通用意见反馈即时推送到企业微信群,方便处理人第一时间跟进。
|
|
依赖:Flask current_app、requests、GeneralFeedback/User 模型。
|
|
逻辑:api/user.py 先保存 GeneralFeedback,再以 best-effort 方式调用本服务;
|
|
通知失败只写日志,不回滚反馈提交,也不影响用户侧响应。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timedelta, timezone
|
|
from urllib.parse import urlencode
|
|
|
|
import requests
|
|
from flask import current_app
|
|
|
|
from app.models import GeneralFeedback, User
|
|
|
|
|
|
def _get_feedback_notify_base_url() -> str:
|
|
"""
|
|
解析反馈通知中“打开后台报表”链接使用的公网基地址。
|
|
|
|
核心逻辑:优先读取反馈通知专用配置;未配置时复用已有企微通知或平台公网地址,
|
|
避免不同环境重复维护同一类外部访问域名。
|
|
|
|
Returns:
|
|
str: 去掉末尾斜杠的公网基地址;所有配置都缺失时返回空字符串。
|
|
"""
|
|
for key in (
|
|
'WECOM_FEEDBACK_NOTIFY_BASE_URL',
|
|
'WECOM_NOTIFY_BASE_URL',
|
|
'WECOM_PUBLIC_BASE_URL',
|
|
'PUBLIC_BASE_URL',
|
|
):
|
|
raw = current_app.config.get(key)
|
|
if isinstance(raw, str) and raw.strip():
|
|
return raw.strip().rstrip('/')
|
|
return ''
|
|
|
|
|
|
def _truncate_text(value: str | None, limit: int) -> str:
|
|
"""
|
|
截断过长的反馈内容,避免企业微信 markdown 消息超长或刷屏。
|
|
|
|
Args:
|
|
value: 用户提交的原始反馈文本或模型字段文本。
|
|
limit: 最多保留的字符数,必须为正整数。
|
|
|
|
Returns:
|
|
str: 截断后的文本;超过限制时追加省略号。
|
|
"""
|
|
text = (value or '').strip()
|
|
if len(text) <= limit:
|
|
return text
|
|
return f'{text[: max(limit - 3, 0)]}...'
|
|
|
|
|
|
def _format_created_at(value: datetime | None) -> str:
|
|
"""
|
|
将反馈创建时间格式化为企业微信群里可读的北京时间文本。
|
|
|
|
Args:
|
|
value: 当前 SQLAlchemy 模型保存的 UTC datetime;允许为空。
|
|
|
|
Returns:
|
|
str: 形如 YYYY-MM-DD HH:MM:SS 的 Asia/Shanghai 时间;缺失时返回空字符串。
|
|
"""
|
|
if not value:
|
|
return ''
|
|
if value.tzinfo is None:
|
|
value = value.replace(tzinfo=timezone.utc)
|
|
return value.astimezone(timezone(timedelta(hours=8))).strftime('%Y-%m-%d %H:%M:%S')
|
|
|
|
|
|
def build_feedback_report_url(feedback_id: int) -> str:
|
|
"""
|
|
构造后台报表链接,帮助处理人从群消息直接定位到对应反馈。
|
|
|
|
Args:
|
|
feedback_id: general_feedbacks 主键,必须是正整数。
|
|
|
|
Returns:
|
|
str: 配置公网基地址时返回完整后台报表 URL;未配置时返回空字符串,
|
|
让通知消息仍可发送,只是不带跳转链接。
|
|
"""
|
|
base_url = _get_feedback_notify_base_url()
|
|
if not base_url or not feedback_id:
|
|
return ''
|
|
return f'{base_url}/admin/reports/general_feedbacks?{urlencode({"id": feedback_id})}'
|
|
|
|
|
|
def build_feedback_markdown(feedback: GeneralFeedback, user: User | None) -> str:
|
|
"""
|
|
组装企业微信群机器人 markdown 消息正文。
|
|
|
|
Args:
|
|
feedback: 已入库的 GeneralFeedback 记录,调用前应已有 id。
|
|
user: 提交反馈的当前用户;测试或异常兜底场景允许为空。
|
|
|
|
Returns:
|
|
str: 企业微信群机器人 webhook 可接受的 markdown 文本。
|
|
"""
|
|
display_name = (
|
|
(getattr(user, 'real_name', None) or '').strip()
|
|
or (getattr(user, 'username', None) or '').strip()
|
|
or feedback.username
|
|
)
|
|
username = (getattr(user, 'username', None) or feedback.username or '').strip()
|
|
employee_id = (getattr(user, 'employee_id', None) or '').strip()
|
|
reporter_parts = [display_name]
|
|
if username and username != display_name:
|
|
reporter_parts.append(username)
|
|
if employee_id:
|
|
reporter_parts.append(f'工号 {employee_id}')
|
|
reporter = ' / '.join([part for part in reporter_parts if part])
|
|
|
|
content = _truncate_text(feedback.content, 900)
|
|
report_url = build_feedback_report_url(feedback.id)
|
|
lines = [
|
|
'### HXOPS 新意见反馈',
|
|
f'>反馈编号:{feedback.id}',
|
|
f'>反馈类型:{feedback.feedback_type}',
|
|
f'>反馈模块:{feedback.feedback_module}',
|
|
f'>提交人:{reporter or "-"}',
|
|
f'>提交时间:{_format_created_at(feedback.created_at) or "-"}',
|
|
]
|
|
if feedback.source_page:
|
|
lines.append(f'>来源页面:{feedback.source_page}')
|
|
if feedback.chat_log_id:
|
|
lines.append(f'>关联对话:{feedback.chat_log_id}')
|
|
# 附图行:仅在有截图时展示数量,置于「反馈内容」之前,便于处理人先感知附件再读正文
|
|
image_count = len(feedback.images or [])
|
|
if image_count:
|
|
lines.append(f'>附图:{image_count} 张')
|
|
lines.extend(['', '**反馈内容:**', content or '-'])
|
|
if report_url:
|
|
lines.extend(['', f'[打开后台报表]({report_url})'])
|
|
return '\n'.join(lines)
|
|
|
|
|
|
def send_feedback_group_notification(feedback: GeneralFeedback, user: User | None) -> dict:
|
|
"""
|
|
发送通用意见反馈的企业微信群机器人通知。
|
|
|
|
触发时机:/api/user/feedback 成功提交 GeneralFeedback 后立即调用,
|
|
让处理人尽量实时看到用户反馈。
|
|
|
|
Args:
|
|
feedback: 需要推送的已入库反馈记录。
|
|
user: 提交人信息,用于在消息中展示姓名、账号和工号。
|
|
|
|
Returns:
|
|
dict: 包含 ok/skipped/reason 等字段,供路由记录日志。函数内部吞掉发送异常,
|
|
因为通知失败不能影响反馈入库和用户侧提交结果。
|
|
"""
|
|
if not current_app.config.get('WECOM_FEEDBACK_NOTIFY_ENABLED', True):
|
|
return {'ok': False, 'skipped': True, 'reason': 'notify_disabled'}
|
|
|
|
webhook = (current_app.config.get('WECOM_FEEDBACK_BOT_WEBHOOK') or '').strip()
|
|
if not webhook:
|
|
return {'ok': False, 'skipped': True, 'reason': 'webhook_unconfigured'}
|
|
|
|
payload = {
|
|
'msgtype': 'markdown',
|
|
'markdown': {
|
|
'content': build_feedback_markdown(feedback, user),
|
|
},
|
|
}
|
|
try:
|
|
response = requests.post(webhook, json=payload, timeout=3)
|
|
data = response.json()
|
|
except Exception as exc:
|
|
current_app.logger.warning(
|
|
'[feedback-notify] send exception feedback_id=%s err=%s',
|
|
getattr(feedback, 'id', None),
|
|
exc,
|
|
)
|
|
return {'ok': False, 'reason': 'exception'}
|
|
|
|
if data.get('errcode') == 0:
|
|
return {'ok': True}
|
|
|
|
current_app.logger.warning(
|
|
'[feedback-notify] send failed feedback_id=%s errcode=%s errmsg=%s',
|
|
getattr(feedback, 'id', None),
|
|
data.get('errcode'),
|
|
str(data.get('errmsg', ''))[:255],
|
|
)
|
|
return {'ok': False, 'reason': 'send_failed', 'raw': data}
|