Files
linkup/dist/social.js
T
2026-10-29 16:27:16 +08:00

330 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 = '<div class="loading">正在加载信用历史…</div>';
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 ? `<div class="public-credit-history">${items.map(item =>
`<article class="public-credit-row"><span>${escapeHtml(item.category)}</span><b class="${Number(item.delta)<0?'neg':'pos'}">${Number(item.delta)>0?'+':''}${Number(item.delta)}</b><time>${escapeHtml(item.date)}</time></article>`
).join('')}</div>` : '<div class="empty-state compact"><span>暂无可公开的信用记录</span></div>';
const hidden = Number(result.hiddenCount) > 0
? `<p class="credit-history-hidden">另有 ${Number(result.hiddenCount)} 条更早记录暂不展示,其中未分类历史不会公开。</p>` : '';
body.innerHTML = history + hidden;
})
.catch(error => { body.innerHTML = `<div class="empty-state compact"><span>信用历史加载失败</span><p>${escapeHtml(error.message)}</p></div>`; 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 = '<div class="empty-state compact"><span>打个招呼,开始私聊</span></div>';
} 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 `<div class="chat-message ${own?'own':'peer'}" data-message-id="${escapeHtml(message.id)}"><span>${escapeHtml(message.content)}</span><time>${escapeHtml(date)}</time></div>`;
}).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 = '<div class="loading">正在加载消息…</div>';
$('#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 = '<button type="button" role="menuitem" data-publisher-choice="profile">查看主页</button><button type="button" role="menuitem" data-publisher-choice="chat">发私信</button>';
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 = `<div class="invite-warning"><strong><svg><use href="#i-shield"/></svg>慎重邀请</strong><p>可提现积分满 <b>80</b> 可生成邀请码,每个账号限一个,最多使用 2 次。邀请关系会用于平台风控;恶意邀请或串通违规经核实后,管理员可调整邀请人的信用分。注册时邀请人仍须信用分达到 90。</p></div>`;
if (info.code) {
body.innerHTML = `<div class="invite-code-box"><code>${escapeHtml(info.code.code)}</code><button type="button" class="btn primary" data-copy-invite>复制</button></div><p class="invite-hint">邀请码还可被使用 ${Number(info.code.usesLeft)||0}/${Number(info.code.maxUses)||2} 次。</p>${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 = `<div class="invite-progress"><div class="score-track"><i style="width:${progress}%"></i></div><small>当前可提现积分 ${points} / 80</small></div>`;
if (info.eligible) {
body.innerHTML = `<p class="invite-hint">当前可提现积分 ${points},已达到生成条件。</p>${progressHtml}<button type="button" class="submit-publish" data-gen-invite>生成邀请码</button>${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 = `<p class="invite-hint">当前可提现积分 ${points},满 80 可生成邀请码。</p>${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
? `<div class="credit-history"><h3>信用分变化记录</h3>${result.history.map(item => `<div class="credit-history-row"><span>${escapeHtml(item.reason)}${item.reversedAt ? ' · 已撤销' : ''}</span><b class="${item.delta < 0 ? 'neg' : 'pos'}">${item.delta > 0 ? '+' : ''}${item.delta}</b><em>${escapeHtml(new Date(Number(item.createdAt)).toLocaleString('zh-CN'))}</em></div>`).join('')}</div>`
: '<p class="invite-hint">暂无信用分变化记录。</p>';
body.innerHTML = `<div class="credit-detail-score"><div><span>当前信用分(0–100)</span><strong>${score}</strong></div><div class="score-track"><i style="width:${score}%"></i></div></div><div class="credit-detail-grid"><div><strong>${escapeHtml(breach)}</strong><span>近 90 天失信率</span></div><div><strong>${Number(result.breachCount90d)||0}</strong><span>近 90 天确认失信</span></div><div><strong>${Number(result.commitments90d)||0}</strong><span>近 90 天履约承诺</span></div><div><strong>${Number(result.completedTasks)||0}</strong><span>完成任务</span></div><div><strong>${Number(result.currentStreak)||0}</strong><span>连续守约</span></div><div><strong>${escapeHtml(pointsProgress)}</strong><span>可提现积分 / 邀请码门槛</span></div></div><div class="credit-rules"><strong>信用分与积分</strong><p>积分用于任务交易与提现;信用分独立记录履约表现,范围为 0–100。普通注册信用分为 70,邀请码注册为 90。正常完成任务分别为发单者 +1、接单者 +2,每 7 天最多获得 +5。邀请码资格按可提现积分满 80 判断,与信用分无关。</p><p>失信率按近 90 天已形成履约承诺的任务数计算;少于 3 条时显示“记录较少”。积分结算不兑换信用分。</p></div>${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}`;
};