Browse Source

修改用户身份显示逻辑:直接返回数据库中的type字段值

pull/1/head
徐飞洋 3 months ago
parent
commit
6da27839b5
  1. 210
      pages/profile/index.js
  2. 77
      pages/settlement/index.js
  3. 31
      server-example/server-mysql-backup-final.js
  4. 34
      server-example/server-mysql.js

210
pages/profile/index.js

@ -47,7 +47,7 @@ Page({
console.log('加载用户信息 - userId:', userId, 'openid:', openid ? '已获取' : '未获取')
if (userId && openid) {
// 从服务器获取最新的用户信息,确保手机号是最新的
// 从服务器获取最新的用户信息,确保身份由数据库决定
this.refreshUserInfoFromServer(openid, userId)
// 确保users存储结构存在
@ -62,68 +62,65 @@ Page({
wx.setStorageSync('users', users)
}
// 先显示本地存储的用户类型,但会被服务器返回的最新值覆盖
const user = users[userId]
const currentType = this.formatUserType(user.type)
this.setData({ userType: currentType })
console.log('加载用户信息 - 当前用户类型:', currentType)
console.log('加载用户信息 - 当前本地存储的用户类型:', currentType)
// 确保tags存储结构存在
let tags = wx.getStorageSync('tags')
if (!tags) {
tags = {}
wx.setStorageSync('tags', tags)
}
// 先使用本地存储的用户类型更新标签,后续会被服务器返回的最新值覆盖
this.updateUserTags(userId, user.type)
}
},
if (!tags[userId]) {
tags[userId] = []
wx.setStorageSync('tags', tags)
}
// 更新用户标签
updateUserTags(userId, userType) {
// 确保tags存储结构存在
let tags = wx.getStorageSync('tags')
if (!tags) {
tags = {}
wx.setStorageSync('tags', tags)
}
if (!tags[userId]) {
tags[userId] = []
wx.setStorageSync('tags', tags)
}
const userTags = tags[userId] || []
console.log('加载用户信息 - 原始标签:', userTags)
const userTags = tags[userId] || []
console.log('加载用户信息 - 原始标签:', userTags)
// 使用indexOf替代includes以解决Babel兼容性问题
let firstCategoryTag = []
let identityTags = []
// 使用indexOf替代includes以解决Babel兼容性问题
let firstCategoryTag = []
// 查找第一个偏好品类标签
for (let i = 0; i < userTags.length; i++) {
if (userTags[i].indexOf('偏好品类') !== -1) {
firstCategoryTag = [userTags[i]]
break
}
// 查找第一个偏好品类标签
for (let i = 0; i < userTags.length; i++) {
if (userTags[i].indexOf('偏好品类') !== -1) {
firstCategoryTag = [userTags[i]]
break
}
}
// 合并保留的标签
let filteredTags = [...firstCategoryTag]
// 合并保留的标签
let filteredTags = [...firstCategoryTag]
// 始终根据当前用户类型显示对应的身份标签,而不是使用存储的标签
if (user.type && user.type !== '') {
let identityLabel = '身份:not_set'
switch (user.type) {
case 'buyer': identityLabel = '身份:buyer'; break
case 'seller': identityLabel = '身份:seller'; break
case 'both': identityLabel = '身份:buyer+seller'; break
}
filteredTags.push(identityLabel)
console.log('加载用户信息 - 根据当前用户类型显示身份标签:', identityLabel)
} else {
// 如果没有用户类型,但有存储的身份标签,显示第一个
for (let i = 0; i < userTags.length; i++) {
if (userTags[i].indexOf('身份') !== -1) {
filteredTags.push(userTags[i])
console.log('加载用户信息 - 显示存储的身份标签:', userTags[i])
break
}
}
// 始终根据当前用户类型显示对应的身份标签
if (userType && userType !== '') {
let identityLabel = 'identity:not_set'
switch (userType) {
case 'buyer': identityLabel = 'identity:buyer'; break
case 'seller': identityLabel = 'identity:seller'; break
case 'both': identityLabel = 'identity:buyer+seller'; break
}
console.log('加载用户信息 - 过滤后的标签:', filteredTags)
this.setData({ userTags: filteredTags })
filteredTags.push(identityLabel)
console.log('加载用户信息 - 根据当前用户类型显示身份标签:', identityLabel)
}
console.log('加载用户信息 - 过滤后的标签:', filteredTags)
this.setData({ userTags: filteredTags })
},
// 从服务器刷新用户信息
// 从服务器刷新用户信息并同步身份数据
refreshUserInfoFromServer(openid, userId) {
const API = require('../../utils/api.js')
@ -144,7 +141,12 @@ Page({
wx.setStorageSync('userInfo', updatedUserInfo)
this.setData({ userInfo: updatedUserInfo })
console.log('用户信息已更新,昵称:', updatedUserInfo.nickName, '手机号:', updatedUserInfo.phoneNumber)
// 同步更新用户身份信息(当前身份由数据库决定)
if (serverUserInfo.type) {
this.syncUserTypeFromServer(userId, serverUserInfo.type)
}
console.log('用户信息已更新,昵称:', updatedUserInfo.nickName, '手机号:', updatedUserInfo.phoneNumber, '身份:', serverUserInfo.type)
}
}).catch(err => {
console.error('从服务器获取用户信息失败:', err)
@ -166,6 +168,11 @@ Page({
wx.setStorageSync('userInfo', updatedUserInfo)
this.setData({ userInfo: updatedUserInfo })
// 同步更新用户身份信息(当前身份由数据库决定)
if (serverUserInfo.type) {
this.syncUserTypeFromServer(userId, serverUserInfo.type)
}
console.log('用户信息已更新(备选方案):', updatedUserInfo)
}
}).catch(validateErr => {
@ -175,61 +182,102 @@ Page({
})
},
// 格式化用户类型显示
formatUserType(type) {
switch (type) {
case 'buyer': return '买家'
case 'seller': return '卖家'
case 'both': return '买家+卖家'
default: return '未设置'
// 从服务器同步用户身份信息
syncUserTypeFromServer(userId, serverType) {
if (!userId || !serverType) {
console.error('同步用户身份信息失败: 参数不完整')
return
}
console.log('从服务器同步用户身份信息:', { userId, serverType })
// 更新本地存储的用户身份
let users = wx.getStorageSync('users') || {}
if (!users[userId]) {
users[userId] = {}
}
// 只有当服务器返回的身份与本地不同时才更新
if (users[userId].type !== serverType) {
users[userId].type = serverType
wx.setStorageSync('users', users)
// 更新全局用户类型
const app = getApp()
app.globalData.userType = serverType
// 更新页面显示的用户类型
this.setData({
userType: this.formatUserType(serverType)
})
console.log('用户身份已从服务器同步:', serverType)
} else {
console.log('用户身份与服务器一致,无需更新:', serverType)
}
// 更新用户标签
this.updateUserTags(userId, serverType)
},
// 格式化用户类型显示 - 直接返回数据库中的type字段值
formatUserType(type) {
return type || 'not_set'
},
// 设置为买家
setAsBuyer() {
this.switchUserType('buyer', '买家')
this.switchUserType('buyer', 'buyer')
},
// 设置为卖家
setAsSeller() {
this.switchUserType('seller', '卖家')
this.switchUserType('seller', 'seller')
},
// 切换用户类型的通用方法
switchUserType(newType, typeName) {
const userId = wx.getStorageSync('userId')
const openid = wx.getStorageSync('openid')
const userInfo = wx.getStorageSync('userInfo')
if (!userId || !openid) {
wx.navigateTo({ url: '/pages/index/index' })
return
}
// 更新本地存储中的用户类型
let users = wx.getStorageSync('users') || {}
if (!users[userId]) {
users[userId] = {}
}
users[userId].type = newType
wx.setStorageSync('users', users)
// 更新全局数据
const app = getApp()
app.globalData.userType = newType
// 上传更新后的用户信息到服务器
this.uploadUserTypeToServer(openid, userId, userInfo, newType)
// 显示操作中的提示
wx.showLoading({ title: 'Switching...' })
// 更新页面显示
this.setData({
userType: this.formatUserType(newType)
})
// 引入API服务
const API = require('../../utils/api.js')
wx.showToast({
title: `已切换为${typeName}`,
icon: 'success',
duration: 2000
// 使用API更新用户类型,确保与服务器同步
API.updateUserType(newType).then(res => {
console.log('用户类型更新成功:', res)
// 更新页面显示
const app = getApp()
this.setData({
userType: this.formatUserType(app.globalData.userType)
})
// 更新用户标签
this.updateUserTags(userId, app.globalData.userType)
wx.showToast({
title: `Switched to ${typeName}`,
icon: 'success',
duration: 2000
})
}).catch(err => {
console.error('用户类型更新失败:', err)
wx.showToast({
title: 'Failed to switch, please retry',
icon: 'none',
duration: 2000
})
}).finally(() => {
wx.hideLoading()
})
},

77
pages/settlement/index.js

@ -601,20 +601,21 @@ Page({
console.log('最终获取到的手机号:', contactPhone);
// 根据后端API要求构建submitData对象(使用独立的省市区字段)
// 确保所有必填字段都有默认值,防止传递undefined到后端
const submitData = {
openid: openid,
collaborationid: this.data.collaborationid, // 合作商身份ID
company: this.data.company || '', // 客户公司名称
province: this.data.province, // 省份
city: this.data.city, // 城市
district: this.data.district, // 区县
detailedaddress: this.data.detailedaddress || '', // 详细地址(即使为空也要传递)
cooperation: this.data.cooperation === '货源委托' ? 'wholesale' : this.data.cooperation, // 合作模式映射为后端期望的值
phoneNumber: contactPhone, // 后端期望的字段名是phoneNumber
openid: openid || '', // 确保openid非空
collaborationid: this.data.collaborationid || '', // 合作商身份ID,确保非空
company: this.data.company || '', // 客户公司名称,确保非空
province: this.data.province || '', // 省份,确保非空
city: this.data.city || '', // 城市,确保非空
district: this.data.district || '', // 区县,确保非空
detailedaddress: this.data.detailedaddress || '', // 详细地址(即使为空也要传递)
cooperation: this.data.cooperation === '货源委托' ? 'wholesale' : (this.data.cooperation || ''), // 确保合作模式非空
phoneNumber: contactPhone || '', // 后端期望的字段名是phoneNumber,确保非空
businesslicenseurl: uploadedFiles.businessLicenseFile || '', // 营业执照URL
proofurl: uploadedFiles.animalQuarantineFile || '', // 动物检疫证明或法人身份证URL(两者共用一个字段)
brandurl: uploadedFiles.brandAuthFile || '', // 品牌授权链URL
userId: userId
proofurl: uploadedFiles.animalQuarantineFile || '', // 动物检疫证明或法人身份证URL(两者共用一个字段)
brandurl: uploadedFiles.brandAuthFile || '', // 品牌授权链URL
userId: userId || '' // 确保userId非空
};
// 特别记录详细地址字段,确保它被正确提交
@ -658,9 +659,34 @@ Page({
title: '请先登录',
icon: 'none'
});
// 显示登录弹窗,引导用户登录
this.setData({
showAuthModal: true
});
return;
}
// 检查用户是否已经获取手机号
let userInfo = wx.getStorageSync('userInfo');
if (!userInfo || !userInfo.phoneNumber || userInfo.phoneNumber === '未绑定') {
wx.showToast({
title: '请先授权手机号',
icon: 'none'
});
// 显示登录弹窗,引导用户授权手机号
this.setData({
showAuthModal: true
});
return;
}
// 如果用户已经获取手机号,确保手机号字段正确赋值
if (userInfo.phoneNumber && userInfo.phoneNumber !== '未绑定') {
submitData.phoneNumber = userInfo.phoneNumber;
contactPhone = userInfo.phoneNumber;
console.log('使用登录获取的手机号:', contactPhone);
}
if (!this.data.collaborationid) {
wx.showToast({
title: '请选择合作商身份',
@ -685,12 +711,19 @@ Page({
return;
}
// 手机号为空时使用默认值,不再强制要求
// 强制要求手机号
if (!contactPhone) {
contactPhone = 'default_phone';
console.log('使用默认手机号:', contactPhone);
wx.showToast({
title: '请填写手机号',
icon: 'none'
});
return;
}
// 更新submitData中的手机号
submitData.phoneNumber = contactPhone;
console.log('使用的手机号:', contactPhone);
// 验证省市区字段是否填写完整(用于构建region字段)
if (!this.data.province || !this.data.city || !this.data.district) {
wx.showToast({
@ -711,9 +744,19 @@ Page({
});
try {
// 调用后端API提交入驻申请
// 使用API.BASE_URL构建正确的请求路径
// 调用后端API提交入驻申请前,先获取用户所有信息
const API = require('../../utils/api');
console.log('开始获取用户所有信息');
const userRes = await API.getUserInfo(openid);
console.log('获取用户信息成功:', userRes);
// 更新本地存储的用户信息
if (userRes && userRes.data) {
wx.setStorageSync('userInfo', userRes.data);
console.log('已更新本地存储的用户信息');
}
// 继续提交入驻申请
console.log('开始提交入驻申请,API地址:', API.BASE_URL + '/api/settlement/submit');
console.log('提交的完整数据:', submitData);
// 详细检查后端必需的关键字段(使用独立的省市区字段)

31
server-example/server-mysql-backup-final.js

@ -2588,6 +2588,37 @@ app.post('/api/product/publish', async (req, res) => {
console.log('发布商品 - 数据库查询后grossWeight:', createdProduct.grossWeight, '类型:', typeof createdProduct.grossWeight);
}
// 更新用户类型:如果字段为空则填入seller,如果为buyer则修改为both
try {
// 重新获取用户信息以确保获取到最新数据
const currentUser = await User.findOne({ where: { userId: user.userId } });
if (currentUser) {
console.log('更新用户类型前 - 当前用户类型:', currentUser.type);
// 检查用户类型并根据需求更新
if ((currentUser.type === null || currentUser.type === undefined || currentUser.type === '') || currentUser.type === 'buyer') {
let newType = '';
if (currentUser.type === 'buyer') {
newType = 'both';
} else {
newType = 'seller';
}
// 更新用户类型
await User.update(
{ type: newType },
{ where: { userId: user.userId } }
);
console.log('用户类型更新成功 - 用户ID:', user.userId, '旧类型:', currentUser.type, '新类型:', newType);
} else {
console.log('不需要更新用户类型 - 用户ID:', user.userId, '当前类型:', currentUser.type);
}
}
} catch (updateError) {
console.error('更新用户类型失败:', updateError);
// 不影响商品发布结果,仅记录错误
}
res.json({
success: true,
code: 200,

34
server-example/server-mysql.js

@ -2802,6 +2802,40 @@ try {
productImageUrlsCount: customResponseData.product?.imageUrls?.length
});
// 更新用户类型:如果字段为空则填入seller,如果为buyer则修改为both
// 只在创建新商品时执行,不更新商品时执行
if (!isUpdate) {
try {
// 获取当前用户信息
const currentUser = await User.findOne({ where: { userId: actualSellerId } });
if (currentUser) {
console.log('更新用户类型前 - 当前用户类型:', currentUser.type, '用户ID:', currentUser.userId);
// 检查用户类型并根据需求更新
if ((currentUser.type === null || currentUser.type === undefined || currentUser.type === '') || currentUser.type === 'buyer') {
let newType = '';
if (currentUser.type === 'buyer') {
newType = 'both';
} else {
newType = 'seller';
}
// 更新用户类型
await User.update(
{ type: newType },
{ where: { userId: actualSellerId } }
);
console.log('用户类型更新成功 - 用户ID:', currentUser.userId, '旧类型:', currentUser.type, '新类型:', newType);
} else {
console.log('不需要更新用户类型 - 用户ID:', currentUser.userId, '当前类型:', currentUser.type);
}
}
} catch (updateError) {
console.error('更新用户类型失败:', updateError);
// 不影响商品发布结果,仅记录错误
}
}
// 发送最终增强的响应
res.status(200).json(customResponseData);
} catch (err) {

Loading…
Cancel
Save