feat: 退件收件任务模块(列表/扫码登记/扫描记录/导出)+ 库存盘点作业页完善

- 退件收件:returnRecord 改为收件任务列表(默认只看本人创建、可切全部、新建任务默认「用户名 当天日期」、左滑删除),扫码登记抽到 ReturnScanPanel 组件并由 returnRecordScan 页面承载,登记带 return_received_task_id

- 扫描记录:按任务 ID 过滤、底部剩余空间独立滚动(上拉/点击加载更多、下拉刷新)、标题显示任务登记总条数、原单退回显示货主名、常用备注抽屉(localStorage)、导出(异步任务+进度轮询+二维码/复制链接)

- 库存盘点:库位/商品/单库位作业页拆分与 workDataDetail/workDataSpaceDetails/recordList 接入;App.vue 图片预览层 z-index、auth-guard 整页启动路由修复;apis.js 补 returnReceivedTask/returnReceived.list/export 与漏登记保护
This commit is contained in:
liufumingren 2026-10-06 04:49:40 +08:00
parent 7c6aedfa6d
commit e8db7a2293
19 changed files with 5158 additions and 659 deletions

View File

@ -76,4 +76,12 @@ export default {
flex-direction: column;
background-color: #f8f8f8;
}
/* uni 系统图片预览层(uni.previewImage):
H5 下框架给 .uni-system-preview-image 的 z-index 只有 999,会被 uView 弹窗
(popup 默认 10075、toast 10090)盖住 —— 表现为"在弹窗里点图片预览看不到"。
这里统一抬高到所有业务弹层之上(App 端预览是原生全屏,不受此样式影响)。 */
.uni-system-preview-image {
z-index: 10100 !important;
}
</style>

View File

@ -436,7 +436,8 @@ export default {
method: "POST",
isSystemApi: true
},
// 盘点任务明细:返回主表 check + 全部明细 rows(含账面/实盘/差异数量)
// 盘点任务详情(只返回主表 check:check_no/type/mode/store_id/status/detail_status/进度/时间等):
// 入参仅 id;不再返回明细范围行(rows),明细结果请调 result,作业记录请调 recordList
detail: {
path: "stock.check.detail",
auth: true,
@ -461,16 +462,25 @@ export default {
method: "POST",
isSystemApi: true
},
// 单条盘点明细的作业数据(workData 单行版,仅库位任务明细):
// 入参仅 detail_id(兼容 detailId),warehouse_id 由服务端注入;
// 返回 data 为单行 location 结构(detail_id/location_id/location_code/location_name/
// status/has_unknown/is_empty/checked_at/checkers/goods),仅 approved/checking 可拉取
// 单条盘点明细的作业数据(入参仅 detail_id,兼容 detailId)——库位明细返回 location 单行结构
// (detail_id/location_code/location_name/status/has_unknown/is_empty/checked_at/checkers/goods);
// 商品明细返回商品行结构(item_name/barcode/spec/store_name/images + 明盘 system/checked/diff_quantity);
// warehouse_id 由服务端注入;仅 approved/checking 可拉取
workDataDetail: {
path: "stock.check.workDataDetail",
auth: true,
method: "POST",
isSystemApi: true
},
// 单库位的 space 作业数据(workData space 视图分页版):
// 入参 id(任务ID)+ location_id(库位ID,兼容 locationId,可选)+ pagination;
// 传 location_id 时只返回该库位行(total=1),行结构与 workData space 视图一致
workDataSpaceDetails: {
path: "stock.check.workDataSpaceDetails",
auth: true,
method: "POST",
isSystemApi: true
},
// 盘点作业上报:单条明细实盘数量(quantity>=0 整数)
report: {
path: "stock.check.report",
@ -486,6 +496,14 @@ export default {
method: "POST",
isSystemApi: true
},
// 盘点作业记录列表(id 与 detail_id 至少传一个,传了 detail_id 只查该明细的记录):
// 每条含 location_code/quantity/checker_name/checked_at/is_empty/images + 商品信息列,按记录 id 倒序分页
recordList: {
path: "stock.check.recordList",
auth: true,
method: "POST",
isSystemApi: true
},
// 完成盘点作业:主表置 completed
finish: {
path: "stock.check.finish",
@ -793,6 +811,51 @@ export default {
auth: true,
method: "POST",
isSystemApi: true
},
list: {
path: "returnReceived.list",
auth: true,
method: "POST",
isSystemApi: true
},
export: {
path: "returnReceived.export",
auth: true,
method: "POST",
isSystemApi: true
},
exportTaskProgress: {
path: "returnReceived.exportTaskProgress",
auth: true,
method: "POST",
isSystemApi: true
}
},
/** 收件任务(退件收件任务列表,warehouse_id 由服务端注入)↓ **/
returnReceivedTask: {
create: {
path: "returnReceivedTask.create",
auth: true,
method: "POST",
isSystemApi: true
},
list: {
path: "returnReceivedTask.list",
auth: true,
method: "POST",
isSystemApi: true
},
delete: {
path: "returnReceivedTask.delete",
auth: true,
method: "POST",
isSystemApi: true
},
batchDelete: {
path: "returnReceivedTask.batchDelete",
auth: true,
method: "POST",
isSystemApi: true
}
}
};

View File

@ -111,5 +111,9 @@ function getApiPath(url) {
apiArray.forEach(v => {
api = api[v];
});
// 未登记时报错信息要可读,避免出现 "Cannot read properties of undefined (reading 'auth')"
if (!api || typeof api !== 'object' || !api.path) {
throw new Error(`接口未注册: ${url}(请在 core/request/apis.js 中登记)`);
}
return api;
}

View File

@ -18,6 +18,28 @@ export function isLoginRoute(route = '') {
return route === LOGIN_URL
}
/**
* 整页启动(H5 F5 / 重新打开页面)时页面栈还是空的,getCurrentPages() 取不到路由;
* 此时若直接判定为“未知路由”就会把深链页面强制跳回首页,导致该页面的数据永远不会被拉取。
* 这里用启动 URL 兵底(只在 H5 history 模式有意义;App 端首屏是入口页,返回空字符串保持原行为)。
*/
export function getBootRoute() {
// #ifdef H5
if (typeof window !== 'undefined' && window.location) {
// 兼容 history(pathname)与 hash(#/pages/xxx)两种模式,query 不参与路由判断
const hashPath = String(window.location.hash || '').replace(/^#/, '').split('?')[0]
const raw = hashPath || String(window.location.pathname || '')
let path = raw.replace(/^\/+/, '').replace(/\/+$/, '')
if (path && path !== 'index.html') {
// 去掉可能存在的 .html 后缀,得到与 getCurrentRoute() 同格式(/pages/xxx)的路由
path = path.replace(/\.html$/, '')
if (path) return `/${path}`
}
}
// #endif
return ''
}
export function clearSession(store) {
removeToken()
if (!store) return
@ -124,7 +146,8 @@ export function goHome() {
export async function ensureEntry(store, forceValidate = false) {
const token = getToken()
const currentRoute = getCurrentRoute()
// 整页启动时页面栈为空,用启动 URL 兵底,避免把深链当成未知路由而跳首页
const currentRoute = getCurrentRoute() || getBootRoute()
// 工作台会话:跳过用户态校验,不调用 user.info;保持当前打包模式页不跳首页
if (isWorkbenchSession()) {

View File

@ -145,6 +145,20 @@
"titleNView": false
}
},
{
"path" : "pages/warehouse/inventoryCountSpace",
"style" :
{
"titleNView": false
}
},
{
"path" : "pages/warehouse/inventoryCountGoods",
"style" :
{
"titleNView": false
}
},
{
"path" : "pages/403",
"style" :
@ -293,6 +307,13 @@
"titleNView": false
}
},
{
"path" : "pages/work/order/returnRecordScan",
"style" :
{
"titleNView": false
}
},
{
"path" : "pages/work/order/pickingRecord",
"style" :

View File

@ -0,0 +1,191 @@
<template>
<view class="goods-card" @click="handleClick">
<view class="goods-card__body">
<!-- 商品主图(有图才渲染,占位不占空间) -->
<view v-if="row.image" class="goods-card__thumb">
<u-image :src="row.image" mode="aspectFill" width="96rpx" height="96rpx" radius="8rpx">
<template #error>
<view class="goods-card__thumb-empty">
<text class="goods-card__thumb-text">无图</text>
</view>
</template>
</u-image>
</view>
<view class="goods-card__info">
<view class="goods-card__head">
<text class="goods-card__title">{{ row.title || '--' }}</text>
<text class="goods-card__flag" :class="row.checked ? 'goods-card__flag--done' : 'goods-card__flag--todo'">
{{ row.checked ? '已盘' : '未盘' }}
</text>
</view>
<text v-if="row.subtitle" class="goods-card__subtitle">{{ row.subtitle }}</text>
<view class="goods-card__metrics">
<template v-if="row.amount">
<text class="goods-card__metric">账面 {{ row.amount.systemText }}</text>
<text class="goods-card__metric">已盘 {{ row.amount.checkedText }}</text>
<text v-if="row.amount.diffText" class="goods-card__diff" :class="diffClass(row)">
{{ row.amount.diffText }}
</text>
</template>
<text v-else class="goods-card__metric">已盘记录 {{ row.recordCount || 0 }} 条</text>
<text v-if="locationText" class="goods-card__metric">{{ locationText }}</text>
</view>
</view>
</view>
</view>
</template>
<script>
/**
* 盘点作业行 · 商品(view=goods)
* 一行一个商品,只展示盘点概况(名称/规格条码货主/账面已盘差异),视觉对齐库位宫格格子;
* 操作剥离到商品作业页,点击整行由父级跳转
*/
export default {
name: 'CountGoodsCard',
props: {
row: {
type: Object,
default: () => ({})
}
},
computed: {
// 已盘库位提示(1 个显示库位码,多个显示「N 个库位」)
locationText() {
const codes = Array.isArray(this.row.locationCodes) ? this.row.locationCodes : [];
if (!codes.length) return '';
if (codes.length === 1) return codes[0];
return `${codes.length} 个库位`;
}
},
methods: {
diffClass(row) {
const tone = row && row.amount ? row.amount.diffTone : '';
return tone ? `goods-card__diff--${tone}` : '';
},
handleClick() {
this.$emit('select', this.row);
}
}
};
</script>
<style lang="scss" scoped>
/* 与库位宫格格子同一视觉(灰底 + 12rpx 圆角 + 2rpx 边框,无阴影) */
.goods-card {
margin-bottom: 12rpx;
padding: 16rpx 24rpx;
box-sizing: border-box;
background: #f5f7fa;
border: 2rpx solid #e6e8eb;
border-radius: 12rpx;
&:last-child {
margin-bottom: 0;
}
}
.goods-card__body {
display: flex;
align-items: center;
}
.goods-card__thumb {
flex-shrink: 0;
margin-right: 16rpx;
}
.goods-card__thumb-empty {
width: 96rpx;
height: 96rpx;
border-radius: 8rpx;
background: #eef0f3;
display: flex;
align-items: center;
justify-content: center;
}
.goods-card__thumb-text {
font-size: 20rpx;
color: #c0c4cc;
}
.goods-card__info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.goods-card__head {
display: flex;
align-items: center;
justify-content: space-between;
}
.goods-card__title {
flex: 1;
min-width: 0;
font-size: 32rpx;
font-weight: 600;
color: #303133;
line-height: 1.3;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.goods-card__flag {
flex-shrink: 0;
margin-left: 16rpx;
font-size: 26rpx;
line-height: 1.2;
}
.goods-card__flag--done {
color: #18a058;
}
.goods-card__flag--todo {
color: #ff9800;
}
.goods-card__subtitle {
margin-top: 6rpx;
font-size: 24rpx;
color: #8a9099;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.goods-card__metrics {
margin-top: 8rpx;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.goods-card__metric {
margin-right: 20rpx;
font-size: 24rpx;
color: #606266;
}
.goods-card__diff {
font-size: 24rpx;
font-weight: 600;
}
.goods-card__diff--gain {
color: #18a058;
}
.goods-card__diff--loss {
color: #e64340;
}
.goods-card__diff--match {
color: #909399;
}
</style>

View File

@ -7,7 +7,7 @@
</view>
<view class="loc-detail__tags">
<text v-if="row.empty" class="loc-detail__tag loc-detail__tag--empty">空库位</text>
<text v-if="row.statusText" class="loc-detail__tag" :class="row.statusClass">{{ row.statusText }}</text>
<text v-if="row.statusText" class="loc-detail__tag" :class="tagClass(row.statusText)">{{ row.statusText }}</text>
</view>
</view>
@ -17,13 +17,13 @@
<view class="loc-detail__section">
<view class="loc-detail__section-head">
<text class="loc-detail__section-title">商品记录</text>
<text class="loc-detail__section-title">{{ sectionTitle }}</text>
<text class="loc-detail__section-count">共 {{ (row.goodsCount || 0) + (row.unknownCount || 0) }} 条</text>
<text v-if="row.unknownCount" class="loc-detail__section-unknown">未知 {{ row.unknownCount }}</text>
</view>
<view v-if="!row.children || !row.children.length" class="loc-detail__empty">
<text class="loc-detail__empty-text">该库位暂无商品记录</text>
<text class="loc-detail__empty-text">{{ emptyText }}</text>
</view>
<view v-else class="loc-detail__list">
<u-swipe-action :key="listKey">
@ -36,13 +36,46 @@
@click="handleSwipeClick(child)"
>
<view class="loc-detail__row">
<view
v-if="child.images && child.images.length"
class="loc-detail__row-thumb"
@click.stop="previewImages(child.images)"
>
<u-image
:src="child.images[0]"
mode="aspectFill"
width="96rpx"
height="96rpx"
radius="8rpx"
>
<template #error>
<view class="loc-detail__row-thumb-empty">
<text class="loc-detail__row-thumb-text">无图</text>
</view>
</template>
</u-image>
<view v-if="child.images.length > 1" class="loc-detail__row-thumb-badge">
<text class="loc-detail__row-thumb-badge-text">{{ child.images.length }}</text>
</view>
</view>
<view class="loc-detail__row-main">
<text class="loc-detail__row-title">{{ child.title }}</text>
<text v-if="child.subtitle" class="loc-detail__row-sub">{{ child.subtitle }}</text>
<!-- 账面 / 实盘 / 盈亏(商品作业页的库位明细带这个;账面>0 高亮,方便找账面库位) -->
<view v-if="child.amounts" class="loc-detail__row-amounts">
<text
class="loc-detail__row-amount"
:class="{ 'loc-detail__row-amount--stock': child.amounts.hasSystemStock }"
>账面 {{ child.amounts.systemText }}</text>
<text class="loc-detail__row-amount">实盘 {{ child.amounts.checkedText }}</text>
<text v-if="child.amounts.diffText" class="loc-detail__row-diff" :class="diffClass(child.amounts)">
{{ child.amounts.diffText }}
</text>
</view>
</view>
<view class="loc-detail__row-side">
<text v-if="child.statusText" class="loc-detail__row-tag" :class="child.statusClass">{{ child.statusText }}</text>
<text v-if="child.quantityText !== ''" class="loc-detail__row-qty">实盘 {{ child.quantityText }}</text>
<text v-if="!child.amounts && child.quantityText !== ''" class="loc-detail__row-qty">实盘 {{ child.quantityText }}</text>
</view>
</view>
</u-swipe-action-item>
@ -54,9 +87,9 @@
<script>
/**
* 库位盘点明细面板
* 展示当前库位状态、盘点人与商品作业记录(商品记录可左滑删除);
* 「添加商品」不放按钮:统一由页面顶部输入框/扫码打开添加弹窗
* 盘点明细面板(库位任务的库位行 / 商品任务的商品行 通用)
* 展示目标状态、概况 meta 与作业记录列表(记录可左滑删除);
* 新增/录入不放按钮:统一由页面顶部输入框/扫码处理
*/
export default {
name: 'CountLocationDetail',
@ -68,6 +101,15 @@ export default {
editable: {
type: Boolean,
default: false
},
// 列表区标题 / 空态文案(库位页与商品页共用)
sectionTitle: {
type: String,
default: '商品记录'
},
emptyText: {
type: String,
default: '该库位暂无商品记录'
}
},
computed: {
@ -83,12 +125,37 @@ export default {
}
},
methods: {
/** 状态标签色调(组件内自映射,不依赖各页面的样式类) */
tagClass(text) {
const key = String(text || '').trim();
if (key === '已盘') return 'loc-detail__tag--done';
if (key === '未盘') return 'loc-detail__tag--todo';
if (key === '未知') return 'loc-detail__tag--unknown';
return '';
},
/** 盈亏色调(gain/loss/match) */
diffClass(amounts) {
const tone = amounts && amounts.diffTone ? amounts.diffTone : '';
if (tone === 'gain') return 'loc-detail__row-diff--gain';
if (tone === 'loss') return 'loc-detail__row-diff--loss';
if (tone === 'match') return 'loc-detail__row-diff--match';
return '';
},
canDelete(child) {
return this.editable && !!(child && child.recordId);
if (!this.editable || !child) return false;
// 商品作业页的库位明细带 recordIds(可能多条),库位页的记录只有单条 recordId
if (Array.isArray(child.recordIds) && child.recordIds.length) return true;
return !!child.recordId;
},
handleSwipeClick(child) {
if (!this.canDelete(child)) return;
this.$emit('delete', child);
},
/** 记录照片预览(点击缩略图) */
previewImages(images) {
const urls = (Array.isArray(images) ? images : []).filter(Boolean);
if (!urls.length) return;
uni.previewImage({ current: urls[0], urls });
}
}
};
@ -156,6 +223,21 @@ export default {
background: #eef0f3;
}
.loc-detail__tag--done {
color: #18a058;
background: #e8f7ee;
}
.loc-detail__tag--todo {
color: #ff9800;
background: #fff5e6;
}
.loc-detail__tag--unknown {
color: #e64340;
background: #fdecec;
}
.loc-detail__meta {
margin-top: 10rpx;
display: flex;
@ -214,6 +296,13 @@ export default {
.loc-detail__list {
margin-top: 4rpx;
/* 左滑时内容向左滑出、被容器裁剪到卡片左内边距边缘(看起来贴死左边):
给滑动容器留一点左间距。
注意必须加在 .u-swipe-action-item 上——__right 是 absolute; right:0,
对它写 margin-left 不会生效(只有非绝对定位的 __content 会跟着一起位移)。 */
::v-deep .u-swipe-action-item {
margin-left: 12rpx;
}
}
.loc-detail__row {
@ -229,6 +318,49 @@ export default {
}
}
/* 记录照片缩略图(有图才渲染) */
.loc-detail__row-thumb {
position: relative;
flex-shrink: 0;
margin-right: 16rpx;
}
.loc-detail__row-thumb-empty {
width: 96rpx;
height: 96rpx;
border-radius: 8rpx;
background: #f5f7fa;
display: flex;
align-items: center;
justify-content: center;
}
.loc-detail__row-thumb-text {
font-size: 20rpx;
color: #c0c4cc;
}
.loc-detail__row-thumb-badge {
position: absolute;
right: 0;
bottom: 0;
min-width: 32rpx;
height: 32rpx;
padding: 0 6rpx;
box-sizing: border-box;
border-radius: 8rpx 0 8rpx 0;
background: rgba(0, 0, 0, 0.55);
display: flex;
align-items: center;
justify-content: center;
}
.loc-detail__row-thumb-badge-text {
font-size: 20rpx;
line-height: 1;
color: #ffffff;
}
.loc-detail__row-main {
flex: 1;
min-width: 0;
@ -250,6 +382,43 @@ export default {
word-break: break-all;
}
/* 账面 / 实盘 / 盈亏 */
.loc-detail__row-amounts {
margin-top: 8rpx;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.loc-detail__row-amount {
margin-right: 20rpx;
font-size: 26rpx;
color: #909399;
}
/* 该库位账面有货:加粗深色,方便一眼找到账面库位 */
.loc-detail__row-amount--stock {
font-weight: 600;
color: #303133;
}
.loc-detail__row-diff {
font-size: 26rpx;
font-weight: 600;
}
.loc-detail__row-diff--gain {
color: #18a058;
}
.loc-detail__row-diff--loss {
color: #e64340;
}
.loc-detail__row-diff--match {
color: #909399;
}
.loc-detail__row-side {
flex-shrink: 0;
margin-left: 16rpx;

View File

@ -2,21 +2,35 @@
<view class="loc-grid">
<view class="loc-grid__head">
<text class="loc-grid__head-title">库位列表</text>
<text class="loc-grid__head-hint">点击库位查看明细</text>
<text class="loc-grid__head-hint">{{ mode === 'space' ? '点击库位录入商品' : '点击库位查看明细' }}</text>
</view>
<view class="loc-grid__body">
<view
v-for="row in rows"
:id="`work-${row.key}`"
:key="row.key"
class="loc-grid__cell"
@click="$emit('select', row.key)"
@click="handleSelect(row)"
>
<view class="loc-grid__inner" :class="cellClass(row)">
<text class="loc-grid__code">{{ row.gridText || row.title || '--' }}</text>
<view class="loc-grid__side">
<text class="loc-grid__flag" :class="flagClass(row)">{{ row.checked ? '已盘' : '未盘' }}</text>
<text class="loc-grid__count">{{ countText(row) }}</text>
</view>
<template v-if="isSpace">
<!-- space:库位独占一行 + 状态独占一行 + 商品数与已盘未盘同一行 -->
<text class="loc-grid__code loc-grid__code--stack">{{ row.gridText || row.title || '--' }}</text>
<text class="loc-grid__flag loc-grid__flag--stack" :class="flagClass(row)">{{ flagText(row) }}</text>
<view class="loc-grid__foot">
<text class="loc-grid__sub">{{ row.gridCountText }}</text>
<text class="loc-grid__count">{{ countText(row) }}</text>
</view>
</template>
<template v-else>
<view class="loc-grid__main">
<text class="loc-grid__code">{{ row.gridText || row.title || '--' }}</text>
</view>
<view class="loc-grid__side">
<text class="loc-grid__flag" :class="flagClass(row)">{{ flagText(row) }}</text>
<text class="loc-grid__count">{{ countText(row) }}</text>
</view>
</template>
</view>
</view>
</view>
@ -25,10 +39,11 @@
<script>
/**
* 库位盘点宫格列表(2 列,每页 20 个 → 2 列 10 行,随页面滚动)
* 行数据来自 countModel.normalizeWorkRows(rows, 'location', mode)
* 格子显示完整 location_name(缺失时回退 location_code)+ 已盘/未盘标记
* 点击格子只派发 select,由父级跳转到库位明细页
* 库位宫格列表(2 列,每页 20 个 → 2 列 10 行,随页面滚动)
* mode=location:行=任务库位,点击格子进入库位明细页;格子单行(左库位名 / 右状态+数量)
* mode=space:行=库位(商品任务按库位聚合),三行:库位名 / 状态 / 商品数+已盘未盘
* 行数据来自 countModel.normalizeWorkRows(rows, view, mode)
* 格子显示完整库位名(缺失时回退库位编码)
*/
export default {
name: 'CountLocationGrid',
@ -37,25 +52,51 @@ export default {
type: Array,
default: () => []
},
// location | space
mode: {
type: String,
default: 'location'
},
// 是否可点击(space 视图仅统计展示,不可点击)
clickable: {
type: Boolean,
default: true
},
selectedKey: {
type: String,
default: ''
}
},
computed: {
isSpace() {
return this.mode === 'space';
}
},
methods: {
handleSelect(row) {
if (!this.clickable || !row) return;
this.$emit('select', row.key);
},
cellClass(row) {
const classes = [];
if (this.isSpace) classes.push('loc-grid__inner--stack');
if (row.checked) classes.push('loc-grid__inner--done');
if (row.empty) classes.push('loc-grid__inner--empty');
if (row.hasUnknown) classes.push('loc-grid__inner--unknown');
if (row.key === this.selectedKey) classes.push('loc-grid__inner--active');
return classes;
},
flagText(row) {
if (this.isSpace && row.partChecked) return '部分';
return row.checked ? '已盘' : '未盘';
},
flagClass(row) {
if (this.isSpace && row.partChecked) return 'loc-grid__flag--part';
return row.checked ? 'loc-grid__flag--done' : 'loc-grid__flag--todo';
},
/** 商品记录数(已盘才有记录,未盘显示 --) */
/** location:商品记录数(已盘才有记录,未盘显示 --);space:已盘/未盘商品条数 */
countText(row) {
if (this.isSpace) return row.gridProgressText || '';
if (!row.checked) return '--';
const total = (Number(row.goodsCount) || 0) + (Number(row.unknownCount) || 0);
return `${total} 项`;
@ -119,6 +160,48 @@ export default {
border-color: #b7e4c7;
}
/* space 视图:竖排三行(库位名 / 状态 / 商品数+已盘未盘) */
.loc-grid__inner--stack {
height: auto;
min-height: 132rpx;
padding: 14rpx 24rpx;
flex-direction: column;
align-items: stretch;
justify-content: center;
}
/* 库位名独占一行(超长省略) */
.loc-grid__code--stack {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 状态独占一行 */
.loc-grid__flag--stack {
margin-top: 6rpx;
}
/* 商品项 + 已盘未盘同一行 */
.loc-grid__foot {
margin-top: 6rpx;
display: flex;
align-items: center;
justify-content: space-between;
}
.loc-grid__foot .loc-grid__count {
margin-top: 0;
}
.loc-grid__main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
}
.loc-grid__inner--empty {
border-style: dashed;
}
@ -134,8 +217,6 @@ export default {
}
.loc-grid__code {
flex: 1;
min-width: 0;
font-size: 30rpx;
font-weight: 600;
color: #303133;
@ -143,6 +224,13 @@ export default {
word-break: break-all;
}
.loc-grid__sub {
margin-top: 6rpx;
font-size: 22rpx;
line-height: 1.1;
color: #909399;
}
.loc-grid__flag {
font-size: 26rpx;
line-height: 1;
@ -171,4 +259,9 @@ export default {
.loc-grid__flag--todo {
color: #ff9800;
}
/* 部分已盘 */
.loc-grid__flag--part {
color: #2979ff;
}
</style>

View File

@ -0,0 +1,354 @@
<template>
<u-popup :show="show" mode="bottom" round="20" :closeable="true" :safeAreaInsetBottom="true" @close="handleClose">
<view class="space-entry">
<view class="space-entry__header">
<text class="space-entry__title">登记实盘数量</text>
<text class="space-entry__subtitle">{{ subtitle }}</text>
</view>
<!-- 扫描/输入库位码 → 查询库位 -->
<view class="space-entry__search">
<u-search
v-model="keyword"
placeholder="扫描/输入库位编码、自定义名称"
bg-color="#f5f5f5"
shape="round"
:show-action="false"
@search="handleSearch"
@clear="handleSearch"
></u-search>
</view>
<scroll-view class="space-entry__scroll" scroll-y>
<view v-if="loading" class="space-entry__empty">加载中...</view>
<view v-else-if="!list.length" class="space-entry__empty">
{{ searched ? '未找到匹配库位' : '请输入关键字或扫码查询库位' }}
</view>
<view
v-for="item in list"
:key="item.key"
class="space-item"
:class="{ 'space-item--selected': selectedKey === item.key }"
@click="selectItem(item)"
>
<view class="space-item__main">
<text class="space-item__title">{{ item.title }}</text>
<text v-if="item.subtitle" class="space-item__subtitle">{{ item.subtitle }}</text>
</view>
<view class="space-item__radio" :class="{ 'space-item__radio--checked': selectedKey === item.key }">
<u-icon v-if="selectedKey === item.key" name="checkmark" size="24rpx" color="#ffffff"></u-icon>
</view>
</view>
</scroll-view>
<view class="space-entry__qty">
<text class="space-entry__label">实盘数量</text>
<input
class="space-entry__qty-input"
type="number"
v-model="quantity"
placeholder="请输入数量"
placeholder-style="color: #c0c4cc;"
:focus="quantityFocus"
confirm-type="done"
@confirm="handleConfirm"
/>
</view>
<view class="space-entry__footer">
<view class="space-entry__btn" :class="{ 'space-entry__btn--disabled': !canConfirm || submitting }" @click="handleConfirm">
<text class="space-entry__btn-text">确认登记</text>
</view>
</view>
</view>
</u-popup>
</template>
<script>
import { normalizeSpaceSearchRows } from './countModel.js';
/**
* 商品作业页的「选库位 + 录数量」底部抽屉(check.report)
* 流程:扫描/输入库位 → 查询(common.searchSpace)→ 选中库位 → 输入实盘数量 → 确认登记
* 父页负责实际上报;支持扫码连续录入:已打开时父页调 applyKeyword(code) 重新查询
*/
export default {
name: 'CountSpaceEntryPopup',
props: {
show: {
type: Boolean,
default: false
},
// 预填关键字(扫码得到库位码后带进抽屉并自动查询)
prefillKeyword: {
type: String,
default: ''
},
// 副标题展示用(商品名 / 单号)
itemName: {
type: String,
default: ''
},
submitting: {
type: Boolean,
default: false
}
},
data() {
return {
keyword: '',
list: [],
selectedKey: '',
quantity: '',
loading: false,
searched: false,
quantityFocus: false
};
},
computed: {
subtitle() {
return this.itemName ? `商品:${this.itemName}` : '按库位登记该商品实盘数量';
},
selectedItem() {
return this.list.find(item => item.key === this.selectedKey) || null;
},
canConfirm() {
return !!this.selectedKey && String(this.quantity).trim() !== '';
}
},
watch: {
show(value) {
if (value) {
this.resetForm();
if (this.prefillKeyword) this.applyKeyword(this.prefillKeyword);
}
}
},
methods: {
handleClose() {
this.$emit('close');
},
resetForm() {
this.keyword = '';
this.list = [];
this.selectedKey = '';
this.quantity = '';
this.loading = false;
this.searched = false;
this.quantityFocus = false;
},
/** 清空后用指定关键字重新查询(扫码/重复扫码时由父页调用) */
applyKeyword(code) {
const keyword = String(code || '').trim();
this.resetForm();
if (!keyword) return;
this.keyword = keyword;
this.handleSearch();
},
async handleSearch() {
const keyword = String(this.keyword || '').trim();
if (!keyword) {
this.list = [];
this.selectedKey = '';
this.searched = false;
return;
}
this.loading = true;
try {
const response = await this.$http('common.searchSpace', { keyword });
this.list = normalizeSpaceSearchRows(response);
this.searched = true;
// 唯一命中直接选中,扫一次就能接着输入数量
if (this.list.length === 1) {
this.selectItem(this.list[0]);
} else {
this.selectedKey = '';
}
} catch (error) {
console.error('[CountSpaceEntryPopup] 库位查询失败:', error);
this.list = [];
this.selectedKey = '';
uni.showToast({ title: '库位查询失败', icon: 'none' });
} finally {
this.loading = false;
}
},
selectItem(item) {
if (!item) return;
this.selectedKey = item.key;
this.focusQuantity();
},
focusQuantity() {
this.quantityFocus = false;
this.$nextTick(() => {
this.quantityFocus = true;
});
},
handleConfirm() {
if (this.submitting) return;
if (!this.selectedKey) {
uni.showToast({ title: '请先选择库位', icon: 'none' });
return;
}
const raw = String(this.quantity).trim();
const quantity = Number(raw);
if (raw === '' || !Number.isInteger(quantity) || quantity < 0) {
uni.showToast({ title: '请输入不小于0的整数数量', icon: 'none' });
this.focusQuantity();
return;
}
const item = this.selectedItem || {};
this.$emit('confirm', {
location: item.code || this.keyword,
locationId: item.id === undefined || item.id === null ? '' : item.id,
quantity
});
}
}
};
</script>
<style lang="scss" scoped>
.space-entry {
display: flex;
flex-direction: column;
max-height: 80vh;
padding: 32rpx 24rpx calc(24rpx + env(safe-area-inset-bottom));
box-sizing: border-box;
}
.space-entry__header {
padding-right: 60rpx;
}
.space-entry__title {
font-size: 36rpx;
font-weight: 600;
color: #303133;
}
.space-entry__subtitle {
margin-top: 8rpx;
font-size: 26rpx;
color: #909399;
}
.space-entry__search {
margin-top: 24rpx;
}
.space-entry__scroll {
flex: 1;
min-height: 200rpx;
max-height: 40vh;
margin-top: 16rpx;
}
.space-entry__empty {
padding: 60rpx 0;
text-align: center;
font-size: 30rpx;
color: #c0c4cc;
}
.space-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 8rpx;
border-bottom: 1rpx solid #f2f4f7;
&:last-child {
border-bottom: none;
}
&--selected {
background: #f5f9ff;
}
}
.space-item__main {
flex: 1;
min-width: 0;
margin-right: 16rpx;
display: flex;
flex-direction: column;
}
.space-item__title {
font-size: 32rpx;
color: #303133;
line-height: 1.4;
word-break: break-all;
}
.space-item__subtitle {
margin-top: 4rpx;
font-size: 26rpx;
color: #909399;
}
.space-item__radio {
flex-shrink: 0;
width: 40rpx;
height: 40rpx;
border-radius: 50%;
border: 2rpx solid #dcdfe6;
background: #ffffff;
display: flex;
align-items: center;
justify-content: center;
}
.space-item__radio--checked {
background: #2979ff;
border-color: #2979ff;
}
.space-entry__qty {
margin-top: 20rpx;
display: flex;
align-items: center;
}
.space-entry__label {
flex-shrink: 0;
margin-right: 20rpx;
font-size: 30rpx;
color: #606266;
}
.space-entry__qty-input {
flex: 1;
min-width: 0;
height: 76rpx;
padding: 0 24rpx;
box-sizing: border-box;
font-size: 32rpx;
color: #303133;
background: #f5f5f5;
border-radius: 12rpx;
}
.space-entry__footer {
margin-top: 24rpx;
}
.space-entry__btn {
height: 84rpx;
display: flex;
align-items: center;
justify-content: center;
background: #2979ff;
border-radius: 12rpx;
}
.space-entry__btn--disabled {
opacity: 0.5;
}
.space-entry__btn-text {
font-size: 32rpx;
color: #ffffff;
}
</style>

View File

@ -52,7 +52,13 @@
<!-- 子项:space=该库位下的商品;goods=该商品的各库位记录;location=该库位的作业记录 -->
<view v-if="row.children && row.children.length" class="work-card__children">
<view v-for="child in row.children" :key="child.key" class="work-child">
<view
v-for="child in row.children"
:id="`work-${child.key}`"
:key="child.key"
class="work-child"
:class="{ 'work-child--active': !!focusedKey && child.key === focusedKey }"
>
<view class="work-child__main">
<text class="work-child__title">{{ child.title }}</text>
<text v-if="child.subtitle" class="work-child__subtitle">{{ child.subtitle }}</text>
@ -126,6 +132,11 @@ export default {
focused: {
type: Boolean,
default: false
},
// 子项定位高亮(按 child.key,如扫码定位到某个商品行)
focusedKey: {
type: String,
default: ''
}
}
};
@ -336,6 +347,12 @@ export default {
}
}
/* 扫码/输入定位到某个商品行时的高亮 */
.work-child--active {
background: #eef4ff;
border-radius: 8rpx;
}
.work-child__main {
display: flex;
flex-direction: column;

View File

@ -513,10 +513,15 @@ function buildWorkAmount(systemQuantity, checkedQuantity, diffQuantity, open) {
const chk = toNumberOrNull(checkedQuantity);
let diff = toNumberOrNull(diffQuantity);
if (diff === null && sys !== null && chk !== null) diff = chk - sys;
// diffTone 供各组件映射自己的样式类(gain/loss/match),diffClass 保持旧口径兼容
const diffTone = diff === null ? '' : (diff > 0 ? 'gain' : (diff < 0 ? 'loss' : 'match'));
return {
systemText: sys === null ? '--' : String(sys),
checkedText: chk === null ? '--' : String(chk),
diffText: diff === null ? '' : (diff > 0 ? `盘盈 +${diff}` : (diff < 0 ? `盘亏 ${diff}` : '账实相符')),
// 盘亏用绝对值(盘亏 49084),避免出现「盘亏 -49084」这种双重负号
diffText: diff === null ? '' : (diff > 0 ? `盘盈 +${diff}` : (diff < 0 ? `盘亏 ${-diff}` : '账实相符')),
diff,
diffTone,
diffClass: diff === null ? '' : (diff > 0 ? 'work-card__diff--gain' : (diff < 0 ? 'work-card__diff--loss' : 'work-card__diff--match'))
};
}
@ -571,7 +576,7 @@ function joinText(parts, sep = ' · ') {
return parts.filter(part => part !== null && part !== undefined && String(part).trim() !== '').map(part => String(part).trim()).join(sep);
}
/** space 视图:行=库位,goods 为该库位下的任务商品(商品任务默认视图) */
/** space 视图:行=库位,goods 为该库位下的任务商品(商品任务默认视图;作业列表按库位宫格展示,仅统计不可点击) */
function normalizeSpaceWorkRow(item, index, open) {
const source = item && typeof item === 'object' ? item : {};
const spaceCode = firstValue(source, ['space_code', 'spaceCode']) || `#${index + 1}`;
@ -592,18 +597,42 @@ function normalizeSpaceWorkRow(item, index, open) {
unit: buildWorkUnit(detailId, spaceCode, checkedRaw, done, firstValue(good, ['stock_id', 'stockId']))
};
});
// 库位统计(口径=商品条数):商品 status=checked 即该明细在该库位已有作业记录
const total = children.length;
const checkedCount = rawGoods.filter(row => String((row && row.status) || '').trim().toLowerCase() === 'checked').length;
const uncheckedCount = Math.max(0, total - checkedCount);
const allDone = total > 0 && checkedCount === total;
const spaceName = firstValue(source, ['custom_name', 'customName']);
return {
key: `space-${firstValue(source, ['id']) || spaceCode}`,
view: 'space',
title: spaceCode,
subtitle: joinText([firstValue(source, ['custom_name', 'customName']), firstValue(source, ['custom_barcode', 'customBarcode'])]),
subtitle: joinText([spaceName, firstValue(source, ['custom_barcode', 'customBarcode'])]),
statusText: '',
statusClass: '',
meta: children.length ? [] : [{ label: '商品', value: '该库位暂无任务商品' }],
amount: null,
quantityText: '',
children,
unit: null
unit: null,
// 宫格展示字段(与 location 视图对齐:行=库位;space 行没有库位明细ID)
// 库位ID(wms_location_space.id)——跳「单库位作业页」(workDataSpaceDetails)用
spaceId: firstValue(source, ['id']) ? String(firstValue(source, ['id'])) : '',
location: spaceCode,
locationName: spaceName || spaceCode,
empty: false,
checked: allDone,
partChecked: checkedCount > 0 && checkedCount < total,
hasUnknown: false,
goodsCount: total,
unknownCount: 0,
checkedCount,
uncheckedCount,
gridText: spaceName || spaceCode,
gridCode: spaceCode,
gridLabel: shortLocationLabel(spaceCode),
gridCountText: `商品 ${total} 项`,
gridProgressText: `已盘 ${checkedCount} / 未盘 ${uncheckedCount}`
};
}
@ -629,18 +658,39 @@ function normalizeGoodsWorkRow(item, index, open) {
};
});
const reported = checkedRaw !== undefined && checkedRaw !== null && checkedRaw !== '';
// 行级商品主图(goods 视图行级 images 仍为商品主图)
const imageList = Array.isArray(source.images) ? source.images.filter(Boolean) : [];
// 作业记录条数(locations[].record_ids 汇总)——已盘判断与概况展示用
const recordCount = rawLocations.reduce((sum, row) => {
const ids = row && Array.isArray(row.record_ids) ? row.record_ids.length : 0;
return sum + ids;
}, 0);
const done = reported || recordCount > 0;
return {
key: `goods-${detailId || index + 1}`,
view: 'goods',
detailId: detailId ? String(detailId) : '',
stockId: firstValue(source, ['stock_id', 'stockId']) === undefined || firstValue(source, ['stock_id', 'stockId']) === null ? '' : String(firstValue(source, ['stock_id', 'stockId'])),
title: firstValue(source, ['item_name', 'itemName']) || '--',
subtitle: joinText([firstValue(source, ['spec']), firstValue(source, ['barcode']), firstValue(source, ['store_name', 'storeName'])]),
statusText: '',
statusClass: '',
statusText: done ? '已盘' : '未盘',
statusClass: done ? 'work-card__tag--done' : 'work-card__tag--todo',
meta: children.length ? [] : [{ label: '库位', value: '暂无作业记录' }],
amount: buildWorkAmount(source.system_quantity !== undefined ? source.system_quantity : source.systemQuantity, checkedRaw, source.diff_quantity !== undefined ? source.diff_quantity : source.diffQuantity, open),
quantityText: '',
children,
unit: buildWorkUnit(detailId, '', checkedRaw, reported, firstValue(source, ['stock_id', 'stockId']))
unit: buildWorkUnit(detailId, '', checkedRaw, reported, firstValue(source, ['stock_id', 'stockId'])),
// 列表行(CountGoodsCard)与商品作业页(概况带入路由)用的字段:一行一个商品,操作剥离到操作页
images: imageList,
image: imageList[0] || '',
itemCode: firstValue(source, ['item_code', 'itemCode']) || '',
barcode: firstValue(source, ['barcode']) || '',
spec: firstValue(source, ['spec']) || '',
storeName: firstValue(source, ['store_name', 'storeName']) || '',
checked: done,
recordCount,
locationCount: rawLocations.length,
locationCodes: rawLocations.map(row => firstValue(row || {}, ['location_code', 'locationCode'])).filter(Boolean)
};
}
@ -751,6 +801,172 @@ export function normalizeLocationWorkDetail(payload, mode) {
return normalizeLocationWorkRow(payload, 0, isOpenCheckMode(mode));
}
/**
* 单库位作业数据归一化(stock.check.workDataSpaceDetails,rows 只有该库位一行)
* 返回结构与 workData space 视图单行一致;rows 为空时返回 null。
*/
export function normalizeSpaceWorkDetail(rows, mode) {
if (!Array.isArray(rows) || !rows.length) return null;
return normalizeWorkRows(rows.slice(0, 1), 'space', mode)[0] || null;
}
/**
* 单条明细的作业记录归一化(stock.check.recordList,按 detail_id 拉该明细的全部记录)
* 返回 { children, count, totalQuantity }:children 结构可直接给 CountLocationDetail 用
* (title=库位码 / quantityText=实盘数量 / recordId 供左滑删除)。
*/
export function normalizeGoodsRecords(rows) {
const list = Array.isArray(rows) ? rows : [];
const children = list.map((item, index) => {
const record = item && typeof item === 'object' ? item : {};
const recordId = firstValue(record, ['id', 'record_id', 'recordId']);
const locationCode = firstValue(record, ['location_code', 'locationCode']);
const quantity = toNumberOrNull(record.quantity);
const checkerName = firstValue(record, ['checker_name', 'checkerName']);
const checkedAt = firstValue(record, ['checked_at', 'checkedAt']);
const isEmpty = toBool(record.is_empty);
const stockIdRaw = record.stock_id !== undefined && record.stock_id !== null ? record.stock_id : record.stockId;
const unknown = !isEmpty && (stockIdRaw === undefined || stockIdRaw === null || String(stockIdRaw).trim() === '');
return {
key: `record-${recordId || index + 1}`,
recordId,
stockId: stockIdRaw === undefined || stockIdRaw === null ? '' : String(stockIdRaw),
empty: isEmpty,
unknown,
locationCode: locationCode || '',
quantity,
title: isEmpty ? '空库位标记' : (locationCode || '未指定库位'),
subtitle: joinText([
checkerName ? `盘点人 ${checkerName}` : '',
checkedAt ? formatDateTime(checkedAt) : '',
unknown ? '未知商品' : ''
]),
statusText: '',
statusClass: '',
amount: null,
quantityText: isEmpty || quantity === null ? '' : String(quantity),
images: Array.isArray(record.images) ? record.images.filter(Boolean) : [],
checkedAt: checkedAt || '',
checkedAtText: checkedAt ? formatDateTime(checkedAt) : '',
unit: null
};
});
const totalQuantity = children.reduce((sum, child) => sum + (Number(child.quantity) || 0), 0);
// 库位码(去重)与最近上报时间(ISO 字符串可按字典序比较)
const locationCodes = [];
children.forEach(child => {
if (child.locationCode && locationCodes.indexOf(child.locationCode) === -1) locationCodes.push(child.locationCode);
});
let lastCheckedAt = '';
children.forEach(child => {
if (child.checkedAt && child.checkedAt > lastCheckedAt) lastCheckedAt = child.checkedAt;
});
return { children, count: children.length, totalQuantity, locationCodes, lastCheckedAt, lastCheckedAtText: lastCheckedAt ? formatDateTime(lastCheckedAt) : '' };
}
/**
* 单条明细的作业数据(stock.check.workDataDetail)→ 商品明细概况
* 用于商品作业页:只传 detail_id,概况由接口反查得出
* 商品行返回:detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images(商品主图)
* + locations[](每库位:location_code/checked_at/checker_name/record_ids/images/system_quantity/quantity)
* + system_quantity/checked_quantity/diff_quantity/is_diff
* 库位行(商品信息在 goods 子列表里)也兼容:信息取 goods 首项兜底
*/
export function normalizeGoodsDetailInfo(row, mode) {
const source = row && typeof row === 'object' && !Array.isArray(row) ? row : {};
if (!Object.keys(source).length) return null;
// 行内只要带了任一数量字段就按明盘口径构建(任务 mode 可能没取到/缺失,别把盈亏丢掉)
const quantityFields = [
source.system_quantity, source.checked_quantity, source.diff_quantity,
source.systemQuantity, source.checkedQuantity, source.diffQuantity
];
const hasQuantity = quantityFields.some(value => value !== undefined && value !== null && value !== '');
const open = isOpenCheckMode(mode) || hasQuantity;
// 库位行形态:商品信息/图片取 goods 首项兜底
const firstGoods = Array.isArray(source.goods) && source.goods.length ? (source.goods[0] || {}) : {};
const pickText = keys => firstValue(source, keys) || firstValue(firstGoods, keys) || '';
const sourceImages = normalizeImageUrls(source.images);
const images = sourceImages.length ? sourceImages : normalizeImageUrls(firstGoods.images);
const stockIdRaw = source.stock_id !== undefined && source.stock_id !== null
? source.stock_id
: (firstGoods.stock_id !== undefined && firstGoods.stock_id !== null ? firstGoods.stock_id : firstValue(source, ['stock_id', 'stockId']));
const checkersRaw = source.checkers;
const checkers = Array.isArray(checkersRaw) ? checkersRaw.filter(Boolean).join('、') : String(checkersRaw || '');
// 库位明细(每库位一行:账面 / 实盘 / 盈亏),顺便汇总记录条数与最近上报时间
const rawLocations = Array.isArray(source.locations) ? source.locations : [];
let recordCount = 0;
let lastCheckedAt = '';
const locations = rawLocations.map((item, index) => {
const loc = item && typeof item === 'object' ? item : {};
const locationCode = firstValue(loc, ['location_code', 'locationCode']) || '';
const recordIds = Array.isArray(loc.record_ids) ? loc.record_ids.filter(id => id !== null && id !== undefined && id !== '') : [];
const systemQuantity = toNumberOrNull(loc.system_quantity !== undefined ? loc.system_quantity : loc.systemQuantity);
const quantity = toNumberOrNull(loc.quantity);
const checkedAt = firstValue(loc, ['checked_at', 'checkedAt']);
const checkerName = firstValue(loc, ['checker_name', 'checkerName']);
recordCount += recordIds.length;
if (checkedAt && checkedAt > lastCheckedAt) lastCheckedAt = checkedAt;
const diff = systemQuantity === null || quantity === null ? null : quantity - systemQuantity;
return {
key: `loc-${locationCode || index + 1}`,
// 左滑删除用:整库位的记录 ID 列表(recordDelete 支持数组)
recordIds,
recordId: recordIds.length === 1 ? recordIds[0] : '',
locationCode,
systemQuantity,
quantity,
title: locationCode || '未指定库位',
subtitle: joinText([
checkerName ? `盘点人 ${checkerName}` : '',
checkedAt ? formatDateTime(checkedAt) : ''
]),
statusText: '',
statusClass: '',
amount: null,
quantityText: quantity === null ? '' : String(quantity),
images: normalizeImageUrls(loc.images),
checkedAt: checkedAt || '',
checkedAtText: checkedAt ? formatDateTime(checkedAt) : '',
// 明细面板展示:账面 / 实盘 / 盈亏(账面>0 时高亮,方便找账面库位)
amounts: systemQuantity === null && quantity === null ? null : {
systemText: systemQuantity === null ? '--' : String(systemQuantity),
checkedText: quantity === null ? '--' : String(quantity),
diffText: diff === null ? '' : (diff > 0 ? `盘盈 +${diff}` : (diff < 0 ? `盘亏 ${-diff}` : '账实相符')),
diffTone: diff === null ? '' : (diff > 0 ? 'gain' : (diff < 0 ? 'loss' : 'match')),
hasSystemStock: systemQuantity !== null && systemQuantity > 0
},
unit: null
};
});
return {
detailId: pickText(['detail_id', 'detailId']),
stockId: stockIdRaw === undefined || stockIdRaw === null ? '' : String(stockIdRaw),
itemName: pickText(['item_name', 'itemName']),
itemCode: pickText(['item_code', 'itemCode']),
barcode: pickText(['barcode']),
spec: pickText(['spec']),
storeName: pickText(['store_name', 'storeName']),
images,
image: images[0] || '',
status: String(source.status || '').trim().toLowerCase(),
systemQuantity: toNumberOrNull(source.system_quantity !== undefined ? source.system_quantity : source.systemQuantity),
checkedQuantity: toNumberOrNull(source.checked_quantity !== undefined ? source.checked_quantity : source.checkedQuantity),
amount: buildWorkAmount(
source.system_quantity !== undefined ? source.system_quantity : source.systemQuantity,
source.checked_quantity !== undefined ? source.checked_quantity : source.checkedQuantity,
source.diff_quantity !== undefined ? source.diff_quantity : source.diffQuantity,
open
),
locations,
recordCount,
locationCodes: locations.map(item => item.locationCode).filter(Boolean),
checkers,
lastCheckedAtText: lastCheckedAt ? formatDateTime(lastCheckedAt) : ''
};
}
/** 作业行内可录入单元(行级 + 子项级) */
export function collectWorkUnits(row) {
if (!row) return [];

View File

@ -59,24 +59,28 @@
<u-icon name="list" size="86" color="#c0c4cc"></u-icon>
<text class="empty-text">{{ workLoading ? '加载中...' : (hasWorkKeyword ? '未找到匹配库位' : '暂无作业数据') }}</text>
</view>
<!-- 库位视图:宫格列表(点击进入库位明细页) -->
<!-- 库位/space 视图:库位宫格列表(点击进入对应作业页) -->
<count-location-grid
v-else-if="isLocationBoard"
v-else-if="isGridBoard"
:rows="workList"
:selected-key="selectedLocationKey"
:mode="workView"
:selected-key="isLocationBoard ? selectedLocationKey : focusKey"
@select="handleLocationOpen"
/>
<view v-else class="item-list">
<count-work-card
v-for="row in workList"
:key="row.key"
:id="`work-${row.key}`"
:row="row"
:editable="true"
:focused="focusKey === row.key"
@report="handleWorkReport"
@action="handleWorkAction"
/>
<!-- 商品视图(goods):一行一个商品,只展示盘点概况,点击进入商品作业页 -->
<view v-else class="goods-list">
<view class="goods-list__head">
<text class="goods-list__head-title">商品列表</text>
<text class="goods-list__head-hint">点击商品录入实盘数量</text>
</view>
<view class="goods-list__body">
<count-goods-card
v-for="row in workList"
:key="row.key"
:row="row"
@select="handleGoodsOpen"
/>
</view>
</view>
</template>
</template>
@ -142,7 +146,7 @@
<script>
import CountSummaryPanel from './inventoryCount-comps/CountSummaryPanel.vue';
import CountSearchPanel from './inventoryCount-comps/CountSearchPanel.vue';
import CountWorkCard from './inventoryCount-comps/CountWorkCard.vue';
import CountGoodsCard from './inventoryCount-comps/CountGoodsCard.vue';
import CountLocationGrid from './inventoryCount-comps/CountLocationGrid.vue';
import CountDetailPicker from './inventoryCount-comps/CountDetailPicker.vue';
import CountRecordAddPopup from './inventoryCount-comps/CountRecordAddPopup.vue';
@ -166,7 +170,7 @@ export default {
components: {
CountSummaryPanel,
CountSearchPanel,
CountWorkCard,
CountGoodsCard,
CountLocationGrid,
CountDetailPicker,
CountRecordAddPopup,
@ -258,12 +262,25 @@ export default {
isLocationBoard() {
return this.isWorkTab && this.canEdit && this.workView === 'location';
},
// 商品任务的按库位视图(view=space):同样按库位宫格展示,点击进入单库位作业页
isSpaceBoard() {
return this.isWorkTab && this.canEdit && this.workView === 'space';
},
// 宫格视图(location / space 行均为库位)
isGridBoard() {
return this.isLocationBoard || this.isSpaceBoard;
},
// 商品任务的按商品视图(view=goods):一行一个商品,点击进入商品作业页
isGoodsBoard() {
return this.isWorkTab && this.canEdit && this.workView === 'goods';
},
// 当前是否有作业筛选关键字(库位视图下由接口 keyword 过滤)
hasWorkKeyword() {
return !!String(this.scanKeyword || '').trim();
},
// 切换按钮文案 = 点击后会切到的模式(明确指引,不歧义)
workModeText() {
return this.workMode === 'goods' ? '按商品' : '按库位';
return this.workMode === 'goods' ? '切换为:库位模式' : '切换为:商品模式';
},
// Tab 列表(参考收货)
tabs() {
@ -359,14 +376,25 @@ export default {
/**
* 扫码回填关键字:
* - 库位视图:带 keyword 重新拉取列表(接口过滤);命中唯一库位时直接进入其明细页
* - 其他视图:在当前页内定位
* - space / goods 视图:在当前页找到含该关键字的行,直接进入对应作业页
*/
async handleScanKeyword(code) {
const keyword = String(code || '').trim();
if (!keyword) return;
this.scanKeyword = keyword;
if (this.workView !== 'location') {
this.locateItem(keyword);
if (this.isSpaceBoard || this.isGoodsBoard) {
this.focusKey = '';
this.selectedLocationKey = '';
const target = this.findWorkRowByKeyword(keyword);
if (!target) {
uni.showToast({ title: '本页未找到该商品', icon: 'none' });
return;
}
if (this.isSpaceBoard) {
this.handleLocationOpen(target.key);
} else {
this.handleGoodsOpen(target);
}
return;
}
this.focusKey = '';
@ -379,7 +407,16 @@ export default {
uni.showToast({ title: '未找到匹配库位', icon: 'none' });
}
},
// 输入框回车/点筛选:库位视图带 keyword 重新拉取列表
/** 在当前页作业行内按关键字(条码/编码/名称、库位码)匹配(先精确后模糊) */
findWorkRowByKeyword(keyword) {
const textsOf = row => collectWorkSearchTexts(row).map(text => String(text));
let target = this.workList.find(row => textsOf(row).some(text => text === keyword));
if (!target) {
target = this.workList.find(row => textsOf(row).some(text => text.indexOf(keyword) !== -1));
}
return target || null;
},
// 输入框回车/点筛选:库位视图带 keyword 重新拉取列表;space / goods 视图直接打开命中的作业页
handleLocateSearch() {
const keyword = String(this.scanKeyword || '').trim();
if (this.workView === 'location') {
@ -388,7 +425,17 @@ export default {
this.loadWorkList(1, keyword);
return;
}
this.locateItem(keyword);
if (!keyword) return;
const target = this.findWorkRowByKeyword(keyword);
if (!target) {
uni.showToast({ title: '本页未找到该商品', icon: 'none' });
return;
}
if (this.isSpaceBoard) {
this.handleLocationOpen(target.key);
return;
}
this.handleGoodsOpen(target);
},
handleLocateClear() {
this.scanKeyword = '';
@ -457,60 +504,61 @@ export default {
Promise.all(pending.map(unit => this.handleWorkReport(unit, { refresh: false })))
.then(() => this.loadWorkList(this.workPage));
},
locateItem(code) {
if (!this.canEdit) return;
const keyword = String(code || '').trim();
if (!keyword) return;
if (!this.workList.length) return;
const isLocationView = this.workView === 'location';
let target = this.workList.find(row => collectWorkSearchTexts(row).some(text => text === keyword));
if (!target) {
target = this.workList.find(row => collectWorkSearchTexts(row).some(text => text.indexOf(keyword) !== -1));
}
if (!target) {
uni.showToast({ title: isLocationView ? '本页未找到该库位' : '未找到匹配商品', icon: 'none' });
return;
}
// 库位视图:直接进入该库位的明细页
if (isLocationView) {
this.handleLocationOpen(target.key);
return;
}
this.focusKey = target.key;
this.scrollIntoViewId = `work-${target.key}`;
this.$nextTick(() => {
setTimeout(() => {
this.scrollIntoViewId = '';
}, 800);
});
},
// ===== 库位宫格:点击进入库位明细页 =====
// ===== 库位宫格:点击进入对应作业页 =====
handleLocationOpen(key) {
const row = this.workList.find(item => item.key === key);
if (!row || !this.taskId) return;
this.selectedLocationKey = row.key;
this.focusKey = '';
// 明细数据由 stock.check.workDataDetail 按 detail_id 拉取,这里只带路由必需参数
const query = [
`detail_id=${encodeURIComponent(row.detailId || '')}`,
`task_id=${encodeURIComponent(this.taskId)}`,
`check_no=${encodeURIComponent(this.taskInfo.checkNo || '')}`,
`store_id=${encodeURIComponent(this.taskInfo.storeId === null || this.taskInfo.storeId === undefined ? '' : this.taskInfo.storeId)}`,
`status=${encodeURIComponent(this.status)}`
].join('&');
// 从库位明细页返回后刷新列表(已盘状态/商品记录已变化)
let url = '';
if (this.isSpaceBoard) {
// space 视图:库位作业页只带 location_id(wms_location_space.id)+ task_id
if (!row.spaceId) {
uni.showToast({ title: '缺少库位ID', icon: 'none' });
return;
}
url = `/pages/warehouse/inventoryCountSpace?${[
`task_id=${encodeURIComponent(this.taskId)}`,
`location_id=${encodeURIComponent(row.spaceId)}`
].join('&')}`;
} else {
// 库位任务:库位明细页只带 detail_id + task_id(单号/状态/货主由 check.detail 反查)
url = `/pages/warehouse/inventoryCountLocation?${[
`task_id=${encodeURIComponent(this.taskId)}`,
`detail_id=${encodeURIComponent(row.detailId || '')}`
].join('&')}`;
}
// 从子页返回后刷新列表(已盘状态/商品记录已变化)
this._pendingWorkRefresh = true;
uni.navigateTo({ url: `/pages/warehouse/inventoryCountLocation?${query}` });
uni.navigateTo({ url });
},
// ===== 商品视图(goods):点击进入商品作业页(只传 id,概况由接口反查) =====
handleGoodsOpen(row) {
if (!row || !this.taskId) return;
if (!row.detailId) {
uni.showToast({ title: '缺少盘点明细ID', icon: 'none' });
return;
}
const params = [
`task_id=${encodeURIComponent(this.taskId)}`,
`detail_id=${encodeURIComponent(row.detailId)}`
].join('&');
// 从商品作业页返回后刷新列表(已盘状态/记录数已变化)
this._pendingWorkRefresh = true;
uni.navigateTo({ url: `/pages/warehouse/inventoryCountGoods?${params}` });
},
// 刷新/分页后保证存在有效选中项(无选中时不高亮任何格子)
ensureLocationSelection() {
if (this.workView !== 'location') {
this.selectedLocationKey = '';
if (this.workView === 'location') {
const exists = this.workList.some(row => row.key === this.selectedLocationKey);
if (!exists) {
this.selectedLocationKey = '';
}
return;
}
const exists = this.workList.some(row => row.key === this.selectedLocationKey);
if (!exists) {
this.selectedLocationKey = '';
// 其他视图(space / goods)用 focusKey 做本地定位高亮,翻页后若不在本页则清除
if (this.focusKey && !this.workList.some(row => row.key === this.focusKey)) {
this.focusKey = '';
}
},
// ===== 作业数据(stock.check.workData)=====
@ -868,8 +916,13 @@ export default {
.tabs-container__switch {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
height: 56rpx;
margin: 0 20rpx;
padding: 8rpx 20rpx;
padding: 0 20rpx;
box-sizing: border-box;
border-radius: 999rpx;
background: #eef4ff;
border: 1rpx solid #cfe1ff;
@ -880,9 +933,9 @@ export default {
}
.tabs-container__switch-text {
font-size: 26rpx;
font-size: 24rpx;
line-height: 1;
color: #2979ff;
line-height: 1.2;
white-space: nowrap;
}
@ -922,6 +975,37 @@ export default {
box-sizing: border-box;
}
/* 商品视图:白底容器 + 头部提示(与库位宫格头部同一视觉) */
.goods-list {
background: #ffffff;
border-top: 1rpx solid #f2f2f2;
}
.goods-list__head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12rpx 24rpx 0;
}
.goods-list__head-title {
font-size: 26rpx;
font-weight: 600;
color: #303133;
}
.goods-list__head-hint {
font-size: 24rpx;
color: #c0c4cc;
}
.goods-list__body {
display: flex;
flex-direction: column;
padding: 12rpx;
box-sizing: border-box;
}
/* 作业分页(固定在底部) */
.work-pagination {
flex-shrink: 0;

View File

@ -0,0 +1,686 @@
<template>
<view class="inv-goods-page">
<view class="normar_container">
<page-nav :title="navTitle" />
<!-- 顶部:扫描/输入库位码 → 打开「选库位 + 录数量」底部抽屉 -->
<count-search-panel
v-if="editable"
v-model="scanKeyword"
placeholder="扫描/输入库位码登记数量"
action-text="登记"
@search="handleEntryOpen"
@clear="handleKeywordClear"
@scan="handleCameraScan"
/>
<scroll-view
class="inv-goods-scroll"
scroll-y
refresher-enabled
:refresher-triggered="refreshing"
refresher-background="#f8f9fa"
@refresherrefresh="handleRefresh"
@refresherrestore="handleRefresherRestore"
>
<view v-if="!editable" class="inv-goods-tip">当前盘点任务状态不可作业,仅可查看</view>
<view v-if="loading && !detailRow" class="inv-goods-tip">加载中...</view>
<!-- 商品概况(紧凑卡片,有图就显示:商品主图优先,否则用作业照片兜底) -->
<view class="inv-goods-card">
<view v-if="cardImage" class="inv-goods-card__thumb" @click="previewGoodsImage">
<u-image
:src="cardImage"
mode="aspectFill"
width="120rpx"
height="120rpx"
radius="10rpx"
>
<template #error>
<view class="inv-goods-card__thumb-empty">
<text class="inv-goods-card__thumb-text">无图</text>
</view>
</template>
</u-image>
</view>
<view class="inv-goods-card__info">
<view class="inv-goods-card__head">
<text class="inv-goods-card__title">{{ goodsInfo.itemName || '--' }}</text>
<text
class="inv-goods-card__flag"
:class="hasChecked ? 'inv-goods-card__flag--done' : 'inv-goods-card__flag--todo'"
>{{ hasChecked ? '已盘' : '未盘' }}</text>
</view>
<text class="inv-goods-card__line">{{ goodsMetaText }}</text>
<view class="inv-goods-card__metrics">
<text v-if="systemQuantityValue !== null" class="inv-goods-card__metric">账面 {{ systemQuantityValue }}</text>
<text class="inv-goods-card__metric">已盘 {{ checkedTotalText }}</text>
<text v-if="diffText" class="inv-goods-card__diff" :class="diffValueClass">盈亏 {{ diffText }}</text>
</view>
</view>
</view>
<!-- 该商品的全部盘点记录(可左滑删除,含作业照片) -->
<count-location-detail
:row="detailRow"
:editable="editable"
section-title="盘点记录"
empty-text="该商品暂无盘点记录"
@delete="handleRecordDelete"
/>
<view v-if="!detailRow && !loading" class="inv-goods-tip">{{ loadError || '未获取到该商品的盘点记录,请返回列表重试' }}</view>
<view class="safe-area-bottom"></view>
</scroll-view>
</view>
<!-- 选库位 + 录数量(底部抽屉,参考库位页的添加商品抽屉) -->
<count-space-entry-popup
ref="spaceEntryPopup"
:show="showEntryPopup"
:prefill-keyword="pendingLocation"
:item-name="goodsInfo.itemName"
:submitting="submitting"
@close="closeEntryPopup"
@confirm="handleEntryConfirm"
/>
</view>
</template>
<script>
import CountSearchPanel from './inventoryCount-comps/CountSearchPanel.vue';
import CountLocationDetail from './inventoryCount-comps/CountLocationDetail.vue';
import CountSpaceEntryPopup from './inventoryCount-comps/CountSpaceEntryPopup.vue';
import {
normalizeScanResult,
extractObjectPayload,
normalizeGoodsDetailInfo,
buildReportParams
} from './inventoryCount-comps/countModel.js';
/** 空商品概况(接口失败/未匹配到明细时的占位) */
function EMPTY_GOODS_INFO() {
return {
itemName: '',
barcode: '',
spec: '',
storeName: '',
image: '',
stockId: '',
systemQuantity: null,
checkedQuantity: null,
amount: null,
locations: [],
recordCount: 0,
locationCodes: [],
lastCheckedAtText: ''
};
}
/**
* 账面数量:接口 system_quantity
* 放在模块级而不是 computed 互调,避免任何“半更新”状态下 this.xxx is not a function 直接白屏
*/
function resolveSystemQuantity(goodsInfo) {
const sys = (goodsInfo || {}).systemQuantity;
return sys === null || sys === undefined ? null : Number(sys);
}
/** 是否已盘(有库位明细/作业记录) */
function resolveHasChecked(goodsInfo) {
const info = goodsInfo || {};
if (Array.isArray(info.locations) && info.locations.length) return true;
return Number(info.recordCount) > 0;
}
/** 已盘合计:优先接口 checked_quantity,缺失时用库位明细合计 */
function resolveCheckedQuantity(goodsInfo) {
const info = goodsInfo || {};
if (info.checkedQuantity !== null && info.checkedQuantity !== undefined) return Number(info.checkedQuantity);
const locations = Array.isArray(info.locations) ? info.locations : [];
return locations.reduce((sum, item) => sum + (Number(item.quantity) || 0), 0);
}
/** 盈亏文案:未盘不动账;已盘 = 已盘合计 - 账面 */
function resolveDiffText(goodsInfo) {
const info = goodsInfo || {};
if (!resolveHasChecked(info)) return '';
const system = resolveSystemQuantity(info);
if (system === null) {
return info.amount && info.amount.diffText ? info.amount.diffText : '';
}
const diff = resolveCheckedQuantity(info) - system;
if (diff > 0) return `盘盈 +${diff}`;
if (diff < 0) return `盘亏 ${-diff}`;
return '账实相符';
}
/**
* 商品作业页(goods 视图;从盘点作业商品列表点击/扫码进入)
* 入参:**只传 id** —— task_id(盘点任务ID)+ detail_id(盘点明细ID)
* 数据:
* - stock.check.workDataDetail(仅 detail_id)→ 本明细单行作业数据,含商品信息/主图/账面/已盘/差异 + locations(每库位:账面/实盘/盘点人/时间/记录ID/照片)
* - stock.check.detail(仅主表 check)→ 任务状态 / 盘点模式
* 能力:扫码/输入库位 → 底部抽屉选库位 + 录数量(check.report);库位记录可左滑删除(recordDelete)
*/
export default {
components: {
CountSearchPanel,
CountLocationDetail,
CountSpaceEntryPopup
},
data() {
return {
taskId: '',
detailId: '',
taskInfo: { status: '', mode: '', type: '' },
goodsInfo: EMPTY_GOODS_INFO(),
loading: false,
refreshing: false,
loadError: '',
submitting: false,
scanKeyword: '',
showEntryPopup: false,
pendingLocation: ''
};
},
computed: {
navTitle() {
return this.goodsInfo.itemName || '商品作业';
},
// 仅 approved/checking 可作业(未取到状态时先按可作业处理,由接口 400 兜底)
editable() {
const status = String(this.taskInfo.status || '').trim().toLowerCase();
if (!status) return true;
return status === 'approved' || status === 'checking';
},
// 是否已盘(有库位明细/作业记录)——用于右上角标记与盈亏门控
hasChecked() {
return resolveHasChecked(this.goodsInfo);
},
// 账面数量(接口 system_quantity)
systemQuantityValue() {
return resolveSystemQuantity(this.goodsInfo);
},
// 已盘合计(接口 checked_quantity,缺失时用库位明细合计)
checkedTotalText() {
return String(resolveCheckedQuantity(this.goodsInfo));
},
// 盈亏:未盘不显示;已盘 = 已盘合计 - 账面
diffText() {
return resolveDiffText(this.goodsInfo);
},
diffValueClass() {
if (!this.diffText) return '';
if (this.diffText.indexOf('盘盈') === 0) return 'inv-goods-card__diff--gain';
if (this.diffText.indexOf('盘亏') === 0) return 'inv-goods-card__diff--loss';
return '';
},
// 概况卡图片:商品主图优先,没有就用第一个有照片的库位记录兑底
cardImage() {
if (this.goodsInfo.image) return this.goodsInfo.image;
return this.cardImages[0] || '';
},
cardImages() {
if (this.goodsInfo.image) return [this.goodsInfo.image];
const locations = this.goodsInfo.locations || [];
return locations.reduce((acc, item) => acc.concat(item.images || []), []);
},
// 规格 · 条码 · 货主(紧凑卡片一行)
goodsMetaText() {
return [this.goodsInfo.spec, this.goodsInfo.barcode, this.goodsInfo.storeName].filter(Boolean).join(' · ') || '--';
},
// CountLocationDetail 只需要 row 结构(概况在卡片,children = 库位明细:账面/实盘/盈亏)
detailRow() {
if (!this.detailId) return null;
const locations = this.goodsInfo.locations || [];
const meta = [];
const codes = this.goodsInfo.locationCodes || [];
if (codes.length) meta.push({ label: '库位', value: codes.length === 1 ? codes[0] : `${codes.length} 个` });
if (this.goodsInfo.lastCheckedAtText) meta.push({ label: '最近上报', value: this.goodsInfo.lastCheckedAtText });
return {
key: `goods-${this.detailId}`,
detailId: this.detailId,
title: '盘点记录',
subtitle: '',
statusText: '',
statusClass: '',
meta,
goodsCount: locations.length,
unknownCount: 0,
children: locations
};
}
},
onLoad(options = {}) {
// 页面只需两个 id:task_id(任务ID)+ detail_id(盘点明细ID)
this.taskId = String(options.task_id || options.taskId || options.id || '').trim();
this.detailId = String(options.detail_id || options.detailId || '').trim();
this.loadAll();
this.syncBroadcastWithMode();
},
onShow() {
this.syncBroadcastWithMode();
},
onHide() {
this.safeDispatchBroadcast('pause');
},
onUnload() {
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(`[inventoryCountGoods] broadcast/${action} 调用失败:`, error));
}
} catch (error) {
console.warn(`[inventoryCountGoods] broadcast/${action} 调用异常:`, error);
}
},
syncBroadcastWithMode() {
if (this.editable) {
this.safeDispatchBroadcast('setCallbacks', { onResult: this.handleBroadcastResult });
this.safeDispatchBroadcast('start');
} else {
this.safeDispatchBroadcast('stop');
}
},
handleBroadcastResult(result) {
if (!this.editable) return;
const code = normalizeScanResult(result);
if (!code) return;
this.handleScanKeyword(code);
},
handleCameraScan() {
if (!this.editable) return;
uni.scanCode({
onlyFromCamera: true,
scanType: ['qrCode', 'barCode', 'datamatrix', 'pdf417'],
success: (res) => {
const code = normalizeScanResult(res);
if (code) this.handleScanKeyword(code);
},
fail: () => {}
});
},
/**
* 扫码得到库位码:
* - 抽屉已打开 → 直接带码重新查询(可连续扫码)
* - 抽屉未打开 → 打开抽屉并带码查询(唯一命中会自动选中,接着输数量)
*/
handleScanKeyword(code) {
const keyword = String(code || '').trim();
if (!keyword || !this.editable) return;
this.scanKeyword = keyword;
if (this.showEntryPopup) {
const popup = this.$refs.spaceEntryPopup;
if (popup && typeof popup.applyKeyword === 'function') {
popup.applyKeyword(keyword);
}
return;
}
this.openEntryPopup(keyword);
},
handleKeywordClear() {
this.scanKeyword = '';
},
// ===== 底部抽屉:选库位 + 录数量 =====
handleEntryOpen() {
if (!this.editable) return;
this.openEntryPopup(this.scanKeyword);
},
openEntryPopup(keyword) {
this.pendingLocation = String(keyword || '').trim();
this.showEntryPopup = true;
},
closeEntryPopup() {
this.showEntryPopup = false;
this.pendingLocation = '';
},
/** 抽屉确认:库位 + 数量 → check.report */
async handleEntryConfirm(payload) {
if (!payload || !payload.location) return;
const ok = await this.submitReport({
detailId: this.detailId,
location: payload.location,
quantity: payload.quantity,
stockId: this.goodsInfo.stockId
});
// 成功才收起抽屉并清空顶部关键字,失败保留输入便于重试
if (ok) {
this.handleKeywordClear();
this.closeEntryPopup();
}
},
/** 上报(check.report:detail_id=商品明细,location=库位) */
async submitReport(payload) {
if (!this.editable || this.submitting) return false;
if (!payload || !payload.detailId) {
uni.showToast({ title: '缺少盘点明细ID', icon: 'none' });
return false;
}
const location = String(payload.location || '').trim();
if (!location) {
uni.showToast({ title: '请选择库位', icon: 'none' });
return false;
}
const quantity = Number(payload.quantity);
if (!Number.isInteger(quantity) || quantity < 0) {
uni.showToast({ title: '请输入不小于0的整数数量', icon: 'none' });
return false;
}
this.submitting = true;
try {
const response = await this.$http('check.report', buildReportParams(this.taskId, {
detailId: payload.detailId,
location,
quantity,
stockId: payload.stockId,
barcode: this.goodsInfo.barcode,
itemName: this.goodsInfo.itemName
}));
if (response?.flag === 'failure') {
uni.showToast({ title: response.message || '上报失败', icon: 'none' });
return false;
}
uni.showToast({ title: `已记录 ${location}`, icon: 'success', duration: 800 });
await this.loadInfo();
return true;
} catch (error) {
console.error('[inventoryCountGoods] 盘点上报失败:', error);
uni.showToast({ title: '盘点上报失败', icon: 'none' });
return false;
} finally {
this.submitting = false;
}
},
/** 概况卡图片预览 */
previewGoodsImage() {
const urls = this.cardImages;
if (!urls.length) return;
uni.previewImage({ current: urls[0], urls });
},
/** 删除该库位的作业记录(stock.check.recordDelete,按 record_ids 批量) */
handleRecordDelete(child) {
if (!this.editable) return;
const recordIds = child && Array.isArray(child.recordIds)
? child.recordIds.filter(Boolean)
: (child && child.recordId ? [child.recordId] : []);
if (!recordIds.length) {
uni.showToast({ title: '该记录不支持删除', icon: 'none' });
return;
}
if (!this.taskId) {
uni.showToast({ title: '缺少盘点任务ID', icon: 'none' });
return;
}
const scope = child.title || '该库位';
const suffix = recordIds.length > 1 ? `的 ${recordIds.length} 条记录` : '这条记录';
uni.showModal({
title: '删除盘点记录',
content: `确认删除「${scope}」${suffix}?`,
confirmText: '删除',
confirmColor: '#f56c6c',
cancelText: '取消',
success: async (res) => {
if (!res.confirm) return;
await this.removeRecords(recordIds);
}
});
},
async removeRecords(recordIds) {
if (!this.editable || !this.taskId) return false;
const ids = (Array.isArray(recordIds) ? recordIds : [recordIds])
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0);
if (!ids.length) return false;
if (this.submitting) return false;
this.submitting = true;
try {
const response = await this.$http('check.recordDelete', {
id: Number(this.taskId),
record_ids: ids
});
if (response?.flag === 'failure') {
uni.showToast({ title: response.message || '删除失败', icon: 'none' });
return false;
}
const payload = extractObjectPayload(response);
const deleted = Number(payload.deleted_count);
const skipped = Array.isArray(payload.skipped_ids) ? payload.skipped_ids.length : 0;
let title = '已删除';
if (Number.isFinite(deleted)) title = `已删除 ${deleted} 条`;
if (skipped) title += `,跳过 ${skipped} 条`;
uni.showToast({ title, icon: 'none', duration: 1600 });
await this.loadInfo();
return true;
} catch (error) {
console.error('[inventoryCountGoods] 删除作业记录失败:', error);
uni.showToast({ title: '删除失败', icon: 'none' });
return false;
} finally {
this.submitting = false;
}
},
// ===== 下拉刷新 =====
async handleRefresh() {
// 防重入:同一手势可能被重复触发
if (this.refreshing) return;
this.refreshing = true;
try {
await this.loadAll();
} finally {
this.refreshing = false;
}
},
handleRefresherRestore() {
this.refreshing = false;
},
// ===== 数据加载 =====
/** 任务信息 → 明细(先拿到 mode,避免数量口径缺失) */
async loadAll() {
await this.loadTaskInfo();
await this.loadInfo();
},
/** 任务概况(stock.check.detail:只返回主表 check)——入参仅任务ID */
async loadTaskInfo() {
const taskId = Number(this.taskId);
if (!Number.isFinite(taskId) || taskId <= 0) return null;
try {
const response = await this.$http('check.detail', { id: taskId });
if (response?.flag === 'failure') return null;
const check = extractObjectPayload(response).check || {};
this.taskInfo = {
status: String(check.status || '').trim().toLowerCase(),
mode: String(check.mode || '').trim().toLowerCase(),
type: check.type || ''
};
return this.taskInfo;
} catch (error) {
console.error('[inventoryCountGoods] 盘点任务信息加载失败:', error);
return null;
}
},
/** 商品明细(stock.check.workDataDetail:入参仅 detail_id)——含商品信息/主图/账面/已盘/差异 + locations 库位明细 */
async loadInfo() {
const detailId = Number(this.detailId);
if (!Number.isFinite(detailId) || detailId <= 0) {
this.loadError = '缺少盘点明细ID';
uni.showToast({ title: this.loadError, icon: 'none' });
return null;
}
this.loading = true;
try {
const response = await this.$http('check.workDataDetail', { detail_id: detailId });
if (response?.flag === 'failure') {
this.goodsInfo = EMPTY_GOODS_INFO();
this.loadError = response.message || '盘点明细加载失败';
uni.showToast({ title: this.loadError, icon: 'none' });
return null;
}
const info = normalizeGoodsDetailInfo(extractObjectPayload(response), this.taskInfo.mode);
if (info) this.goodsInfo = Object.assign({}, this.goodsInfo, info);
this.loadError = '';
return this.goodsInfo;
} catch (error) {
console.error('[inventoryCountGoods] 盘点明细加载失败:', error);
this.goodsInfo = EMPTY_GOODS_INFO();
this.loadError = '盘点明细加载失败';
uni.showToast({ title: this.loadError, icon: 'none' });
return null;
} finally {
this.loading = false;
}
}
}
};
</script>
<style lang="scss" scoped>
.inv-goods-page {
height: 100vh;
background: #f8f9fa;
}
.normar_container {
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* 数量录入条(紧接 CountSearchPanel,同一白底 + 分隔线视觉) */
.inv-goods-scroll {
flex: 1;
min-height: 0;
height: auto;
padding: 20rpx 0 0;
box-sizing: border-box;
}
/* 商品概况(紧凑卡片:图片 + 名称/规格/数量,密度比逐行 label/value 高) */
.inv-goods-card {
display: flex;
align-items: flex-start;
margin: 0 12rpx 16rpx;
padding: 20rpx 24rpx;
background: #ffffff;
border: 2rpx solid #ebedf2;
border-radius: 20rpx;
box-shadow: 0 6rpx 20rpx rgba(31, 45, 61, 0.06);
}
.inv-goods-card__thumb {
flex-shrink: 0;
margin-right: 20rpx;
}
.inv-goods-card__thumb-empty {
width: 120rpx;
height: 120rpx;
border-radius: 10rpx;
background: #f5f7fa;
display: flex;
align-items: center;
justify-content: center;
}
.inv-goods-card__thumb-text {
font-size: 22rpx;
color: #c0c4cc;
}
.inv-goods-card__info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.inv-goods-card__head {
display: flex;
align-items: center;
justify-content: space-between;
}
.inv-goods-card__title {
flex: 1;
min-width: 0;
font-size: 32rpx;
font-weight: 600;
color: #303133;
line-height: 1.3;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.inv-goods-card__flag {
flex-shrink: 0;
margin-left: 16rpx;
font-size: 26rpx;
line-height: 1.2;
}
.inv-goods-card__flag--done {
color: #18a058;
}
.inv-goods-card__flag--todo {
color: #ff9800;
}
.inv-goods-card__line {
margin-top: 6rpx;
font-size: 24rpx;
color: #8a9099;
word-break: break-all;
}
.inv-goods-card__metrics {
margin-top: 10rpx;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.inv-goods-card__metric {
margin-right: 20rpx;
font-size: 26rpx;
color: #606266;
}
.inv-goods-card__diff {
font-size: 26rpx;
font-weight: 600;
}
.inv-goods-card__diff--gain {
color: #18a058;
}
.inv-goods-card__diff--loss {
color: #e64340;
}
.inv-goods-tip {
margin: 0 12rpx 16rpx;
padding: 24rpx;
background: #fff8e6;
border: 2rpx solid #ffe1a8;
border-radius: 16rpx;
font-size: 28rpx;
color: #b8811a;
text-align: center;
}
.safe-area-bottom {
height: 20rpx;
}
</style>

View File

@ -96,22 +96,12 @@ import {
buildReportParams
} from './inventoryCount-comps/countModel.js';
/** query 参数解码(H5 可能已解码,容错处理非法百分号) */
function decodeParam(value) {
const raw = String(value === undefined || value === null ? '' : value);
if (!raw) return '';
try {
return decodeURIComponent(raw);
} catch (error) {
return raw;
}
}
/**
* 库位盘点明细页(从盘点作业宫格列表点击/扫码进入)
* 入参:detail_id(盘点明细ID,必需,兼容 id/detailId 别名)+ task_id(盘点任务ID,上报用)
* + check_no / store_id / status(展示与搜索用,可选)
* 数据:stock.check.workDataDetail(仅传 detail_id 即可拿到该库位的单行作业数据)
* 入参:**只传 id** —— task_id(盘点任务ID)+ detail_id(盘点明细ID,scope_type=location)
* 数据:
* - stock.check.workDataDetail(仅 detail_id)→ 该库位单行作业数据
* - stock.check.detail(仅主表 check)→ 盘点单号 / 状态 / 任务货主(商品搜索用)
* 能力:查看该库位状态与商品记录 + 添加商品记录 / 标记空库位(check.report)
*/
export default {
@ -159,16 +149,11 @@ export default {
}
},
onLoad(options = {}) {
// 明细ID:std 字段为 detail_id,兼容 id / detailId 别名(页面只需这一个 id 即可拉明细)
// 只接 id:明细ID(必需)+ 任务ID(上报与任务概况用)
this.detailId = String(options.detail_id || options.detailId || options.id || '').trim();
// 任务ID:check.report 需要;兼容 id 与 task_id 两种写法
this.taskId = String(options.task_id || options.taskId || options.id || '').trim();
this.checkNo = decodeParam(options.check_no || options.checkNo);
this.taskStatus = decodeParam(options.status).trim().toLowerCase();
const storeId = options.store_id === undefined || options.store_id === null ? '' : String(options.store_id);
this.storeId = storeId === '' || storeId === 'null' || storeId === 'undefined' ? null : storeId;
this.loadRow();
this.loadAll();
this.syncBroadcastWithMode();
},
onShow() {
@ -396,7 +381,7 @@ export default {
if (this.refreshing) return;
this.refreshing = true;
try {
await this.loadRow();
await this.loadAll();
} finally {
this.refreshing = false;
}
@ -404,6 +389,27 @@ export default {
handleRefresherRestore() {
this.refreshing = false;
},
// ===== 数据加载 =====
async loadAll() {
await Promise.all([this.loadTaskInfo(), this.loadRow()]);
},
/** 任务概况(stock.check.detail:只返回主表 check)——入参仅任务ID */
async loadTaskInfo() {
const taskId = Number(this.taskId);
if (!Number.isFinite(taskId) || taskId <= 0) return null;
try {
const response = await this.$http('check.detail', { id: taskId });
if (response?.flag === 'failure') return null;
const check = extractObjectPayload(response).check || {};
this.checkNo = check.check_no || '';
this.taskStatus = String(check.status || '').trim().toLowerCase();
this.storeId = check.store_id === undefined || check.store_id === null ? null : check.store_id;
return check;
} catch (error) {
console.error('[inventoryCountLocation] 盘点任务信息加载失败:', error);
return null;
}
},
// ===== 数据加载(stock.check.workDataDetail,只需传 detail_id)=====
async loadRow() {
if (!this.detailId) {
@ -416,8 +422,7 @@ export default {
detail_id: Number(this.detailId)
});
if (response?.flag === 'failure') {
// 状态不允许(如已完成)时后端返回 400,按只读展示
this.taskStatus = '';
// 状态不允许(如已完成)时后端返回 400:保留任务状态(只读展示),仅清空明细
this.row = null;
uni.showToast({ title: response.message || '明细加载失败', icon: 'none' });
return null;

View File

@ -0,0 +1,426 @@
<template>
<view class="inv-space-page">
<view class="normar_container">
<page-nav :title="navTitle" />
<!-- 扫码/输入商品条码 → 定位本库位下的任务商品 -->
<count-search-panel
v-if="editable"
v-model="scanKeyword"
placeholder="扫描/输入商品条码定位本库位商品"
action-text="定位"
@search="handleKeywordLocate"
@clear="handleKeywordClear"
@scan="handleCameraScan"
/>
<scroll-view
class="inv-space-scroll"
scroll-y
:scroll-into-view="scrollIntoViewId"
scroll-with-animation
refresher-enabled
:refresher-triggered="refreshing"
refresher-background="#f8f9fa"
@refresherrefresh="handleRefresh"
@refresherrestore="handleRefresherRestore"
>
<view class="inv-space-card">
<view class="inv-space-card__row">
<text class="inv-space-card__label">库位</text>
<text class="inv-space-card__value">{{ locationCode || '--' }}</text>
</view>
<view class="inv-space-card__row">
<text class="inv-space-card__label">商品进度</text>
<text class="inv-space-card__value">{{ progressText }}</text>
</view>
</view>
<view v-if="!editable" class="inv-space-tip">当前盘点任务状态不可作业,仅可查看</view>
<view v-if="loading && !row" class="inv-space-tip">加载中...</view>
<!-- 该库位下的任务商品:逐条录入实盘数量并上报(check.report) -->
<count-work-card
v-if="row"
:row="row"
:editable="editable"
:focused-key="focusChildKey"
@report="handleWorkReport"
/>
<view v-if="!row && !loading" class="inv-space-tip">{{ loadError || '未获取到该库位的作业数据,请返回列表重试' }}</view>
<view class="safe-area-bottom"></view>
</scroll-view>
</view>
</view>
</template>
<script>
import CountSearchPanel from './inventoryCount-comps/CountSearchPanel.vue';
import CountWorkCard from './inventoryCount-comps/CountWorkCard.vue';
import {
normalizeScanResult,
extractObjectPayload,
extractListPayload,
normalizeSpaceWorkDetail,
buildReportParams
} from './inventoryCount-comps/countModel.js';
/**
* 单库位作业页(space 视图;从盘点作业宫格列表点击/扫码进入)
* 入参:**只传 id** —— task_id(盘点任务ID)+ location_id(库位ID wms_location_space.id)
* 数据:
* - stock.check.workDataSpaceDetails(id + location_id)→ 本库位的任务商品行
* - stock.check.detail(仅主表 check)→ 盘点单号 / 状态 / 盘点模式
* 能力:查看该库位下的任务商品(账面/已盘/状态)+ 逐条录入实盘数量(check.report)
*/
export default {
components: {
CountSearchPanel,
CountWorkCard
},
data() {
return {
taskId: '',
locationId: '',
taskInfo: { status: '', mode: '' },
row: null,
loading: false,
refreshing: false,
loadError: '',
scanKeyword: '',
focusChildKey: '',
scrollIntoViewId: '',
submitting: false
};
},
computed: {
navTitle() {
return (this.row && this.row.title) || '库位作业';
},
// 仅 approved/checking 可作业(未取到状态时先按可作业处理,由接口 400 兜底)
editable() {
const status = String(this.taskInfo.status || '').trim().toLowerCase();
if (!status) return true;
return status === 'approved' || status === 'checking';
},
// 库位编码/名称全部取接口数据(名称在下方卡片副标题里展示)
locationCode() {
return String((this.row && this.row.location) || '');
},
progressText() {
if (!this.row) return '--';
return this.row.gridProgressText || `${this.row.goodsCount || 0} 项`;
}
},
onLoad(options = {}) {
// 只接 id:库位ID(必需)+ 任务ID(上报/任务概况用)
this.taskId = String(options.task_id || options.taskId || '').trim();
this.locationId = String(options.location_id || options.locationId || '').trim();
this.loadAll();
this.syncBroadcastWithMode();
},
onShow() {
this.syncBroadcastWithMode();
},
onHide() {
this.safeDispatchBroadcast('pause');
},
onUnload() {
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(`[inventoryCountSpace] broadcast/${action} 调用失败:`, error));
}
} catch (error) {
console.warn(`[inventoryCountSpace] broadcast/${action} 调用异常:`, error);
}
},
syncBroadcastWithMode() {
if (this.editable) {
this.safeDispatchBroadcast('setCallbacks', { onResult: this.handleBroadcastResult });
this.safeDispatchBroadcast('start');
} else {
this.safeDispatchBroadcast('stop');
}
},
handleBroadcastResult(result) {
if (!this.editable) return;
const code = normalizeScanResult(result);
if (!code) return;
this.handleScanKeyword(code);
},
handleCameraScan() {
if (!this.editable) return;
uni.scanCode({
onlyFromCamera: true,
scanType: ['qrCode', 'barCode', 'datamatrix', 'pdf417'],
success: (res) => {
const code = normalizeScanResult(res);
if (code) this.handleScanKeyword(code);
},
fail: () => {}
});
},
// ===== 扫码/输入:定位本库位下的商品 =====
handleScanKeyword(code) {
const keyword = String(code || '').trim();
if (!keyword || !this.editable) return;
this.scanKeyword = keyword;
this.locateItem(keyword);
},
handleKeywordLocate() {
if (!this.editable) return;
const keyword = String(this.scanKeyword || '').trim();
if (!keyword) {
uni.showToast({ title: '请输入或扫描商品条码', icon: 'none' });
return;
}
this.handleScanKeyword(keyword);
},
handleKeywordClear() {
this.scanKeyword = '';
this.focusChildKey = '';
},
/** 在本库位商品里定位(先精确后模糊),命中后高亮并滚动到该行 */
locateItem(keyword) {
const children = this.row && Array.isArray(this.row.children) ? this.row.children : [];
const textsOf = child => [child.title, child.subtitle]
.filter(text => text !== null && text !== undefined && String(text).trim() !== '')
.map(text => String(text).trim());
let target = children.find(child => textsOf(child).some(text => text === keyword));
if (!target) {
target = children.find(child => textsOf(child).some(text => text.indexOf(keyword) !== -1));
}
if (!target) {
this.focusChildKey = '';
uni.showToast({ title: '本库位未找到该商品', icon: 'none' });
return;
}
this.focusChildKey = target.key;
this.scrollIntoViewId = `work-${target.key}`;
this.$nextTick(() => {
setTimeout(() => {
this.scrollIntoViewId = '';
}, 800);
});
},
// ===== 录入上报(check.report)=====
async handleWorkReport(unit) {
if (!this.editable || !unit || unit.reporting) return;
const raw = String(unit.inputValue || '').trim();
if (raw === '') return;
if (raw === String(unit.original || '')) return;
unit.reporting = true;
try {
await this.submitReport({
detailId: unit.detailId,
location: unit.location,
quantity: Number(raw),
stockId: unit.stockId
}, '已记录');
} finally {
unit.reporting = false;
}
},
/** 统一上报入口:单库位下逐条商品实盘数量 */
async submitReport(payload, successText) {
if (!this.editable || !this.taskId) return false;
if (!payload || !payload.detailId) {
uni.showToast({ title: '缺少盘点明细ID', icon: 'none' });
return false;
}
const quantity = Number(payload.quantity);
if (!Number.isInteger(quantity) || quantity < 0) {
uni.showToast({ title: '实盘数量须为不小于0的整数', icon: 'none' });
return false;
}
if (this.submitting) return false;
this.submitting = true;
try {
const response = await this.$http('check.report', buildReportParams(this.taskId, {
detailId: payload.detailId,
location: payload.location,
quantity,
stockId: payload.stockId
}));
if (response?.flag === 'failure') {
uni.showToast({ title: response.message || '上报失败', icon: 'none' });
return false;
}
uni.showToast({ title: successText || '已记录', icon: 'success', duration: 600 });
// 上报后重拉该库位单行数据(状态/已盘数量以服务端口径为准)
await this.loadRow();
return true;
} catch (error) {
console.error('[inventoryCountSpace] 盘点上报失败:', error);
uni.showToast({ title: '盘点上报失败', icon: 'none' });
return false;
} finally {
this.submitting = false;
}
},
// ===== 下拉刷新 =====
async handleRefresh() {
// 防重入:同一手势可能被重复触发
if (this.refreshing) return;
this.refreshing = true;
try {
await this.loadAll();
} finally {
this.refreshing = false;
}
},
handleRefresherRestore() {
this.refreshing = false;
},
// ===== 数据加载 =====
async loadAll() {
// 必须先拿到任务信息(明盘/盲盘决定数量口径)再拉本库位数据:
// 并行时 mode 还是空 → 明盘下「账面 X / 已盘 Y」不会被拉出来(看起来像没请求)
await this.loadTaskInfo();
await this.loadRow();
},
/** 任务概况(stock.check.detail:只返回主表 check)——入参仅任务ID */
async loadTaskInfo() {
const taskId = Number(this.taskId);
if (!Number.isFinite(taskId) || taskId <= 0) return null;
try {
const response = await this.$http('check.detail', { id: taskId });
if (response?.flag === 'failure') return null;
const check = extractObjectPayload(response).check || {};
this.taskInfo = {
status: String(check.status || '').trim().toLowerCase(),
mode: String(check.mode || '').trim().toLowerCase()
};
return this.taskInfo;
} catch (error) {
console.error('[inventoryCountSpace] 盘点任务信息加载失败:', error);
return null;
}
},
// ===== 单库位作业数据(stock.check.workDataSpaceDetails:id + location_id)=====
async loadRow() {
const id = Number(this.taskId);
const locationId = Number(this.locationId);
if (!Number.isFinite(id) || id <= 0) {
this.loadError = '缺少盘点任务ID';
uni.showToast({ title: this.loadError, icon: 'none' });
return null;
}
if (!Number.isFinite(locationId) || locationId <= 0) {
this.loadError = '缺少库位ID';
uni.showToast({ title: this.loadError, icon: 'none' });
return null;
}
this.loading = true;
try {
const response = await this.$http('check.workDataSpaceDetails', {
id,
location_id: locationId
});
if (response?.flag === 'failure') {
// 状态不允许(如已完成)时后端返回 400,按只读展示
this.row = null;
this.loadError = response.message || '库位作业数据加载失败';
uni.showToast({ title: this.loadError, icon: 'none' });
return null;
}
const payload = extractObjectPayload(response);
const rows = extractListPayload(payload, response);
this.row = normalizeSpaceWorkDetail(rows, this.taskInfo.mode);
this.loadError = this.row ? '' : '该库位暂无任务商品';
return this.row;
} catch (error) {
console.error('[inventoryCountSpace] 库位作业数据加载失败:', error);
this.row = null;
this.loadError = '库位作业数据加载失败';
uni.showToast({ title: this.loadError, icon: 'none' });
return null;
} finally {
this.loading = false;
}
}
}
};
</script>
<style lang="scss" scoped>
.inv-space-page {
height: 100vh;
background: #f8f9fa;
}
.normar_container {
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
.inv-space-scroll {
flex: 1;
min-height: 0;
height: auto;
padding: 20rpx 0 0;
box-sizing: border-box;
}
.inv-space-card {
margin: 0 12rpx 16rpx;
padding: 8rpx 28rpx;
background: #ffffff;
border: 2rpx solid #ebedf2;
border-radius: 20rpx;
box-shadow: 0 6rpx 20rpx rgba(31, 45, 61, 0.06);
}
.inv-space-card__row {
display: flex;
align-items: flex-start;
padding: 14rpx 0;
border-bottom: 1rpx solid #f5f6f8;
&:last-child {
border-bottom: none;
}
}
.inv-space-card__label {
flex-shrink: 0;
width: 160rpx;
font-size: 28rpx;
color: #8a9099;
}
.inv-space-card__value {
flex: 1;
min-width: 0;
font-size: 30rpx;
color: #303133;
word-break: break-all;
}
.inv-space-tip {
margin: 0 12rpx 16rpx;
padding: 24rpx;
background: #fff8e6;
border: 2rpx solid #ffe1a8;
border-radius: 16rpx;
font-size: 28rpx;
color: #b8811a;
text-align: center;
}
.safe-area-bottom {
height: 20rpx;
}
</style>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,269 @@
/**
* 收件任务模块共享逻辑(纯函数 / 无副作用)
* 供 pages/work/order/returnRecord.vue(任务列表)与 returnRecord-comps/ReturnScanPanel.vue(扫码登记)复用,
* 避免列表页与登记页各维护一份字段映射与响应解析。
*/
/** 系统预设任务ID:历史收件(warehouse_id=0,不可删除) */
export const DEFAULT_TASK_ID = 1;
/** 任务范围切换项:默认只看自己创建的 */
export const TASK_SCOPE_OPTIONS = [
{ label: '我的任务', value: 'mine' },
{ label: '全部任务', value: 'all' }
];
// ===== 取值 / 格式化 =====
/** 扫码结果归一化:兼容字符串 / {result:[]} / {data} 等多种回调结构 */
export function 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 '';
}
/** 时间格式化(yyyy-MM-dd HH:mm:ss) */
export function 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}`;
}
/** 取第一个非空字段值 */
export function firstValue(source, keys) {
const target = source && typeof source === 'object' ? source : {};
for (let i = 0; i < keys.length; i += 1) {
const value = target[keys[i]];
if (value !== null && value !== undefined && String(value).trim() !== '') {
return String(value).trim();
}
}
return '';
}
// ===== 响应体解析 =====
/** 取响应里的第一个普通对象(各接口包裹层级不一) */
export function extractObjectPayload(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 {};
}
/** 取响应里的第一个数组(list/rows/items/records) */
export function extractListPayload(payload, response) {
const candidates = [
payload?.list,
payload?.rows,
payload?.items,
payload?.records,
payload?.data?.list,
payload?.data?.rows,
response?.data?.list,
response?.data?.rows,
response?.data?.data?.list,
response?.data?.data?.rows,
response?.list,
response?.rows
];
for (let i = 0; i < candidates.length; i += 1) {
if (Array.isArray(candidates[i])) return candidates[i];
}
return [];
}
/** 解析分页总数(兼容 pagination.total / total / 数组长度) */
export function resolveListTotal(payload, response, list) {
const pagination = (payload && typeof payload === 'object') ? (payload.pagination || {}) : {};
const candidates = [
pagination?.total,
payload?.pagination?.total,
payload?.total,
payload?.count,
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;
}
// ===== 列表:请求参数与行归一化 =====
/**
* 构造收件任务列表查询参数
* - warehouse_id 由服务端从登录上下文注入,前端禁止传入
* - onlyMine=true 时按 creator_id 等值筛选(当前登录账号ID)
*/
export function buildTaskListParams({ page = 1, pageSize = 20, keyword = '', onlyMine = false, creatorId = '' } = {}) {
const params = {
pagination: {
page: Math.max(1, Number(page || 1)),
pageSize: Math.max(1, Number(pageSize || 20))
},
sort: {
sortField: 'id',
sortOrder: 'desc'
}
};
const where = {};
const kw = String(keyword || '').trim();
if (kw) {
// quickWhere:title / batch_no / creator_name 三字段 OR 模糊匹配
where.quickWhere = { value: kw };
}
if (onlyMine) {
const id = Number(creatorId);
if (Number.isFinite(id) && id > 0) {
where.creator_id = id;
}
}
if (Object.keys(where).length) {
params.where = where;
}
return params;
}
/** 是否系统预设任务(id=1 历史收件) */
export function isSystemTask(row) {
const id = Number((row && (row.id ?? row.task_id)) || 0);
return id === DEFAULT_TASK_ID;
}
/**
* 任务行归一化(列表卡片展示字段)
* deletable:系统预设任务(id=1)、系统级任务(warehouse_id=0)、已有登记的(register_count>0)都不可删除
* (最终仍以服务端 404/409 判定为准)
*/
export function normalizeTaskRows(list) {
if (!Array.isArray(list)) return [];
return list.map((item, index) => {
const source = item && typeof item === 'object' ? item : {};
const id = Number(source.id ?? source.task_id ?? 0);
const warehouseId = Number(source.warehouse_id ?? source.warehouseId ?? 0);
const registerCount = Number(source.register_count ?? source.registerCount ?? 0);
const systemTask = id === DEFAULT_TASK_ID;
return {
id,
key: `task-${id || index + 1}`,
batchNo: firstValue(source, ['batch_no', 'batchNo']),
title: firstValue(source, ['title']),
creatorId: firstValue(source, ['creator_id', 'creatorId']),
creatorName: firstValue(source, ['creator_name', 'creatorName']),
warehouseId: Number.isFinite(warehouseId) ? warehouseId : 0,
createdAt: formatDateTime(source.created_at ?? source.createdAt),
updatedAt: formatDateTime(source.updated_at ?? source.updatedAt),
registerCount: Number.isFinite(registerCount) && registerCount > 0 ? registerCount : 0,
isSystem: systemTask,
deletable: !systemTask && warehouseId !== 0 && !(registerCount > 0)
};
});
}
// ===== 导出任务(returnReceived.export / exportTaskProgress)=====
/**
* 导出任务响应归一化
* 数组/进度接口的 task_id/status/progress/download_url 都在**顶层**,而 result 里另有上传信息对象
* (不能用 extractObjectPayload——会优先命中 result,导致 status 取不到)
*
* @param {Object} response 接口原始响应
* @return {{ taskId: string, status: string, progress: number, message: string, currentCount: number, totalCount: number, error: string, downloadUrl: string, fileName: string }}
*/
export function normalizeExportTask(response) {
const source = response && typeof response === 'object' ? response : {};
const result = (source.result && typeof source.result === 'object' && !Array.isArray(source.result)) ? source.result : {};
return {
taskId: firstValue(source, ['task_id', 'taskId']),
status: firstValue(source, ['status']).toLowerCase(),
progress: Math.max(0, Math.min(100, Number(source.progress || 0) || 0)),
message: firstValue(source, ['message']),
currentCount: Number(source.current_count ?? source.currentCount ?? 0) || 0,
totalCount: Number(source.total_count ?? source.totalCount ?? 0) || 0,
error: firstValue(source, ['error']),
downloadUrl: firstValue(source, ['download_url', 'downloadUrl']) ||
firstValue(result, ['url', 'cdnUrl', 'cosUrl', 'fileKey']),
fileName: firstValue(result, ['filename'])
};
}
/** 创建任务的响应归一化:返回 { id, batchNo, title } */
export function normalizeCreatedTask(payload) {
const source = extractObjectPayload(payload);
return {
id: Number(source.id ?? 0),
batchNo: firstValue(source, ['batch_no', 'batchNo']),
title: firstValue(source, ['title'])
};
}
// ===== 扫描记录(returnReceived.list)行归一化 =====
/**
* 退回收到登记行归一化(扫描记录列表)
* 只保留属于当前任务的行:接口按 return_received_task_id 过滤时全部命中;
* 若后端过滤未生效(返回了其它任务的行),此处兜底剔除,并通过 dropped 告知调用方
*
* @param {Array} list 接口返回的 list
* @param {number|string} taskId 当前收件任务ID
* @return {{ rows: Array, dropped: number }}
*/
export function normalizeReceivedRows(list, taskId) {
const rows = Array.isArray(list) ? list : [];
const targetTaskId = Number(taskId);
const normalized = [];
let dropped = 0;
rows.forEach((item, index) => {
const source = item && typeof item === 'object' ? item : {};
const rowTaskId = Number(source.return_received_task_id ?? source.returnReceivedTaskId ?? 0);
if (Number.isFinite(targetTaskId) && targetTaskId > 0 && rowTaskId > 0 && rowTaskId !== targetTaskId) {
dropped += 1;
return;
}
const isOriginal = !!(source.is_original_return ?? source.isOriginalReturn);
// 原单退回优先展示货主名(store_remark),无货主名时回落「原单退回」
const storeRemark = firstValue(source, ['store_remark', 'storeRemark']);
normalized.push({
key: `rec-${source.id || index + 1}`,
id: Number(source.id || 0),
waybillCode: firstValue(source, ['waybill_code', 'waybillCode']),
scanDate: firstValue(source, ['scan_date', 'scanDate']),
scannerName: firstValue(source, ['scanner_name', 'scannerName']),
remark: firstValue(source, ['remark']),
isOriginal,
storeRemark,
tagText: storeRemark || (isOriginal ? '原单退回' : '非原单'),
createdAt: formatDateTime(source.created_at ?? source.createdAt),
taskId: rowTaskId
});
});
return { rows: normalized, dropped };
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,113 @@
<template>
<view class="return-record-scan-page">
<view class="normar_container">
<return-scan-panel
ref="panel"
:task-id="taskId"
:task-title="taskTitle"
:task-batch-no="taskBatchNo"
/>
</view>
</view>
</template>
<script>
/**
* 退回收件扫码登记页(承载 ReturnScanPanel 组件)
* 入口:pages/work/order/returnRecord(收件任务列表)点击任务行,携带 task_id
* 广播/相机扫码的回调生命周期放在页面(广播回调是全局单例,谁显示谁设置),登记业务在组件内完成
*/
import ReturnScanPanel from './returnRecord-comps/ReturnScanPanel.vue';
import { DEFAULT_TASK_ID, normalizeScanResult } from './returnRecord-comps/returnTaskModel.js';
export default {
components: {
ReturnScanPanel
},
data() {
return {
taskId: DEFAULT_TASK_ID,
taskTitle: '',
taskBatchNo: ''
};
},
onLoad(options = {}) {
const rawId = Number(options.task_id || options.taskId || 0);
this.taskId = Number.isFinite(rawId) && rawId > 0 ? rawId : DEFAULT_TASK_ID;
this.taskTitle = this.decodeOption(options.title);
this.taskBatchNo = this.decodeOption(options.batch_no || options.batchNo);
this.safeDispatchBroadcast('setCallbacks', { onResult: this.handleBroadcastResult });
this.safeDispatchBroadcast('start');
},
onShow() {
this.safeDispatchBroadcast('setCallbacks', { onResult: this.handleBroadcastResult });
this.safeDispatchBroadcast('resume');
// 返回页面时重新检测网络并尝试补提(兜底 onNetworkStatusChange 未触发场景)
this.refreshPanelNetwork();
},
onHide() {
this.safeDispatchBroadcast('pause');
},
onUnload() {
this.safeDispatchBroadcast('stop');
},
methods: {
// ===== 路由参数 =====
decodeOption(value) {
const text = String(value === undefined || value === null ? '' : value);
if (!text || text.indexOf('%') === -1) return text;
try {
return decodeURIComponent(text);
} catch (error) {
return text;
}
},
// ===== 广播/扫码基础设施 =====
safeDispatchBroadcast(action, payload) {
try {
const task = this.$store.dispatch(`broadcast/${action}`, payload);
if (task && typeof task.catch === 'function') {
task.catch(error => console.warn(`[returnRecordScan] broadcast/${action} 调用失败:`, error));
}
} catch (error) {
console.warn(`[returnRecordScan] broadcast/${action} 调用异常:`, error);
}
},
handleBroadcastResult(result) {
const code = normalizeScanResult(result);
if (!code) return;
// onLoad 阶段组件可能尚未挂载,延迟到下一 tick 再投递
this.$nextTick(() => {
const panel = this.$refs.panel;
if (panel && typeof panel.submitScan === 'function') {
panel.submitScan(code);
}
});
},
refreshPanelNetwork() {
this.$nextTick(() => {
const panel = this.$refs.panel;
if (panel && typeof panel.refreshNetworkStatus === 'function') {
panel.refreshNetworkStatus();
}
});
}
}
};
</script>
<style lang="scss" scoped>
.return-record-scan-page {
height: 100vh;
background-color: #f5f5f5;
/* 顶部固定(导航 + 登记区),底部剩余空间给扫描记录列表 */
.normar_container {
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
}
</style>