let publicProfileUserId = ''; let activeChatId = ''; let activeChatPeer = null; let chatPollTimer = null; let reportTarget = null; let publicHistoryFilter = 'all'; function closeOtherDialogs(keepId) { $$('dialog[open]').forEach(dialog => { if (dialog.id === keepId) return; dialog.classList.remove('closing'); dialog.close(); }); } const previousPublicProfileLoader = loadPublicProfile; loadPublicProfile = async function (userId) { publicProfileUserId = String(userId || ''); await previousPublicProfileLoader(userId); const body = $('#publicProfileBody'); const stats = body?.querySelectorAll('.profile-numbers > div'); if (!stats || stats.length < 2 || !body.querySelector('.public-profile-head h3')) return; try { const profile = await apiRequest(`/api/users/${encodeURIComponent(publicProfileUserId)}/profile`, null, {auth:true}); const breachValue = stats[1].querySelector('strong'); if (breachValue) breachValue.textContent = profile.user.breachRateLabel || '记录较少'; } catch (error) { toast(error.message); } [['score', '查看信用分调整历史'], ['breach', '查看失信记录']].forEach(([kind, label], index) => { const stat = stats[index]; stat.dataset.publicCreditHistory = kind; stat.classList.add('profile-credit-action'); stat.setAttribute('role', 'button'); stat.setAttribute('tabindex', '0'); stat.setAttribute('aria-label', label); }); const head = body.querySelector('.public-profile-head'); if (!head.querySelector('[data-public-chat]')) { const button = document.createElement('button'); button.type = 'button'; button.className = 'public-chat-button'; button.dataset.publicChat = publicProfileUserId; button.textContent = '发私信'; head.append(button); } }; function showCreditHistory(kind) { if (!publicProfileUserId) return; publicHistoryFilter = kind === 'breach' ? 'negative' : 'all'; const dialog = $('#creditHistoryDialog'); const body = $('#creditHistoryBody'); $('#creditHistoryTitle').textContent = kind === 'breach' ? '失信记录' : '信用历史'; body.innerHTML = '
正在加载信用历史…
'; dialog.showModal(); const suffix = publicHistoryFilter === 'negative' ? '?negativeOnly=true' : ''; apiRequest(`/api/users/${encodeURIComponent(publicProfileUserId)}/credit-history${suffix}`, null, {auth:true}) .then(result => { const items = result.items || []; const history = items.length ? `
${items.map(item => `
${escapeHtml(item.category)}${Number(item.delta)>0?'+':''}${Number(item.delta)}
` ).join('')}
` : '
暂无可公开的信用记录
'; const hidden = Number(result.hiddenCount) > 0 ? `

另有 ${Number(result.hiddenCount)} 条更早记录暂不展示,其中未分类历史不会公开。

` : ''; body.innerHTML = history + hidden; }) .catch(error => { body.innerHTML = `
信用历史加载失败

${escapeHtml(error.message)}

`; toast(error.message); }); } async function openChatForUser(userId, button) { if (!signedInUser) { openLogin(); return; } return withButtonFeedback(button, async () => { const result = await apiRequest('/api/chats', {userId:String(userId)}, {auth:true}); closeOtherDialogs('chatDialog'); await openChatDialog(result.id, result.peer); }, {label:'正在打开…', onError:error => { if (error.status === 401) openLogin(); }}); } function renderChatMessages(result) { activeChatPeer = result.peer || activeChatPeer; const name = activeChatPeer?.nickname || '同学'; $('#chatPeerName').textContent = name; const messages = (result.items || []).slice().reverse(); const list = $('#chatMessages'); const previousLast = list.lastElementChild?.dataset.messageId || ''; if (!messages.length) { list.innerHTML = '
打个招呼,开始私聊
'; } else { list.innerHTML = messages.map(message => { const own = String(message.senderId) === String(signedInUser?.id); const date = message.createdAt ? new Date(Number(message.createdAt)).toLocaleString('zh-CN', {month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'}) : ''; return `
${escapeHtml(message.content)}
`; }).join(''); } const last = messages.at(-1); const waiting = !!last && String(last.senderId) === String(signedInUser?.id); $('#chatInput').disabled = waiting; $('#chatSendButton').disabled = waiting || activeButtons.has($('#chatSendButton')); $('#chatSendRule').textContent = waiting ? '等待对方回复后可继续发送。' : '发送一条消息后,等待对方回复。'; $('#chatStatus').textContent = ''; if (last && String(last.id) !== previousLast) list.scrollTop = list.scrollHeight; } async function refreshChatMessages(showError = false) { if (!activeChatId || !$('#chatDialog').open) return; try { const result = await apiRequest(`/api/chats/${encodeURIComponent(activeChatId)}/messages`, null, {auth:true}); renderChatMessages(result); } catch (error) { if (showError) { $('#chatStatus').textContent = error.message; toast(error.message); } } } async function openChatDialog(conversationId, peer = null) { activeChatId = String(conversationId); activeChatPeer = peer; $('#chatPeerName').textContent = peer?.nickname || '同学'; $('#chatMessages').innerHTML = '
正在加载消息…
'; $('#chatStatus').textContent = ''; $('#chatDialog').showModal(); await refreshChatMessages(true); clearInterval(chatPollTimer); chatPollTimer = setInterval(() => refreshChatMessages(), 10000); } async function sendChatMessage(event) { event.preventDefault(); const input = $('#chatInput'); const button = $('#chatSendButton'); const content = input.value.trim(); if (!content || !activeChatId || input.disabled || content.length > 200) return; return withButtonFeedback(button, async () => { await apiRequest(`/api/chats/${encodeURIComponent(activeChatId)}/messages`, {content}, {auth:true}); input.value = ''; input.disabled = true; $('#chatSendRule').textContent = '等待对方回复后可继续发送。'; toast('消息已发送'); await refreshChatMessages(true); loadNotificationSummary(); }, {label:'发送中…', disabledAfter:() => input.disabled, onError:error => { if (error.status === 403) { input.disabled = true; $('#chatSendRule').textContent = '等待对方回复后可继续发送。'; $('#chatStatus').textContent = '等待对方回复后可继续发送。'; } else { $('#chatStatus').textContent = error.message; } }}); } async function submitSocialReport(event) { event.preventDefault(); const form = event.currentTarget; if (!form.reportValidity()) return; const reason = Object.fromEntries(new FormData(form)).reason; const button = $('#reportSubmit'); const target = reportTarget || {targetType:'task', targetId:reportTargetId}; return withButtonFeedback(button, async () => { await apiRequest('/api/reports', { ...target, reason }, {auth:true}); form.reset(); closeOtherDialogs(''); toast('举报已提交,我们会尽快核实处理'); }, {label:'正在提交…',onError:error => { $('#reportError').textContent = error.message; }}); } const previousOpenTaskForSocial = openTask; openTask = function (id) { previousOpenTaskForSocial(id); const task = tasks.find(item => item.id === id); const publisher = $('#taskDetail .publisher'); if (!task?.userId || !publisher) return; const avatar = publisher.querySelector('.avatar'); if (avatar && !publisher.querySelector('[data-publisher-actions]')) { const button = document.createElement('button'); button.type = 'button'; button.className = 'publisher-avatar-button'; button.dataset.publisherActions = task.userId; button.setAttribute('aria-label', `查看 ${task.user} 主页或发私信`); button.setAttribute('aria-haspopup', 'menu'); const face = document.createElement('span'); face.className = avatar.className; face.textContent = task.user.slice(0, 1) || '同'; button.append(face); avatar.replaceWith(button); } }; document.addEventListener('click', event => { const action = event.target.closest('[data-publisher-choice]'); if (action) { event.preventDefault(); event.stopPropagation(); const menu = action.closest('.publisher-action-popover'); const userId = menu?.dataset.userId; const choice = action.dataset.publisherChoice; if (!userId) { menu?.remove(); return; } if (choice === 'profile') { menu?.remove(); closeOtherDialogs(''); loadPublicProfile(userId); } else openChatForUser(userId, action).finally(() => menu?.remove()); return; } const avatar = event.target.closest('[data-publisher-actions]'); if (avatar) { event.preventDefault(); event.stopPropagation(); document.querySelectorAll('.publisher-action-popover').forEach(menu => menu.remove()); const menu = document.createElement('div'); menu.className = 'publisher-action-popover'; menu.dataset.userId = avatar.dataset.publisherActions; menu.setAttribute('role', 'menu'); menu.innerHTML = ''; avatar.closest('.publisher').append(menu); menu.querySelector('button').focus(); return; } if (!event.target.closest('.publisher-action-popover')) document.querySelectorAll('.publisher-action-popover').forEach(menu => menu.remove()); const profileChat = event.target.closest('[data-public-chat]'); if (profileChat) { event.preventDefault(); openChatForUser(profileChat.dataset.publicChat, profileChat); return; } const history = event.target.closest('[data-public-credit-history]'); if (history) { event.preventDefault(); showCreditHistory(history.dataset.publicCreditHistory); } }, true); document.addEventListener('keydown', event => { const history = event.target.closest('[data-public-credit-history]'); if (history && (event.key === 'Enter' || event.key === ' ')) { event.preventDefault(); showCreditHistory(history.dataset.publicCreditHistory); } }); $('#chatForm').addEventListener('submit', sendChatMessage); $('#chatReportButton').addEventListener('click', () => { if (!signedInUser) { openLogin(); return; } reportTarget = {targetType:'chat', targetId:activeChatId, targetUserId:activeChatPeer?.id, conversationId:activeChatId}; $('#reportError').textContent = ''; $('#reportDialog').showModal(); }); $('#chatDialog').addEventListener('close', () => { // A queued close event from the previous opening must not clear a reopened chat. if ($('#chatDialog').open) return; clearInterval(chatPollTimer); chatPollTimer = null; activeChatId = ''; activeChatPeer = null; }); $('#reportForm').onsubmit = submitSocialReport; NOTIFICATION_GROUPS.chat = {label:'私聊', kinds:['chat_message'], empty:'暂无私聊消息', hint:'同学回复你的私聊后,消息通知会显示在这里。'}; NOTIFICATION_KIND_GROUP.chat_message = 'chat'; const notifTabs = document.querySelector('.notif-tabs'); if (notifTabs && !notifTabs.querySelector('[data-notif-filter="chat"]')) { const button = document.createElement('button'); button.type = 'button'; button.className = 'notif-filter'; button.dataset.notifFilter = 'chat'; button.setAttribute('role','tab'); button.setAttribute('aria-selected','false'); button.textContent = '私聊'; button.onclick = () => setNotificationFilter('chat'); notifTabs.append(button); } const previousNotificationClick = handleNotificationClick; handleNotificationClick = async function (item) { const link = item.dataset.notificationLink || ''; const opened = await previousNotificationClick(item); if (!opened || opened.feedbackError) return; if (link.startsWith('chat:')) { const chatId = link.slice(5); closeOtherDialogs('chatDialog'); await openChatDialog(chatId); loadNotificationSummary(); } }; setInterval(() => { if (signedInUser) loadNotificationSummary(); }, 30000); const previousRenderInviteV1 = renderInvite; renderInvite = function (info) { const body = $('#inviteBody'); const points = Math.max(0, Number(info.withdrawablePoints) || 0); const progress = Math.min(100, Math.floor(points / 80 * 100)); const warning = `
慎重邀请

可提现积分满 80 可生成邀请码,每个账号限一个,最多使用 2 次。邀请关系会用于平台风控;恶意邀请或串通违规经核实后,管理员可调整邀请人的信用分。注册时邀请人仍须信用分达到 90。

`; if (info.code) { body.innerHTML = `
${escapeHtml(info.code.code)}

邀请码还可被使用 ${Number(info.code.usesLeft)||0}/${Number(info.code.maxUses)||2} 次。

${warning}`; body.querySelector('[data-copy-invite]').onclick = event => withButtonFeedback(event.currentTarget, async () => { const text = `【LinkUp 校园互助】邀请邀请码:${info.code.code}\n注册时填写此邀请码,你的初始信用分为 90。\n注册地址:${location.origin}`; if (!await copyText(text)) throw new Error('复制失败,请长按邀请码手动复制'); toast('邀请文案已复制,直接发给同学即可'); }, {label:'复制中…'}); return; } const progressHtml = `
当前可提现积分 ${points} / 80
`; if (info.eligible) { body.innerHTML = `

当前可提现积分 ${points},已达到生成条件。

${progressHtml}${warning}`; body.querySelector('[data-gen-invite]').onclick = async event => { return withButtonFeedback(event.currentTarget, async () => { renderInvite(await apiRequest('/api/invite-code', {}, {auth:true})); toast('邀请码已生成'); }, {label:'正在生成…'}); }; } else { body.innerHTML = `

当前可提现积分 ${points},满 80 可生成邀请码。

${progressHtml}${warning}`; } }; const previousRenderCreditDetailsV1 = renderCreditDetails; renderCreditDetails = function (result) { const body = $('#creditBody'); if (!body) return previousRenderCreditDetailsV1(result); const score = Math.max(0, Math.min(100, Number(result.creditScore) || 0)); const breach = result.breachRateLabel || '记录较少'; const pointsProgress = `${result.invitationEligible ? '可生成' : '未达标'} · ${Math.max(0, Number(result.withdrawablePoints) || 0)} / 80`; const history = result.history?.length ? `

信用分变化记录

${result.history.map(item => `
${escapeHtml(item.reason)}${item.reversedAt ? ' · 已撤销' : ''}${item.delta > 0 ? '+' : ''}${item.delta}${escapeHtml(new Date(Number(item.createdAt)).toLocaleString('zh-CN'))}
`).join('')}
` : '

暂无信用分变化记录。

'; body.innerHTML = `
当前信用分(0–100)${score}
${escapeHtml(breach)}近 90 天失信率
${Number(result.breachCount90d)||0}近 90 天确认失信
${Number(result.commitments90d)||0}近 90 天履约承诺
${Number(result.completedTasks)||0}完成任务
${Number(result.currentStreak)||0}连续守约
${escapeHtml(pointsProgress)}可提现积分 / 邀请码门槛
信用分与积分

积分用于任务交易与提现;信用分独立记录履约表现,范围为 0–100。普通注册信用分为 70,邀请码注册为 90。正常完成任务分别为发单者 +1、接单者 +2,每 7 天最多获得 +5。邀请码资格按可提现积分满 80 判断,与信用分无关。

失信率按近 90 天已形成履约承诺的任务数计算;少于 3 条时显示“记录较少”。积分结算不兑换信用分。

${history}`; if (result.pendingCases?.length) { const notice = document.createElement('div'); notice.className = 'credit-pending-notice'; notice.textContent = `有 ${result.pendingCases.length} 条任务信用处理待管理员核实;处理完成前不会计入已确认失信。`; body.querySelector('.credit-rules')?.after(notice); } }; const previousRenderAccountMetricsV1 = renderAccountMetrics; renderAccountMetrics = function (user) { previousRenderAccountMetricsV1(user); const stats = user?.stats; const breach = stats ? (stats.breachRateLabel || '记录较少') : '—'; $('[data-breach-rate]').textContent = breach; $('[data-profile-breach]').textContent = breach; }; publisherMeta = function (task) { const date = task.registeredAt ? new Date(task.registeredAt).toLocaleDateString('zh-CN', {year:'numeric',month:'2-digit',day:'2-digit'}) : '—'; const rate = typeof task.breachRate === 'number' ? `${task.breachRate}%` : (task.breachRate || '记录较少'); return `注册于 ${date} · 近 90 天失信率 ${rate}`; };