diff --git a/.env.shared b/.env.shared index ea5a0890..358740d3 100644 --- a/.env.shared +++ b/.env.shared @@ -71,6 +71,10 @@ WECOM_PUBLIC_BASE_URL= WECOM_NOTIFY_ENABLED=true WECOM_NOTIFY_BASE_URL= WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset +WECOM_FEEDBACK_NOTIFY_ENABLED=true +WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881 +# 企业微信群机器人 webhook,按环境写入 .env. 或部署平台变量;不要提交真实 URL。 +WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bdb65cf6-e537-44b2-a10b-d826b15f4498 # Common integration defaults diff --git a/backend/app/api/user.py b/backend/app/api/user.py index 5e4ce6fd..05c13651 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -1,6 +1,7 @@ from flask import Blueprint, request, jsonify, current_app from app import db from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog +from app.services.feedback_notify import send_feedback_group_notification 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.auth_jwt import get_current_user as _auth_current_user @@ -1608,6 +1609,15 @@ def submit_general_feedback(): row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id) db.session.add(row) db.session.commit() + notify_result = send_feedback_group_notification(row, user) + if notify_result.get('ok'): + current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id) + elif not notify_result.get('skipped'): + current_app.logger.warning( + '[feedback] group notification failed feedback_id=%s reason=%s', + row.id, + notify_result.get('reason'), + ) return jsonify({'status': 'ok', 'id': row.id}) @user_bp.route('/home', methods=['GET']) diff --git a/backend/app/config.py b/backend/app/config.py index adf61791..57f5c194 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -207,6 +207,9 @@ class Config: WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true' WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL') WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset') + WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true' + WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL') + WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK') # JWT/Casdoor auth configuration (phase-1 compatible rollout) AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true' diff --git a/backend/app/env_persistence.py b/backend/app/env_persistence.py index d974cc0c..21e6c0fb 100644 --- a/backend/app/env_persistence.py +++ b/backend/app/env_persistence.py @@ -42,6 +42,7 @@ WECOM_BOOL_KEYS = { 'WECOM_AUTO_CREATE_USER', 'WECOM_MOBILE_NORMALIZE', 'WECOM_NOTIFY_ENABLED', + 'WECOM_FEEDBACK_NOTIFY_ENABLED', } diff --git a/backend/app/services/feedback_notify.py b/backend/app/services/feedback_notify.py new file mode 100644 index 00000000..4b38eb01 --- /dev/null +++ b/backend/app/services/feedback_notify.py @@ -0,0 +1,186 @@ +""" +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}') + 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} diff --git a/docs/funclist.md b/docs/funclist.md index 23241548..b5adf5c9 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -1,5 +1,12 @@ # 智能HR请假管理功能清单 +## 通用意见反馈 + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 | +| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 | + ## 1. 功能总览 | 模块 | 功能项 | 状态 | 优先级 | diff --git a/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts b/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts index ae1a7b5e..f0dadbd0 100644 --- a/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts +++ b/frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts @@ -15,6 +15,7 @@ import { import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage'; import { buildOffsetPageButtons } from '@/shared/composables/useOffsetPagination'; import { useMessage } from '@/shared/composables/useMessage'; +import { formatLocalDateTime } from '@/shared/utils/dateTime'; import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules'; import type { ChatLogsLayoutPref, @@ -561,27 +562,7 @@ const getTranslatedFeedbackValue = (group: 'types' | 'modules' | 'pages', value: const formatReportDateTime = (value: any) => { if (value === null || value === undefined || value === '') return value; - const d = new Date(value); - if (Number.isNaN(d.getTime())) return value; - - const localeMap: Record = { - 'zh-CN': 'zh-CN', - 'zh-TW': 'zh-TW', - en: 'en-US', - th: 'th-TH', - }; - const lang = resolveReportLang(); - const localeName = localeMap[lang] || 'en-US'; - - return new Intl.DateTimeFormat(localeName, { - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - hour12: false, - }).format(d); + return formatLocalDateTime(String(value)); }; const getReportCellValue = (row: any, key: string) => {