Browse Source

修复goods页面只显示今天数据的问题:重构商品加载逻辑,先获取所有商品再在前端处理

pull/12/head
Default User 2 months ago
parent
commit
92fecc69cc
  1. 334
      pages/goods/index.js
  2. 6
      utils/api.js

334
pages/goods/index.js

@ -118,10 +118,14 @@ Page({
onRefresherRefresh() {
if (this.data.isLoading) return
// 清除缓存,确保获取最新数据
this.setData({
isRefreshing: true,
goodsList: [],
isLoading: false
isLoading: false,
'cache.publishedGoods': [],
'cache.soldOutGoods': [],
'cache.timestamp': 0
})
this.loadGoodsList()
},
@ -314,6 +318,73 @@ Page({
});
},
/**
* 加载所有商品数据 - 辅助方法
*/
async loadAllGoodsData() {
try {
// 使用getProducts方法获取所有商品数据
const allGoods = await API.getProducts()
// 对所有商品进行格式化处理
const formattedGoods = allGoods.map(item => {
// 确定creatorName
const sellerNickName = item.seller?.nickName || item.seller?.sellerNickName || item.seller?.name || '未知';
const creatorName = sellerNickName;
// 处理媒体URL
const imageUrls = item.imageUrls || item.images || []
const formattedImageUrls = Array.isArray(imageUrls) ? imageUrls : [imageUrls]
const mediaItems = formattedImageUrls.map(url => ({
url: url,
type: isVideoUrl(url) ? 'video' : 'image'
}))
// 处理商品状态
let status = item.status
const isSoldOut = status === 'sold_out' ||
status === 'sold' ||
status === 'out_of_stock' ||
(item.supplyStatus && item.supplyStatus.includes('售空'));
if (isSoldOut) {
status = 'sold_out'
} else if (status !== 'published') {
status = 'published'
}
// 处理价格
let processedPrice = item.price;
if (processedPrice && typeof processedPrice === 'string') {
const priceArray = processedPrice.split(/[,,、]/).map(p => p.trim()).filter(p => p);
if (priceArray.length > 0) {
processedPrice = priceArray[0];
}
}
const productName = item.productName || item.name || '未命名商品';
const displayTime = item.updated_at || item.updatedAt || item.created_at || item.createTime;
return {
...item,
productName: productName,
name: productName,
status: status,
price: processedPrice,
formattedCreatedAt: this.formatDateTime(displayTime),
creatorName: creatorName,
imageUrls: formattedImageUrls,
mediaItems: mediaItems
}
})
return formattedGoods
} catch (err) {
console.error('加载所有商品数据失败:', err)
return []
}
},
/**
* 加载已上架(published)状态的货源 - 支持分页
*/
@ -332,97 +403,35 @@ Page({
})
try {
const res = await API.getGoodsList({
page: page,
pageSize: pageSize,
keyword: this.data.searchKeyword
})
// 先获取所有商品数据
const allGoods = await this.loadAllGoodsData()
if (res.success) {
let publishedGoods = res.products || []
// 数据格式化处理
publishedGoods = publishedGoods.map(item => {
// 确定creatorName
const sellerNickName = item.seller?.nickName || item.seller?.sellerNickName || item.seller?.name || '未知';
const creatorName = sellerNickName;
// 处理媒体URL
const imageUrls = item.imageUrls || item.images || []
const formattedImageUrls = Array.isArray(imageUrls) ? imageUrls : [imageUrls]
const mediaItems = formattedImageUrls.map(url => ({
url: url,
type: isVideoUrl(url) ? 'video' : 'image'
}))
// 处理商品状态
let status = item.status
const isSoldOut = status === 'sold_out' ||
status === 'sold' ||
status === 'out_of_stock' ||
(item.supplyStatus && item.supplyStatus.includes('售空'));
if (isSoldOut) {
status = 'sold_out'
} else if (status !== 'published') {
status = 'published'
}
// 只保留published状态的商品
if (status !== 'published') {
return null
}
// 处理价格
let processedPrice = item.price;
if (processedPrice && typeof processedPrice === 'string') {
const priceArray = processedPrice.split(/[,,、]/).map(p => p.trim()).filter(p => p);
if (priceArray.length > 0) {
processedPrice = priceArray[0];
}
}
const productName = item.productName || item.name || '未命名商品';
const displayTime = item.updated_at || item.updatedAt || item.created_at || item.createTime;
return {
...item,
productName: productName,
name: productName,
status: status,
price: processedPrice,
formattedCreatedAt: this.formatDateTime(displayTime),
creatorName: creatorName,
imageUrls: formattedImageUrls,
mediaItems: mediaItems
}
}).filter(Boolean) // 过滤掉null值
// 应用筛选和搜索
let filteredGoods = publishedGoods
if (this.data.searchKeyword && this.data.searchKeyword.trim() !== '') {
filteredGoods = this.searchGoodsList(filteredGoods, this.data.searchKeyword)
} else {
filteredGoods = this.filterGoodsList(filteredGoods)
}
// 按时间倒序排序
filteredGoods.sort((a, b) => {
const timeA = new Date(a.updated_at || a.updatedAt || a.created_at || a.createTime).getTime()
const timeB = new Date(b.updated_at || b.updatedAt || b.created_at || b.createTime).getTime()
return timeB - timeA
})
// 判断是否有更多数据
const hasMore = publishedGoods.length >= pageSize
console.log('已上架货源加载完成,数量:', filteredGoods.length, ',是否有更多:', hasMore)
return { goods: filteredGoods, hasMore: hasMore }
// 过滤出已上架状态的商品
let publishedGoods = allGoods.filter(item => item.status === 'published')
// 应用筛选和搜索
if (this.data.searchKeyword && this.data.searchKeyword.trim() !== '') {
publishedGoods = this.searchGoodsList(publishedGoods, this.data.searchKeyword)
} else {
console.error('加载已上架货源失败:', res.message)
return { goods: [], hasMore: false }
publishedGoods = this.filterGoodsList(publishedGoods)
}
// 按时间倒序排序
publishedGoods.sort((a, b) => {
const timeA = new Date(a.updated_at || a.updatedAt || a.created_at || a.createTime).getTime()
const timeB = new Date(b.updated_at || b.updatedAt || b.created_at || b.createTime).getTime()
return timeB - timeA
})
// 进行分页处理
const startIndex = (page - 1) * pageSize
const endIndex = startIndex + pageSize
const paginatedGoods = publishedGoods.slice(startIndex, endIndex)
const hasMore = endIndex < publishedGoods.length
console.log('已上架货源加载完成,数量:', paginatedGoods.length, ',是否有更多:', hasMore)
return { goods: paginatedGoods, hasMore: hasMore }
} catch (err) {
console.error('加载已上架货源失败:', err)
return { goods: [], hasMore: false }
@ -452,97 +461,35 @@ Page({
})
try {
const res = await API.getGoodsList({
page: page,
pageSize: pageSize,
keyword: this.data.searchKeyword
})
// 先获取所有商品数据
const allGoods = await this.loadAllGoodsData()
if (res.success) {
let soldOutGoods = res.products || []
// 数据格式化处理
soldOutGoods = soldOutGoods.map(item => {
// 确定creatorName
const sellerNickName = item.seller?.nickName || item.seller?.sellerNickName || item.seller?.name || '未知';
const creatorName = sellerNickName;
// 处理媒体URL
const imageUrls = item.imageUrls || item.images || []
const formattedImageUrls = Array.isArray(imageUrls) ? imageUrls : [imageUrls]
const mediaItems = formattedImageUrls.map(url => ({
url: url,
type: isVideoUrl(url) ? 'video' : 'image'
}))
// 处理商品状态
let status = item.status
const isSoldOut = status === 'sold_out' ||
status === 'sold' ||
status === 'out_of_stock' ||
(item.supplyStatus && item.supplyStatus.includes('售空'));
if (isSoldOut) {
status = 'sold_out'
} else if (status !== 'published') {
status = 'published'
}
// 只保留sold_out状态的商品
if (status !== 'sold_out') {
return null
}
// 处理价格
let processedPrice = item.price;
if (processedPrice && typeof processedPrice === 'string') {
const priceArray = processedPrice.split(/[,,、]/).map(p => p.trim()).filter(p => p);
if (priceArray.length > 0) {
processedPrice = priceArray[0];
}
}
const productName = item.productName || item.name || '未命名商品';
const displayTime = item.updated_at || item.updatedAt || item.created_at || item.createTime;
return {
...item,
productName: productName,
name: productName,
status: status,
price: processedPrice,
formattedCreatedAt: this.formatDateTime(displayTime),
creatorName: creatorName,
imageUrls: formattedImageUrls,
mediaItems: mediaItems
}
}).filter(Boolean) // 过滤掉null值
// 应用筛选和搜索
let filteredGoods = soldOutGoods
if (this.data.searchKeyword && this.data.searchKeyword.trim() !== '') {
filteredGoods = this.searchGoodsList(filteredGoods, this.data.searchKeyword)
} else {
filteredGoods = this.filterGoodsList(filteredGoods)
}
// 按时间倒序排序
filteredGoods.sort((a, b) => {
const timeA = new Date(a.updated_at || a.updatedAt || a.created_at || a.createTime).getTime()
const timeB = new Date(b.updated_at || b.updatedAt || b.created_at || b.createTime).getTime()
return timeB - timeA
})
// 判断是否有更多数据
const hasMore = soldOutGoods.length >= pageSize
console.log('售空货源加载完成,数量:', filteredGoods.length, ',是否有更多:', hasMore)
return { goods: filteredGoods, hasMore: hasMore }
// 过滤出售空状态的商品
let soldOutGoods = allGoods.filter(item => item.status === 'sold_out')
// 应用筛选和搜索
if (this.data.searchKeyword && this.data.searchKeyword.trim() !== '') {
soldOutGoods = this.searchGoodsList(soldOutGoods, this.data.searchKeyword)
} else {
console.error('加载售空货源失败:', res.message)
return { goods: [], hasMore: false }
soldOutGoods = this.filterGoodsList(soldOutGoods)
}
// 按时间倒序排序
soldOutGoods.sort((a, b) => {
const timeA = new Date(a.updated_at || a.updatedAt || a.created_at || a.createTime).getTime()
const timeB = new Date(b.updated_at || b.updatedAt || b.created_at || b.createTime).getTime()
return timeB - timeA
})
// 进行分页处理
const startIndex = (page - 1) * pageSize
const endIndex = startIndex + pageSize
const paginatedGoods = soldOutGoods.slice(startIndex, endIndex)
const hasMore = endIndex < soldOutGoods.length
console.log('售空货源加载完成,数量:', paginatedGoods.length, ',是否有更多:', hasMore)
return { goods: paginatedGoods, hasMore: hasMore }
} catch (err) {
console.error('加载售空货源失败:', err)
return { goods: [], hasMore: false }
@ -599,22 +546,23 @@ Page({
})
try {
// 如果是初始加载,检查缓存是否有效
if (!isLoadMore && this.isCacheValid()) {
console.log('使用缓存数据')
const cache = this.data.cache
this.setData({
goodsList: [...cache.publishedGoods, ...cache.soldOutGoods],
publishedLoaded: true,
soldOutLoaded: true,
publishedHasMore: false,
soldOutHasMore: false,
total: cache.publishedGoods.length + cache.soldOutGoods.length
})
return
}
// 为了确保获取最新数据,暂时禁用缓存,直接从服务器获取
// 后续可以根据需要恢复缓存逻辑
// if (!isLoadMore && this.isCacheValid()) {
// console.log('使用缓存数据')
// const cache = this.data.cache
//
// this.setData({
// goodsList: [...cache.publishedGoods, ...cache.soldOutGoods],
// publishedLoaded: true,
// soldOutLoaded: true,
// publishedHasMore: false,
// soldOutHasMore: false,
// total: cache.publishedGoods.length + cache.soldOutGoods.length
// })
//
// return
// }
console.log('缓存无效或加载更多,从服务器获取数据')

6
utils/api.js

@ -1050,9 +1050,11 @@ module.exports = {
const requestData = {
openid: openid,
page: params.page || 1,
pageSize: params.pageSize || 10,
pageSize: params.pageSize || 20,
status: 'all', // 获取所有状态的货源,包括已上架和已下架
viewMode: 'shopping', // 确保能够查看所有内部人员创建的货源
viewMode: 'buyer', // 使用buyer模式获取所有商品
dateRange: 'all', // 明确指定获取所有时间段的数据
showAll: true, // 添加showAll参数,确保获取所有数据
_t: new Date().getTime() // 添加时间戳防止缓存
};

Loading…
Cancel
Save