yin bb92c720fd refactor: update dialog components for consistent styling and button sizes
- Adjusted button sizes in CameraPreviewDialog and OperationCellRenderer for uniformity.
- Enhanced the layout and structure of ServerFormDialog and sign dialog to improve user experience.
- Implemented a new task panel design for better alignment and readability in various dialogs.
- Added computed properties for dynamic subtitles and footers in the sign dialog.
- Replaced ElMessageBox.prompt with a custom rename remark dialog for better styling consistency.
2026-10-26 17:59:21 +08:00

1067 lines
42 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

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

<!--
CheckItemsPanel — 盘点明细面板(库存盘点 stock.check)
职责:
1. 拉取盘点明细并渲染(**统一走 stock.check.result**):
- `stock.check.detail` 已**不再返回明细列表**(仅返回任务主体 `check`),故无论任务状态
(created/rejected/submitted/approved/checking/completed/cancelled)都取 result:
`{ check, rows, total }`,未开始作业阶段 rows 只是「范围行」(已盘=null、差异=null、状态=未盘)。
- 不再多发一次聚合查询,也不再需要按状态切接口。
明细行形态由任务 type 决定,表格统一「平铺」展示(不用展开行):
- 商品行(scope_type=goods,type=store/goods):一行一个库存商品(商品快照 + 已盘聚合);
行级聚合(checked_quantity/diff_quantity)**已含未知商品**,故不再平铺 unknown_items,
改为在「商品名称」列提示「含未知商品 N 项」,避免合计重复展示
- 库位行(scope_type=location,type=all/location):一行一个库位 + 行内商品各一行
(result 的 stocks[] 平铺)+ **未知商品各一行**(unknown_items 平铺,带「未知」标记);
行级合计不单独展示(只展示明细),所以平铺不会重复
2. 盘点作业:行内上报(stock.check.report,**覆盖式**:同明细+同商品+同库位重复上报为更新)
· **库位以 `space_id` 为准且必传**(2026-10-26 文档):取明细行 `space_id` / `location_id`,
`location`(编码)仅做一致性校验,缺失 space_id 时前端直接拦下(服务端会 400)
· 行内「上报」→ CheckReportDialog 弹窗(可填实盘数量与「未匹配条码」):
填了条码 → 后端按条码匹配系统商品,命中=已知商品;未命中记**未知商品**(无账面,实盘>0 即盘盈)
· 批量上报(仅商品类,行内数量列):逐行串行提交,不走弹窗
2b. 标记库位为空(stock.check.markEmpty,仅库位类任务的**无商品库位行**):
写空标记记录(quantity=0、is_empty=1)并清除该库位下商品记录;空标记计入已盘,
库位账面有库存时计入盘亏;已标记空的行展示「空库位」 tag。
3. 完成盘点(stock.check.finish,允许部分未盘完成:
未盘商品明细按实盘 0 计入盘亏与差异行数,未盘库位明细不计差异)
4. 「添加商品 / 添加库位」交给宿主 index.vue 打开 CheckStockPickerDialog(emit add-items)
4b. 「导出明细」(仅 completed 任务)交给宿主 index.vue 走 stock.check.exportDetail
(异步任务 + exportTaskProgress 进度弹窗,emit export-detail)
5. 作业图片列:result 的 records[].images(RecordImages 缩略图 + 点击放大)
状态约束(与后端一致):
- created/rejected → 可添加明细(商品类 addDetail / 库位类 addLocationDetail)
- approved/checking → 可上报(report)、可完成(finish)
- mode=blind 盲盘 → 账面数量/差异在前端不可见
- 明细 status:checked=有作业记录 / unchecked=未盘
-->
<template>
<div class="check-items-panel">
<!-- 按钮行(间距 6px 对齐 toolbar) -->
<div class="header-actions">
<div class="left-actions">
<el-button size="small" type="primary" :loading="loading" @click="loadItems">刷新</el-button>
<el-button v-if="canAddItems" size="small" type="primary" plain @click="emit('add-items')">
{{ isLocationTask ? '添加库位' : '添加商品' }}
</el-button>
<el-button
v-if="canReport && !isLocationTask"
size="small"
type="primary"
plain
:disabled="!selectedReportTargets.length"
:loading="reporting"
@click="reportSelected"
>
批量上报
</el-button>
<el-button
v-if="canReport"
size="small"
type="primary"
plain
:loading="finishing"
@click="finishCheck"
>
完成盘点
</el-button>
<!-- 导出盘点明细(stock.check.exportDetail,仅「已完成」任务) -->
<el-button
v-if="isCompleted"
size="small"
type="primary"
plain
@click="emit('export-detail')"
>
导出明细
</el-button>
</div>
<div class="right-actions">
<span v-if="isQuantityMasked" class="hint-text">盲盘:账面数量不可见</span>
<span class="stat-text">
明细 {{ stats.total }} · 已盘 {{ stats.checked }} · 差异 {{ stats.diff }}
</span>
</div>
</div>
<div ref="tableHostRef" class="table-host">
<upper-table
ref="tableRef"
table-id="stockcheck-items"
:data="pagedRows"
:columns="tableColumns"
row-key="flat_key"
table-size="small"
default-align="center"
:loading="loading"
:show-selection="true"
:selectable="isReportableRow"
:span-method="spanMethod"
:virtual-threshold="100000"
:pagination="pagination"
:page-sizes="[10, 20, 50, 100]"
:show-pagination="flatRows.length > pageSize"
@selection-change="handleSelectionChange"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
>
<!-- 明细类型:商品行 / 库位行(同一单内由任务 type 决定,显式标注便于核对) -->
<template #column-scope_label="{ row }">{{ itemScopeLabel(row) }}</template>
<!-- 商品列:仅商品类任务显示(库位类任务不展示商品快照,商品明细看「作业明细」) -->
<template #column-item_code="{ row }">{{ row.item_code || '—' }}</template>
<template #column-item_name="{ row }">
<span>{{ row.item_name || '—' }}</span>
<!-- 商品行的聚合值已含未知商品(result 的 unknown_items),此处仅提示数量,不再平铺(避免重复) -->
<el-tag v-if="row.unknown_count" type="warning" size="small" class="unknown-tag">
含未知商品 {{ row.unknown_count }} 项
</el-tag>
</template>
<template #column-spec="{ row }">{{ row.spec || '—' }}</template>
<template #column-batch_no="{ row }">{{ row.batch_no || '—' }}</template>
<template #column-location="{ row }">
<!-- 库位行:库位以明细自身库位为准,只读(同明细的行合并单元格);商品行仅展示/校验绑定库位 -->
<span v-if="isLocationTask">{{ formatLocationCodes(row) }}</span>
<el-input
v-else-if="canReport"
v-model="locationMap[row.item.id]"
size="small"
placeholder="库位编码(默认=明细库位)"
/>
<span v-else>{{ formatLocationCodes(row) }}</span>
</template>
<!-- 库位类任务:商品 / 条码(已知商品取 result 的 stocks 快照;未知商品行显示条码) -->
<template #column-item_display="{ row }">
<el-tag v-if="row.item?.is_empty" type="info" size="small" class="unknown-tag">空库位</el-tag>
<el-tag v-else-if="row.is_unknown" type="warning" size="small" class="unknown-tag">未知</el-tag>
<template v-if="row.item_name || row.item_code">
{{ row.item_name || '—' }}
<span v-if="row.item_code" class="hint-text">{{ row.item_code }}</span>
</template>
<span v-else-if="!row.item?.is_empty" class="hint-text">—</span>
</template>
<!-- 账面/实盘输入列:仅商品类任务(库位类任务的实盘数量在「上报」弹窗里填) -->
<template #column-system_quantity="{ row }">{{ maskQuantity(row.system_quantity) }}</template>
<template #column-row_quantity="{ row }">
<el-input-number
v-if="isReportableRow(row)"
:model-value="rowQuantity(row)"
size="small"
:min="0"
:step="1"
step-strictly
controls-position="right"
class="quantity-input"
@update:model-value="onRowQuantityChange(row, $event)"
/>
<span v-else class="hint-text">—</span>
</template>
<template #column-checked_quantity="{ row }">{{ row.checked_quantity ?? '—' }}</template>
<template #column-diff_quantity="{ row }">
<span v-if="isQuantityMasked" class="hint-text">—</span>
<span v-else :class="diffClass(row.diff_quantity)">{{ formatDiff(row.diff_quantity) }}</span>
</template>
<template #column-status="{ row }">
<span :class="getStatusTextClass(itemStatusTag(row.status))">
{{ translate('check_item_status', row.status) }}
</span>
</template>
<template #column-checkers="{ row }">{{ formatCheckers(row) }}</template>
<template #column-last_checked_at="{ row }">{{ formatTime(row.last_checked_at) }}</template>
<!-- 作业图片:result 的 records[].images(业务类型 stock_check_record) -->
<template #column-images="{ row }">
<RecordImages :images="rowImages(row)" :max="2" />
</template>
<!-- 操作列:商品行/库位行的商品 → 上报;**无商品的库位行 → 标记为空** -->
<template #column-actions="{ row }">
<el-button
v-if="isReportableRow(row)"
link
type="primary"
size="small"
@click="openReportDialog(row)"
>
上报
</el-button>
<el-button
v-else-if="canMarkEmpty(row)"
link
type="warning"
size="small"
:loading="markingEmptyId === Number(row.item?.id)"
@click="handleMarkEmpty(row)"
>
标记为空
</el-button>
<span v-else class="hint-text">—</span>
</template>
<template #empty>
<div class="empty-tip">{{ emptyText }}</div>
</template>
</upper-table>
</div>
<!-- 上报弹窗(stock.check.report,支持「未匹配条码」→ 未知商品) -->
<CheckReportDialog
v-model:visible="reportDialogVisible"
:task-id="taskId"
:detail="reportTarget?.item ?? null"
:stock="reportTarget?.stock ?? null"
:location="reportTarget?.location ?? ''"
:space-id="reportTarget?.spaceId ?? null"
:default-quantity="reportTarget?.quantity ?? null"
@success="handleReportSuccess"
/>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getStatusTextClass } from '@/views/order/orderManagement/config/order-common-config'
import { formatTime, isCheckApiSuccess, isLocationScopeType, translate } from '../template-config'
import UpperTable from '@/components/UpperTable/index.vue'
import RecordImages from './RecordImages.vue'
import CheckReportDialog from './CheckReportDialog.vue'
import {
stockCheckFinish,
stockCheckMarkEmpty,
stockCheckReport,
stockCheckResult,
type StockCheckReportParams
} from '@/api/stock.check/stock.check'
defineOptions({ name: 'CheckItemsPanel' })
const props = defineProps<{
/** 当前选中的盘点单(列表行数据,含 id/status/mode 等) */
row: Record<string, any> | null
}>()
const emit = defineEmits<{
/** 点击「添加商品 / 添加库位」→ 宿主打开 CheckStockPickerDialog */
(e: 'add-items'): void
/** 点击「导出明细」→ 宿主提交 stock.check.exportDetail 导出任务(仅 completed 任务显示) */
(e: 'export-detail'): void
/** 明细发生变化(加商品 / 上报 / 完成)→ 宿主刷新列表 */
(e: 'changed'): void
}>()
// ============================================================
// 状态判定
// ============================================================
const taskId = computed(() => Number(props.row?.id) || 0)
const taskStatus = computed(() => String(props.row?.status ?? ''))
/**
* created/rejected:可添加明细
* - 商品类:addDetail 传 stock_ids
* - 库位类:勾选库位走 addLocationDetail(location_ids)/ 手填编码走 addDetail(locations)
*/
const canAddItems = computed(() => ['created', 'rejected'].includes(taskStatus.value))
/** approved/checking:可上报实盘、可完成 */
const canReport = computed(() => ['approved', 'checking'].includes(taskStatus.value))
/** completed:可导出盘点明细(stock.check.exportDetail) */
const isCompleted = computed(() => taskStatus.value === 'completed')
/** 库位类任务(type=all/location):明细为「库位行」,上报需带 stock_id → 在展开行里按商品上报 */
const isLocationTask = computed(() => isLocationScopeType(props.row?.type))
/** 盲盘:账面数量前端不可见 */
const isBlind = computed(() => String(props.row?.mode ?? '') === 'blind')
const isQuantityMasked = computed(
() => isBlind.value && !['completed', 'cancelled'].includes(taskStatus.value)
)
// ============================================================
// 明细数据
// ============================================================
const items = ref<Record<string, any>[]>([])
const loading = ref(false)
const reporting = ref(false)
const reportingId = ref<number | null>(null)
const finishing = ref(false)
const stats = reactive({ total: 0, checked: 0, diff: 0 })
/** 商品行实盘数量输入(明细ID → 数量) */
const quantityMap = reactive<Record<string, number | undefined>>({})
/** 库位行实盘数量输入(`明细ID:stockID` → 数量) */
const stockQuantityMap = reactive<Record<string, number | undefined>>({})
/** 商品行库位输入(明细ID → 库位编码) */
const locationMap = reactive<Record<string, string>>({})
/** 明细类型文案(scope_type:goods=商品 / location=库位;接口未返回时按任务类型兜底) */
function itemScopeLabel(item: Record<string, any>): string {
const scope = item?.scope_type
if (scope !== undefined && scope !== null && scope !== '') return translate('scope_type', scope)
return isLocationTask.value ? '库位' : '商品'
}
/** 库位行内商品的数量输入 key */
function stockKey(detailId: unknown, stockId: unknown): string {
return `${detailId}:${stockId}`
}
/** 库位行内的商品聚合(无 stocks 时返回空数组) */
function rowStocks(item: Record<string, any>): Record<string, any>[] {
return Array.isArray(item?.stocks) ? item.stocks : []
}
/**
* 行内未知商品聚合(result 的 unknown_items:stock_id 为空、按条码归组)
*
* 口径:无账面数量,差异 = 实盘 - 0(实盘 >0 即盘盈),已计入行级 checked_quantity/diff_quantity。
* 商品行与库位行都可能有。
*/
function rowUnknowns(item: Record<string, any>): Record<string, any>[] {
return Array.isArray(item?.unknown_items) ? item.unknown_items : []
}
/**
* 平铺行对应的作业图片(result 的 records[].images)
*
* - 库位行的商品行:该明细下同 stock_id 的记录
* - 未知商品行:同条码且 stock_id 为空的记录
* - 商品行:该明细全部记录
*/
function rowImages(row: Record<string, any>): any[] {
const records: Record<string, any>[] = Array.isArray(row?.item?.records) ? row.item.records : []
let matched = records
if (row?.stock) {
matched = records.filter((r) => Number(r?.stock_id) === Number(row.stock?.stock_id))
} else if (row?.unknown) {
const barcode = String(row.unknown?.barcode ?? '')
matched = records.filter(
(r) => (r?.stock_id === null || r?.stock_id === undefined) && String(r?.barcode ?? '') === barcode
)
}
return matched.flatMap((r) => (Array.isArray(r?.images) ? r.images : []))
}
/**
* 平铺行(表格数据源)
*
* - 商品行(scope_type=goods):一行一个明细,商品快照取自明细自身
* - 库位行(scope_type=location):将行内商品(result 的 stocks[])平铺为多行,
* 一行一个商品,商品快照/账面数量/已盘/差异取商品(stock)的值;
* 无商品时保留库位行本身(商品列显示 —,不可上报)
* - 未知商品(result 的 unknown_items)**仅库位类任务平铺为独立行**:
* 该行级合计不单独展示(库位类只展示 stocks 明细),所以平铺不会重复;
* 商品类行级聚合(checked_quantity 等)已含未知商品,故不额外平铺,
* 改为在商品名称列提示「含未知商品 N 项」,避免合计重复展示
* 每行带 `flat_key`(行 key)与 `item`(明细行,上报/库位等仍以明细为准)
*/
const flatRows = computed<Record<string, any>[]>(() => {
const list: Record<string, any>[] = []
for (const item of items.value) {
const detailId = Number(item.id) || 0
const unknowns = rowUnknowns(item)
if (!isLocationTask.value) {
list.push({ ...item, flat_key: `d${detailId}`, detail_id: detailId, item, unknown_count: unknowns.length })
continue
}
const stocks = rowStocks(item)
if (!stocks.length) {
list.push({ ...item, flat_key: `d${detailId}`, detail_id: detailId, item })
} else {
for (const stock of stocks) {
list.push({
...item,
flat_key: `d${detailId}:s${stock.stock_id}`,
detail_id: detailId,
item,
stock,
item_code: stock.item_code ?? null,
item_name: stock.item_name ?? null,
spec: stock.spec ?? null,
batch_no: stock.batch_no ?? null,
system_quantity: stock.system_quantity ?? null,
checked_quantity: stock.checked_quantity ?? null,
diff_quantity: stock.diff_quantity ?? null
})
}
}
// 未知商品行(无账面,差异 = 实盘 - 0 = 盘盈)
for (const unknown of unknowns) {
const quantity = unknown?.checked_quantity ?? null
list.push({
...item,
flat_key: `d${detailId}:u${unknown?.barcode ?? ''}`,
detail_id: detailId,
item,
unknown,
is_unknown: true,
item_code: unknown?.barcode ?? null,
item_name: unknown?.item_name ?? unknown?.barcode ?? null,
spec: null,
batch_no: null,
system_quantity: 0,
checked_quantity: quantity,
diff_quantity: quantity,
status: 'checked'
})
}
}
return list
})
/** 本次上报目标:商品行只带明细;库位行还需带 stock_id */
type ReportTarget = { item: Record<string, any>; stock?: Record<string, any> }
const emptyText = computed(() =>
canAddItems.value
? `暂无盘点明细,可点击「${isLocationTask.value ? '添加库位' : '添加商品'}」生成明细`
: '暂无盘点明细'
)
/** 表格勾选行(UpperTable selection-change) */
const selectedRows = ref<Record<string, any>[]>([])
/** 已勾选且可上报的行(库位行按明细+商品 / 商品行按明细) */
const selectedReportTargets = computed<ReportTarget[]>(() =>
selectedRows.value
.filter((row) => isReportableRow(row))
.map((row) => (row.stock ? { item: row.item, stock: row.stock } : { item: row.item }))
)
// ============================================================
// 表格列配置 / 分页
// ============================================================
const tableRef = ref<any>(null)
const tableHostRef = ref<HTMLElement | null>(null)
const page = ref(1)
const pageSize = ref(20)
/** 表格列(与上方 slot 名对应,库位类任务隐藏商品快照列) */
const tableColumns = computed<Record<string, any>[]>(() => {
const cols: Record<string, any>[] = [
{ prop: 'scope_label', label: '明细类型', width: 90, align: 'center' },
]
if (!isLocationTask.value) {
cols.push(
{ prop: 'item_code', label: '商品编码', minWidth: 130, showOverflowTooltip: true },
{ prop: 'item_name', label: '商品名称', minWidth: 160, showOverflowTooltip: true },
{ prop: 'spec', label: '规格', minWidth: 110, showOverflowTooltip: true },
{ prop: 'batch_no', label: '批次号', minWidth: 110, showOverflowTooltip: true },
{ prop: 'location', label: '库位', minWidth: 130, showOverflowTooltip: true },
)
} else {
cols.push(
{ prop: 'location', label: '库位', minWidth: 130, showOverflowTooltip: true },
{ prop: 'item_display', label: '商品 / 条码', minWidth: 180, showOverflowTooltip: true },
)
}
if (!isLocationTask.value) {
cols.push(
{ prop: 'system_quantity', label: '账面数量', width: 100, align: 'center' },
{ prop: 'row_quantity', label: '本库位数量', width: 140, align: 'center' },
)
}
cols.push(
{ prop: 'checked_quantity', label: '已盘合计', width: 100, align: 'center' },
{ prop: 'diff_quantity', label: '差异', width: 90, align: 'center' },
{ prop: 'status', label: '盘点状态', width: 100, align: 'center' },
{ prop: 'checkers', label: '盘点人', width: 110, showOverflowTooltip: true },
{ prop: 'last_checked_at', label: '最近上报', width: 160 },
{ prop: 'images', label: '作业图片', width: 110, align: 'center' },
{ prop: 'actions', label: '操作', width: 110, align: 'center', fixed: 'right' },
)
return cols
})
const pagination = computed(() => ({
currentPage: page.value,
pageSize: pageSize.value,
total: flatRows.value.length
}))
const pagedRows = computed(() => {
const start = (page.value - 1) * pageSize.value
return flatRows.value.slice(start, start + pageSize.value)
})
/**
* 平铺后按明细合并「明细类型 / 库位」单元格(仅库位类任务、仅当前页内)
* 首个同明细行返回 [跨行数, 1],其余返回 [0, 0](不渲染)
*/
function spanMethod({ rowIndex, column }: any): number[] | undefined {
if (!isLocationTask.value) return undefined
const label = String(column?.label ?? '')
if (label !== '明细类型' && label !== '库位') return undefined
const rows = pagedRows.value
const row = rows[rowIndex]
if (!row) return undefined
const prev = rows[rowIndex - 1]
if (prev && prev.detail_id === row.detail_id) return [0, 0]
let count = 1
for (let i = rowIndex + 1; i < rows.length; i += 1) {
if (rows[i]?.detail_id === row.detail_id) count += 1
else break
}
return [count, 1]
}
function handleSelectionChange(rows: Record<string, any>[]) {
selectedRows.value = rows
}
function handlePageChange(nextPage: number) {
page.value = nextPage
nextTick(() => tableRef.value?.getTableRef?.()?.setScrollTop?.(0))
}
function handlePageSizeChange(size: number) {
pageSize.value = size
page.value = 1
}
/** 该行是否可上报(库位行需有对应商品库存且非未知商品行;商品行直接可报) */
function isReportableRow(row: Record<string, any>): boolean {
if (!canReport.value) return false
// 未知商品行已是作业记录,不是盘点范围行
if (row?.is_unknown) return false
return isLocationTask.value ? Boolean(row?.stock) : true
}
/** 该行当前的实盘输入值(库位行按明细+商品,商品行按明细) */
function rowQuantity(row: Record<string, any>): number | undefined {
return row?.stock
? stockQuantityMap[stockKey(row.item.id, row.stock.stock_id)]
: quantityMap[String(row.item.id)]
}
function setRowQuantity(row: Record<string, any>, value: number | undefined) {
if (row?.stock) stockQuantityMap[stockKey(row.item.id, row.stock.stock_id)] = value
else quantityMap[String(row.item.id)] = value
}
function onRowQuantityChange(row: Record<string, any>, value: number | undefined | null) {
setRowQuantity(row, value === null ? undefined : value)
}
// ============================================================
// 加载明细
// ============================================================
async function loadItems() {
if (!taskId.value) {
items.value = []
return
}
loading.value = true
try {
// 统一走 result:stock.check.detail 已不再返回明细列表(只返回 check),
// 未开始作业阶段 result 也能正常返回「范围行」(已盘/差异为 null、状态=未盘)
const res: any = await stockCheckResult({ id: taskId.value })
if (!isCheckApiSuccess(res)) {
throw new Error(res?.message || '获取盘点明细失败')
}
const data = res.data ?? res
items.value = Array.isArray(data.rows) ? data.rows : []
const check = data.check ?? {}
stats.total = Number(check.total_items ?? items.value.length) || 0
stats.checked = Number(check.checked_items ?? 0) || 0
stats.diff = Number(check.diff_items ?? 0) || 0
resetInputs()
selectedRows.value = []
page.value = 1
} catch (e: any) {
console.error('[stockcheck] 加载盘点明细失败', e)
ElMessage.error(e?.message || '获取盘点明细失败')
items.value = []
} finally {
loading.value = false
}
}
/** 明细自身的库位编码快照(rows[].location_code;「无库位」分组为空) */
function ownLocationCode(item: Record<string, any>): string {
const code = item?.location_code
return code === null || code === undefined || String(code).trim() === '' ? '' : String(code)
}
/**
* 上报用的库位ID(`space_id`,**必传**)
*
* 2026-10-26 文档:report 的库位一律以 `space_id`(wms_location_space.id)为准,
* `location`(库位编码)降级为**仅做一致性校验**;缺失直接 400「缺少库位ID(space_id)」。
* 取值:明细行同义字段 `space_id` / `location_id`(两者同值)。
*/
function resolveReportSpaceId(item: Record<string, any> | null | undefined): number | null {
const raw = item?.space_id ?? item?.location_id
const id = Number(raw)
return Number.isFinite(id) && id > 0 ? id : null
}
/**
* 明细库位编码集合
*
* - 结果行(stock.check.result):取 location_codes,其次 locations 兜底
* - 未开始作业阶段的范围行(result 同样返回):无聚合字段,取明细自身 `location_code` 快照
* (否则库位列显示「—」)
* 「无库位」分组的空串/null 一律剔除。
*
* 2026-10-26:商品明细行已按「商品+库位」拆行(每条明细都绑定库位快照),
* 故**两类行都掺入自身 location_code**(原来只掺库位行 → 商品行库位列/上报库位不预填)。
*/
function resolveLocationCodes(item: Record<string, any>): string[] {
const raw = Array.isArray(item?.location_codes) && item.location_codes.length
? item.location_codes
: Array.isArray(item?.locations)
? item.locations.map((loc: any) => loc?.location_code)
: []
const codes = raw
.filter((code: unknown) => code !== null && code !== undefined && String(code).trim() !== '')
.map((code: any) => String(code))
const own = ownLocationCode(item)
if (own && !codes.includes(own)) codes.push(own)
return [...new Set(codes)]
}
/** 是否存在「无库位」分组的记录(该分组库中存空串,接口返回归一为 null) */
function hasBlankLocationRecord(item: Record<string, any>): boolean {
const raw: any[] = Array.isArray(item?.location_codes) && item.location_codes.length
? item.location_codes
: Array.isArray(item?.locations)
? item.locations.map((loc: any) => loc?.location_code)
: []
return raw.some((code) => code === null || code === undefined || String(code).trim() === '')
}
/** 库位列(只读态):多库位用、拼接;含无库位分组的记录时同时标出「无库位」 */
function formatLocationCodes(item: Record<string, any>): string {
const parts = resolveLocationCodes(item)
if (hasBlankLocationRecord(item)) parts.push('无库位')
if (parts.length) return parts.join('、')
return item?.checked_quantity === null || item?.checked_quantity === undefined ? '—' : '无库位'
}
/** 盘点人(checkers 数组去重拼接) */
function formatCheckers(item: Record<string, any>): string {
const list: string[] = Array.isArray(item?.checkers)
? [...new Set(item.checkers.filter(Boolean).map((c: any) => String(c)))]
: []
return list.length ? list.join('、') : '—'
}
/**
* 上报输入回填:商品行库位仅有 1 个时回填(便于覆盖上报);数量不预填
* (行上的 checked_quantity 是该明细全部作业记录的合计,不等于本次上报值)
*/
function resetInputs() {
for (const key of Object.keys(quantityMap)) delete quantityMap[key]
for (const key of Object.keys(stockQuantityMap)) delete stockQuantityMap[key]
for (const key of Object.keys(locationMap)) delete locationMap[key]
for (const item of items.value) {
const codes = resolveLocationCodes(item)
locationMap[String(item.id)] = codes.length === 1 ? (codes[0] ?? '') : ''
}
}
// ============================================================
// 上报实盘(stock.check.report)
// ============================================================
/** 取本次待上报的数量;非法返回 null */
function resolveQuantity(target: ReportTarget): number | null {
const raw = target.stock
? stockQuantityMap[stockKey(target.item.id, target.stock.stock_id)]
: quantityMap[String(target.item.id)]
if (raw === undefined || raw === null || (raw as any) === '') return null
const qty = Number(raw)
if (!Number.isFinite(qty) || qty < 0) return null
return Math.trunc(qty)
}
/**
* 上报一行;silent=true 时不弹单行成功提示(批量上报用)
* @returns 是否成功
*/
async function doReport(target: ReportTarget, silent = false): Promise<boolean> {
const { item, stock } = target
const quantity = resolveQuantity(target)
if (quantity === null) {
if (!silent) ElMessage.warning('请输入不小于 0 的实盘数量')
return false
}
// 库位ID(space_id)**必传**:服务端以它为准落库,缺失会 400「缺少库位ID(space_id)」
const spaceId = resolveReportSpaceId(item)
if (!spaceId) {
if (!silent) ElMessage.warning('该明细未绑定库位(缺少 space_id),无法上报')
return false
}
const payload: StockCheckReportParams = {
id: taskId.value,
detail_id: Number(item.id),
space_id: spaceId,
quantity
}
if (stock) {
// 库位行:stock_id 必填,库位以明细库位为准(location 仅做一致性校验)
payload.stock_id = Number(stock.stock_id)
const loc = ownLocationCode(item) || resolveLocationCodes(item)[0]
if (loc) payload.location = loc
} else {
// 商品行:stock_id 可选(传入必须与明细商品一致)
const stockId = Number(item.stock_id)
if (Number.isFinite(stockId) && stockId > 0) payload.stock_id = stockId
// 商品行库位以 space_id 为准,location 仅做一致性校验 → 仅在一致时下发
const location = String(locationMap[String(item.id)] ?? '').trim()
const own = ownLocationCode(item)
if (location && own && location !== own) {
if (!silent) {
ElMessage.warning(`库位编码「${location}」与明细库位「${own}」不一致,请按明细库位上报`)
}
return false
}
if (location) payload.location = location
}
reportingId.value = Number(item.id)
try {
const res: any = await stockCheckReport(payload)
if (!isCheckApiSuccess(res)) {
throw new Error(res?.message || '上报失败')
}
const data = res.data ?? res
// 覆盖式上报:进度/差异以接口返回为准,明细聚合字段稍后重新拉取
if (data.total_items !== undefined) stats.total = Number(data.total_items) || 0
if (data.checked_items !== undefined) stats.checked = Number(data.checked_items) || 0
if (data.diff_items !== undefined) stats.diff = Number(data.diff_items) || 0
if (!silent) ElMessage.success(String(data.mode ?? '') === 'updated' ? '已覆盖上报' : '上报成功')
return true
} catch (e: any) {
console.error('[stockcheck] 上报实盘失败', e)
if (!silent) ElMessage.error(e?.message || '上报失败')
return false
} finally {
reportingId.value = null
}
}
// ============================================================
// 行内上报弹窗(stock.check.report,支持「未匹配条码」→ 未知商品)
// ============================================================
const reportDialogVisible = ref(false)
/** 「标记为空」进行中的明细ID(按钮 loading) */
const markingEmptyId = ref<number | null>(null)
/** 弹窗目标快照(打开时定格,避免表格重渲染后引用漂移) */
const reportTarget = ref<{
item: Record<string, any>
stock: Record<string, any> | null
location: string
spaceId: number | null
quantity: number | null
} | null>(null)
/**
* 打开上报弹窗(行内「上报」)
*
* - 库位行:需带 stock_id + 明细库位,数量取该行已填值
* - 商品行:按明细商品上报,库位取行内填写值
* - 两者均可另填「未匹配条码」,由后端按条码解析(命中=已知商品 / 未命中=未知商品)
*/
function openReportDialog(row: Record<string, any>) {
const item = row?.item
if (!item) return
const spaceId = resolveReportSpaceId(item)
if (!spaceId) {
ElMessage.warning('该明细未绑定库位(缺少 space_id),无法上报')
return
}
const stock = row?.stock ?? null
const location = stock
? (ownLocationCode(item) || resolveLocationCodes(item)[0] || '')
: String(locationMap[String(item.id)] ?? '').trim()
const rawQuantity = stock
? stockQuantityMap[stockKey(item.id, stock.stock_id)]
: quantityMap[String(item.id)]
const quantity =
rawQuantity === undefined || rawQuantity === null || (rawQuantity as any) === ''
? null
: Number(rawQuantity)
reportTarget.value = {
item,
stock,
location,
spaceId,
quantity: Number.isFinite(Number(quantity)) ? Number(quantity) : null
}
reportDialogVisible.value = true
}
/** 上报成功:覆盖式上报可能更新已有记录,明细聚合字段需重拉 */
async function handleReportSuccess() {
// 不复位 reportTarget:弹窗关闭动画期间保留内容,下次打开会整体覆盖
await loadItems()
emit('changed')
}
// ============================================================
// 标记库位为空(stock.check.markEmpty,库位盘点专用)
// ============================================================
/**
* 该行是否可「标记为空」
*
* 仅库位类任务 + 可上报状态(approved/checking),且该行是**没有商品记录的库位明细行**
* (有商品/未知商品的行走「上报」);已标记为空的不重复提供。
*/
function canMarkEmpty(row: Record<string, any>): boolean {
if (!canReport.value || !isLocationTask.value) return false
if (row?.is_unknown || row?.stock) return false
if (row?.item?.is_empty) return false
const scope = row?.item?.scope_type
return scope === undefined || scope === null || scope === '' || scope === 'location'
}
/**
* 标记库位为空(stock.check.markEmpty)
*
* 等价于 report(is_empty=true):写空标记记录(quantity=0、is_empty=1),并**清除该库位下的商品记录**;
* 空标记计入已盘;库位账面有库存时计入盘亏差异。
*/
async function handleMarkEmpty(row: Record<string, any>) {
const detailId = Number(row?.item?.id)
if (!taskId.value || !Number.isFinite(detailId) || detailId <= 0) return
const location = formatLocationCodes(row?.item ?? row)
try {
await ElMessageBox.confirm(
`确认库位「${location}」为空?\n标记后该库位下的商品记录将被清除;若库位账面还有库存,会按盘亏计入差异。`,
'标记库位为空',
{ confirmButtonText: '确认标记', cancelButtonText: '取消', type: 'warning', buttonSize: 'small' }
)
} catch {
return
}
markingEmptyId.value = detailId
try {
const res: any = await stockCheckMarkEmpty({ id: taskId.value, detail_id: detailId })
if (!isCheckApiSuccess(res)) {
throw new Error(res?.message || '标记库位为空失败')
}
ElMessage.success('已将库位标记为空')
// 主表进度/差异由后端重算 → 重拉明细 + 通知宿主刷新列表
await loadItems()
emit('changed')
} catch (e: any) {
console.error('[stockcheck] 标记库位为空失败', e)
ElMessage.error(e?.message || '标记库位为空失败')
} finally {
markingEmptyId.value = null
}
}
/**
* 批量上报:上报表格中**勾选**的行(逐行串行提交,避免并发写同一盘点单)。
* 已勾选但未填写实盘数量的行会被跳过并提示。
*/
async function reportSelected() {
const targets = [...selectedReportTargets.value]
if (!targets.length) {
ElMessage.warning('请先勾选要上报的盘点明细')
return
}
const ready = targets.filter(
(target) => resolveQuantity(target) !== null && resolveReportSpaceId(target.item) !== null
)
if (!ready.length) {
ElMessage.warning('请先填写已勾选明细的实盘数量(且明细需绑定库位)')
return
}
if (ready.length < targets.length) {
ElMessage.warning(
`已勾选 ${targets.length} 行,其中 ${targets.length - ready.length} 行未填写实盘数量或缺库位ID,将跳过`
)
}
reporting.value = true
let success = 0
let failed = 0
try {
for (const target of ready) {
const ok = await doReport(target, true)
if (ok) success += 1
else failed += 1
}
} finally {
reporting.value = false
}
if (failed === 0) {
ElMessage.success(`已上报 ${success} 项`)
} else {
ElMessage.warning(`上报完成:成功 ${success} 项,失败 ${failed} 项`)
}
// 重新拉取明细(聚合字段由后端按作业记录重算)
await loadItems()
emit('changed')
}
// ============================================================
// 完成盘点(stock.check.finish)
// ============================================================
async function finishCheck() {
try {
await ElMessageBox.confirm(
'完成后不再允许修改盘点记录;未盘商品明细将按实盘 0 处理(计入盘亏与差异行数),未盘库位明细不计差异。确定完成?',
'完成盘点',
{ confirmButtonText: '确定完成', cancelButtonText: '取消', type: 'warning', buttonSize: 'small' }
)
} catch {
return
}
finishing.value = true
try {
const res: any = await stockCheckFinish({ id: taskId.value })
if (!isCheckApiSuccess(res)) {
throw new Error(res?.message || '完成盘点失败')
}
const data = res.data ?? res
const profit = Number(data.profit_total ?? 0)
const loss = Number(data.loss_total ?? 0)
const unchecked = Number(data.unchecked_items ?? 0)
ElMessage.success(
`盘点已完成(盘盈 ${profit} / 盘亏 ${loss}${unchecked > 0 ? `;未盘 ${unchecked} 项按 0 处理` : ''})`
)
await loadItems()
emit('changed')
} catch (e: any) {
console.error('[stockcheck] 完成盘点失败', e)
ElMessage.error(e?.message || '完成盘点失败')
} finally {
finishing.value = false
}
}
// ============================================================
// 单元格渲染辅助
// ============================================================
function maskQuantity(value: any) {
if (isQuantityMasked.value) return '***'
return value === undefined || value === null || value === '' ? '—' : value
}
function formatDiff(value: any) {
if (value === undefined || value === null || value === '') return '—'
const n = Number(value)
if (!Number.isFinite(n)) return String(value)
return n > 0 ? `+${n}` : String(n)
}
function diffClass(value: any) {
const n = Number(value)
if (!Number.isFinite(n) || n === 0) return 'diff-text'
return n > 0 ? 'diff-text diff-text--profit' : 'diff-text diff-text--loss'
}
function itemStatusTag(status: any) {
return String(status ?? '') === 'checked' ? 'success' : 'info'
}
// ============================================================
// 联动:切换盘点单 / 主表状态变化时重新拉取
// ============================================================
watch(
() => [props.row?.id, props.row?.status],
() => {
void loadItems()
},
{ immediate: true }
)
</script>
<style lang="scss" scoped>
/* ut-status-text 系列状态文字颜色类定义在 order-sub.scss 里(scoped 样式需要本组件自行引入) */
@use "../../../../order/orderManagement/styles/order-sub.scss";
.check-items-panel {
width: 100%;
height: 100%;
padding: 6px 10px 8px;
box-sizing: border-box;
background: #fff;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* 按钮行:Element Plus 默认 .el-button + .el-button 会与 gap 叠加,必须清零 */
.header-actions {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 5px;
flex-shrink: 0;
.left-actions,
.right-actions {
display: flex;
align-items: center;
gap: 6px;
}
.left-actions {
:deep(.el-button) {
margin-left: 0;
margin-right: 0;
}
/* 动作类按钮(含「批量上报」)禁用:白底 + 蓝边 + 蓝字(对齐 storage/receiving「批量审核」) */
:deep(.el-button--primary.is-plain.is-disabled),
:deep(.el-button--primary.is-plain.is-disabled:hover),
:deep(.el-button--primary.is-plain.is-disabled:focus),
:deep(.el-button--primary.is-plain.is-disabled:active) {
color: #409eff;
background-color: #fff;
border-color: #409eff;
}
}
}
.stat-text {
font-size: 12px;
color: #909399;
}
.hint-text {
font-size: 12px;
color: #c0c4cc;
}
/* 未知商品标记(result 的 unknown_items:条码匹配不到系统商品) */
.unknown-tag {
margin-right: 4px;
}
.table-host {
flex: 1;
min-height: 120px;
min-width: 0;
overflow: hidden;
.quantity-input {
width: 110px;
}
}
/* 库位行内的商品已平铺到主表,无需展开区样式 */
.diff-text {
color: #606266;
&--profit {
color: #67c23a;
}
&--loss {
color: #f56c6c;
}
}
.empty-tip {
font-size: 13px;
color: #909399;
}
</style>