Browse Source

Fix: Remove default comments and fix comment display issue

pull/18/head
徐飞洋 1 month ago
parent
commit
7a5a1ba300
  1. 16
      pages/eggbar/create-post.js
  2. 22
      pages/evaluate2/product-list.js
  3. 37
      pages/goods-detail/goods-detail.js
  4. 4
      server-example/.env
  5. 93
      server-example/server-mysql.js
  6. 18
      utils/api.js

16
pages/eggbar/create-post.js

@ -125,10 +125,24 @@ Page({
this.uploadImages(this.data.images) this.uploadImages(this.data.images)
.then(uploadedImages => { .then(uploadedImages => {
console.log('图片上传完成,上传的图片数量:', uploadedImages.length); console.log('图片上传完成,上传的图片数量:', uploadedImages.length);
// 获取用户ID
const userId = wx.getStorageSync('userId');
if (!userId) {
throw new Error('用户未登录');
}
// 获取用户电话号码
const userInfo = wx.getStorageSync('userInfo');
const phoneNumber = userInfo?.phoneNumber || wx.getStorageSync('phoneNumber');
console.log('获取到的用户电话号码:', phoneNumber);
const postData = { const postData = {
user_id: userId,
phone: phoneNumber,
content: this.data.content, content: this.data.content,
images: uploadedImages, images: uploadedImages,
topic: this.data.selectedTopic topic: this.data.selectedTopic?.name || this.data.selectedTopic
}; };
console.log('准备发送的发布数据:', postData); console.log('准备发送的发布数据:', postData);

22
pages/evaluate2/product-list.js

@ -73,6 +73,8 @@ Page({
// 从原始商品数据中计算价格范围 // 从原始商品数据中计算价格范围
const allProducts = wx.getStorageSync('allProducts') || []; const allProducts = wx.getStorageSync('allProducts') || [];
console.log('本地存储中的商品总数:', allProducts.length);
console.log('当前分类:', this.data.category);
if (allProducts.length > 0) { if (allProducts.length > 0) {
// 过滤出当前分类下的商品 // 过滤出当前分类下的商品
const categoryProducts = allProducts.filter(product => { const categoryProducts = allProducts.filter(product => {
@ -80,19 +82,26 @@ Page({
const productCategory = String(product.category).trim(); const productCategory = String(product.category).trim();
return productCategory === this.data.category; return productCategory === this.data.category;
}); });
console.log('当前分类下的商品数量:', categoryProducts.length);
console.log('当前分类下的商品详情:', categoryProducts);
// 按规格分组计算平均价格 // 按规格分组计算平均价格
const specPriceMap = {}; const specPriceMap = {};
categoryProducts.forEach(product => { categoryProducts.forEach(product => {
console.log('处理商品:', product.productName || product.name, '价格:', product.price, '规格:', product.specification || product.spec);
if (product.price && (product.specification || product.spec)) { if (product.price && (product.specification || product.spec)) {
const priceStr = String(product.price).trim(); const priceStr = String(product.price).trim();
const specStr = String(product.specification || product.spec).trim(); const specStr = String(product.specification || product.spec).trim();
console.log('商品价格字符串:', priceStr, '规格字符串:', specStr);
// 处理逗号分隔的多个价格 // 处理逗号分隔的多个价格
const priceArray = priceStr.split(',').map(p => p.trim()).filter(p => p && p.trim() !== ''); const priceArray = priceStr.split(',').map(p => p.trim()).filter(p => p && p.trim() !== '');
console.log('处理后的价格数组:', priceArray);
// 处理逗号分隔的多个规格 // 处理逗号分隔的多个规格
let specs = specStr.split(',').map(spec => spec.trim()).filter(spec => spec.length > 0); let specs = specStr.split(',').map(spec => spec.trim()).filter(spec => spec.length > 0);
console.log('处理后的规格数组:', specs);
// 进一步处理规格,确保每个规格都是独立的 // 进一步处理规格,确保每个规格都是独立的
const processedSpecs = []; const processedSpecs = [];
@ -106,9 +115,11 @@ Page({
} }
}); });
specs = processedSpecs; specs = processedSpecs;
console.log('最终规格数组:', specs);
// 将规格和价格配对 // 将规格和价格配对
specs.forEach((spec, index) => { specs.forEach((spec, index) => {
console.log('处理规格:', spec, '对应价格索引:', index);
if (spec.length > 0 && index < priceArray.length) { if (spec.length > 0 && index < priceArray.length) {
const price = priceArray[index]; const price = priceArray[index];
if (price && price.trim() !== '') { if (price && price.trim() !== '') {
@ -116,6 +127,7 @@ Page({
if (!isNaN(priceValue)) { if (!isNaN(priceValue)) {
// 解析规格 // 解析规格
const specInfo = this.parseSpecification(spec); const specInfo = this.parseSpecification(spec);
console.log('解析规格结果:', specInfo);
// 价格<10的需要按照公式计算 // 价格<10的需要按照公式计算
let finalPrice = priceValue; let finalPrice = priceValue;
@ -127,6 +139,7 @@ Page({
// 毛重:(规格平均值 - 5) × 价格 // 毛重:(规格平均值 - 5) × 价格
finalPrice = (specInfo.avg - 5) * priceValue; finalPrice = (specInfo.avg - 5) * priceValue;
} }
console.log('价格计算:', priceValue, '->', finalPrice);
} }
// 按规格分组存储价格 // 按规格分组存储价格
@ -134,10 +147,19 @@ Page({
specPriceMap[spec] = []; specPriceMap[spec] = [];
} }
specPriceMap[spec].push(finalPrice); specPriceMap[spec].push(finalPrice);
console.log('存储价格:', finalPrice, '到规格:', spec);
} else {
console.log('价格解析失败:', price);
} }
} else {
console.log('价格为空或无效:', price);
} }
} else {
console.log('规格长度为0或价格索引超出范围:', spec.length, index, priceArray.length);
} }
}); });
} else {
console.log('商品缺少价格或规格:', !product.price ? '无价格' : '', !product.specification && !product.spec ? '无规格' : '');
} }
}); });

37
pages/goods-detail/goods-detail.js

@ -1887,31 +1887,6 @@ Page({
}); });
}, },
// 20 default comments
getDefaultComments() {
return [
"鸡蛋品相贼好无破损,规格统一超适合批发",
"个头匀溜大小一致,装箱发货一点不费劲",
"包装严实防震,整车运输下来个个完好",
"蛋液浓稠清亮,品相达标完全符合供货要求",
"性价比真绝了,新鲜度在线囤货超划算",
"农家散养蛋品相佳,蛋黄紧实供货超稳定",
"物流嗖嗖快,到货鸡蛋无磕碰超省心",
"蛋壳干净无污渍,分拣打包效率直接拉满",
"个个饱满无瘪壳,市场铺货回头客贼多",
"分量超足规格齐,商超供货完全没毛病",
"无抗生素达标蛋,走商超渠道妥妥放心",
"蛋壳硬度够,装卸搬运全程零损耗",
"防震包装太贴心,长途运输损耗率超低",
"保鲜期够长,放一周品相依旧很能打",
"蛋体完整无瑕疵,分拣挑拣省超多功夫",
"品质稳定没色差,长期合作完全没问题",
"货源稳定供货及时,补货节奏卡得刚刚好",
"发货快包装硬,对接商超渠道超靠谱",
"蛋黄蛋清分层好,加工拿货性价比拉满",
"品质远超预期,后续订单必须锁定这家"
];
},
// Seeded random number generator for consistent results // Seeded random number generator for consistent results
seededRandom(seed) { seededRandom(seed) {
@ -2016,9 +1991,8 @@ Page({
}); });
console.log('应用审核逻辑后剩余评论数量:', filteredComments.length); console.log('应用审核逻辑后剩余评论数量:', filteredComments.length);
// Always add default comments at the beginning // Use only filtered comments without default comments
const defaultComments = this.getConsistentRandomComments(productId, 2); commentsData = filteredComments;
commentsData = [...defaultComments, ...filteredComments];
// 检查返回的评论是否都属于当前用户 // 检查返回的评论是否都属于当前用户
const allCommentsBelongToCurrentUser = commentsData.every(comment => const allCommentsBelongToCurrentUser = commentsData.every(comment =>
@ -2053,11 +2027,10 @@ Page({
.catch(err => { .catch(err => {
console.error('获取评论失败:', err); console.error('获取评论失败:', err);
console.error('错误详情:', JSON.stringify(err, null, 2)); console.error('错误详情:', JSON.stringify(err, null, 2));
// 加载失败时使用默认评论 // 加载失败时使用空数组
console.log('使用默认评论'); console.log('使用空评论数组');
const defaultComments = this.getConsistentRandomComments(productId, 2);
this.setData({ this.setData({
comments: defaultComments comments: []
}); });
}); });
}, },

4
server-example/.env

@ -4,10 +4,10 @@ WECHAT_APPSECRET=78fd81bce5a2968a8e7c607ae68c4c0b
WECHAT_TOKEN=your-random-token WECHAT_TOKEN=your-random-token
# MySQL数据库配置(请根据您的实际环境修改) # MySQL数据库配置(请根据您的实际环境修改)
# 如果是首次使用,可能需要先在MySQL中创建wechat_app数据库 # 连接到eggbar数据库
DB_HOST=1.95.162.61 DB_HOST=1.95.162.61
DB_PORT=3306 DB_PORT=3306
DB_DATABASE=wechat_app DB_DATABASE=eggbar
# 请使用您实际的MySQL用户名 # 请使用您实际的MySQL用户名
DB_USER=root DB_USER=root
# 请使用您实际的MySQL密码 # 请使用您实际的MySQL密码

93
server-example/server-mysql.js

@ -132,27 +132,29 @@ app.post('/api/eggbar/posts', async (req, res) => {
console.log('===== 收到帖子创建请求 ====='); console.log('===== 收到帖子创建请求 =====');
console.log('1. 收到请求体:', JSON.stringify(req.body, null, 2)); console.log('1. 收到请求体:', JSON.stringify(req.body, null, 2));
const { content, images, topic } = req.body; const { user_id, content, images, topic, phone } = req.body;
// 数据验证 - 允许只填写内容或话题中的一项 // 数据验证
if ((!content || content.trim() === '') && !topic) { if (!user_id) {
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
code: 400, code: 400,
message: '文本内容和话题至少需要填写一项' message: '缺少用户ID'
}); });
} }
// 处理图片数据,确保是JSON格式 // 处理图片数据
let imagesJson = null; let imagesData = null;
if (images && Array.isArray(images) && images.length > 0) { if (images && Array.isArray(images) && images.length > 0) {
imagesJson = JSON.stringify(images); imagesData = images;
} }
// 创建帖子记录 // 创建帖子记录
const newPost = await EggbarPost.create({ const newPost = await EggbarPost.create({
content: content.trim(), user_id: user_id,
images: imagesJson, phone: phone || null,
content: content || null,
images: imagesData,
topic: topic || null topic: topic || null
}); });
@ -525,6 +527,29 @@ const userLoginSequelize = new Sequelize(
} }
); );
// 3. eggbar数据源连接
const eggbarSequelize = new Sequelize(
'eggbar',
dbConfig.user,
dbConfig.password,
{
host: dbConfig.host,
port: dbConfig.port,
dialect: 'mysql',
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
},
logging: console.log,
define: {
timestamps: false
},
timezone: '+08:00' // 设置时区为UTC+8
}
);
// 为保持兼容性,保留默认sequelize引用(指向wechat_app) // 为保持兼容性,保留默认sequelize引用(指向wechat_app)
const sequelize = wechatAppSequelize; const sequelize = wechatAppSequelize;
@ -1441,28 +1466,68 @@ EggbarPost.init({
autoIncrement: true, autoIncrement: true,
comment: '帖子ID' comment: '帖子ID'
}, },
user_id: {
type: DataTypes.STRING(100),
allowNull: false,
comment: '用户ID'
},
phone: {
type: DataTypes.STRING(20),
allowNull: true,
comment: '用户电话号码'
},
content: { content: {
type: DataTypes.TEXT, type: DataTypes.TEXT,
allowNull: false, allowNull: true,
comment: '帖子内容' comment: '动态内容'
}, },
images: { images: {
type: DataTypes.TEXT, type: DataTypes.JSON,
allowNull: true, allowNull: true,
comment: '图片URL,JSON格式存储' comment: '图片URL数组'
}, },
topic: { topic: {
type: DataTypes.STRING(255), type: DataTypes.STRING(255),
allowNull: true, allowNull: true,
comment: '话题' comment: '话题'
}, },
likes: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0,
comment: '点赞数'
},
comments: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0,
comment: '评论数'
},
shares: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0,
comment: '分享数'
},
status: {
type: DataTypes.ENUM('active', 'inactive'),
allowNull: true,
defaultValue: 'active',
comment: '状态'
},
created_at: { created_at: {
type: DataTypes.DATE, type: DataTypes.DATE,
defaultValue: Sequelize.NOW, defaultValue: Sequelize.NOW,
comment: '创建时间' comment: '创建时间'
},
updated_at: {
type: DataTypes.DATE,
defaultValue: Sequelize.NOW,
onUpdate: Sequelize.NOW,
comment: '更新时间'
} }
}, { }, {
sequelize, sequelize: eggbarSequelize,
modelName: 'EggbarPost', modelName: 'EggbarPost',
tableName: 'eggbar_posts', tableName: 'eggbar_posts',
timestamps: false timestamps: false

18
utils/api.js

@ -1364,11 +1364,14 @@ module.exports = {
console.log('商品数据:', productData); console.log('商品数据:', productData);
console.log('图片数量:', imageUrls.length); console.log('图片数量:', imageUrls.length);
// 【新增】确保sellerId使用userId // 【关键修复】确保sellerId使用userId,无论是否已存在
const userId = wx.getStorageSync('userId'); const userId = wx.getStorageSync('userId');
if (userId && productData.sellerId) { if (userId) {
console.log('【修复】确保sellerId使用userId:', userId); console.log('【修复】确保sellerId使用userId:', userId);
productData.sellerId = userId; // 确保使用userId productData.sellerId = userId;
} else {
console.error('【错误】本地缓存中没有userId,请重新登录');
return Promise.reject(new Error('用户未登录,请重新登录'));
} }
// 如果没有图片,使用普通请求 // 如果没有图片,使用普通请求
@ -1382,7 +1385,7 @@ module.exports = {
// 创建包含所有图片URL的商品数据 // 创建包含所有图片URL的商品数据
const productDataWithAllImages = { const productDataWithAllImages = {
...productData, ...productData,
sellerId: userId || productData.sellerId, // 【确保】使用userId sellerId: userId, // 【确保】使用userId
imageUrls: imageUrls, // 设置imageUrls字段,确保服务器端能正确识别 imageUrls: imageUrls, // 设置imageUrls字段,确保服务器端能正确识别
allImageUrls: imageUrls, // 添加完整的图片URL列表(备用字段) allImageUrls: imageUrls, // 添加完整的图片URL列表(备用字段)
// 生成会话ID,确保所有图片上传关联同一个商品 // 生成会话ID,确保所有图片上传关联同一个商品
@ -1403,11 +1406,14 @@ module.exports = {
console.log('===== 最终版uploadProductWithRecursiveImages开始执行 ====='); console.log('===== 最终版uploadProductWithRecursiveImages开始执行 =====');
console.log('待上传图片数量:', imageUrls.length); console.log('待上传图片数量:', imageUrls.length);
// 【新增】确保sellerId使用userId // 【关键修复】确保sellerId使用userId,无论是否已存在
const userId = wx.getStorageSync('userId'); const userId = wx.getStorageSync('userId');
if (userId && productData.sellerId) { if (userId) {
console.log('【修复】确保sellerId使用userId:', userId); console.log('【修复】确保sellerId使用userId:', userId);
productData.sellerId = userId; productData.sellerId = userId;
} else {
console.error('【错误】本地缓存中没有userId,请重新登录');
return Promise.reject(new Error('用户未登录,请重新登录'));
} }
// 防御性检查 // 防御性检查

Loading…
Cancel
Save