Browse Source

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

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

220
pages/goods/index.js

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

6
utils/api.js

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

Loading…
Cancel
Save