WMS_PDA/pages/warehouse/inventoryTransfer.vue

772 lines
21 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<view class="transfer-record-page">
<view class="normar_container">
<page-nav title="移库记录"></page-nav>
<!-- 搜索区 -->
<view class="search-panel">
<view class="search-input-wrap">
<u-search
v-model="keyword"
:placeholder="searchPlaceholder"
:bg-color="'#f5f5f5'"
shape="round"
:show-action="false"
@search="handleSearch"
@clear="handleClear"
></u-search>
<view class="search-actions">
<view class="scan-btn" @click="handleCameraScan">
<u-icon name="scan" size="38rpx" color="#2979ff"></u-icon>
</view>
<view class="search-divider"></view>
<view class="search-btn" @click="handleSearch">
<text class="search-btn__text">搜索</text>
</view>
</view>
</view>
<view class="filter-row">
<view class="filter-group">
<view
v-for="opt in searchDimensionOptions"
:key="opt.value"
class="filter-group__item"
:class="{ 'filter-group__item--active': searchDimension === opt.value }"
@click="handleDimensionChange(opt.value)"
>
<text class="filter-group__item-text">{{ opt.label }}</text>
</view>
</view>
<view class="filter-divider"></view>
<view class="filter-group">
<view
v-for="opt in transferTypeOptions"
:key="opt.value"
class="filter-group__item"
:class="{
'filter-group__item--active': transferType === opt.value,
'filter-group__item--warning': transferType === opt.value && opt.value === 'TRANSFER_OUT'
}"
@click="handleTypeChange(opt.value)"
>
<text class="filter-group__item-text">{{ opt.label }}</text>
</view>
</view>
</view>
</view>
<!-- 列表区 -->
<scroll-view class="detail-scroll" scroll-y>
<view v-if="recordList.length === 0" class="empty-state">
<u-icon name="list" size="86" color="#c0c4cc"></u-icon>
<text class="empty-text">{{ loading ? '加载中...' : '暂无移库记录' }}</text>
<text class="empty-hint">{{ keyword ? '请检查关键字后重试' : '请在上方输入关键字查询' }}</text>
</view>
<view v-else class="record-list">
<view v-for="(item, index) in recordList" :key="item.id || index" class="record-card" :class="{ 'record-card--stripe': index % 2 === 1 }">
<view class="record-card__row">
<text class="record-card__label">商品名称</text>
<text class="record-card__value">{{ item.name || '--' }}</text>
</view>
<view class="record-card__row">
<text class="record-card__label">商品编码</text>
<text class="record-card__value">{{ item.barcode || '--' }}</text>
</view>
<view class="record-card__row">
<text class="record-card__label">数量</text>
<text class="record-card__value record-card__value--strong">{{ item.quantityText }}</text>
</view>
<view class="record-card__row">
<text class="record-card__label">{{ item.transactionType === 'TRANSFER_OUT' ? '移出库位' : '移入库位' }}</text>
<text class="record-card__value">{{ item.transactionType === 'TRANSFER_OUT' ? (item.fromSpace || '--') : (item.toSpace || '--') }}</text>
</view>
<view class="record-card__row">
<text class="record-card__label">批次号</text>
<text class="record-card__value">{{ item.batchNo || '--' }}</text>
</view>
<view class="record-card__row">
<text class="record-card__label">操作人</text>
<text class="record-card__value">{{ item.operator || '--' }}</text>
</view>
<view class="record-card__row record-card__row--last">
<text class="record-card__label">操作时间</text>
<text class="record-card__value">{{ item.timeText || '--' }}</text>
</view>
</view>
</view>
<view class="safe-area-bottom"></view>
</scroll-view>
<!-- 分页 -->
<view class="pagination-wrap">
<pagination
:pageNum.sync="currentPage"
:pageSize="pageSize"
:total="paginationTotal"
:showTotal="true"
:prevText="'上一页'"
:nextText="'下一页'"
:showFirstLast="true"
:firstText="'首页'"
:lastText="'末页'"
@change="handlePageChange"
/>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
keyword: '',
searchDimension: 'PRODUCT',
searchDimensionOptions: [
{ label: '商品', value: 'PRODUCT' },
{ label: '操作人', value: 'OPERATOR' }
],
transferType: 'TRANSFER_IN',
transferTypeOptions: [
{ label: '移入', value: 'TRANSFER_IN' },
{ label: '移出', value: 'TRANSFER_OUT' }
],
pageSize: 20,
currentPage: 1,
paginationTotal: 0,
recordList: [],
loading: false
}
},
computed: {
searchPlaceholder() {
return this.searchDimension === 'OPERATOR' ? '请输入操作人名称' : '请输入/扫描商品条码或名称';
}
},
onLoad(options = {}) {
// 支持通过 ?keyword=xxx 预填关键字并自动查询
const preset = String(options.keyword || '').trim();
if (preset) {
this.keyword = preset;
this.$nextTick(() => this.loadRecordList(1));
} else {
this.loadRecordList(1);
}
this.safeDispatchBroadcast('setCallbacks', { onResult: this.handleBroadcastResult });
this.safeDispatchBroadcast('start');
},
onShow() {
this.safeDispatchBroadcast('setCallbacks', { onResult: this.handleBroadcastResult });
this.safeDispatchBroadcast('resume');
this.scheduleBroadcastSelfHeal();
},
onHide() {
this.safeDispatchBroadcast('pause');
},
onUnload() {
if (this._broadcastHealTimer) {
clearTimeout(this._broadcastHealTimer);
this._broadcastHealTimer = null;
}
this.safeDispatchBroadcast('stop');
},
methods: {
// ===== 广播/扫码基础设施 =====
safeDispatchBroadcast(action, payload) {
try {
const task = this.$store.dispatch(`broadcast/${action}`, payload);
if (task && typeof task.catch === 'function') {
task.catch(error => console.warn(`[inventoryTransfer] broadcast/${action} 调用失败:`, error));
}
} catch (error) {
console.warn(`[inventoryTransfer] broadcast/${action} 调用异常:`, error);
}
},
scheduleBroadcastSelfHeal() {
if (this._broadcastHealTimer) {
clearTimeout(this._broadcastHealTimer);
}
this._broadcastHealTimer = setTimeout(() => {
// 兼容跳转时序竞态:旧页 onHide 的 pause(=stop) 可能晚于本页 onShow 执行,导致广播被误停
this.safeDispatchBroadcast('setCallbacks', { onResult: this.handleBroadcastResult });
this.safeDispatchBroadcast('start');
}, 1200);
},
normalizeScanResult(scanResult) {
if (!scanResult) return '';
if (typeof scanResult === 'string') return scanResult.trim();
if (typeof scanResult.result === 'string') return scanResult.result.trim();
if (Array.isArray(scanResult.result)) {
const first = scanResult.result.find(item => item);
if (typeof first === 'string') return first.trim();
if (first && typeof first.data === 'string') return first.data.trim();
}
if (typeof scanResult.data === 'string') return scanResult.data.trim();
return '';
},
handleBroadcastResult(result) {
const code = this.normalizeScanResult(result);
if (!code) return;
this.keyword = code;
this.loadRecordList(1);
},
handleCameraScan() {
uni.scanCode({
onlyFromCamera: true,
scanType: ['qrCode', 'barCode', 'datamatrix', 'pdf417'],
success: (res) => {
const code = this.normalizeScanResult(res);
if (!code) return;
this.keyword = code;
this.loadRecordList(1);
},
fail: () => {}
});
},
// ===== 查询 =====
handleSearch() {
this.loadRecordList(1);
},
handleClear() {
this.keyword = '';
this.loadRecordList(1);
},
handleTypeChange(value) {
if (this.transferType === value) return;
this.transferType = value;
this.recordList = [];
this.paginationTotal = 0;
this.loadRecordList(1);
},
handleDimensionChange(value) {
if (this.searchDimension === value) return;
this.searchDimension = value;
this.recordList = [];
this.paginationTotal = 0;
this.loadRecordList(1);
},
handlePageChange(page) {
const targetPage = Math.max(1, Number(page || 1));
if (targetPage === this.currentPage) return;
this.currentPage = targetPage;
this.loadRecordList(targetPage);
},
buildRecordParams(page = this.currentPage) {
const targetPage = Math.max(1, Number(page || 1));
const pageSize = Math.max(1, Number(this.pageSize || 20));
const params = {
group_by_batch: true,
pagination: {
page: targetPage,
pageSize
},
sort: {
sortField: 'created_at',
sortOrder: 'DESC'
}
};
const where = {};
const keyword = String(this.keyword || '').trim();
if (keyword) {
if (this.searchDimension === 'OPERATOR') {
where.operator_name = {
operator: 'like',
value: keyword,
type: 'text'
};
} else {
where.keyword = {
operator: 'contains',
value: [keyword],
type: 'text'
};
}
}
if (this.transferType) {
where.transaction_type = {
operator: 'eq',
value: this.transferType,
type: 'select'
};
}
if (Object.keys(where).length) {
params.where = where;
}
return params;
},
extractRecordPayload(response) {
const candidates = [
response?.data?.data,
response?.data,
response?.result,
response
];
for (let i = 0; i < candidates.length; i += 1) {
const current = candidates[i];
if (current && typeof current === 'object' && !Array.isArray(current)) {
return current;
}
}
return {};
},
extractRecordList(payload, response) {
const candidates = [
payload?.list,
payload?.rows,
payload?.items,
payload?.records,
payload?.data?.list,
response?.data?.list,
response?.data?.data?.list,
response?.list
];
for (let i = 0; i < candidates.length; i += 1) {
if (Array.isArray(candidates[i])) return candidates[i];
}
return [];
},
resolveRecordTotal(payload, response, list) {
const pagination = (payload && typeof payload === 'object') ? (payload.pagination || {}) : {};
const candidates = [
pagination?.total,
pagination?.count,
payload?.pagination?.total,
payload?.total,
payload?.count,
payload?.totalCount,
response?.data?.pagination?.total,
response?.data?.total,
response?.total,
Array.isArray(list) ? list.length : 0
];
for (let i = 0; i < candidates.length; i += 1) {
const value = Number(candidates[i]);
if (Number.isFinite(value) && value >= 0) return value;
}
return 0;
},
firstValue(source, keys) {
for (let i = 0; i < keys.length; i += 1) {
const value = source[keys[i]];
if (value !== null && value !== undefined && String(value).trim() !== '') {
return String(value).trim();
}
}
return '';
},
formatDateTime(value) {
if (value === null || value === undefined || value === '') return '';
const date = new Date(String(value).trim());
if (Number.isNaN(date.getTime())) return String(value).trim();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
},
normalizeRecordList(list) {
if (!Array.isArray(list)) return [];
return list
.map((item, index) => {
const source = item && typeof item === 'object' ? item : {};
// 商品信息嵌套在 stockItem 内(可能为 null),合并进查找源
const stockItem = source.stockItem && typeof source.stockItem === 'object' ? source.stockItem : {};
const merged = { ...source, ...stockItem };
const barcode = this.firstValue(merged, [
'barcode', 'item_code', 'item_barcode', 'bar_code', 'goods_code', 'product_barcode'
]);
const name = this.firstValue(merged, [
'item_name', 'product_name', 'goods_name', 'name', 'itemName'
]);
const operator = this.firstValue(source, [
'operator_name', 'operatorName', 'operator', 'operate_user', 'operateUser',
'create_user', 'createUser', 'user_name', 'userName', 'scanner_name'
]);
const batchNo = this.firstValue(merged, [
'batch_no', 'batchNo', 'batch_number', 'batchNumber'
]);
const transactionType = String(source.transaction_type || source.transactionType || '').trim();
// 单库位流水:库位可能是 space_code/space_name 或仅 space_id
const spaceId = this.firstValue(source, ['space_id', 'spaceId']);
const spaceText = this.firstValue(merged, [
'space_code', 'spaceCode', 'space_name', 'spaceName', 'space_no', 'spaceNo'
]) || spaceId;
let fromSpace = this.firstValue(merged, [
'from_space_code', 'fromSpaceCode', 'source_space_code', 'sourceSpaceCode',
'out_space_code', 'outSpaceCode', 'from_location', 'fromLocation', 'from_space', 'from_space_id'
]);
let toSpace = this.firstValue(merged, [
'to_space_code', 'toSpaceCode', 'target_space_code', 'targetSpaceCode',
'in_space_code', 'inSpaceCode', 'to_location', 'toLocation', 'to_space', 'to_space_id'
]);
// 无明确 from/to 时:移出记录的空间为「移出库位」,移入记录的空间为「移入库位」
if (!fromSpace && !toSpace && spaceText) {
if (transactionType === 'TRANSFER_OUT') {
fromSpace = spaceText;
} else {
toSpace = spaceText;
}
}
const timeValue = this.firstValue(source, [
'created_at', 'createdAt', 'create_time', 'createTime',
'operate_time', 'operateTime', 'operation_time', 'operationTime',
'transfer_time', 'transferTime'
]);
const quantityValue = this.firstValue(source, [
'quantity', 'qty', 'num', 'transfer_quantity', 'transferQuantity', 'count'
]);
const quantity = Number(quantityValue);
const id = this.firstValue(source, ['id', 'transfer_id', 'transferId', 'record_id'])
|| `${this.currentPage}-${index + 1}`;
return {
id,
barcode,
name,
operator,
batchNo,
fromSpace,
toSpace,
spaceId,
transactionType,
timeText: this.formatDateTime(timeValue),
quantityText: quantityValue === '' ? '--' : (Number.isFinite(quantity) ? String(quantity) : quantityValue)
};
})
.filter(item => !!(item.barcode || item.name || item.fromSpace || item.toSpace || item.operator));
},
// 按 space_id 批量拉取库位信息,用 custom_name 回填库位显示
async fetchSpaceNames(records) {
if (!Array.isArray(records) || !records.length) return;
const idSet = new Set();
records.forEach(item => {
const raw = item?.spaceId;
if (raw !== '' && raw !== undefined && raw !== null) {
idSet.add(String(raw));
}
});
const ids = Array.from(idSet);
if (!ids.length) return;
const nameMap = {};
const limit = 4;
let cursor = 0;
while (cursor < ids.length) {
const batch = ids.slice(cursor, cursor + limit);
cursor += limit;
await Promise.all(batch.map(async (idStr) => {
try {
const numId = Number(idStr);
const res = await this.$http('warehouse.getSpaceInfo', { id: Number.isFinite(numId) ? numId : idStr }, '', false);
if (res?.flag === 'failure' || Number(res?.code) !== 200) return;
const data = (res?.data && typeof res.data === 'object') ? res.data : {};
const name = String(data.custom_name ?? data.customName ?? data.space_code ?? data.spaceCode ?? '').trim();
if (name) nameMap[idStr] = name;
} catch (error) {
console.warn('[inventoryTransfer] 获取库位信息失败:', idStr, error);
}
}));
}
records.forEach(item => {
const resolved = nameMap[String(item.spaceId)];
if (!resolved) return;
if (item.transactionType === 'TRANSFER_OUT') {
if (!item.fromSpace || item.fromSpace === String(item.spaceId)) {
item.fromSpace = resolved;
}
} else {
if (!item.toSpace || item.toSpace === String(item.spaceId)) {
item.toSpace = resolved;
}
}
});
},
async loadRecordList(page = this.currentPage) {
const targetPage = Math.max(1, Number(page || 1));
this.loading = true;
try {
const response = await this.$http('storage.transaction.list', this.buildRecordParams(targetPage));
const payload = this.extractRecordPayload(response);
const list = this.extractRecordList(payload, response);
this.recordList = this.normalizeRecordList(list);
this.paginationTotal = this.resolveRecordTotal(payload, response, list);
const spaceTask = this.fetchSpaceNames(this.recordList);
if (spaceTask && typeof spaceTask.catch === 'function') {
spaceTask.catch(error => console.warn('[inventoryTransfer] 拉取库位名称失败:', error));
}
const pageInfo = (payload && typeof payload === 'object') ? (payload.pagination || {}) : {};
const pageNo = Number(pageInfo?.page ?? payload?.page ?? targetPage);
this.currentPage = Number.isFinite(pageNo) && pageNo > 0 ? pageNo : targetPage;
const pageSize = Number(pageInfo?.pageSize ?? pageInfo?.page_size ?? this.pageSize);
this.pageSize = Number.isFinite(pageSize) && pageSize > 0 ? pageSize : this.pageSize;
} catch (error) {
console.error('[inventoryTransfer] 移库记录加载失败:', error);
this.recordList = [];
this.paginationTotal = 0;
uni.showToast({ title: '移库记录加载失败', icon: 'none' });
} finally {
this.loading = false;
}
}
}
}
</script>
<style lang="scss" scoped>
.transfer-record-page {
height: 100vh;
background: #f8f9fa;
}
.normar_container {
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* 搜索区 */
.search-panel {
background: #ffffff;
border-bottom: 1rpx solid #f2f2f2;
padding: 16rpx;
box-sizing: border-box;
flex-shrink: 0;
}
.search-input-wrap {
position: relative;
::v-deep .u-search {
width: 100%;
}
::v-deep .u-search__content {
padding-right: 200rpx;
}
::v-deep .u-search__content__close {
margin-right: 12rpx;
}
}
.search-actions {
position: absolute;
right: 24rpx;
top: 50%;
transform: translateY(-50%);
height: 68rpx;
display: flex;
align-items: center;
}
.scan-btn {
height: 68rpx;
padding: 0 8rpx 0 4rpx;
display: flex;
align-items: center;
justify-content: center;
&:active {
opacity: 0.88;
}
}
.search-divider {
width: 1rpx;
height: 28rpx;
background: #dcdfe6;
margin: 0 16rpx 0 10rpx;
}
.search-btn {
height: 68rpx;
padding: 0 8rpx;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
&__text {
font-size: 34rpx;
font-weight: 500;
color: #2979ff;
line-height: 1;
}
&:active {
opacity: 0.88;
}
}
/* 筛选条件行(商品/操作人 | 移入/移出) */
.filter-row {
margin-top: 16rpx;
display: flex;
align-items: center;
}
.filter-group {
flex: 1;
display: flex;
}
.filter-group__item {
flex: 1;
height: 56rpx;
padding: 0 12rpx;
display: flex;
align-items: center;
justify-content: center;
background: #f5f7fa;
border: 1rpx solid #ebeef5;
border-radius: 28rpx;
}
.filter-group__item + .filter-group__item {
margin-left: 16rpx;
}
.filter-group__item--active {
background: #2979ff;
border-color: #2979ff;
box-shadow: 0 4rpx 12rpx rgba(41, 121, 255, 0.28);
}
.filter-group__item-text {
font-size: 30rpx;
color: #303133;
white-space: nowrap;
}
.filter-group__item--active .filter-group__item-text {
color: #ffffff;
font-weight: 600;
}
/* 移出(橙色警示) */
.filter-group__item--warning {
background: #ff9800;
border-color: #ff9800;
box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.28);
}
.filter-group__item--warning .filter-group__item-text {
color: #ffffff;
font-weight: 600;
}
.filter-divider {
width: 1rpx;
height: 36rpx;
margin: 0 16rpx;
background: #dcdfe6;
flex-shrink: 0;
}
/* 列表区 */
.detail-scroll {
flex: 1;
min-height: 0;
height: auto;
padding: 20rpx 0 0;
box-sizing: border-box;
}
.empty-state {
padding: 160rpx 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.empty-text {
margin-top: 24rpx;
font-size: 36rpx;
color: #909399;
}
.empty-hint {
margin-top: 12rpx;
font-size: 30rpx;
color: #c0c4cc;
}
.record-list {
display: flex;
flex-direction: column;
padding: 0 12rpx;
box-sizing: border-box;
}
.record-card {
background: #ffffff;
border: 2rpx solid #ebedf2;
border-radius: 20rpx;
padding: 4rpx 28rpx;
margin-bottom: 20rpx;
box-shadow: 0 6rpx 20rpx rgba(31, 45, 61, 0.06);
}
.record-card--stripe {
background: #dde9fb;
border-color: #dfe7f5;
}
.record-card--stripe .record-card__label {
color: #606266;
}
.record-card__row {
display: flex;
align-items: flex-start;
padding: 20rpx 0;
border-bottom: 1rpx solid #f0f2f5;
}
.record-card__row--last {
border-bottom: none;
}
.record-card__label {
flex-shrink: 0;
width: 160rpx;
font-size: 36rpx;
color: #8a9099;
line-height: 1.5;
}
.record-card__value {
flex: 1;
min-width: 0;
font-size: 40rpx;
color: #303133;
line-height: 1.5;
word-break: break-all;
overflow-wrap: break-word;
}
.record-card__value--strong {
font-weight: 600;
color: #2979ff;
}
.safe-area-bottom {
height: calc(20rpx + env(safe-area-inset-bottom));
}
/* 分页 */
.pagination-wrap {
background: #ffffff;
border-top: 1rpx solid #f0f0f0;
padding: 0 24rpx env(safe-area-inset-bottom);
flex-shrink: 0;
::v-deep .total-info {
font-size: 32rpx;
color: #606266;
}
}
</style>