diff --git a/wechat-miniprogram/api/ai.js b/wechat-miniprogram/api/ai.js index 4a09392..4afa455 100644 --- a/wechat-miniprogram/api/ai.js +++ b/wechat-miniprogram/api/ai.js @@ -38,6 +38,15 @@ const refreshAIRecommendations = (activityId) => { return del(`/ai/recommendations/${activityId}`); }; +/** + * 活动主题分析(拆约推荐板块·组织者入口) + * @param {string} activityId - 活动 ID + * @returns {Promise} + */ +const getThemeAnalysis = (activityId) => { + return post(`/ai/theme-analysis/${activityId}`, {}, { timeout: 30000, showLoading: false }); +}; + /** * 合作可能性分析 * @param {string} targetUserId - 目标用户 ID @@ -53,4 +62,5 @@ module.exports = { analyzeActivityMatch, refreshAIRecommendations, getCollaborationAnalysis, + getThemeAnalysis, }; diff --git a/wechat-miniprogram/pages/activity-detail/index.js b/wechat-miniprogram/pages/activity-detail/index.js index 0926bb7..4fd7d59 100644 --- a/wechat-miniprogram/pages/activity-detail/index.js +++ b/wechat-miniprogram/pages/activity-detail/index.js @@ -1,6 +1,6 @@ // pages/activity-detail/index.js const { getActivityDetail, joinActivity, cancelJoin, shareActivity } = require('../../api/activity'); -const { getAIRecommendations, refreshAIRecommendations } = require('../../api/ai'); +const { getAIRecommendations, refreshAIRecommendations, getThemeAnalysis } = require('../../api/ai'); const { getFullImageUrl, formatDateTime, formatDuration } = require('../../utils/helpers'); const { isLoggedIn, getIsAdmin } = require('../../utils/auth'); @@ -11,6 +11,8 @@ Page({ aiRecommendation: null, aiLoading: true, aiRefreshing: false, + themeAnalysis: '', + themeLoading: false, loading: false, isLoggedIn: false, isJoined: false, @@ -65,12 +67,6 @@ Page({ avatarUrl: p.user.avatarUrl ? getFullImageUrl(p.user.avatarUrl) : '', } : null, })); - // 创建者排在第一位 - const creatorIndex = activity.participants.findIndex(p => p.user && p.user.id === activity.creatorId); - if (creatorIndex > 0) { - const creator = activity.participants.splice(creatorIndex, 1)[0]; - activity.participants.unshift(creator); - } } this.setData({ activity, @@ -79,7 +75,7 @@ Page({ // 编辑入口仅管理员可见:creatorId 曾被服务端回退污染,不可作为判断依据 isCreator: isLoggedIn() && getIsAdmin(), }); - // 加载AI建议 + // 加载拆约推荐(按我的视角) this.loadAIRecommendation(); } } catch (err) { @@ -87,6 +83,7 @@ Page({ title: err.message || '加载失败', icon: 'none', }); + this.setData({ aiLoading: false }); } finally { this.setData({ loading: false }); } @@ -98,10 +95,10 @@ Page({ this.setData({ aiRefreshing: true, aiLoading: true }); try { - await refreshAIRecommendations(this.data.activityId, { showLoading: false }); + await refreshAIRecommendations(this.data.activityId); await this.loadAIRecommendation({ timeout: 60000 }); } catch (err) { - console.error('刷新AI推荐失败:', err); + console.error('刷新拆约推荐失败:', err); wx.showToast({ title: '刷新失败', icon: 'error' }); this.setData({ aiLoading: false }); } finally { @@ -113,7 +110,6 @@ Page({ try { const res = await getAIRecommendations(this.data.activityId, options); if (res.success && res.data) { - // 处理参与者数据,确保头像 URL 完整 const participants = (res.data.participants || []).map(p => ({ ...p, avatar: p.avatar ? getFullImageUrl(p.avatar) : '', @@ -123,6 +119,7 @@ Page({ aiRecommendation: { participants, suggestions: res.data.suggestions || '', + profileComplete: res.data.profileComplete !== false, }, aiLoading: false, }); @@ -130,11 +127,74 @@ Page({ this.setData({ aiLoading: false }); } } catch (err) { - console.error('AI推荐加载失败:', err); + console.error('拆约推荐加载失败:', err); this.setData({ aiLoading: false }); } }, + // 点击拆约推荐列表项:自己→完善资料;组织者→主题分析;其他→合作分析 + onMatchItemTap(e) { + const { userId, self, organizer } = e.currentTarget.dataset; + if (self) { + wx.navigateTo({ url: '/pages/edit-profile/index' }); + return; + } + if (organizer) { + this.showThemeAnalysis(); + return; + } + if (!this.data.isLoggedIn) { + wx.showToast({ title: '登录后可查看合作分析', icon: 'none' }); + return; + } + if (!userId) { + wx.showToast({ title: '该成员未绑定平台账号', icon: 'none' }); + return; + } + wx.navigateTo({ + url: `/pages/collaboration-analysis/index?targetUserId=${userId}&activityId=${this.data.activityId}`, + }); + }, + + // 组织者主题分析(有缓存用缓存,无则请求) + async showThemeAnalysis() { + if (this.data.themeAnalysis) { + wx.showModal({ + title: '主题分析', + content: this.data.themeAnalysis, + showCancel: false, + confirmText: '知道了', + }); + return; + } + if (this.data.themeLoading) return; + this.setData({ themeLoading: true }); + wx.showLoading({ title: '分析中...', mask: true }); + try { + const res = await getThemeAnalysis(this.data.activityId); + wx.hideLoading(); + if (res.success && res.data && res.data.analysis) { + this.setData({ themeAnalysis: res.data.analysis }); + wx.showModal({ + title: '主题分析', + content: res.data.analysis, + showCancel: false, + confirmText: '知道了', + }); + } else { + wx.showToast({ title: (res.data && res.data.message) || '分析失败', icon: 'none' }); + } + } catch (err) { + wx.hideLoading(); + console.error('主题分析失败:', err); + if (!err.silent) { + wx.showToast({ title: '主题分析失败', icon: 'none' }); + } + } finally { + this.setData({ themeLoading: false }); + } + }, + async handleJoinOrCancel() { // 报名属于需要身份的操作:游客可浏览详情,仅报名时弹窗引导登录,可取消 if (!this.data.isLoggedIn) { @@ -208,13 +268,6 @@ Page({ }); }, - goToAnalysis(e) { - const { userId, activityId } = e.currentTarget.dataset; - let url = `/pages/collaboration-analysis/index?targetUserId=${userId}`; - if (activityId) url += `&activityId=${activityId}`; - wx.navigateTo({ url }); - }, - previewImage(e) { const { url } = e.currentTarget.dataset; wx.previewImage({ diff --git a/wechat-miniprogram/pages/activity-detail/index.wxml b/wechat-miniprogram/pages/activity-detail/index.wxml index 1efb9c2..c8be18c 100644 --- a/wechat-miniprogram/pages/activity-detail/index.wxml +++ b/wechat-miniprogram/pages/activity-detail/index.wxml @@ -36,19 +36,6 @@ {{activity.description}} - - - 活动创建者 - - - - {{activity.creator.nickname}} - {{activity.creator.position}} - 🎖️ {{activity.creator.chaishuLevel}} - - - - @@ -64,12 +51,12 @@ - + - 参与人员及 AI 合作建议 + 拆约推荐 @@ -80,10 +67,17 @@ {{aiRecommendation.suggestions}} - + - - + {{item.name[0]}} - {{item.name}} - {{item.company}} · {{item.position}} + + {{item.name}} + 组织者 + {{item.level}} + + {{item.company || item.name}}{{item.position ? ' · ' + item.position : ''}} + + {{tag}} + + + + + 完善信息 + 点击补充 + + + 主题分析 + 点击查看 + + + {{item.matchScore}}% + {{item.matchLabel}} + + + 查看 + 点击分析 + - - + + - 🤖 - AI 合作建议 + 🤝 + {{item.aiSuggestion}} - {{item.aiSuggestion}} - AI 正在为参与者生成建议中... + AI 正在为你拆约推荐中... - 暂无参与者建议 - - - - - - - 活动参与者 ({{activity.participants.length}}人) - › - - - - - {{item.user.nickname}} - 组织者 - - + 暂无参与者,等伙伴加入后再来看看 diff --git a/wechat-miniprogram/pages/activity-detail/index.wxss b/wechat-miniprogram/pages/activity-detail/index.wxss index fb84404..079ca68 100644 --- a/wechat-miniprogram/pages/activity-detail/index.wxss +++ b/wechat-miniprogram/pages/activity-detail/index.wxss @@ -222,6 +222,98 @@ margin-top: 4rpx; } +/* 拆约推荐:姓名行徽章与右侧匹配列 */ +.ai-participant-name-row { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8rpx; +} + +.ai-participant-name-row .ai-participant-name { + display: inline; +} + +.ai-badge { + font-size: 20rpx; + border-radius: 6rpx; + padding: 2rpx 10rpx; + font-weight: 500; +} + +.ai-badge-organizer { + color: #b8860b; + background: #fdf6e3; +} + +.ai-badge-level { + color: #4A90E2; + background: #eef5fc; +} + +.ai-participant-tags { + display: flex; + flex-wrap: wrap; + gap: 8rpx; + margin-top: 8rpx; +} + +.ai-tag { + font-size: 20rpx; + color: #666666; + background: #f0f0f0; + border-radius: 6rpx; + padding: 2rpx 10rpx; +} + +.ai-match-col { + display: flex; + flex-direction: column; + align-items: flex-end; + justify-content: center; + flex-shrink: 0; + margin-left: 12rpx; +} + +.ai-match-score { + font-size: 34rpx; + font-weight: 700; + color: #e67e22; +} + +.ai-match-label { + font-size: 20rpx; + color: #999999; + margin-top: 2rpx; +} + +.ai-match-action { + font-size: 24rpx; + font-weight: 600; + color: #4A90E2; +} + +.ai-match-hint { + font-size: 20rpx; + color: #999999; + margin-top: 2rpx; +} + +.ai-participant-card.is-self { + background-color: #f5faff; + border: 1rpx solid #d4e7fa; +} + +/* 拆约推荐:建议框单行化 */ +.ai-suggestion-header .ai-suggestion-content { + flex: 1; + line-height: 1.6; +} + +.ai-suggestion-header { + margin-bottom: 0; +} + /* AI 建议框 */ .ai-suggestion-box { background-color: #ffffff; diff --git a/yaoyue-sever/database/schema.sql b/yaoyue-sever/database/schema.sql index b9f9115..c7f2fed 100644 --- a/yaoyue-sever/database/schema.sql +++ b/yaoyue-sever/database/schema.sql @@ -105,14 +105,16 @@ CREATE TABLE IF NOT EXISTS survey_clicks ( FOREIGN KEY (user_id) REFERENCES users(id) ); --- AI推荐记录表 +-- AI推荐记录表(拆约推荐:按查看者视角缓存) CREATE TABLE IF NOT EXISTS ai_recommendations ( id TEXT PRIMARY KEY, activity_id TEXT NOT NULL, + viewer_id TEXT DEFAULT '', -- 查看者用户ID(空=匿名/无视角) suggestions TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (activity_id) REFERENCES activities(id) ON DELETE CASCADE ); +CREATE INDEX IF NOT EXISTS idx_ai_rec_activity_viewer ON ai_recommendations(activity_id, viewer_id); -- AI推荐参与者表 CREATE TABLE IF NOT EXISTS ai_recommendation_participants ( @@ -178,4 +180,4 @@ CREATE INDEX IF NOT EXISTS idx_activity_tags_activity_id ON activity_tags(activi CREATE INDEX IF NOT EXISTS idx_activity_participants_activity_id ON activity_participants(activity_id); CREATE INDEX IF NOT EXISTS idx_activity_participants_user_id ON activity_participants(user_id); CREATE INDEX IF NOT EXISTS idx_survey_clicks_survey_id ON survey_clicks(survey_id); -CREATE INDEX IF NOT EXISTS idx_ai_recommendations_activity_id ON ai_recommendations(activity_id); +CREATE INDEX IF NOT EXISTS idx_ai_rec_activity_viewer ON ai_recommendations(activity_id, viewer_id); diff --git a/yaoyue-sever/server/server.js b/yaoyue-sever/server/server.js index 298241a..062a8ff 100644 --- a/yaoyue-sever/server/server.js +++ b/yaoyue-sever/server/server.js @@ -243,14 +243,26 @@ function initDatabase() { db.exec(schema); console.log('数据库表结构已创建'); - // 数据库迁移:添加 ai_suggestion 字段(如果不存在) - try { - const tableInfo = db.prepare('PRAGMA table_info(ai_recommendation_participants)').all(); - const hasAiSuggestion = tableInfo.some(col => col.name === 'ai_suggestion'); - if (!hasAiSuggestion) { - db.prepare('ALTER TABLE ai_recommendation_participants ADD COLUMN ai_suggestion TEXT DEFAULT \'\'').run(); - console.log('已添加 ai_suggestion 字段'); + // 数据库迁移:添加 ai_suggestion 字段(如果不存在) + try { + const tableInfo = db.prepare('PRAGMA table_info(ai_recommendation_participants)').all(); + const hasAiSuggestion = tableInfo.some(col => col.name === 'ai_suggestion'); + if (!hasAiSuggestion) { + db.prepare('ALTER TABLE ai_recommendation_participants ADD COLUMN ai_suggestion TEXT DEFAULT \'\'').run(); + console.log('已添加 ai_suggestion 字段'); + } + + // 迁移:ai_recommendations 表添加 viewer_id 字段(拆约推荐按查看者视角缓存) + const recInfo = db.prepare('PRAGMA table_info(ai_recommendations)').all(); + if (!recInfo.some(col => col.name === 'viewer_id')) { + db.prepare('ALTER TABLE ai_recommendations ADD COLUMN viewer_id TEXT DEFAULT \'\'').run(); + console.log('已添加 ai_recommendations.viewer_id 字段'); + // 清空旧版全量缓存(旧数据无视角概念,与新逻辑不兼容) + db.prepare('DELETE FROM ai_recommendation_participants').run(); + db.prepare('DELETE FROM ai_recommendations').run(); + console.log('已清空旧版AI推荐缓存'); } + db.exec('CREATE INDEX IF NOT EXISTS idx_ai_rec_activity_viewer ON ai_recommendations(activity_id, viewer_id)'); // 迁移:activities 表添加 fee / organizer 字段 const activityInfo = db.prepare('PRAGMA table_info(activities)').all(); @@ -996,7 +1008,10 @@ app.get('/user/stats', (req, res) => { try { const userId = req.headers['x-user-id'] || 'user-1'; const createdCount = db.prepare('SELECT COUNT(*) as count FROM activities WHERE creator_id = ?').get(userId); - const joinedCount = db.prepare("SELECT COUNT(*) as count FROM activity_participants WHERE user_id = ? AND status != 'cancelled'").get(userId); + // 参与数与「我参与的活动」同口径:排除自己发起的活动(创建时自动生成的参与行) + const joinedCount = db.prepare(`SELECT COUNT(*) as count FROM activity_participants ap + JOIN activities a ON a.id = ap.activity_id + WHERE ap.user_id = ? AND ap.status != 'cancelled' AND a.creator_id != ?`).get(userId, userId); res.json({ success: true, data: { createdCount: createdCount.count, joinedCount: joinedCount.count } }); } catch (error) { console.error('获取用户统计失败:', error); @@ -1118,18 +1133,19 @@ app.get('/activities', (req, res) => { total = ranked.length; activities = ranked.slice(offset, offset + pageSizeNum); } else if (tab === 'joined') { + // 仅显示报名的他人活动:排除自己发起的活动(创建时自动生成的参与行不算「参与」) const result = db.prepare(` SELECT COUNT(DISTINCT a.id) as count FROM activities a JOIN activity_participants ap ON a.id = ap.activity_id - WHERE ap.user_id = ? AND ap.status != 'cancelled' - `).get(userId); + WHERE ap.user_id = ? AND ap.status != 'cancelled' AND a.creator_id != ? + `).get(userId, userId); total = result.count; activities = db.prepare(` SELECT DISTINCT a.* FROM activities a JOIN activity_participants ap ON a.id = ap.activity_id - WHERE ap.user_id = ? AND ap.status != 'cancelled' + WHERE ap.user_id = ? AND ap.status != 'cancelled' AND a.creator_id != ? ORDER BY a.start_time DESC LIMIT ? OFFSET ? - `).all(userId, pageSizeNum, offset); + `).all(userId, userId, pageSizeNum, offset); } else if (tab === 'created') { const result = db.prepare('SELECT COUNT(*) as count FROM activities WHERE creator_id = ?').get(userId); total = result.count; @@ -1610,78 +1626,269 @@ app.get('/tags/recommended', (req, res) => { // ==================== AI 推荐路由 ==================== // 获取AI推荐 +// ============ 拆约推荐(活动详情页,按查看者视角) ============ + +// 合并平台资料 + 拆书帮会员资料,返回打分所需字段 +function getMergedProfile(userId) { + const user = db.prepare(` + SELECT u.id, u.nickname, u.avatar_url, u.position, u.industry, u.hometown, u.expertise, u.chaishu_uid, + (SELECT company_name FROM user_companies WHERE user_id = u.id ORDER BY sort_order LIMIT 1) as company + FROM users u WHERE u.id = ? + `).get(userId); + if (!user) return null; + const merged = { + userId: user.id, + name: user.nickname, + avatar: user.avatar_url || '', + company: user.company || '', + position: user.position || '', + industry: user.industry || '', + hometown: user.hometown || '', + expertise: user.expertise || '', + level: '非会员', + tags: [], + memberDescription: '', + branch: '', + city: '', + }; + (user.expertise || '').split(/[、,,;;\s]+/).forEach(t => t && t.trim() && merged.tags.push(t.trim())); + if (user.chaishu_uid) { + const m = db.prepare('SELECT name, city, branch, level, level1, level2, level3, tags, description, position, industry, hometown, expertise FROM chaishu_members WHERE uid = ?').get(user.chaishu_uid); + if (m) { + merged.level = memberLevelLabel(m); + merged.branch = m.branch || ''; + merged.city = m.city || ''; + merged.memberDescription = m.description || ''; + merged.position = merged.position || m.position || ''; + merged.industry = merged.industry || m.industry || ''; + merged.hometown = merged.hometown || m.hometown || m.city || ''; + merged.expertise = merged.expertise || m.expertise || ''; + (safeParseJson(m.tags, []) || []).forEach(t => t && t.trim() && !merged.tags.includes(t.trim()) && merged.tags.push(t.trim())); + } + } + return merged; +} + +// 查看者与某参与者的匹配打分:兴趣点 / 价值交换 / 共创机会 三维 +function computeMatchScore(me, other) { + const reasons = []; + const myTags = new Set(me.tags); + const otherTags = new Set(other.tags); + const overlapTags = [...otherTags].filter(t => myTags.has(t)); + + // 维度一:兴趣点(标签重叠度) + let interest = 60; + if (overlapTags.length > 0) { + interest = Math.min(96, 78 + overlapTags.length * 6); + reasons.push(`共同兴趣:${overlapTags.slice(0, 3).join('、')}`); + } else if (otherTags.size > 0) { + interest = 68; + } + + // 维度二:价值交换(行业互补) + let value = 65; + if (me.industry && other.industry) { + const techKeywords = ['互联网', '科技', 'IT', '软件', 'AI', '人工智能']; + const financeKeywords = ['金融', '投资', '银行', '基金']; + const isTech = (v) => techKeywords.some(k => v.includes(k)); + const isFinance = (v) => financeKeywords.some(k => v.includes(k)); + if (me.industry === other.industry) { + value = 78; + reasons.push(`同属${me.industry}行业,资源互通`); + } else if ((isTech(me.industry) && isFinance(other.industry)) || (isFinance(me.industry) && isTech(other.industry))) { + value = 90; + reasons.push(`${me.industry}×${other.industry}跨界互补`); + } else { + value = 72; + reasons.push(`${me.industry}与${other.industry}视角互补`); + } + } + + // 维度三:共创机会(专长互补 + 地理便利) + let cocreate = 66; + if (me.expertise && other.expertise && me.expertise !== other.expertise) { + cocreate = 82; + reasons.push(`专长互补(${me.expertise} × ${other.expertise})`); + } + const myGeo = me.hometown || me.city; + const otherGeo = other.hometown || other.city; + if (myGeo && otherGeo) { + if (myGeo === otherGeo) { + cocreate = Math.min(95, cocreate + 8); + reasons.push(`同在${myGeo},线下共创便利`); + } else if (myGeo.slice(0, 2) === otherGeo.slice(0, 2)) { + cocreate = Math.min(95, cocreate + 4); + reasons.push(`同城圈(${myGeo.slice(0, 2)})交流方便`); + } + } + + const score = Math.round(Math.min(97, (interest + value + cocreate) / 3)); + const label = ['不推荐', '一般', '推荐', '高度推荐', '强烈推荐'][Math.min(Math.floor(score / 20), 4)]; + return { score, label, reasons }; +} + +// 查看者资料完善度(8 项:昵称/职位/行业/家乡/专长/公司/会员标签/会员自介) +function isProfileComplete(p) { + if (!p) return false; + const base = ['name', 'position', 'industry', 'hometown', 'expertise'].filter(f => p[f] && String(p[f]).trim() !== '').length; + const bonus = (p.company ? 1 : 0) + (p.tags.length > 0 ? 1 : 0) + (p.memberDescription ? 1 : 0); + return base + bonus >= 6; +} + app.get('/ai/recommendations/:activityId', async (req, res) => { try { const { activityId } = req.params; - let recommendation = db.prepare('SELECT * FROM ai_recommendations WHERE activity_id = ?').get(activityId); + const viewerId = (req.headers['x-user-id'] || '').trim(); + + const activity = db.prepare('SELECT id, title, creator_id FROM activities WHERE id = ?').get(activityId); + if (!activity) { + return res.json({ success: false, message: '活动不存在' }); + } + + // 按查看者视角缓存 + let recommendation = db.prepare('SELECT * FROM ai_recommendations WHERE activity_id = ? AND viewer_id = ?').get(activityId, viewerId); if (!recommendation) { - // 生成模拟推荐 - const activity = db.prepare('SELECT title, description FROM activities WHERE id = ?').get(activityId); - if (!activity) { - return res.json({ success: false, message: '活动不存在' }); - } - - // 获取参与者完整信息(包括职位、行业、专长等) - const participants = db.prepare(` - SELECT - u.id as user_id, - u.nickname as name, - u.avatar_url as avatar, - u.position, - u.chaishu_level, - u.industry, - u.expertise, - (SELECT company_name FROM user_companies WHERE user_id = u.id ORDER BY sort_order LIMIT 1) as company - FROM activity_participants ap - LEFT JOIN users u ON ap.user_id = u.id + // 参与者(含组织者),合并会员资料 + const rows = db.prepare(` + SELECT ap.user_id FROM activity_participants ap WHERE ap.activity_id = ? AND ap.status != 'cancelled' - ORDER BY ap.joined_at - LIMIT 10 + ORDER BY ap.joined_at LIMIT 20 `).all(activityId); + const profiles = rows.map(r => getMergedProfile(r.user_id)).filter(Boolean); - const suggestions = `建议围绕"${activity.title}"主题展开交流,关注每位参与者的专业背景,寻找合作机会。`; - const recommendationId = uuidv4(); - db.prepare('INSERT INTO ai_recommendations (id, activity_id, suggestions) VALUES (?, ?, ?)').run(recommendationId, activityId, suggestions); + // 组织者排最前 + profiles.sort((a, b) => (b.userId === activity.creator_id ? 1 : 0) - (a.userId === activity.creator_id ? 1 : 0)); - // 为每个参与者生成 AI 建议并保存 - for (let index = 0; index < participants.length; index++) { - const p = participants[index]; - const aiSuggestion = await generateParticipantSuggestion(p, activity.title); - db.prepare(` - INSERT INTO ai_recommendation_participants - (recommendation_id, name, avatar, company, position, ai_suggestion, sort_order) - VALUES (?, ?, ?, ?, ?, ?, ?) - `).run(recommendationId, p.name, p.avatar, p.company || '', p.position || '', aiSuggestion, index); + const viewer = viewerId ? getMergedProfile(viewerId) : null; + const viewerKnown = !!(viewer && profiles.some(p => p.userId === viewerId)); + const scored = profiles.map(p => { + if (viewerId && p.userId === viewerId) { + return { ...p, isSelf: true, isOrganizer: p.userId === activity.creator_id, matchScore: null, matchLabel: null, aiSuggestion: '' }; + } + if (!viewer) { + return { ...p, isSelf: false, isOrganizer: p.userId === activity.creator_id, matchScore: null, matchLabel: null, aiSuggestion: '' }; + } + const m = computeMatchScore(viewer, p); + return { + ...p, + isSelf: false, + isOrganizer: p.userId === activity.creator_id, + matchScore: m.score, + matchLabel: m.label, + aiSuggestion: m.reasons.slice(0, 2).join(';') || '背景多元,值得当面聊聊', + }; + }); + + // 总体建议 + let suggestions; + const others = scored.filter(p => !p.isSelf && p.matchScore !== null).sort((a, b) => b.matchScore - a.matchScore); + if (viewer && others.length > 0) { + const top = others[0]; + suggestions = `本场最值得你约的是${top.name}(匹配度 ${top.matchScore}%·${top.matchLabel}):${top.aiSuggestion}。其次可关注${others.slice(1, 3).map(p => p.name).join('、') || '其他伙伴'}。`; + } else if (viewer && viewerKnown) { + suggestions = `本活动暂无其他参与者,等你约的伙伴加入后,这里会给出匹配分析。`; + } else { + suggestions = `建议围绕"${activity.title}"主题展开交流,登录并完善资料后可查看每个人的合作匹配度。`; } - recommendation = { id: recommendationId, activity_id: activityId, suggestions }; + const recommendationId = uuidv4(); + db.prepare('INSERT INTO ai_recommendations (id, activity_id, viewer_id, suggestions) VALUES (?, ?, ?, ?)').run(recommendationId, activityId, viewerId, suggestions); + const insertP = db.prepare(` + INSERT INTO ai_recommendation_participants + (recommendation_id, name, avatar, company, position, ai_suggestion, sort_order) + VALUES (?, ?, ?, ?, ?, ?, ?) + `); + scored.forEach((p, i) => { + insertP.run(recommendationId, p.name, p.avatar || '', p.company || '', p.position || '', JSON.stringify({ + userId: p.userId, level: p.level, isSelf: p.isSelf, isOrganizer: p.isOrganizer, + matchScore: p.matchScore, matchLabel: p.matchLabel, matchReason: p.aiSuggestion, tags: p.tags.slice(0, 6), + }), i); + }); + + recommendation = { id: recommendationId, suggestions, viewer_complete: viewer ? (isProfileComplete(viewer) ? 1 : 0) : null }; } const aiParticipants = db.prepare(` - SELECT name, avatar, company, position, ai_suggestion as aiSuggestion + SELECT name, avatar, company, position, ai_suggestion, sort_order FROM ai_recommendation_participants WHERE recommendation_id = ? ORDER BY sort_order - `).all(recommendation.id); + `).all(recommendation.id).map(row => { + let meta = {}; + try { meta = JSON.parse(row.ai_suggestion || '{}') || {}; } catch (e) { meta = {}; } + return { + userId: meta.userId || '', + name: row.name, + avatar: row.avatar, + company: row.company, + position: row.position, + level: meta.level || '非会员', + tags: meta.tags || [], + isSelf: !!meta.isSelf, + isOrganizer: !!meta.isOrganizer, + matchScore: meta.matchScore !== undefined ? meta.matchScore : null, + matchLabel: meta.matchLabel || '', + aiSuggestion: meta.matchReason || '', + }; + }); - res.json({ success: true, data: { participants: aiParticipants, suggestions: recommendation.suggestions } }); + res.json({ + success: true, + data: { + participants: aiParticipants, + suggestions: recommendation.suggestions, + profileComplete: recommendation.viewer_complete === 1, + }, + }); } catch (error) { - console.error('获取AI推荐失败:', error); - res.json({ success: false, message: '获取AI推荐失败' }); + console.error('获取拆约推荐失败:', error); + res.json({ success: false, message: '获取拆约推荐失败' }); } }); -// 删除缓存的AI推荐(强制重新生成) +// 主题分析(活动详情页组织者「主题分析」按钮) +app.post('/ai/theme-analysis/:activityId', async (req, res) => { + try { + const { activityId } = req.params; + const activity = db.prepare('SELECT title, description, organizer, location FROM activities WHERE id = ?').get(activityId); + if (!activity) { + return res.json({ success: false, message: '活动不存在' }); + } + const tags = db.prepare('SELECT tag_name FROM activity_tags WHERE activity_id = ?').all(activityId).map(r => r.tag_name); + + let analysis = ''; + if (GLM_ENABLED) { + analysis = await callGLMAPI(`请为以下活动写一段主题分析(120字以内,说明参与者能获得什么价值、适合什么人、现场可能的共创形式,口吻务实不吹捧): + +活动名称:${activity.title} +活动标签:${tags.join('、') || '无'} +主办方:${activity.organizer || '未知'} +地点:${activity.location} +活动介绍:${(activity.description || '').slice(0, 300)}`); + } + if (!analysis) { + const tagLine = tags.length ? `围绕${tags.join('、')}` : '围绕活动主题'; + analysis = `本活动${tagLine}展开,由${activity.organizer || '主办方'}组织。参与者可期待:了解主题相关的方法与实战案例,结识同领域伙伴,并在现场交流中找到可落地的合作切入点。适合对主题有兴趣、想找人共创或跨界取经的朋友。`; + } + res.json({ success: true, data: { analysis } }); + } catch (error) { + console.error('主题分析失败:', error); + res.json({ success: false, message: '主题分析失败' }); + } +}); + +// 删除缓存的拆约推荐(只清当前查看者视角,强制重新生成) app.delete('/ai/recommendations/:activityId', requireEmail, (req, res) => { try { const { activityId } = req.params; - db.prepare('DELETE FROM ai_recommendation_participants WHERE recommendation_id IN (SELECT id FROM ai_recommendations WHERE activity_id = ?)').run(activityId); - db.prepare('DELETE FROM ai_recommendations WHERE activity_id = ?').run(activityId); - res.json({ success: true, message: 'AI recommendations cleared' }); + const viewerId = (req.headers['x-user-id'] || '').trim(); + db.prepare('DELETE FROM ai_recommendation_participants WHERE recommendation_id IN (SELECT id FROM ai_recommendations WHERE activity_id = ? AND viewer_id = ?)').run(activityId, viewerId); + db.prepare('DELETE FROM ai_recommendations WHERE activity_id = ? AND viewer_id = ?').run(activityId, viewerId); + res.json({ success: true, message: '拆约推荐已刷新' }); } catch (error) { - console.error('删除AI推荐缓存失败:', error); - res.json({ success: false, message: '删除AI推荐缓存失败' }); + console.error('删除拆约推荐缓存失败:', error); + res.json({ success: false, message: '删除拆约推荐缓存失败' }); } }); @@ -2813,7 +3020,8 @@ app.listen(PORT, () => { console.log(' ==================== 标签 ===================='); console.log(' GET /tags/recommended - 获取推荐标签'); console.log(' ==================== AI ======================'); - console.log(' GET /ai/recommendations/:id - 获取AI推荐'); + console.log(' GET /ai/recommendations/:id - 拆约推荐(按查看者视角)'); + console.log(' POST /ai/theme-analysis/:id - 活动主题分析'); console.log(' POST /ai/collaboration-analysis - 合作可能性分析'); console.log(' ==================== 问卷 ===================='); console.log(' GET /survey/current - 获取当前问卷');