修改商品查询页面
This commit is contained in:
parent
5fd9db9ee0
commit
28bad8a62e
@ -24,6 +24,8 @@ export default class Request {
|
||||
params: {},
|
||||
method: 'GET',
|
||||
dataType: 'json',
|
||||
// 默认请求超时 20s,避免弱网下请求长时间挂起(真机 PDA 网络环境差异明显)
|
||||
timeout: 20000,
|
||||
// #ifndef MP-ALIPAY || APP-PLUS
|
||||
responseType: 'text',
|
||||
// #endif
|
||||
|
||||
@ -230,7 +230,13 @@
|
||||
sectionKey: '',
|
||||
top: 0
|
||||
},
|
||||
routeStockId: ''
|
||||
routeStockId: '',
|
||||
// 搜索请求序号:用于竞态保护,只有最新一次搜索的结果才会被采用
|
||||
searchSeq: 0,
|
||||
// 商品图片/条码缓存(按商品 id),避免重复搜索重复请求;TTL 5 分钟
|
||||
productImageCache: {},
|
||||
productBarcodeCache: {},
|
||||
CACHE_TTL: 5 * 60 * 1000
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
@ -265,6 +271,8 @@
|
||||
onResult: this.handleBroadcastResult
|
||||
});
|
||||
this.safeDispatchBroadcast('start');
|
||||
// 监听商品保存成功事件,失效对应商品的图片/条码缓存,避免返回查询页后仍显示旧值
|
||||
uni.$on('product:query:updated', this.handleProductQueryUpdated);
|
||||
this.routeStockId = options?.stock_id || '';
|
||||
// 优先从存储中读取关键字(解决 URL 传参中文乱码问题)
|
||||
const storageKeyword = uni.getStorageSync('replenish_query_keyword') || '';
|
||||
@ -312,6 +320,7 @@
|
||||
this.stopQuerySpeak();
|
||||
},
|
||||
onUnload() {
|
||||
uni.$off('product:query:updated', this.handleProductQueryUpdated);
|
||||
if (this.storageMetaRefreshTimer) {
|
||||
clearTimeout(this.storageMetaRefreshTimer);
|
||||
this.storageMetaRefreshTimer = null;
|
||||
@ -320,6 +329,19 @@
|
||||
this.stopQuerySpeak();
|
||||
},
|
||||
methods: {
|
||||
handleProductQueryUpdated(event) {
|
||||
// 商品在编辑页保存成功:失效该商品的图片/条码缓存,保证下次搜索拉到最新数据
|
||||
const payload = (event && event.item) || {};
|
||||
const updatedId = this.normalizePositiveId(payload.id || payload.stock_id || payload.goods_id);
|
||||
if (updatedId) {
|
||||
delete this.productImageCache[updatedId];
|
||||
delete this.productBarcodeCache[updatedId];
|
||||
} else {
|
||||
// 拿不到 id 时兜底清空缓存
|
||||
this.productImageCache = {};
|
||||
this.productBarcodeCache = {};
|
||||
}
|
||||
},
|
||||
getGoodsItemKey(item, index) {
|
||||
if (!item || typeof item !== 'object') {
|
||||
return `goods_${index}`;
|
||||
@ -508,24 +530,6 @@
|
||||
|
||||
run();
|
||||
},
|
||||
async ensureStorageSectionMetasReady() {
|
||||
if (!this.list.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delays = [0, 60, 120, 240, 400];
|
||||
for (let i = 0; i < delays.length; i++) {
|
||||
await this.wait(delays[i]);
|
||||
await this.waitForNextTick();
|
||||
this.refreshStorageSectionMetas();
|
||||
await this.wait(40);
|
||||
|
||||
if (this.storageSectionMetas.length && this.pageHeaderHeight) {
|
||||
this.updateFloatingStorageHeader(this.listScrollTopCache);
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
refreshStorageSectionMetas() {
|
||||
this.$nextTick(() => {
|
||||
const query = uni.createSelectorQuery().in(this);
|
||||
@ -693,6 +697,43 @@
|
||||
}
|
||||
});
|
||||
},
|
||||
/**
|
||||
* 带并发上限的 map 执行器:结果与入参顺序一一对应(形态同 Promise.allSettled)
|
||||
* @param {Array} items 待处理数组
|
||||
* @param {Number} limit 最大并发数
|
||||
* @param {Function} mapper 异步处理函数 (item, index) => Promise
|
||||
* @returns {Promise<Array>} [{ status: 'fulfilled'|'rejected', value | reason }]
|
||||
*/
|
||||
async runMapWithConcurrency(items, limit, mapper) {
|
||||
const source = Array.isArray(items) ? items : [];
|
||||
if (!source.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const results = new Array(source.length);
|
||||
const maxConcurrency = Math.max(1, Math.min(Number(limit) || 1, source.length));
|
||||
let cursor = 0;
|
||||
|
||||
const worker = async () => {
|
||||
while (cursor < source.length) {
|
||||
const index = cursor;
|
||||
cursor += 1;
|
||||
try {
|
||||
const value = await mapper(source[index], index);
|
||||
results[index] = { status: 'fulfilled', value };
|
||||
} catch (error) {
|
||||
results[index] = { status: 'rejected', reason: error };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const workers = [];
|
||||
for (let i = 0; i < maxConcurrency; i++) {
|
||||
workers.push(worker());
|
||||
}
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
},
|
||||
/**
|
||||
* 从 index.getImages 接口获取商品图片
|
||||
* @param {Array} mergedList 合并后的商品列表
|
||||
@ -719,7 +760,23 @@
|
||||
}
|
||||
|
||||
const id = item.id || item.stock_id;
|
||||
if (id && (warehouseItemMap.has(id) || !warehouseItemMap.size)) {
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 已加载过图片则跳过
|
||||
if (Array.isArray(item.images) && item.images.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 命中缓存直接回填,避免重复请求
|
||||
const cached = this.productImageCache[id];
|
||||
if (cached && Array.isArray(cached.data) && cached.data.length && (Date.now() - cached.ts < this.CACHE_TTL)) {
|
||||
item.images = cached.data;
|
||||
return;
|
||||
}
|
||||
|
||||
if (warehouseItemMap.has(id) || !warehouseItemMap.size) {
|
||||
itemsToFetch.push({ item, id });
|
||||
}
|
||||
});
|
||||
@ -730,15 +787,15 @@
|
||||
|
||||
console.log('[ProductQuery] 开始获取商品图片,数量:', itemsToFetch.length);
|
||||
|
||||
// 并行请求图片
|
||||
const results = await Promise.allSettled(
|
||||
itemsToFetch.map(({ id }) =>
|
||||
this.$http('common.getImages', { type: 'stock', id })
|
||||
)
|
||||
// 限制并发请求图片,避免 PDA 上一股脑发起大量请求导致卡顿
|
||||
const results = await this.runMapWithConcurrency(
|
||||
itemsToFetch,
|
||||
4,
|
||||
async ({ id }) => this.$http('common.getImages', { type: 'stock', id })
|
||||
);
|
||||
|
||||
// 将图片数据关联到对应商品
|
||||
itemsToFetch.forEach(({ item }, index) => {
|
||||
itemsToFetch.forEach(({ item, id }, index) => {
|
||||
const result = results[index];
|
||||
if (result.status === 'rejected') {
|
||||
return;
|
||||
@ -769,6 +826,7 @@
|
||||
|
||||
if (imageUrls.length > 0) {
|
||||
item.images = imageUrls;
|
||||
this.productImageCache[id] = { data: imageUrls, ts: Date.now() };
|
||||
console.log(`[ProductQuery] 商品 id=${item.id} 获取到 ${imageUrls.length} 张图片`);
|
||||
}
|
||||
});
|
||||
@ -782,10 +840,30 @@
|
||||
return;
|
||||
}
|
||||
|
||||
const itemsToFetch = mergedList.filter(item => {
|
||||
if (!item || typeof item !== 'object') return false;
|
||||
const itemsToFetch = [];
|
||||
mergedList.forEach(item => {
|
||||
if (!item || typeof item !== 'object') {
|
||||
return;
|
||||
}
|
||||
|
||||
const id = item.id || item.stock_id;
|
||||
return !!id;
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 已加载过条码则跳过
|
||||
if (Array.isArray(item.barcodes) && item.barcodes.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 命中缓存直接回填,避免重复请求
|
||||
const cached = this.productBarcodeCache[id];
|
||||
if (cached && Array.isArray(cached.data) && cached.data.length && (Date.now() - cached.ts < this.CACHE_TTL)) {
|
||||
item.barcodes = cached.data;
|
||||
return;
|
||||
}
|
||||
|
||||
itemsToFetch.push(item);
|
||||
});
|
||||
|
||||
if (!itemsToFetch.length) {
|
||||
@ -794,11 +872,13 @@
|
||||
|
||||
console.log('[ProductQuery] 开始获取商品条码,数量:', itemsToFetch.length);
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
itemsToFetch.map((item) => {
|
||||
const results = await this.runMapWithConcurrency(
|
||||
itemsToFetch,
|
||||
4,
|
||||
async (item) => {
|
||||
const id = item.id || item.stock_id;
|
||||
return this.$http('stock.warehouse.getBarcodes', { id: Number(id) });
|
||||
})
|
||||
}
|
||||
);
|
||||
|
||||
itemsToFetch.forEach((item, index) => {
|
||||
@ -824,6 +904,10 @@
|
||||
|
||||
if (allBarcodes.length > 0) {
|
||||
item.barcodes = allBarcodes;
|
||||
const id = item.id || item.stock_id;
|
||||
if (id) {
|
||||
this.productBarcodeCache[id] = { data: allBarcodes, ts: Date.now() };
|
||||
}
|
||||
console.log(`[ProductQuery] 商品 id=${item.id || item.stock_id} 获取到 ${allBarcodes.length} 个条码`);
|
||||
}
|
||||
});
|
||||
@ -921,6 +1005,16 @@
|
||||
},
|
||||
isBarcodeLike(value) {
|
||||
const text = this.normalizeKeyword(value);
|
||||
if (!text) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 纯数字输入一律视为条码(商品名称极少为纯数字)
|
||||
if (/^\d+$/.test(text)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 其他情况:长度 >= 6 且为字母/数字组合视为条码
|
||||
return text.length >= 6 && /^[A-Za-z0-9._-]+$/.test(text);
|
||||
},
|
||||
extractBarcodeList(item) {
|
||||
@ -1663,99 +1757,86 @@
|
||||
|
||||
const isBarcodeKeyword = this.isBarcodeLike(keyword);
|
||||
const queryParams = this.buildQueryParams(keyword);
|
||||
let listQueryParams = null;
|
||||
const searchSeq = ++this.searchSeq;
|
||||
console.log('[ProductQuery] 搜索参数:', queryParams);
|
||||
|
||||
this.loading = true;
|
||||
try {
|
||||
const searchRes = await this.$http('stock.warehouse.search', queryParams);
|
||||
const warehouseRes = await this.$http('stock.warehouse.list', this.buildWarehouseListQueryParams(keyword)).catch(error => {
|
||||
// 阶段1:stock.warehouse.search 与 stock.warehouse.list 互不依赖,并行发出
|
||||
const warehouseListPromise = this.$http('stock.warehouse.list', this.buildWarehouseListQueryParams(keyword)).catch(error => {
|
||||
console.warn('[ProductQuery] stock.warehouse.list 调用失败:', error);
|
||||
return null;
|
||||
});
|
||||
const stage1StartTime = Date.now();
|
||||
const [searchRes, warehouseRes] = await Promise.all([
|
||||
this.$http('stock.warehouse.search', queryParams),
|
||||
warehouseListPromise
|
||||
]);
|
||||
console.log('[ProductQuery] 阶段1 并行(search+list)耗时:', Date.now() - stage1StartTime, 'ms');
|
||||
|
||||
// 竞态保护:若已有更新的搜索发起,则丢弃本次结果,避免旧响应覆盖新结果
|
||||
if (searchSeq !== this.searchSeq) {
|
||||
return;
|
||||
}
|
||||
|
||||
const searchOk = searchRes && searchRes.code === 200;
|
||||
const warehouseOk = warehouseRes && warehouseRes.code === 200;
|
||||
const nextList = searchOk ? this.extractListFromResponse(searchRes) : [];
|
||||
const warehouseList = warehouseOk ? this.extractListFromResponse(warehouseRes) : [];
|
||||
const stockIdList = this.extractStockIdList([].concat(nextList || [], warehouseList || []));
|
||||
listQueryParams = this.buildListQueryParams(stockIdList);
|
||||
console.log('[ProductQuery] 列表参数:', listQueryParams);
|
||||
|
||||
const listRes = stockIdList.length
|
||||
? await this.$http('storage.inventory.list', listQueryParams).catch(error => {
|
||||
console.warn('[ProductQuery] storage.inventory.list 调用失败:', error);
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
const listOk = listRes && listRes.code === 200;
|
||||
|
||||
if (searchOk || warehouseOk || listOk) {
|
||||
const detailList = listOk ? this.extractListFromResponse(listRes) : [];
|
||||
let mergedList = this.mergeProductResultLists(nextList, warehouseList, detailList);
|
||||
|
||||
// 优先使用 stock.warehouse.search 的库存数据(storage 数组),覆盖其他来源的库存数据
|
||||
// 注意:必须用 id 精确匹配,不能用条码等共享字段,否则多个商品共用同一条码时会互相覆盖
|
||||
if (searchOk && Array.isArray(nextList) && nextList.length) {
|
||||
const searchStorageById = new Map();
|
||||
nextList.forEach(item => {
|
||||
if (item && typeof item === 'object' && Array.isArray(item.storage)) {
|
||||
const id = this.normalizePositiveId(item.id);
|
||||
if (id) {
|
||||
searchStorageById.set(id, item.storage);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (searchStorageById.size) {
|
||||
mergedList = mergedList.map(item => {
|
||||
const id = this.normalizePositiveId(item.id || item.stock_id);
|
||||
if (id && searchStorageById.has(id)) {
|
||||
return { ...item, storage: searchStorageById.get(id) };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 从分拣缺货补货进入时,根据 stock_id 精确匹配
|
||||
if (this.routeStockId) {
|
||||
const targetStockId = Number(this.routeStockId);
|
||||
mergedList = mergedList.filter(item => {
|
||||
const id = Number(item.id || item.stock_id);
|
||||
return id === targetStockId;
|
||||
});
|
||||
}
|
||||
|
||||
// 异步获取商品图片(不阻塞主流程)
|
||||
this.fetchProductImages(mergedList, warehouseList).then(() => {
|
||||
// 图片加载完成后,重新触发视图更新(如列表未变则自动跳过)
|
||||
this.$forceUpdate();
|
||||
}).catch(error => {
|
||||
console.warn('[ProductQuery] 获取商品图片异常:', error);
|
||||
});
|
||||
|
||||
// 异步获取商品条码(不阻塞主流程)
|
||||
this.fetchProductBarcodes(mergedList).catch(error => {
|
||||
console.warn('[ProductQuery] 获取商品条码异常:', error);
|
||||
});
|
||||
|
||||
this.rawList = mergedList;
|
||||
this.updateDisplayListByMode(mergedList, keyword, isBarcodeKeyword);
|
||||
console.log('[ProductQuery] 搜索结果数量:', this.list.length);
|
||||
console.log('[ProductQuery] 搜索结果列表:', this.list);
|
||||
} else {
|
||||
// 基础接口全部失败(此时 stockIdList 为空,inventory 也无法查询),按失败处理
|
||||
if (!searchOk && !warehouseOk) {
|
||||
this.rawList = [];
|
||||
this.list = [];
|
||||
console.log('[ProductQuery] 搜索失败响应:', searchRes || listRes);
|
||||
console.log('[ProductQuery] 搜索失败响应:', searchRes || warehouseRes);
|
||||
uni.showToast({
|
||||
title: (searchRes && searchRes.message) || (warehouseRes && warehouseRes.message) || (listRes && listRes.message) || '查询失败',
|
||||
title: (searchRes && searchRes.message) || (warehouseRes && warehouseRes.message) || '查询失败',
|
||||
icon: 'none'
|
||||
});
|
||||
if (!silentVoice) {
|
||||
this.speakQueryMessage('查询失败,请重试');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 阶段1:先用 search + warehouse 渲染首屏,提前关闭 loading(真机上缩短串行等待)
|
||||
let stockIdList = this.extractStockIdList([].concat(nextList || [], warehouseList || []));
|
||||
// inventory.list 分页上限 20 条,只需传入前 20 个商品 id 即可。
|
||||
// search 匹配大量商品时若传入全部 id,后端 IN 聚合查询会非常慢(真机实测约 4.5s)
|
||||
const MAX_INVENTORY_STOCK_IDS = 20;
|
||||
if (stockIdList.length > MAX_INVENTORY_STOCK_IDS) {
|
||||
stockIdList = stockIdList.slice(0, MAX_INVENTORY_STOCK_IDS);
|
||||
}
|
||||
console.log('[ProductQuery] stockIdList 数量:', stockIdList.length);
|
||||
let mergedList = this.mergeProductResultLists(nextList, warehouseList, []);
|
||||
mergedList = this.applySearchStorageOverride(mergedList, nextList);
|
||||
mergedList = this.applyRouteStockFilter(mergedList);
|
||||
|
||||
// 异步获取商品图片/条码(不阻塞主流程)
|
||||
this.fetchProductImages(mergedList, warehouseList).then(() => {
|
||||
if (searchSeq === this.searchSeq) {
|
||||
this.$forceUpdate();
|
||||
}
|
||||
}).catch(error => {
|
||||
console.warn('[ProductQuery] 获取商品图片异常:', error);
|
||||
});
|
||||
this.fetchProductBarcodes(mergedList).catch(error => {
|
||||
console.warn('[ProductQuery] 获取商品条码异常:', error);
|
||||
});
|
||||
|
||||
this.rawList = mergedList;
|
||||
this.updateDisplayListByMode(mergedList, keyword, isBarcodeKeyword);
|
||||
this.loading = false;
|
||||
console.log('[ProductQuery] 首屏搜索结果数量:', this.list.length);
|
||||
|
||||
// 阶段2:异步补充库存明细(不阻塞首屏)
|
||||
this.fetchInventoryDetails(nextList, warehouseList, stockIdList, searchSeq).catch(error => {
|
||||
console.warn('[ProductQuery] 补充库存明细异常:', error);
|
||||
});
|
||||
} catch (error) {
|
||||
if (searchSeq !== this.searchSeq) {
|
||||
return;
|
||||
}
|
||||
this.rawList = [];
|
||||
this.list = [];
|
||||
console.error('[ProductQuery] 搜索异常:', error);
|
||||
@ -1767,15 +1848,101 @@
|
||||
this.speakQueryMessage('查询失败,请检查网络后重试');
|
||||
}
|
||||
} finally {
|
||||
if (searchSeq !== this.searchSeq) {
|
||||
return;
|
||||
}
|
||||
this.loading = false;
|
||||
if (this.list.length) {
|
||||
// 合并重复的布局测量:单次调度多次延时刷新即可覆盖图片/布局稳定,
|
||||
// 避免真机上反复 createSelectorQuery 造成卡顿
|
||||
await this.waitForNextTick();
|
||||
await this.ensureStorageSectionMetasReady();
|
||||
this.refreshStorageSectionMetas();
|
||||
this.updateFloatingStorageHeader(this.listScrollTopCache);
|
||||
this.scheduleRefreshStorageSectionMetas([30, 120, 260, 520]);
|
||||
this.scheduleRefreshStorageSectionMetas([0, 60, 160, 320]);
|
||||
}
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 阶段2:用 search + warehouse 的 stock_id 集合异步补充库存明细,不阻塞首屏
|
||||
*/
|
||||
async fetchInventoryDetails(nextList, warehouseList, stockIdList, searchSeq) {
|
||||
if (!Array.isArray(stockIdList) || !stockIdList.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const listStartTime = Date.now();
|
||||
const listRes = await this.$http('storage.inventory.list', this.buildListQueryParams(stockIdList)).catch(error => {
|
||||
console.warn('[ProductQuery] storage.inventory.list 调用失败:', error);
|
||||
return null;
|
||||
});
|
||||
console.log('[ProductQuery] 阶段2 inventory.list 耗时:', Date.now() - listStartTime, 'ms');
|
||||
|
||||
// 竞态保护:请求期间可能已发起新的搜索
|
||||
if (searchSeq !== this.searchSeq) {
|
||||
return;
|
||||
}
|
||||
|
||||
const listOk = listRes && listRes.code === 200;
|
||||
if (!listOk) {
|
||||
return;
|
||||
}
|
||||
|
||||
const detailList = this.extractListFromResponse(listRes);
|
||||
let mergedList = this.mergeProductResultLists(nextList, warehouseList, detailList);
|
||||
mergedList = this.applySearchStorageOverride(mergedList, nextList);
|
||||
mergedList = this.applyRouteStockFilter(mergedList);
|
||||
|
||||
if (searchSeq !== this.searchSeq) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.rawList = mergedList;
|
||||
this.updateDisplayListByMode(mergedList, this.keyword, this.isBarcodeLike(this.keyword));
|
||||
this.scheduleRefreshStorageSectionMetas([0, 80, 200]);
|
||||
},
|
||||
/**
|
||||
* 优先使用 stock.warehouse.search 的库存数据(storage 数组)覆盖其他来源
|
||||
* 注意:必须用 id 精确匹配,不能用条码等共享字段,否则多个商品共用同一条码时会互相覆盖
|
||||
*/
|
||||
applySearchStorageOverride(mergedList, nextList) {
|
||||
if (!Array.isArray(nextList) || !nextList.length) {
|
||||
return mergedList;
|
||||
}
|
||||
|
||||
const searchStorageById = new Map();
|
||||
nextList.forEach(item => {
|
||||
if (item && typeof item === 'object' && Array.isArray(item.storage)) {
|
||||
const id = this.normalizePositiveId(item.id);
|
||||
if (id) {
|
||||
searchStorageById.set(id, item.storage);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!searchStorageById.size) {
|
||||
return mergedList;
|
||||
}
|
||||
|
||||
return (mergedList || []).map(item => {
|
||||
const id = this.normalizePositiveId(item.id || item.stock_id);
|
||||
if (id && searchStorageById.has(id)) {
|
||||
return { ...item, storage: searchStorageById.get(id) };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
},
|
||||
/**
|
||||
* 从分拣缺货补货进入时,根据 stock_id 精确匹配
|
||||
*/
|
||||
applyRouteStockFilter(mergedList) {
|
||||
if (!this.routeStockId) {
|
||||
return mergedList;
|
||||
}
|
||||
|
||||
const targetStockId = Number(this.routeStockId);
|
||||
return (mergedList || []).filter(item => {
|
||||
const id = Number(item.id || item.stock_id);
|
||||
return id === targetStockId;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user