聊天:订单状态实时展示、图片收发修复、联系打手跳转优化

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
XingQue
2026-06-24 00:43:31 +08:00
parent 7b3e7a39e9
commit 53548b6a61
10 changed files with 515 additions and 139 deletions

View File

@@ -1,7 +1,8 @@
// utils/chat-core.js
import GoEasy from '../static/lib/goeasy-2.13.24.esm.min';
import { jianquanxian } from './imAuth/jianquanxian';
import { getFreshImUser } from './im-user.js';
import { parseOrderCardText } from './group-chat.js';
import { persistGroupMeta } from './im-user.js';
let _globalPrivateHandler = null;
let _globalGroupHandler = null;
@@ -200,7 +201,9 @@ function disconnectGoEasy(app) {
async function connectWithIdentity(app, identityType, userId, isAutoRestore = false) {
const quanxian = await jianquanxian(app);
if (!quanxian.allowed) return Promise.reject(quanxian.reason);
if (!quanxian.allowed) {
return Promise.reject(new Error(quanxian.reason || '无聊天权限'));
}
app.globalData.goEasyConnection.autoReconnect = true;
app.globalData.goEasyConnection.status = 'connecting';
@@ -444,14 +447,8 @@ function handleNewMessage(app, message) {
function shouldShowNotification(app) {
if (app.globalData.messageManager.notificationMuted) return false;
if (isDoNotDisturbTime(app)) return false;
if (app.globalData.pageState.isInChatPage) {
const pages = getCurrentPages();
if (pages.length > 0) {
const currentPage = pages[pages.length - 1];
if (currentPage.data && currentPage.data.currentChatId) {
if (isMessageFromCurrentChat(app, currentPage.data.currentChatId)) return false;
}
}
if (app.globalData.pageState.isInChatPage && app.globalData.pageState.currentChatId) {
return false;
}
return true;
}
@@ -472,8 +469,16 @@ function isDoNotDisturbTime(app) {
}
}
function isMessageFromCurrentChat(app, currentChatId) {
return false;
function isMessageFromCurrentChat(app, message) {
const pageState = app.globalData.pageState || {};
if (!pageState.isInChatPage || !pageState.currentChatId) return false;
if (message.groupId) {
return message.groupId === pageState.currentChatId;
}
const myId = app.globalData.goEasyConnection?.userId || getCurrentGoEasyUserId();
if (!myId) return false;
const peerId = message.senderId === myId ? message.receiverId : message.senderId;
return peerId === pageState.currentChatId || message.senderId === pageState.currentChatId;
}
function showNotificationDirect(app, data) {
@@ -534,6 +539,20 @@ function formatMessageForNotification(message) {
}
function cacheMessage(app, message) {
if (message.groupId && message.type === 'text' && message.payload?.text) {
const card = parseOrderCardText(message.payload.text);
if (card && card.zhuangtai != null) {
if (!app.globalData.groupInfoMap) app.globalData.groupInfoMap = {};
const meta = {
...(app.globalData.groupInfoMap[message.groupId] || {}),
orderId: card.orderId,
orderZhuangtai: card.zhuangtai,
orderDesc: card.jieshao,
};
app.globalData.groupInfoMap[message.groupId] = meta;
persistGroupMeta(app, message.groupId, meta);
}
}
const { latestMessages } = app.globalData.messageManager;
latestMessages.unshift({
id: message.messageId,

View File

@@ -8,6 +8,39 @@ const ZHUANGTAI_MAP = {
5: '已退款', 6: '退款失败', 7: '指定中', 8: '结算中',
};
export function getZhuangtaiText(zhuangtai) {
if (zhuangtai == null || zhuangtai === '') return '';
const n = Number(zhuangtai);
return ZHUANGTAI_MAP[n] || ZHUANGTAI_MAP[zhuangtai] || '';
}
export function buildDashouShangjiaGroupId(dashouUid, shangjiaUid) {
return `group_Ds${dashouUid}_Sj${shangjiaUid}`;
}
export function buildDashouBossGroupId(dashouUid, bossUid) {
return `group_Ds${dashouUid}_Boss${bossUid}`;
}
export function resolveLocalGroupId(identityType, myUid, partnerUid, fadanPingtai, orderId, isCross) {
const cross = isCross === 1 || isCross === true || String(isCross) === '1';
if (cross && orderId) {
return `group_${orderId}`;
}
if (!myUid) return orderId ? `group_${orderId}` : null;
if (!partnerUid) return orderId ? `group_${orderId}` : null;
if (identityType === 'shangjia') {
return buildDashouShangjiaGroupId(partnerUid, myUid);
}
if (identityType === 'dashou') {
if (fadanPingtai === 2 || String(fadanPingtai) === '2') {
return buildDashouShangjiaGroupId(myUid, partnerUid);
}
return buildDashouBossGroupId(myUid, partnerUid);
}
return orderId ? `group_${orderId}` : null;
}
export function isPairGroupId(groupId) {
return /^group_Ds\w+_(Sj|Boss)\w+$/.test(groupId || '');
}
@@ -108,6 +141,8 @@ export function parseOrderCardText(text) {
}
}
import { getChatImageUrl } from '../static/lib/utils.js';
export function normalizeGroupMessage(msg) {
if (!msg) return msg;
if (msg.type === 'text' && msg.payload && msg.payload.text) {
@@ -117,6 +152,26 @@ export function normalizeGroupMessage(msg) {
msg.payload = card;
}
}
if (msg.type === 'custom' && msg.payload) {
const inner = msg.payload.payload || msg.payload;
if (inner && (inner.orderId || inner.dingdan_id)) {
msg.type = 'order';
msg.payload = {
orderId: inner.orderId || inner.dingdan_id,
jieshao: inner.jieshao || '',
jine: inner.jine || '',
beizhu: inner.beizhu || '',
zhuangtai: inner.zhuangtai,
nicheng: inner.nicheng || '',
create_time: inner.create_time || '',
};
}
}
if (msg.type === 'image') {
const url = getChatImageUrl(msg);
msg.payload = { ...(msg.payload || {}), url };
msg.imageUrl = url;
}
return msg;
}

View File

@@ -3,6 +3,11 @@ const app = getApp();
import { formatDate } from '../static/lib/utils';
import request from './request.js';
import { getFreshImUser } from './im-user.js';
import { sendGoEasyImage } from './chatImageSend.js';
function isCrossPlatformOrder(isCross) {
return isCross === 1 || isCross === true || String(isCross) === '1';
}
function sendGroupMessage(options) {
const { msgData, onSuccess, onSendStart } = options;
@@ -20,8 +25,7 @@ function sendGroupMessage(options) {
const localMsg = buildLocalMessage(msgData);
if (onSendStart) onSendStart(localMsg);
// 只有 isCross 明确为 0 才走前端 SDK其余一律走后端
if (isCross === 0) {
if (!isCrossPlatformOrder(isCross)) {
sendViaSDK(localMsg, currentUser, groupId, onSuccess, orderId, isCross, groupName, groupAvatar);
return;
}
@@ -32,7 +36,7 @@ function buildLocalMessage(data) {
const { type, text, filePath, orderPayload, currentUser, groupId } = data;
const now = Date.now();
const base = {
messageId: `${type}-${now}`,
messageId: `local-${type}-${now}`,
timestamp: now,
senderId: currentUser.id,
groupId: groupId,
@@ -45,7 +49,7 @@ function buildLocalMessage(data) {
};
if (type === 'text') return { ...base, type: 'text', payload: { text } };
if (type === 'image') return { ...base, type: 'image', payload: { url: filePath } };
if (type === 'image') return { ...base, type: 'image', payload: { url: filePath }, imageUrl: filePath };
if (type === 'order') return { ...base, type: 'order', payload: orderPayload };
return base;
}
@@ -66,6 +70,7 @@ function sendViaSDK(localMsg, currentUser, groupId, onSuccess, orderId, isCross,
dashouAvatar: groupMeta.dashouAvatar,
partnerAvatar: groupMeta.partnerAvatar,
orderDesc: groupMeta.orderDesc,
orderZhuangtai: groupMeta.orderZhuangtai,
};
const to = {
@@ -74,18 +79,35 @@ function sendViaSDK(localMsg, currentUser, groupId, onSuccess, orderId, isCross,
data: toData
};
if (localMsg.type === 'image') {
sendGoEasyImage({
file: localMsg.payload.url,
to,
onSuccess: (res) => {
const serverMsg = res && res.content;
if (serverMsg && onSuccess) {
onSuccess(localMsg.messageId, 'success', serverMsg);
} else if (onSuccess) {
onSuccess(localMsg.messageId, 'success');
}
},
onFailed: () => { if (onSuccess) onSuccess(localMsg.messageId, 'failed'); }
});
return;
}
let message;
if (localMsg.type === 'text') {
message = wx.goEasy.im.createTextMessage({ text: localMsg.payload.text, to });
} else if (localMsg.type === 'image') {
message = wx.goEasy.im.createImageMessage({ file: localMsg.payload.url, to });
} else if (localMsg.type === 'order') {
message = wx.goEasy.im.createCustomMessage({ type: 'order', payload: localMsg.payload, to });
}
wx.goEasy.im.sendMessage({
message,
onSuccess: () => { if (onSuccess) onSuccess(localMsg.messageId, 'success'); },
onSuccess: (res) => {
if (onSuccess) onSuccess(localMsg.messageId, 'success', res && res.content);
},
onFailed: () => { if (onSuccess) onSuccess(localMsg.messageId, 'failed'); }
});
}
@@ -93,18 +115,17 @@ function sendViaSDK(localMsg, currentUser, groupId, onSuccess, orderId, isCross,
function sendViaBackend(localMsg, currentUser, groupId, orderId, onSuccess) {
const apiUrl = '/dingdan/kptxxfs';
// 🔥 实时获取当前身份,不再依赖外部传入的 currentUser.id
const uid = wx.getStorageSync('uid');
const role = app.globalData.currentRole || 'normal';
const prefixMap = { normal: 'Boss', dashou: 'Ds', shangjia: 'Sj', guanshi: 'Gs', zuzhang: 'Zz' };
const identityType = role === 'dashou' ? 'dashou' : (role === 'shangjia' ? 'shangjia' : 'boss');
const prefixMap = { normal: 'Boss', dashou: 'Ds', shangjia: 'Sj', guanshi: 'Gs', zuzhang: 'Zz' };
const prefix = prefixMap[role] || 'Boss';
const senderId = prefix + uid;
const freshUser = getFreshImUser(app, role, uid);
const params = {
orderId: orderId,
groupId: groupId,
identityType: identityType, // 告诉后端当前是什么身份
identityType: identityType,
senderId: senderId,
senderName: freshUser.name || currentUser.name || ('用户' + uid),
senderAvatar: freshUser.avatar || currentUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang),
@@ -135,7 +156,6 @@ function sendViaBackend(localMsg, currentUser, groupId, orderId, onSuccess) {
return;
}
// 图片消息
if (localMsg.type === 'image') {
const token = wx.getStorageSync('token');
const formData = {
@@ -169,4 +189,4 @@ function sendViaBackend(localMsg, currentUser, groupId, orderId, onSuccess) {
}
}
module.exports = { sendGroupMessage };
module.exports = { sendGroupMessage };

View File

@@ -1,42 +1,46 @@
/**
* 连接管理模块 - 订单群聊跳转(后端准备群 + 稳定连接)
* 订单群聊跳转:先确定群 IDIM 连接失败也尽量能进聊天页
*/
import request from './request';
import { persistGroupMeta } from './im-user.js';
import { resolveLocalGroupId } from './group-chat.js';
const app = getApp();
function waitForConnection(expectedUserId, timeout = 15000) {
function formatError(err) {
if (!err) return '进入聊天失败';
if (typeof err === 'string') return err;
if (err.message) return err.message;
if (err.content) return String(err.content);
if (err.msg) return String(err.msg);
if (err.code) return `连接失败(${err.code})`;
try {
return JSON.stringify(err);
} catch (e) {
return '进入聊天失败';
}
}
function withTimeout(promise, ms, errMsg) {
return new Promise((resolve, reject) => {
const status = wx.goEasy?.getConnectionStatus?.();
const currentUserId = wx.goEasy?.im?.userId;
if ((status === 'connected' || status === 'reconnected') && currentUserId === expectedUserId) {
resolve();
return;
}
const timer = setTimeout(() => {
app.off('connectionChanged', handler);
reject(new Error('连接超时'));
}, timeout);
const handler = (event) => {
if (event.status === 'connected') {
const uid = event.userId || wx.goEasy?.im?.userId;
if (uid === expectedUserId) {
clearTimeout(timer);
app.off('connectionChanged', handler);
resolve();
}
} else if (event.status === 'disconnected' && event.manual) {
clearTimeout(timer);
app.off('connectionChanged', handler);
reject(new Error('连接已断开'));
}
};
app.on('connectionChanged', handler);
const timer = setTimeout(() => reject(new Error(errMsg || '操作超时')), ms);
promise
.then((v) => { clearTimeout(timer); resolve(v); })
.catch((e) => { clearTimeout(timer); reject(e); });
});
}
function getConnectedUserId() {
const fromState = app.globalData?.goEasyConnection?.userId;
const fromIm = wx.goEasy?.im?.userId;
return fromState || fromIm || '';
}
function isImConnected() {
const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
return status === 'connected' || status === 'reconnected';
}
async function ensureIdentityConnection(identityType, userId) {
app.globalData.currentRole = identityType;
wx.setStorageSync('currentRole', identityType);
@@ -50,21 +54,88 @@ async function ensureIdentityConnection(identityType, userId) {
avatar: avatar,
};
const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
const currentUserId = wx.goEasy?.im?.userId;
if (!app.globalData.chatEnabled || !wx.goEasy?.im) {
throw new Error('聊天服务未就绪,请稍后重试');
}
if ((status === 'connected' || status === 'reconnected') && currentUserId === userId) {
if (isImConnected() && getConnectedUserId() === userId) {
return;
}
if (currentUserId && currentUserId !== userId && app.disconnectGoEasy) {
const connectedId = getConnectedUserId();
if (connectedId && connectedId !== userId && app.disconnectGoEasy) {
await app.disconnectGoEasy();
}
const waitPromise = waitForConnection(userId);
const connectPromise = app.connectWithIdentity(identityType, userId, true);
await waitPromise;
await connectPromise;
if (!app.connectWithIdentity) {
throw new Error('聊天功能未初始化');
}
await withTimeout(
app.connectWithIdentity(identityType, userId, true),
12000,
'IM连接超时'
);
if (!isImConnected()) {
throw new Error('IM连接失败请检查网络后重试');
}
}
async function prepareGroupChat(identityType, userId, orderId, partnerUid, fadanPingtai, groupName, isCross) {
let chatData = null;
try {
const res = await withTimeout(
request({
url: '/dingdan/ltdhzb',
method: 'POST',
data: {
dingdan_id: orderId,
identityType,
push_order_card: true,
},
}),
12000,
'准备群聊超时'
);
const body = res?.data || {};
if (body.code === 0 && body.data?.groupId) {
chatData = body.data;
} else if (body.msg) {
console.warn('ltdhzb:', body.msg);
}
} catch (e) {
console.warn('ltdhzb 请求失败,尝试本地 groupId', e);
}
if (!chatData?.groupId) {
const myUid = userId.replace(/^(Ds|Sj|Boss)/, '');
let localGroupId = resolveLocalGroupId(
identityType, myUid, partnerUid, fadanPingtai, orderId, isCross
);
if (!localGroupId && orderId) {
localGroupId = `group_${orderId}`;
}
if (!localGroupId) {
throw new Error('无法确定群聊,请确认订单已接单且对方信息完整');
}
chatData = {
groupId: localGroupId,
orderId,
groupName: groupName || '订单群聊',
isCross: isCross || fadanPingtai || 0,
};
try {
await request({
url: '/dingdan/ltdhzb',
method: 'POST',
data: { dingdan_id: orderId, identityType, push_order_card: true },
});
} catch (e) { /* ignore */ }
}
return chatData;
}
class ConnectionManager {
@@ -89,39 +160,30 @@ class ConnectionManager {
};
const param = { to, currentUser };
const path = '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param));
wx.navigateTo({ url: path });
wx.navigateTo({ url: '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param)) });
}
async connectToGroupChat(params) {
const { identityType, userId, orderId, groupName, groupAvatar, isCross } = params;
const {
identityType, userId, orderId, groupName, groupAvatar, isCross,
partnerUid, fadanPingtai,
} = params;
if (!identityType || !userId || !orderId) {
throw new Error('参数不完整identityType, userId, orderId 必填');
throw new Error('参数不完整');
}
app.globalData.currentRole = identityType;
wx.setStorageSync('currentRole', identityType);
wx.showLoading({ title: '建立联系中...', mask: true });
try {
await ensureIdentityConnection(identityType, userId);
const chatData = await prepareGroupChat(
identityType, userId, orderId, partnerUid, fadanPingtai || isCross, groupName, isCross
);
const res = await request({
url: '/dingdan/ltdhzb',
method: 'POST',
data: {
dingdan_id: orderId,
identityType,
push_order_card: true,
},
});
const body = res?.data || {};
if (body.code !== 0 || !body.data || !body.data.groupId) {
throw new Error(body.msg || '准备群聊失败');
}
const chatData = body.data;
const realGroupId = chatData.groupId;
let avatar = chatData.counterpartAvatar || chatData.groupAvatar || groupAvatar || '';
if (avatar && !avatar.startsWith('http')) {
avatar = app.globalData.ossImageUrl + avatar.replace(/^\//, '');
@@ -148,30 +210,57 @@ class ConnectionManager {
app.globalData.groupInfoMap[realGroupId] = meta;
persistGroupMeta(app, realGroupId, meta);
await new Promise((resolve, reject) => {
wx.goEasy.im.subscribeGroup({
groupIds: [realGroupId],
onSuccess: () => resolve(),
onFailed: (error) => reject(error),
});
});
let imReady = false;
try {
await ensureIdentityConnection(identityType, userId);
imReady = true;
try {
await withTimeout(
new Promise((resolve, reject) => {
wx.goEasy.im.subscribeGroup({
groupIds: [realGroupId],
onSuccess: () => resolve(),
onFailed: (error) => reject(error),
});
}),
8000,
'订阅群聊超时'
);
} catch (subErr) {
console.warn('订阅群聊失败,仍尝试进入页面', subErr);
}
} catch (imErr) {
console.warn('IM连接失败仍进入聊天页由页面重连', imErr);
}
const uid = userId.replace(/^(Ds|Sj|Boss)/, '');
const param = {
groupId: realGroupId,
orderId: chatData.orderId || orderId,
groupName: chatData.counterpartName || chatData.groupName || groupName || '订单群聊',
groupAvatar: avatar,
isCross: chatData.isCross != null ? chatData.isCross : (isCross || 0),
currentUserId: userId,
currentUserName: app.globalData.currentUser?.name || `用户${uid}`,
currentUserAvatar: app.globalData.currentUser?.avatar ||
(wx.getStorageSync('touxiang') || (app.globalData.ossImageUrl + app.globalData.morentouxiang)),
orderZhuangtai: chatData.orderZhuangtai,
orderJine: chatData.orderJine,
orderDesc: chatData.orderDesc || '',
imReady,
};
wx.hideLoading();
wx.navigateTo({
url: '/pages/qunliaotian/qunliaotian?data=' + encodeURIComponent(JSON.stringify(param)),
fail: (navErr) => {
wx.showToast({ title: formatError(navErr), icon: 'none', duration: 2500 });
},
});
} catch (err) {
wx.hideLoading();
console.error('跳转群聊失败:', err);
wx.showToast({ title: err.message || '进入聊天失败', icon: 'none' });
wx.showToast({ title: formatError(err), icon: 'none', duration: 2500 });
throw err;
}
}