Browse Source

修复客服列表页面网络请求失败问题

pull/1/head
SwTt29 2 months ago
parent
commit
77e4750737
  1. 134
      pages/customer-service/index.js
  2. 537
      utils/api.js

134
pages/customer-service/index.js

@ -11,40 +11,26 @@ Page({
onlineCount: 0, onlineCount: 0,
userType: 'seller' // 初始化用户类型,默认为销售员 userType: 'seller' // 初始化用户类型,默认为销售员
}, },
// 获取客服列表的方法 // 获取客服列表的方法
async fetchCustomerServices() { async fetchCustomerServices() {
try { try {
console.log('开始请求客服列表...'); console.log('开始请求客服列表...');
// 导入API工具并使用正确的请求方法 // 导入API工具并使用正确的请求方法
const api = require('../../utils/api'); const api = require('../../utils/api');
// 获取当前用户类型参数 // 获取当前用户类型参数
const userType = this.data.userType || 'seller'; const userType = this.data.userType || 'seller';
const res = await new Promise((resolve, reject) => { // 使用api.js中的请求工具,自动获取正确的服务器地址
wx.request({ const apiResponse = await api.request(`/api/managers?type=${userType}`, 'GET');
url: `http://localhost:3003/api/managers?type=${userType}`,
method: 'GET', console.log('API响应数据:', apiResponse ? JSON.stringify(apiResponse) : 'undefined');
timeout: 15000,
header: {
'content-type': 'application/json'
},
success: resolve,
fail: (error) => {
console.error('网络请求失败:', error);
reject(error);
}
});
});
console.log('API响应状态码:', res?.statusCode);
console.log('API响应数据:', res?.data ? JSON.stringify(res.data) : 'undefined');
// 更宽松的响应检查,确保能处理各种有效的响应格式 // 更宽松的响应检查,确保能处理各种有效的响应格式
if (res && res.statusCode === 200 && res.data) { if (apiResponse) {
// 无论success字段是否存在,只要有data字段就尝试处理 // 无论success字段是否存在,只要有data字段就尝试处理
const dataSource = res.data.data || res.data; const dataSource = apiResponse.data || apiResponse;
if (Array.isArray(dataSource)) { if (Array.isArray(dataSource)) {
const processedData = dataSource.map(item => { const processedData = dataSource.map(item => {
// 解析information字段中的信息 // 解析information字段中的信息
@ -53,11 +39,11 @@ Page({
let purchaseCount = ''; let purchaseCount = '';
let profitFarmCount = ''; let profitFarmCount = '';
let profitIncreaseRate = ''; let profitIncreaseRate = '';
if (item.information) { if (item.information) {
// 处理不同类型的换行符(\r\n和\n) // 处理不同类型的换行符(\r\n和\n)
const lines = item.information.split(/\r?\n/).filter(line => line.trim()); const lines = item.information.split(/\r?\n/).filter(line => line.trim());
// 解析第一行:服务平台X年 服务X+鸡场 // 解析第一行:服务平台X年 服务X+鸡场
if (lines[0]) { if (lines[0]) {
const firstLine = lines[0].trim(); const firstLine = lines[0].trim();
@ -65,13 +51,13 @@ Page({
if (experienceMatch) { if (experienceMatch) {
experience = experienceMatch[1].trim() + '年'; experience = experienceMatch[1].trim() + '年';
} }
const serviceCountMatch = firstLine.match(/服务(.*?)鸡场/); const serviceCountMatch = firstLine.match(/服务(.*?)鸡场/);
if (serviceCountMatch) { if (serviceCountMatch) {
serviceCount = serviceCountMatch[1].trim(); serviceCount = serviceCountMatch[1].trim();
} }
} }
// 解析第二行:数字 数字 数字% // 解析第二行:数字 数字 数字%
if (lines[1]) { if (lines[1]) {
const secondLine = lines[1].trim(); const secondLine = lines[1].trim();
@ -83,7 +69,7 @@ Page({
} }
} }
} }
// 提取egg_section中的数字部分,去掉"鸡蛋分"后缀 // 提取egg_section中的数字部分,去掉"鸡蛋分"后缀
let score = Math.floor(Math.random() * 20) + 980; let score = Math.floor(Math.random() * 20) + 980;
if (item.egg_section) { if (item.egg_section) {
@ -92,7 +78,7 @@ Page({
score = scoreMatch[1]; score = scoreMatch[1];
} }
} }
return { return {
id: item.id || `id_${Date.now()}_${Math.random()}`, // 确保有id id: item.id || `id_${Date.now()}_${Math.random()}`, // 确保有id
managerId: item.managerId || '', managerId: item.managerId || '',
@ -160,14 +146,14 @@ Page({
const allSkills = ['渠道拓展', '供应商维护', '质量把控', '精准把控市场价格', '谈判技巧', '库存管理']; const allSkills = ['渠道拓展', '供应商维护', '质量把控', '精准把控市场价格', '谈判技巧', '库存管理'];
const skillCount = Math.floor(Math.random() * 3) + 2; // 2-4个技能 const skillCount = Math.floor(Math.random() * 3) + 2; // 2-4个技能
const selectedSkills = []; const selectedSkills = [];
while (selectedSkills.length < skillCount) { while (selectedSkills.length < skillCount) {
const skill = allSkills[Math.floor(Math.random() * allSkills.length)]; const skill = allSkills[Math.floor(Math.random() * allSkills.length)];
if (!selectedSkills.includes(skill)) { if (!selectedSkills.includes(skill)) {
selectedSkills.push(skill); selectedSkills.push(skill);
} }
} }
return selectedSkills; return selectedSkills;
}, },
@ -198,16 +184,16 @@ Page({
} catch (e) { } catch (e) {
console.log('没有正在显示的loading'); console.log('没有正在显示的loading');
} }
wx.showLoading({ title: '加载中...' }); wx.showLoading({ title: '加载中...' });
try { try {
const services = await this.fetchCustomerServices(); const services = await this.fetchCustomerServices();
console.log('获取到的客服数量:', services.length); console.log('获取到的客服数量:', services.length);
// 计算在线数量 // 计算在线数量
const onlineCount = services.filter(item => item.isOnline).length; const onlineCount = services.filter(item => item.isOnline).length;
console.log('在线客服数量:', onlineCount); console.log('在线客服数量:', onlineCount);
// 更新数据 // 更新数据
this.setData({ this.setData({
customerServices: services, customerServices: services,
@ -215,11 +201,11 @@ Page({
onlineCount: onlineCount onlineCount: onlineCount
}); });
console.log('数据更新成功'); console.log('数据更新成功');
// 应用当前的筛选条件 // 应用当前的筛选条件
this.filterServices(); this.filterServices();
console.log('筛选条件应用完成'); console.log('筛选条件应用完成');
// 如果没有数据,显示提示(确保在hideLoading后显示) // 如果没有数据,显示提示(确保在hideLoading后显示)
if (services.length === 0) { if (services.length === 0) {
setTimeout(() => { setTimeout(() => {
@ -251,18 +237,18 @@ Page({
userType: options.type || 'seller' // 默认销售员 userType: options.type || 'seller' // 默认销售员
}); });
console.log('客服列表页面加载,类型:', this.data.userType); console.log('客服列表页面加载,类型:', this.data.userType);
// 加载客服列表 // 加载客服列表
this.loadCustomerServices(); this.loadCustomerServices();
// 检查当前用户身份 // 检查当前用户身份
this.checkUserType(); this.checkUserType();
}, },
/** /**
* 检查当前用户身份 * 检查当前用户身份
*/ */
checkUserType: function() { checkUserType: function () {
const app = getApp(); const app = getApp();
const userInfo = app.globalData.userInfo || {}; const userInfo = app.globalData.userInfo || {};
const isManager = userInfo.userType === 'manager' || userInfo.type === 'manager'; const isManager = userInfo.userType === 'manager' || userInfo.type === 'manager';
@ -279,12 +265,12 @@ Page({
selected: -1 // 不选中任何tab selected: -1 // 不选中任何tab
}); });
} }
// 当页面显示时重新加载数据,确保数据最新 // 当页面显示时重新加载数据,确保数据最新
this.loadCustomerServices(); this.loadCustomerServices();
}, },
onUnload: function() { onUnload: function () {
// 停止定期刷新 // 停止定期刷新
this.stopPeriodicRefresh(); this.stopPeriodicRefresh();
}, },
@ -314,27 +300,27 @@ Page({
filterServices: function () { filterServices: function () {
const { customerServices, searchKeyword, selectedArea } = this.data; const { customerServices, searchKeyword, selectedArea } = this.data;
let filtered = customerServices; let filtered = customerServices;
// 关键词搜索 // 关键词搜索
if (searchKeyword) { if (searchKeyword) {
const keyword = searchKeyword.toLowerCase(); const keyword = searchKeyword.toLowerCase();
filtered = filtered.filter(item => { filtered = filtered.filter(item => {
return item.alias?.toLowerCase().includes(keyword) || return item.alias?.toLowerCase().includes(keyword) ||
item.name.toLowerCase().includes(keyword) || item.name.toLowerCase().includes(keyword) ||
item.phoneNumber?.includes(keyword) || item.phoneNumber?.includes(keyword) ||
item.managercompany?.toLowerCase().includes(keyword); item.managercompany?.toLowerCase().includes(keyword);
}); });
} }
// 区域筛选 // 区域筛选
if (selectedArea && selectedArea !== '全部') { if (selectedArea && selectedArea !== '全部') {
filtered = filtered.filter(item => { filtered = filtered.filter(item => {
return item.responsibleArea?.includes(selectedArea); return item.responsibleArea?.includes(selectedArea);
}); });
} }
this.setData({ this.setData({
filteredServices: filtered filteredServices: filtered
}); });
@ -346,72 +332,72 @@ Page({
console.log('=== 开始测试聊天列表功能 ==='); console.log('=== 开始测试聊天列表功能 ===');
console.log('测试用户手机号:', userPhone); console.log('测试用户手机号:', userPhone);
console.log('测试客服手机号:', managerPhone); console.log('测试客服手机号:', managerPhone);
// 1. 测试添加聊天记录(双向) // 1. 测试添加聊天记录(双向)
console.log('\n1. 测试添加聊天记录(双向)...'); console.log('\n1. 测试添加聊天记录(双向)...');
const addChatResponse = await api.addChatRecord(userPhone, managerPhone); const addChatResponse = await api.addChatRecord(userPhone, managerPhone);
console.log('添加聊天记录响应:', addChatResponse); console.log('添加聊天记录响应:', addChatResponse);
// 2. 测试用户获取聊天列表 // 2. 测试用户获取聊天列表
console.log('\n2. 测试用户获取聊天列表...'); console.log('\n2. 测试用户获取聊天列表...');
const userChatListResponse = await api.getChatList(userPhone); const userChatListResponse = await api.getChatList(userPhone);
console.log('用户聊天列表响应:', userChatListResponse); console.log('用户聊天列表响应:', userChatListResponse);
console.log('用户聊天列表数量:', Array.isArray(userChatListResponse) ? userChatListResponse.length : 0); console.log('用户聊天列表数量:', Array.isArray(userChatListResponse) ? userChatListResponse.length : 0);
// 3. 测试客服获取聊天列表 // 3. 测试客服获取聊天列表
console.log('\n3. 测试客服获取聊天列表...'); console.log('\n3. 测试客服获取聊天列表...');
const managerChatListResponse = await api.getChatList(managerPhone); const managerChatListResponse = await api.getChatList(managerPhone);
console.log('客服聊天列表响应:', managerChatListResponse); console.log('客服聊天列表响应:', managerChatListResponse);
console.log('客服聊天列表数量:', Array.isArray(managerChatListResponse) ? managerChatListResponse.length : 0); console.log('客服聊天列表数量:', Array.isArray(managerChatListResponse) ? managerChatListResponse.length : 0);
// 4. 验证双向聊天记录是否都能正确获取 // 4. 验证双向聊天记录是否都能正确获取
console.log('\n4. 验证双向聊天记录...'); console.log('\n4. 验证双向聊天记录...');
// 检查用户是否能看到与客服的聊天记录 // 检查用户是否能看到与客服的聊天记录
const userHasManagerChat = Array.isArray(userChatListResponse) && userChatListResponse.some(chat => const userHasManagerChat = Array.isArray(userChatListResponse) && userChatListResponse.some(chat =>
(chat.user_phone === userPhone && chat.manager_phone === managerPhone) || (chat.user_phone === userPhone && chat.manager_phone === managerPhone) ||
(chat.user_phone === managerPhone && chat.manager_phone === userPhone) (chat.user_phone === managerPhone && chat.manager_phone === userPhone)
); );
// 检查客服是否能看到与用户的聊天记录 // 检查客服是否能看到与用户的聊天记录
const managerHasUserChat = Array.isArray(managerChatListResponse) && managerChatListResponse.some(chat => const managerHasUserChat = Array.isArray(managerChatListResponse) && managerChatListResponse.some(chat =>
(chat.user_phone === userPhone && chat.manager_phone === managerPhone) || (chat.user_phone === userPhone && chat.manager_phone === managerPhone) ||
(chat.user_phone === managerPhone && chat.manager_phone === userPhone) (chat.user_phone === managerPhone && chat.manager_phone === userPhone)
); );
if (userHasManagerChat) { if (userHasManagerChat) {
console.log('✓ 用户可以看到与客服的聊天记录'); console.log('✓ 用户可以看到与客服的聊天记录');
} else { } else {
console.log('❌ 用户无法看到与客服的聊天记录'); console.log('❌ 用户无法看到与客服的聊天记录');
} }
if (managerHasUserChat) { if (managerHasUserChat) {
console.log('✓ 客服可以看到与用户的聊天记录'); console.log('✓ 客服可以看到与用户的聊天记录');
} else { } else {
console.log('❌ 客服无法看到与用户的聊天记录'); console.log('❌ 客服无法看到与用户的聊天记录');
} }
// 5. 测试重复添加聊天记录(应该不会重复创建) // 5. 测试重复添加聊天记录(应该不会重复创建)
console.log('\n5. 测试重复添加聊天记录...'); console.log('\n5. 测试重复添加聊天记录...');
const duplicateAddResponse = await api.addChatRecord(userPhone, managerPhone); const duplicateAddResponse = await api.addChatRecord(userPhone, managerPhone);
console.log('重复添加聊天记录响应:', duplicateAddResponse); console.log('重复添加聊天记录响应:', duplicateAddResponse);
// 6. 再次测试获取聊天列表,确保数量没有变化 // 6. 再次测试获取聊天列表,确保数量没有变化
console.log('\n6. 再次测试获取聊天列表,确保数量没有变化...'); console.log('\n6. 再次测试获取聊天列表,确保数量没有变化...');
const finalUserChatListResponse = await api.getChatList(userPhone); const finalUserChatListResponse = await api.getChatList(userPhone);
console.log('最终用户聊天列表数量:', Array.isArray(finalUserChatListResponse) ? finalUserChatListResponse.length : 0); console.log('最终用户聊天列表数量:', Array.isArray(finalUserChatListResponse) ? finalUserChatListResponse.length : 0);
const initialLength = Array.isArray(userChatListResponse) ? userChatListResponse.length : 0; const initialLength = Array.isArray(userChatListResponse) ? userChatListResponse.length : 0;
const finalLength = Array.isArray(finalUserChatListResponse) ? finalUserChatListResponse.length : 0; const finalLength = Array.isArray(finalUserChatListResponse) ? finalUserChatListResponse.length : 0;
if (finalLength === initialLength) { if (finalLength === initialLength) {
console.log('✓ 重复添加聊天记录没有导致重复数据'); console.log('✓ 重复添加聊天记录没有导致重复数据');
} else { } else {
console.log('❌ 重复添加聊天记录导致了重复数据'); console.log('❌ 重复添加聊天记录导致了重复数据');
} }
console.log('\n=== 聊天列表功能测试完成 ==='); console.log('\n=== 聊天列表功能测试完成 ===');
// 总结测试结果 // 总结测试结果
if (userHasManagerChat && managerHasUserChat) { if (userHasManagerChat && managerHasUserChat) {
console.log('\n🎉 所有测试通过!聊天列表功能正常工作。'); console.log('\n🎉 所有测试通过!聊天列表功能正常工作。');
@ -420,7 +406,7 @@ Page({
console.log('\n❌ 测试失败!聊天列表功能存在问题。'); console.log('\n❌ 测试失败!聊天列表功能存在问题。');
return false; return false;
} }
} catch (error) { } catch (error) {
console.error('测试过程中出现错误:', error.message); console.error('测试过程中出现错误:', error.message);
if (error.response) { if (error.response) {
@ -496,17 +482,17 @@ Page({
console.log('聊天建立成功:', JSON.stringify(res, null, 2)); console.log('聊天建立成功:', JSON.stringify(res, null, 2));
// 隐藏加载提示 // 隐藏加载提示
wx.hideLoading(); wx.hideLoading();
// 使用客服手机号作为聊天会话ID // 使用客服手机号作为聊天会话ID
const chatSessionId = service.phoneNumber; const chatSessionId = service.phoneNumber;
// 跳转到聊天页面,确保正确传递客服手机号和用户名 // 跳转到聊天页面,确保正确传递客服手机号和用户名
wx.navigateTo({ wx.navigateTo({
url: `/pages/chat-detail/index?userId=${chatSessionId}&userName=${encodeURIComponent(service?.alias || '')}&phone=${service?.phoneNumber || ''}&isManager=true` url: `/pages/chat-detail/index?userId=${chatSessionId}&userName=${encodeURIComponent(service?.alias || '')}&phone=${service?.phoneNumber || ''}&isManager=true`
}); });
console.log('跳转到聊天页面:', { console.log('跳转到聊天页面:', {
chatUserId: chatSessionId, chatUserId: chatSessionId,
userName: service?.alias, userName: service?.alias,
customerServicePhone: service?.phoneNumber, customerServicePhone: service?.phoneNumber,
userPhone: userPhone userPhone: userPhone
}); });

537
utils/api.js

File diff suppressed because it is too large
Loading…
Cancel
Save