feat(库存盘点): 明细平铺/批量删除、库位级联选择器与 addDetail 新契约

- 明细面板:库位行内商品平铺成行、新增「明细类型」列、批量删除明细(stock.check.detailDelete,按明细ID去重,上限 200)

- 新增 LocationPicker(仓库→库区→货架→库位逐层下拉,v-model 为库位ID数组),「添加盘点库位」接入该组件

- addDetail 改走 location_ids(优先于 locations),补 invalid_location_ids 提示

- 删除调试用临时文件 temp_stockcheck_tail.txt
This commit is contained in:
liufumingren 2026-10-02 03:22:21 +08:00
parent 4d89cd31d0
commit eb305306eb
5 changed files with 728 additions and 213 deletions

View File

@ -500,18 +500,27 @@ export function stockCheckList(
// ============ stock.check.addDetail ============
/** stock.check.addDetail 请求参数(与任务 type 对齐:商品类传 stock_ids,库位类传 locations) */
/** stock.check.addDetail 请求参数(与任务 type 对齐:商品类传 stock_ids,库位类传 location_ids/locations) */
export type StockCheckAddDetailParams = {
/** 盘点任务ID */
id: number
/**
* 商品库存ID列表(wms_stock_warehouse.id):type=store/goods 按商品盘点时使用,
* 与 locations 按任务类型二选一
* 与 location_ids/locations 按任务类型二选一
*/
stock_ids?: number[]
/**
* 库位编码列表(wms_location_space.space_code):type=all/location 按库位盘点时使用,
* 与 stock_ids 按任务类型二选一;**type=all 未传时由后端自动拉取全仓库启用库位生成盘点范围**
* 库位ID列表(wms_location_space.id):type=all/location 按库位盘点时使用,
* **优先于 locations**(与 locations 同时传时 locations 被忽略),
* 服务端直接按 id + warehouse_id 查库校验,不再按编码二次解析;
* 查不到的 ID 记入 invalid_location_ids(不报错)
*/
location_ids?: number[]
/** 库位ID列表(驼峰别名,兼容写法;location_ids 优先) */
locationIds?: number[]
/**
* 库位编码列表(wms_location_space.space_code):仅传编码时按 warehouse_id + space_code 匹配,
* 不存在的编码记入 invalid_locations;**type=all 未传库位且未传库位ID时由后端自动拉取全仓库启用库位**
*/
locations?: string[]
/** 库位编码列表(兼容别名;locations 优先,两者都传时以 locations 为准) */
@ -528,11 +537,22 @@ export type StockCheckAddDetailResponse = {
invalid_stock_ids: number[]
/** 无效库位编码列表(当前仓库不存在对应库位编码) */
invalid_locations: string[]
/** 无效库位ID列表(按 wms_location_space.id 直查当前仓库不存在) */
invalid_location_ids: number[]
/** 重算后的明细总行数 */
total_items: number
}
/** stock.check.addDetail:添加盘点明细(仅 created/rejected 允许;同 stock_id 幂等跳过) */
/**
* stock.check.addDetail:添加盘点明细(商品或库位,按任务盘点类型决定)
*
* - 仅 created/rejected 允许;stock_ids 与 location_ids/locations 按任务类型二选一
* (传错维度后端报 400:按库位盘点传 stock_ids / 按商品盘点传 locations 或 location_ids)
* - 已存在同盘点项(商品行 stock_id / 库位行 location_code)自动跳过(幂等)
* - 完成后重算主表 total_items
*
* 注:兼容入口 stock.check.addLocationDetail 是 addDetail 库位ID路径的薄封装,前端无需单独接入。
*/
export function stockCheckAddDetail(
data: StockCheckAddDetailParams
): Promise<
@ -553,32 +573,36 @@ export function stockCheckAddDetail(
// ============ stock.check.detailDelete ============
/** stock.check.detailDelete 请求参数 */
/** stock.check.detailDelete 请求参数(批量;单次上限 200) */
export type StockCheckDetailDeleteParams = {
/** 盘点任务ID */
id: number
/** 盘点明细ID(与 detailId 二选一,detail_id 优先) */
/** 盘点明细ID数组(单次上限 200;优先级 detail_ids > detailIds > detail_id) */
detail_ids?: number[]
/** 盘点明细ID数组(驼峰别名,兼容写法) */
detailIds?: number[]
/** 旧版单值写法(自动转数组;detail_ids/detailIds 优先) */
detail_id?: number
/** 盘点明细ID(驼峰别名,兼容写法) */
detailId?: number
}
/** stock.check.detailDelete 响应 */
export type StockCheckDetailDeleteResponse = {
/** 被删除的盘点明细ID */
detail_id: number
/** 是否删除成功 */
deleted: boolean
/** 实际删除的明细数量 */
deleted_count: number
/** 实际删除的明细ID列表(保持入参顺序) */
deleted_ids: number[]
/** 未命中被跳过的明细ID列表(明细不存在或不属于当前仓库,不报错;保持入参顺序) */
skipped_ids: number[]
/** 删除后重算的主表明细总行数 */
total_items: number
}
/**
* stock.check.detailDelete:删除盘点明细(从任务中移除某个商品)
* stock.check.detailDelete:**批量**删除盘点明细(从任务中移除商品/库位行)
*
* - 仅主表状态 created/rejected 允许删除
* - 该明细若存在作业记录(wms_stock_check_record)会防御性一并删除
* (正常流程 created/rejected 状态不应有记录)
* - 仅主表状态 created/rejected 允许删除(非该状态报错)
* - 单次最多 200 条;未命中的明细ID计入 skipped_ids(不报错)
* - 命中明细批量删除,并防御性清理 wms_stock_check_record(正常流程该状态不应有记录)
* - 删除后服务端重算主表 total_items
*/
export function stockCheckDetailDelete(

View File

@ -0,0 +1,564 @@
<!--
LocationPicker — 盘点库位选择(逐层下拉:仓库 → 库区 → 货架 → 库位)
数据来源(/system 网关,均限当前登录主体可见范围):
- warehouse.getWarehouseZones → 仓库列表(wms_location_zone 中 zone_type=warehouse)
- warehouse.getWarehouseTree → 仓库下的库区(area)/ 通道(aisle)/ 货架(rack)树
- warehouse.getSpacesByRack → 货架下的库位(wms_location_space)
v-model 为**库位ID数组**(wms_location_space.id),即 stock.check.addDetail 的 location_ids
(新契约:location_ids 直查 id+warehouse_id 校验,优先于 locations 编码,前端默认走 ID 路径)。
allowEmpty=true(type=all)时允许不选:不选库位ID = 由后端拉取全仓启用库位。
「手工输入」为兔底通道:粘贴的**编码**会经 index.searchSpaces 反查精确匹配为库位ID 后并入已选。
-->
<template>
<div class="location-picker">
<!-- 逐层下拉:仓库 → 库区 → 货架;最右为库位筛选 -->
<div class="cascade-row">
<el-select
v-model="warehouseId"
class="cascade-item"
placeholder="仓库"
filterable
clearable
:disabled="disabled"
:loading="warehouseLoading"
@change="handleWarehouseChange"
>
<el-option v-for="w in warehouses" :key="w.id" :label="w.label" :value="w.id" />
<template #empty>暂无仓库</template>
</el-select>
<el-select
v-model="areaId"
class="cascade-item"
placeholder="库区"
filterable
clearable
:disabled="disabled || !warehouseId || treeLoading"
:loading="treeLoading"
@change="handleAreaChange"
>
<el-option v-for="a in areas" :key="a.id" :label="a.label" :value="a.id" />
<template #empty>该仓库暂无库区</template>
</el-select>
<el-select
v-model="rackId"
class="cascade-item"
placeholder="货架"
filterable
clearable
:disabled="disabled || !areaId || spaceLoading"
:loading="spaceLoading"
@change="handleRackChange"
>
<el-option v-for="r in racks" :key="r.id" :label="r.label" :value="r.id" />
<template #empty>该库区暂无货架</template>
</el-select>
<el-input
v-model="keyword"
class="cascade-item"
placeholder="库位编码/名称筛选"
clearable
:disabled="disabled"
/>
</div>
<!-- 操作行 -->
<div class="space-toolbar">
<el-button
size="small"
:disabled="disabled || !filteredSpaces.length"
@click="selectAllVisible"
>
全选当前列表
</el-button>
<el-button size="small" :disabled="disabled || !selected.length" @click="clearSelected">
清空已选
</el-button> <span class="stat-text">
当前列表 {{ filteredSpaces.length }} 个库位 · 已选 {{ selected.length }} 个
</span>
<el-link type="primary" :underline="false" @click="manualVisible = !manualVisible">
{{ manualVisible ? '收起手工输入' : '手工输入编码' }}
</el-link>
</div>
<!-- 手工输入(可折叠):失焦时把编码反查为库位ID 并入已选 -->
<el-input
v-if="manualVisible"
v-model="manualText"
type="textarea"
:rows="3"
resize="none"
:disabled="manualLoading"
placeholder="每行一个库位编码,也可用逗号 / 空格分隔,如:A-01-01;输入完点击其他处(失焦)即识别编码并并入已选"
@blur="flushManualText"
/>
<!-- 库位多选列表(分页渲染,避免上千库位一次性上屏) -->
<div v-loading="spaceLoading" class="space-list">
<el-checkbox-group v-if="visibleSpaces.length" v-model="selected" :disabled="disabled">
<el-checkbox
v-for="space in visibleSpaces"
:key="space.id"
:value="space.id"
class="space-item"
>
{{ space.space_code }}
<span v-if="space.custom_name" class="space-name">({{ space.custom_name }})</span>
</el-checkbox>
</el-checkbox-group>
<div v-else class="empty-tip">{{ emptyText }}</div>
</div>
<div v-if="filteredSpaces.length > spacePageSize" class="space-pager">
<el-pagination
v-model:current-page="spacePage"
v-model:page-size="spacePageSize"
:page-sizes="[100, 200, 500]"
:total="filteredSpaces.length"
layout="total, sizes, prev, pager, next"
background
size="small"
/>
</div>
<!-- 已选预览 -->
<div class="selected-preview">
<span class="hint-text">
已选 {{ selected.length }} 个
<template v-if="!selected.length && allowEmpty">(不选 = 后端自动拉取全仓启用库位)</template>
</span>
<el-tag
v-for="id in selected.slice(0, 60)"
:key="id"
size="small"
closable
class="location-tag"
@close="removeSelected(id)"
>
{{ labelOf(id) }}
</el-tag>
<span v-if="selected.length > 60" class="hint-text">
…等共 {{ selected.length }} 个
</span>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { searchSpaces } from '@/api/index/index'
import {
getSpacesByRack,
getWarehouseTree,
getWarehouseZones
} from '@/api/warehouse/warehouse'
defineOptions({ name: 'LocationPicker' })
const props = withDefaults(
defineProps<{
/** 已选库位ID数组(wms_location_space.id) */
modelValue: number[]
/** 允许不选(type=all:不选 = 后端拉取全仓启用库位) */
allowEmpty?: boolean
/** 只读 */
disabled?: boolean
}>(),
{ modelValue: () => [], allowEmpty: false, disabled: false }
)
const emit = defineEmits<{
(e: 'update:modelValue', value: number[]): void
}>()
/** 已选库位ID(与父组件 v-model 双向同步) */
const selected = computed<number[]>({
get: () => props.modelValue ?? [],
set: (value) => {
const ids = (Array.isArray(value) ? value : [])
.map((id) => Number(id))
.filter((id) => Number.isFinite(id) && id > 0)
emit('update:modelValue', [...new Set(ids)])
}
})
/** 库位ID → 展示文案缓存(切货架后已选项仍能显示编码) */
const spaceLabelById = reactive<Record<number, string>>({})
function rememberSpaces(list: SpaceOption[]) {
for (const space of list) {
spaceLabelById[space.id] = space.custom_name
? `${space.space_code}(${space.custom_name})`
: space.space_code
}
}
function labelOf(id: number): string {
return spaceLabelById[id] ?? `#${id}`
}
type Option = { id: number; label: string }
type SpaceOption = { id: number; space_code: string; custom_name?: string }
// ===== 逐层下拉 =====
const warehouses = ref<Option[]>([])
const areas = ref<Option[]>([])
const racks = ref<Option[]>([])
const warehouseId = ref<number | undefined>(undefined)
const areaId = ref<number | undefined>(undefined)
const rackId = ref<number | undefined>(undefined)
const warehouseLoading = ref(false)
const treeLoading = ref(false)
const spaceLoading = ref(false)
const spaces = ref<SpaceOption[]>([])
const keyword = ref('')
const manualVisible = ref(false)
const manualText = ref('')
const manualLoading = ref(false)
/** 上一次已识别的手工输入(避免同一段文本重复请求) */
const lastManualText = ref('')
/** 库位列表分页(单个货架可能有上千库位) */
const spacePage = ref(1)
const spacePageSize = ref(200)
/** 当前仓库的库区树children(缓存,切换库区时复用,不再多拉一次) */
const treeChildren = ref<any[]>([])
/** 从树节点中按类型递归收集(库区下可能隔着 aisle 通道层) */
function collectByType(nodes: any[], type: string, out: any[] = []): any[] {
for (const node of Array.isArray(nodes) ? nodes : []) {
if (node?.type === type) out.push(node)
if (node?.children?.length) collectByType(node.children, type, out)
}
return out
}
function toOption(node: any): Option {
return {
id: Number(node?.id) || 0,
label: String(node?.label ?? node?.name ?? node?.code ?? node?.id ?? '')
}
}
/** 库位列表(本地按编码/名称筛选) */
const filteredSpaces = computed<SpaceOption[]>(() => {
const kw = keyword.value.trim().toLowerCase()
if (!kw) return spaces.value
return spaces.value.filter(
(s) =>
String(s.space_code).toLowerCase().includes(kw) ||
String(s.custom_name ?? '').toLowerCase().includes(kw)
)
})
/** 当前页库位 */
const visibleSpaces = computed<SpaceOption[]>(() => {
const start = (spacePage.value - 1) * spacePageSize.value
return filteredSpaces.value.slice(start, start + spacePageSize.value)
})
// 筛选/切货架时回到第一页,避免停在空白页
watch([keyword, rackId], () => {
spacePage.value = 1
})
// 已选被外部清空时同步清掉手工输入,避免下次失焦又把旧编码加回来
watch(
() => props.modelValue,
(value) => {
if (!value?.length) {
manualText.value = ''
lastManualText.value = ''
}
}
)
const emptyText = computed(() => {
if (!warehouseId.value) return '请先选择仓库'
if (!areaId.value) return '请选择库区'
if (!rackId.value) return '请选择货架'
if (!spaces.value.length) return '该货架下暂无启用库位'
return '没有匹配的库位'
})
/** 加载仓库列表(默认选中唯一仓库) */
async function loadWarehouses() {
warehouseLoading.value = true
try {
const res: any = await getWarehouseZones({})
const list = Array.isArray(res?.zones)
? res.zones
: Array.isArray(res?.data?.zones)
? res.data.zones
: []
warehouses.value = list.map((z: any) => toOption(z)).filter((z: Option) => z.id > 0)
const first = warehouses.value[0]
if (!warehouseId.value && warehouses.value.length === 1 && first) {
warehouseId.value = first.id
await loadTree()
}
} catch (e) {
console.error('[stockcheck] 加载仓库列表失败', e)
ElMessage.error('加载仓库列表失败')
} finally {
warehouseLoading.value = false
}
}
/** 加载仓库下的库区/货架树(缓存 children 供库区切换复用) */
async function loadTree() {
areas.value = []
racks.value = []
treeChildren.value = []
if (!warehouseId.value) return
treeLoading.value = true
try {
const res: any = await getWarehouseTree(warehouseId.value)
const root = res?.warehouseRoot ?? res?.data?.warehouseRoot
const children = Array.isArray(root?.children) ? root.children : []
treeChildren.value = children
areas.value = children
.filter((node: any) => node?.type === 'area')
.map((node: any) => toOption(node))
.filter((node: Option) => node.id > 0)
} catch (e) {
console.error('[stockcheck] 加载库区失败', e)
ElMessage.error('加载库区失败')
} finally {
treeLoading.value = false
}
}
/** 库区变化 → 收集库区下的货架(含通道层下的货架) */
function handleAreaChange() {
racks.value = []
spaces.value = []
rackId.value = undefined
if (!areaId.value) return
const areaNode = treeChildren.value.find(
(node: any) => Number(node?.id) === Number(areaId.value)
)
racks.value = collectByType(areaNode?.children ?? [], 'rack')
.map((node: any) => toOption(node))
.filter((node: Option) => node.id > 0)
}
async function handleWarehouseChange() {
areaId.value = undefined
rackId.value = undefined
spaces.value = []
keyword.value = ''
spacePage.value = 1
await loadTree()
}
/** 货架变化 → 拉取库位 */
async function handleRackChange() {
spaces.value = []
keyword.value = ''
spacePage.value = 1
if (!rackId.value) return
spaceLoading.value = true
try {
const res: any = await getSpacesByRack(rackId.value)
const list = Array.isArray(res?.spaces)
? res.spaces
: Array.isArray(res?.data?.spaces)
? res.data.spaces
: []
spaces.value = list
.filter((space: any) => space?.is_enabled !== false && Number(space?.is_enabled) !== 0)
.map((space: any) => ({
id: Number(space?.id) || 0,
space_code: String(space?.space_code ?? ''),
custom_name: space?.custom_name ? String(space.custom_name) : ''
}))
.filter((space: SpaceOption) => space.id > 0 && space.space_code !== '')
rememberSpaces(spaces.value)
} catch (e) {
console.error('[stockcheck] 加载库位失败', e)
ElMessage.error('加载库位失败')
} finally {
spaceLoading.value = false
}
}
// ===== 已选维护 =====
/** 全选当前筛选结果(含跨页) */
function selectAllVisible() {
const ids = filteredSpaces.value.map((s) => s.id)
selected.value = [...new Set([...selected.value, ...ids])]
}
function clearSelected() {
selected.value = []
}
function removeSelected(id: number) {
selected.value = selected.value.filter((item) => item !== id)
}
/**
* 手工输入的**库位编码**经验证后并入已选
*
* 走 index.searchSpaces(每个编码一次查询,最多 50 条)后按 space_code 精确匹配,
* 命中转成库位ID(提交走 addDetail 的 location_ids);未命中的编码提示且不并入。
*/
async function flushManualText() {
const text = manualText.value.trim()
if (!text || text === lastManualText.value) return
const codes = [
...new Set(
text
.split(/[\s,,、;;]+/)
.map((s) => s.trim())
.filter(Boolean)
)
]
if (!codes.length) return
lastManualText.value = text
manualLoading.value = true
try {
const res: any = await searchSpaces({ keywords: codes })
const groups: any[] = Array.isArray(res?.data) ? res.data : []
const ids: number[] = []
const missing: string[] = []
codes.forEach((code, index) => {
const list = Array.isArray(groups[index]) ? groups[index] : []
const hit = list.find(
(space: any) => String(space?.space_code ?? '').toUpperCase() === code.toUpperCase()
)
const hitId = Number(hit?.id) || 0
if (hitId > 0) {
ids.push(hitId)
spaceLabelById[hitId] = hit?.custom_name
? `${hit.space_code}(${hit.custom_name})`
: String(hit?.space_code ?? code)
} else {
missing.push(code)
}
})
if (ids.length) selected.value = [...new Set([...selected.value, ...ids])]
if (missing.length) {
ElMessage.warning(
`未识别库位编码:${missing.slice(0, 5).join('、')}${missing.length > 5 ? ' 等' : ''}`
)
} else if (ids.length) {
ElMessage.success(`已并入 ${ids.length} 个库位`)
}
} catch (e) {
console.error('[stockcheck] 库位编码识别失败', e)
ElMessage.error('库位编码识别失败')
} finally {
manualLoading.value = false
}
}
onMounted(() => {
void loadWarehouses()
})
defineExpose({ reload: loadWarehouses })
</script>
<style lang="scss" scoped>
.location-picker {
display: flex;
flex-direction: column;
gap: 8px;
}
.cascade-row {
display: flex;
gap: 8px;
flex-wrap: wrap;
.cascade-item {
width: 190px;
flex: 0 0 auto;
}
}
.space-toolbar {
display: flex;
align-items: center;
gap: 8px;
:deep(.el-button) {
margin-left: 0;
margin-right: 0;
}
.stat-text {
font-size: 12px;
color: #909399;
}
.el-link {
margin-left: auto;
font-size: 12px;
}
}
.space-list {
min-height: 120px;
max-height: 260px;
overflow-y: auto;
padding: 6px 8px;
border: 1px solid #ebeef5;
border-radius: 4px;
:deep(.el-checkbox-group) {
display: flex;
flex-wrap: wrap;
gap: 2px 12px;
}
.space-item {
margin-right: 0;
min-width: 150px;
}
.space-name {
color: #909399;
}
}
.space-pager {
display: flex;
justify-content: flex-end;
}
.selected-preview {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
min-height: 24px;
.hint-text {
font-size: 12px;
color: #909399;
}
.location-tag {
margin: 0;
}
}
.empty-tip {
display: flex;
align-items: center;
justify-content: center;
min-height: 100px;
font-size: 12px;
color: #c0c4cc;
}
</style>

View File

@ -14,9 +14,11 @@
上报需带 stock_id → 商品行直接上报;同明细的「明细类型 / 库位」单元格合并显示
2. 盘点作业:行内或批量上报(stock.check.report,**覆盖式**:
商品行=同明细+同库位;库位行=同明细+同商品+同库位,均重复上报为更新)
3. 完成盘点(stock.check.finish,允许部分未盘完成:
3. 批量删除明细(stock.check.detailDelete,仅 created/rejected):勾选行按**明细ID**去重提交,
单次上限 200 条;未命中的明细ID由服务端计入 skipped_ids(不报错)
4. 完成盘点(stock.check.finish,允许部分未盘完成:
未盘商品明细按实盘 0 计入盘亏与差异行数,未盘库位明细不计差异)
4. 「添加商品 / 添加库位」交给宿主 index.vue 打开 CheckStockPickerDialog(emit add-items)
5. 「添加商品 / 添加库位」交给宿主 index.vue 打开 CheckStockPickerDialog(emit add-items)
状态约束(与后端一致):
- created/rejected → 可添加明细(addDetail)
@ -33,6 +35,17 @@
<el-button v-if="canAddItems" size="small" type="primary" plain @click="emit('add-items')">
{{ isLocationTask ? '添加库位' : '添加商品' }}
</el-button>
<el-button
v-if="canAddItems"
size="small"
type="danger"
plain
:disabled="!selectedDetailIds.length"
:loading="deleting"
@click="deleteSelected"
>
批量删除明细{{ selectedDetailIds.length ? `(${selectedDetailIds.length})` : '' }}
</el-button>
<el-button
v-if="canReport && !isLocationTask"
size="small"
@ -75,7 +88,10 @@
size="small"
:height="tableHeight"
:span-method="spanMethod"
@selection-change="handleSelectionChange"
>
<!-- 批量删除:仅 created/rejected(可增删明细)时提供勾选,按明细ID去重提交 -->
<el-table-column v-if="canAddItems" type="selection" width="45" :reserve-selection="true" />
<el-table-column type="index" label="#" width="56" align="center" :index="indexMethod" />
<!-- 明细类型:商品行 / 库位行(同一单内由任务 type 决定,显式标注便于核对) -->
<el-table-column label="明细类型" width="90" align="center">
@ -195,6 +211,7 @@ import { getStatusTextClass } from '@/views/order/orderManagement/config/order-c
import { formatTime, isCheckApiSuccess, isLocationScopeType, translate } from '../template-config'
import {
stockCheckDetail,
stockCheckDetailDelete,
stockCheckFinish,
stockCheckReport,
stockCheckResult,
@ -440,6 +457,8 @@ async function loadItems() {
stats.checked = Number(check.checked_items ?? 0) || 0
stats.diff = Number(check.diff_items ?? 0) || 0
resetInputs()
selectedRows.value = []
nextTick(() => tableRef.value?.clearSelection?.())
page.value = 1
} catch (e: any) {
console.error('[stockcheck] 加载盘点明细失败', e)
@ -520,6 +539,72 @@ function resetInputs() {
}
}
// ============================================================
// 批量删除明细(stock.check.detailDelete,仅 created/rejected)
// ============================================================
const selectedRows = ref<Record<string, any>[]>([])
const deleting = ref(false)
/** 选中行对应的明细ID(按明细去重:库位行平铺后同一明细可能对应多行) */
const selectedDetailIds = computed<number[]>(() => {
const ids = selectedRows.value.map((row) =>
Number(row?.detail_id ?? row?.item?.id ?? row?.id)
)
return [...new Set(ids.filter((id) => Number.isFinite(id) && id > 0))]
})
function handleSelectionChange(rows: Record<string, any>[]) {
selectedRows.value = Array.isArray(rows) ? rows : []
}
/** 批量删除选中的盘点明细(单次上限 200,与后端一致) */
async function deleteSelected() {
const ids = selectedDetailIds.value
if (!ids.length) {
ElMessage.warning('请先勾选要删除的盘点明细')
return
}
if (ids.length > 200) {
ElMessage.warning(`单次最多删除 200 条明细(已选 ${ids.length} 条),请分批删除`)
return
}
try {
await ElMessageBox.confirm(
`确定删除选中的 ${ids.length} 个盘点明细?删除后需重新添加。`,
'批量删除盘点明细',
{ confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning' }
)
} catch {
return
}
deleting.value = true
try {
const res: any = await stockCheckDetailDelete({ id: taskId.value, detail_ids: ids })
if (!isCheckApiSuccess(res)) {
throw new Error(res?.message || '删除盘点明细失败')
}
const data = res.data ?? res
const deletedCount = Number(data.deleted_count ?? 0)
const skippedIds: number[] = Array.isArray(data.skipped_ids) ? data.skipped_ids : []
if (skippedIds.length) {
ElMessage.warning(
`已删除 ${deletedCount} 条明细,跳过 ${skippedIds.length} 条(不存在或不属于当前仓库)`
)
} else {
ElMessage.success(`已删除 ${deletedCount} 条盘点明细`)
}
// loadItems 内部会重置页码与勾选
await loadItems()
emit('changed')
} catch (e: any) {
console.error('[stockcheck] 删除盘点明细失败', e)
ElMessage.error(e?.message || '删除盘点明细失败')
} finally {
deleting.value = false
}
}
// ============================================================
// 上报实盘(stock.check.report)
// ============================================================

View File

@ -3,11 +3,13 @@
两种模式(由来源盘点单的 type 决定):
- 商品类(type=store/goods):从 storage.inventory.list 选商品 → 传 stock_ids
- 库位类(type=all/location):填写/粘贴库位编码(wms_location_space.space_code)→ 传 locations
· type=all 不填库位 = 不传 locations,由后端自动拉取全仓启用库位
- 库位类(type=all/location):LocationPicker 逐层下拉(仓库 → 库区 → 货架 → 库位)选择
→ 传 **location_ids**(wms_location_space.id,服务端按 id + warehouse_id 直查校验,
优先于 locations 编码;新契约下不再走编码二次解析)
· type=all 不选库位 = 不传库位/库位ID,由后端自动拉取全仓启用库位
响应含 invalid_stock_ids(商品)与 invalid_locations(库位)两类无效项,均需在提示中体现。
仅 created(新建)/ rejected(驳回)状态可添加,后端会校验。
响应含 invalid_stock_ids(商品)/ invalid_locations(无效编码)/ invalid_location_ids(无效库位ID)三类无效项,
均需在提示中体现。仅 created(新建)/ rejected(驳回)状态可添加,后端会校验。
-->
<template>
<el-dialog
@ -91,7 +93,7 @@
</div>
</template>
<!-- ===== 库位类任务:填写/粘贴库位编码 → locations ===== -->
<!-- ===== 库位类任务:逐层下拉(仓库 → 库区 → 货架 → 库位)选择 → locations ===== -->
<template v-else>
<el-alert
type="info"
@ -99,27 +101,7 @@
show-icon
:title="locationAlertText"
/>
<el-input
v-model="locationText"
type="textarea"
:rows="8"
resize="none"
placeholder="每行一个库位编码,也可用逗号 / 空格分隔,如:A-01-01"
/>
<div class="location-preview">
<span class="stat-text">已识别 {{ locationCodes.length }} 个库位</span>
<el-tag
v-for="code in locationCodes.slice(0, 50)"
:key="code"
size="small"
class="location-tag"
>
{{ code }}
</el-tag>
<span v-if="locationCodes.length > 50" class="stat-text">
…等共 {{ locationCodes.length }} 个
</span>
</div>
<LocationPicker v-model="locationIds" :allow-empty="taskType === 'all'" />
</template>
</div>
@ -127,7 +109,7 @@
<div class="dialog-footer">
<span class="selected-tip">
{{ isLocationMode
? `已填 ${locationCodes.length} 个库位`
? `已选 ${locationIds.length} 个库位`
: `已选 ${selectedRows.length} 行 · 去重后 ${selectedStockIds.length} 个商品` }}
</span>
<div class="footer-buttons">
@ -156,6 +138,7 @@ import {
stockCheckAddDetail,
type StockCheckAddDetailParams
} from '@/api/stock.check/stock.check'
import LocationPicker from '../components/LocationPicker.vue'
import { isCheckApiSuccess, isLocationScopeType } from '../config/template-config'
defineOptions({ name: 'CheckStockPickerDialog' })
@ -185,24 +168,18 @@ const dialogTitle = computed(() => {
})
// ===== 库位模式 =====
/** 库位编码输入(每行一个,或逗号/空格/顿号分隔) */
const locationText = ref('')
/** 解析后的库位编码(去重去空) */
const locationCodes = computed<string[]>(() => {
const parts = locationText.value.split(/[\s,,、;;]+/)
return [...new Set(parts.map((s) => s.trim()).filter(Boolean))]
})
/** 已选库位ID(wms_location_space.id,由 LocationPicker 逐层选择维护;type=all 可留空) */
const locationIds = ref<number[]>([])
const locationAlertText = computed(() =>
props.taskType === 'all'
? '按库位盘点(默认全仓):不填库位时,由后端自动拉取全仓库启用库位生成盘点范围。'
: '按库位盘点:请填写要盘点的库位编码(不存在的库位会被后端列入无效库位)。'
? '按库位盘点(默认全仓):逐层选择库位,不选时由后端自动拉取全仓库启用库位生成盘点范围。'
: '按库位盘点:请逐层(仓库 → 库区 → 货架)选择要盘点的库位;不存在的库位会被后端列入无效库位。'
)
/** 库位模式:填了库位,或 all 类型(允许不填=全仓) */
/** 库位模式:选了库位,或 all 类型(允许不选=全仓) */
const canSubmit = computed(() => {
if (isLocationMode.value) return locationCodes.value.length > 0 || props.taskType === 'all'
if (isLocationMode.value) return locationIds.value.length > 0 || props.taskType === 'all'
return selectedStockIds.value.length > 0
})
@ -239,7 +216,7 @@ function handleClosed() {
tableRef.value?.clearSelection?.()
selectedRows.value = []
rows.value = []
locationText.value = ''
locationIds.value = []
submitting.value = false
}
@ -337,16 +314,16 @@ async function handleSubmit() {
const payload: StockCheckAddDetailParams = { id: taskId }
if (isLocationMode.value) {
const codes = locationCodes.value
if (!codes.length) {
const ids = locationIds.value
if (!ids.length) {
if (props.taskType !== 'all') {
ElMessage.warning('请填写至少一个库位编码')
ElMessage.warning('请至少选择一个库位')
return
}
// type=all:不传 locations,由后端自动拉取全仓启用库位
// type=all:不传库位(也不传库位ID),由后端自动拉取全仓启用库位
try {
await ElMessageBox.confirm(
'未填写库位编码,将由后端自动拉取全仓库启用库位生成盘点范围,确定继续?',
'未选择库位,将由后端自动拉取全仓库启用库位生成盘点范围,确定继续?',
'添加盘点库位',
{ confirmButtonText: '确定继续', cancelButtonText: '取消', type: 'warning' }
)
@ -354,7 +331,8 @@ async function handleSubmit() {
return
}
} else {
payload.locations = codes
// 新契约:库位ID直查(id + warehouse_id 校验,不再按编码二次解析),优先于 locations
payload.location_ids = ids
}
} else {
const stockIds = selectedStockIds.value
@ -376,12 +354,19 @@ async function handleSubmit() {
const skipped = Number(data.skipped ?? 0)
const invalidStocks: number[] = Array.isArray(data.invalid_stock_ids) ? data.invalid_stock_ids : []
const invalidLocations: string[] = Array.isArray(data.invalid_locations) ? data.invalid_locations : []
const invalidLocationIds: number[] = Array.isArray(data.invalid_location_ids)
? data.invalid_location_ids
: []
const parts = [`新增 ${added} 项`]
if (skipped) parts.push(`跳过已存在 ${skipped} 项`)
if (invalidStocks.length) parts.push(`无效商品 ${invalidStocks.length} 个`)
if (invalidLocations.length) parts.push(`无效库位 ${invalidLocations.length} 个`)
if (invalidStocks.length || invalidLocations.length) ElMessage.warning(parts.join(','))
else ElMessage.success(parts.join(','))
if (invalidLocations.length) parts.push(`无效库位编码 ${invalidLocations.length} 个`)
if (invalidLocationIds.length) parts.push(`无效库位 ${invalidLocationIds.length} 个`)
if (invalidStocks.length || invalidLocations.length || invalidLocationIds.length) {
ElMessage.warning(parts.join(','))
} else {
ElMessage.success(parts.join(','))
}
emit('update:visible', false)
emit('success', { added, skipped })
} catch (e: any) {
@ -402,7 +387,7 @@ watch(
pagination.total = 0
selectedRows.value = []
rows.value = []
locationText.value = ''
locationIds.value = []
nextTick(() => tableRef.value?.clearSelection?.())
// 库位模式不需要拉库存列表
if (!isLocationMode.value) void loadRows()
@ -446,19 +431,7 @@ watch(
color: #909399;
}
/* 库位模式:预览已识别的库位编码 */
.location-preview {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
max-height: 120px;
overflow-y: auto;
}
.location-tag {
margin: 0;
}
/* 库位模式:已选的库位编码由 LocationPicker 内部展示预览 */
.stat-text {
font-size: 12px;

View File

@ -1,131 +0,0 @@
storageQuantityMap,
}));
}
/**
* å°†å<E280A0>•æ<E280A2>¡ç›˜ç‚¹æ˜Žç»†æ ¼å¼<C3A5>化为è<C2BA>šå<C5A1>ˆè¾“出行ã€?
* 商å“<C3A5>行:è<C5A1>šå<C5A1>ˆä½œä¸šè®°å½•输出已盘数é‡<C3A9>/差异/库ä½<C3A4>列表等;
* 库ä½<C3A4>行:按商å“<C3A5>è<EFBFBD>šå<C5A1>ˆä½œä¸šè®°å½•输å‡?stocks 列表(å<CB86>« wms_storage è´¦é<C2A6>¢ä¸Žå·®å¼‚)ã€?
*
* @param {Object} params æ ¼å¼<C3A5>化å<E28093>‚æ•°ã€?
* @param {Object} params.detailRow 明细原始行�
* @param {Map<number, Array<Object>>} params.recordsByDetail 按明细ID分组的作业记录�
* @param {Map<number, Object>} params.stockMap 商å“<C3A5>快照映射ã€?
* @param {Map<string, number>} params.storageQuantityMap 库ä½<C3A4>商å“<C3A5>è´¦é<C2A6>¢æ•°é‡<C3A9>映射(键 `${space_id}_${stock_id}`)ã€?
* @return {Object} æ ¼å¼<C3A5>化å<E28093>Žçš„æ˜Žç»†è¡Œã€?
*/
_formatDetailAggregationRow(params = {}) {
const { detailRow, recordsByDetail, stockMap, storageQuantityMap } = params;
const detailRowId = Number(detailRow.id);
const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods';
const detailRecords = recordsByDetail.get(detailRowId) || [];
const locationCodes = [ ...new Set(detailRecords
.map(record => String(record.location_code || '').trim())
.filter(Boolean)) ];
const checkers = [ ...new Set(detailRecords
.map(record => String(record.checker_name || '').trim())
.filter(Boolean)) ];
const lastCheckedAt = detailRecords.length > 0
? detailRecords[detailRecords.length - 1].checked_at
: null;
// 按库ä½<C3A4>è<EFBFBD>šå<C5A1>ˆä½œä¸šè®°å½•(库ä½<C3A4>为空归入"无库ä½?分组,location_code ä¸?null),按首æ<E28093>¡è®°å½?id å<>‡åº<C3A5>
const locationGroups = new Map();
for (const record of detailRecords) {
const recordLocationCode = record.location_code !== null && record.location_code !== undefined
? String(record.location_code).trim()
: '';
if (!locationGroups.has(recordLocationCode)) {
locationGroups.set(recordLocationCode, {
location_id: recordLocationCode ? (Number(record.location_id) || null) : null,
location_code: recordLocationCode || null,
quantity: 0,
first_record_id: Number(record.id) || 0,
});
}
const locationGroup = locationGroups.get(recordLocationCode);
locationGroup.quantity += Number(record.quantity) || 0;
}
const locations = [ ...locationGroups.values() ]
.sort((left, right) => left.first_record_id - right.first_record_id)
.map(locationGroup => ({
location_id: locationGroup.location_id,
location_code: locationGroup.location_code,
quantity: locationGroup.quantity,
}));
const base = {
...detailRow,
scope_type: scopeType,
location_codes: locationCodes,
checkers,
last_checked_at: lastCheckedAt,
records: detailRecords,
locations,
};
if (scopeType === 'goods') {
const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0);
const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0);
return {
...base,
checked_quantity: detailRecords.length > 0 ? checkedQuantity : null,
diff_quantity: detailRecords.length > 0 ? diffQuantity : null,
is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0,
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
};
}
// 库ä½<C3A4>行:按商å“<C3A5>è<EFBFBD>šå<C5A1>ˆè®°å½•,账é<C2A6>¢ä»?wms_storage å<>–(location_id 为空时账é<C2A6>¢æŒ‰ 0ï¼?
const quantityByStock = new Map();
for (const record of detailRecords) {
const stockId = Number(record.stock_id);
if (!Number.isInteger(stockId) || stockId <= 0) {
continue;
}
const agg = quantityByStock.get(stockId) || { checked: 0 };
agg.checked += Number(record.quantity) || 0;
quantityByStock.set(stockId, agg);
}
const locationId = detailRow.location_id !== null && detailRow.location_id !== undefined
? Number(detailRow.location_id)
: 0;
let checkedQuantity = 0;
let diffQuantitySum = 0;
let hasDiff = false;
const stocks = [ ...quantityByStock.keys() ]
.sort((left, right) => left - right)
.map(stockId => {
const agg = quantityByStock.get(stockId);
const stock = stockMap.get(stockId) || {};
const systemQuantity = locationId > 0
? (storageQuantityMap.get(`${locationId}_${stockId}`) || 0)
: 0;
const diffQuantity = agg.checked - systemQuantity;
checkedQuantity += agg.checked;
diffQuantitySum += diffQuantity;
if (diffQuantity !== 0) {
hasDiff = true;
}
return {
stock_id: stockId,
item_code: stock.item_code || null,
item_name: stock.item_name || null,
system_quantity: systemQuantity,
checked_quantity: agg.checked,
diff_quantity: diffQuantity,
};
});
return {
...base,
stocks,
checked_quantity: detailRecords.length > 0 ? checkedQuantity : null,
diff_quantity: detailRecords.length > 0 ? diffQuantitySum : null,
is_diff: hasDiff ? 1 : 0,
status: detailRecords.length > 0 ? 'checked' : 'unchecked',
};
}
/**