WEB/src/views/storage/entry/index.vue
2026-09-08 18:04:27 +08:00

1283 lines
41 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

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

<template>
<div class="order-sub-container" :style="{ height: containerHeight }">
<scan-box
ref="scanBox"
cache-key="storage-entry"
width="220px"
:tree-props="{ children: 'children', label: 'label' }"
:auto-submit="false"
:initial-conditions="initialConditions"
:preset-tree="presetTree"
:available-fields="availableFieldsRef"
@condition-change="handleConditionChange"
@reset="handleConditionReset"
@condition-clear="handleConditionClear"
/>
<div class="main-content">
<div class="toolbar">
<div class="toolbar-left">
<order-toolbar-button-group
:buttons="entryToolbarButtons"
:resolve-disabled="resolveButtonDisabled"
:resolve-loading="resolveButtonLoading"
:resolve-label="resolveButtonLabel"
:layout-key="toolbarLayoutKey"
@action="handleToolbarButtonClick"
/>
</div>
</div>
<div class="split-stack" ref="splitStackRef">
<div class="upper-wrapper" :style="detailVisible ? upperPaneStyle : upperPaneFullStyle">
<upper-table
ref="upperTable"
title="入库单列表"
default-align="center"
table-id="storage-entry-list"
:enable-column-config="true"
:column-config-schema-version="2"
:data="list"
:columns="columns"
:table-size="tableSize"
:pagination="pagination"
:show-index="true"
:show-selection="true"
:loading="loading"
:queryTime="queryTime"
@current-change="handleRowClick"
@sort-change="handleSortChange"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
@refresh="loadData"
@selection-change="onSelectionChange"
>
<template #column-order_status="{ row }">
<span :class="getStatusTextClass(getEntryOrderStatusTagType(row.order_status))">
{{ formatEntryOrderStatus(row.order_status) }}
</span>
</template>
<template #column-hasReceiving="{ row }">
<span
:class="[getStatusTextClass(getEntryHasReceivingTagType(row.hasReceiving, row)), { 'clickable-tag': resolveEntryHasReceiving(row) }]"
@click.stop="openReceivingBindingsDialog(row)"
>
{{ formatEntryHasReceiving(row.hasReceiving, row) }}
</span>
</template>
<template #column-receivingBindings="{ row }">
<span
class="receiving-bindings-cell"
:title="'点击复制收货单号\n' + formatReceivingBindingsSummary(row.receivingBindings)"
@click.stop="copyReceivingBindings(row)"
>
{{ formatReceivingBindingsSummary(row.receivingBindings) }}
</span>
</template>
<template #column-order_type="{ row }">
<span>{{ translateEntryField('order_type', row.order_type) }}</span>
</template>
<template #column-sync_status="{ row }">
<span :class="getStatusTextClass(getSyncStatusType(row.sync_status))">
{{ translateEntryField('sync_status', row.sync_status) }}
</span>
</template>
<template #column-sync_message="{ row }">
<el-tooltip
:content="syncMessageFullText(row)"
placement="top"
:disabled="!syncMessageFullText(row)"
:show-after="400"
>
<span
class="sync-message-cell"
:class="syncMessageCellClass(row)"
role="button"
tabindex="0"
@click.stop="copySyncMessage(row)"
@keydown.enter.prevent="copySyncMessage(row)"
>
{{ syncMessageCellText(row) }}
</span>
</el-tooltip>
</template>
<template #column-order_create_time="{ row }">
{{ formatTime(row.order_create_time) }}
</template>
<template #column-expect_start_time="{ row }">
{{ formatTime(row.expect_start_time) }}
</template>
<template #column-expect_end_time="{ row }">
{{ formatTime(row.expect_end_time) }}
</template>
<template #column-source_type="{ row }">
<span :class="getStatusTextClass(row.source_type === 'WMS' ? 'info' : row.source_type === 'QM' ? 'warning' : 'success')">
{{ translateEntryField('source_type', row.source_type) }}
</span>
</template>
<template #column-row_action="{ row }">
<el-button
v-if="canStartReceiving(row.order_status, row.hasReceiving, row.receivingBindings)"
link
type="warning"
size="small"
@click.stop="handleReviewEntry(row)"
>
推送到仓库
</el-button>
<el-button
v-if="canQuickInbound(row.order_status, row.hasReceiving, row.receivingBindings)"
link
type="success"
size="small"
@click.stop="handleRowQuickInbound(row)"
>
一键上架
</el-button>
<el-button
v-if="canBindEntryOrder(row.order_status)"
link
type="primary"
size="small"
@click.stop="openBindDialog(row)"
>
绑定
</el-button>
<el-button
v-if="canUnbindEntryOrder(row)"
link
type="danger"
size="small"
@click.stop="openUnbindDialog(row)"
>
解绑
</el-button>
</template>
<template #empty>
<div class="empty-tip">暂无入库单</div>
</template>
</upper-table>
</div>
<template v-if="detailVisible">
<div
class="pane-resizer"
title="拖动调整列表与详情区域高度"
@mousedown="beginSplitDrag"
/>
<div v-if="selectedEntryId" class="lower-level" :class="tableSize" :style="lowerPaneStyle">
<div class="detail-header">
<el-tabs v-model="activeTab" class="detail-tab">
<!-- <el-tab-pane label="收货对照" name="operate" /> -->
<el-tab-pane label="入库明细" name="details" />
<el-tab-pane label="绑定关系" name="bindingRelations" />
<!-- <el-tab-pane label="入库记录" name="directInboundLogs" /> -->
<el-tab-pane label="操作日志" name="logs" />
</el-tabs>
</div>
<div class="detail-container">
<KeepAlive>
<component
:is="activeComponent"
ref="detailComponentRef"
:id="selectedEntryId"
:row="selectedRow"
:entry-detail-refresh-tick="entryDetailRefreshTick"
@refresh="handleDetailRefresh"
/>
</KeepAlive>
</div>
</div>
<div v-else class="no-selection" :style="lowerPaneStyle">
<div class="empty-tip">
<p>请从上方列表中选择一项查看详情</p>
</div>
</div>
</template>
</div>
</div>
<BindReceivingToEntryDialog
v-model="bindDialogVisible"
:row="bindTargetRow"
@closed="handleBindDialogClosed"
@success="handleBindDialogSuccess"
/>
<UnbindReceivingToEntryDialog
v-model="unbindDialogVisible"
:row="unbindTargetRow"
@closed="handleUnbindDialogClosed"
@success="handleUnbindDialogSuccess"
/>
<!-- 收货绑定详情弹窗 -->
<ReceivingBindingDetailDialog
v-model:visible="receivingBindingsDialogVisible"
:receiving-bindings="receivingBindingsDialogData"
/>
<!-- 新建入库单对话框 -->
<el-dialog
v-model="createDialogVisible"
title="新建入库单"
width="600px"
align-center
@closed="handleCreateDialogClosed"
>
<el-form :model="createForm" label-width="100px" size="small">
<el-row :gutter="20">
<el-col v-for="field in addEntryFieldsRef" :key="field.prop" :span="field.type === 'textarea' ? 24 : 12">
<el-form-item :label="field.label">
<el-select v-if="field.type === 'select'" v-model="createForm[field.prop]" :placeholder="'请选择' + field.label" style="width: 100%" filterable>
<el-option v-for="opt in field.options" :key="opt.value" :label="opt.label" :value="opt.value" />
</el-select>
<el-input v-else-if="field.type === 'textarea'" v-model="createForm[field.prop]" type="textarea" :rows="3" :placeholder="'请输入' + field.label" />
<el-input v-else v-model="createForm[field.prop]" :placeholder="'请输入' + field.label" />
</el-form-item>
</el-col>
</el-row>
</el-form>
<template #footer>
<el-button size="small" @click="createDialogVisible = false">取消</el-button>
<el-button size="small" type="primary" :loading="createLoading" @click="submitCreateEntry">确定</el-button>
</template>
</el-dialog>
<!-- 开始入库确认对话框 -->
<el-dialog
v-model="reviewDialogVisible"
title="开始入库确认"
width="800px"
align-center
@closed="handleReviewDialogClosed"
>
<div v-if="reviewTargetRow" class="review-dialog-content">
<div class="review-summary">
<el-descriptions :column="2" size="small" border>
<el-descriptions-item label="入库单号">{{ reviewTargetRow.entry_order_code || '--' }}</el-descriptions-item>
<el-descriptions-item label="货主">{{ reviewTargetRow.store_name || '--' }}</el-descriptions-item>
<el-descriptions-item label="订单状态">
<el-tag size="small" :type="getEntryOrderStatusTagType(reviewTargetRow.order_status)">
{{ formatEntryOrderStatus(reviewTargetRow.order_status) }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="入库类型">{{ translateEntryField('order_type', reviewTargetRow.order_type) }}</el-descriptions-item>
</el-descriptions>
</div>
<div class="review-binding-section">
<div class="review-section-title">收货对照预览</div>
<el-table
v-loading="reviewCompareLoading"
:data="reviewCompareRows"
border
stripe
size="small"
row-key="rowKey"
empty-text="暂无对照数据"
max-height="360"
>
<el-table-column label="匹配" width="80" align="center">
<template #default="{ row }">
<el-tag size="small" :type="row.matchTagType">{{ row.matchStatusLabel }}</el-tag>
</template>
</el-table-column>
<el-table-column label="入库商品" min-width="150" show-overflow-tooltip>
<template #default="{ row }">{{ row.entryName }}</template>
</el-table-column>
<el-table-column label="收货商品" min-width="150" show-overflow-tooltip>
<template #default="{ row }">{{ row.receivingName }}</template>
</el-table-column>
<el-table-column label="计划数量" width="100" align="right">
<template #default="{ row }">{{ row.entryQty }}</template>
</el-table-column>
<el-table-column label="收货可用" width="100" align="right">
<template #default="{ row }">{{ row.receivingAvailable }}</template>
</el-table-column>
</el-table>
</div>
</div>
<template #footer>
<el-button size="small" :disabled="reviewSubmitting" @click="reviewDialogVisible = false">取消</el-button>
<el-button
size="small"
type="warning"
:loading="reviewSubmitting"
@click="handleReviewConfirm"
>
确定开始入库
</el-button>
</template>
</el-dialog>
<!-- 打印对话框 -->
<BatchReceivingPrintDialog
v-model="printDialogVisible"
:selection-rows="selectionRows"
business-type="ENTRY_ORDER"
dialog-title="打印入库单"
:queue-no-field="'entry_order_code'"
document-label="入库单"
:fetch-print-data="fetchEntryPrintData"
:business-type-options="[{ label: '入库单 (ENTRY_ORDER)', value: 'ENTRY_ORDER' }]"
/>
<AsyncExportProgressDialog
v-model:visible="exportDialogVisible"
title="入库单导出进度"
:loading="exportLoading"
:progress-percent="exportProgressPercent"
:progress-status="exportProgressStatus"
:status-label="exportStatusLabel"
:task-id="exportTaskProgress.taskId"
:message="exportTaskProgress.message"
:error="exportTaskProgress.error"
:update-time="exportTaskProgress.updateTime"
/>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
import type { ToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
import { getStatusTextClass } from '@/views/order/orderManagement/config/order-common-config'
import { safeInvoke } from '@/utils/safe-invoke'
import * as indexApi from '@/api/index/index'
import * as entryApi from '@/api/storage.entry/entry'
import type { StorageEntryListParams } from '@/api/storage.entry/entry'
import {
availableFields,
entryColums,
addEntryFields,
entryToolbarButtons,
formatEntryOrderStatus,
getEntryOrderStatusTagType,
isPendingEntryOrderStatus,
canQuickInbound,
canBindEntryOrder,
canUnbindEntryOrder,
canStartReceiving,
finalizeEntryListWhere,
formatEntryHasReceiving,
formatReceivingBindingsSummary,
getEntryHasReceivingTagType,
resolveEntryHasReceiving,
translateEntryField,
buildEntryPrintFormData
} from './entry-config'
import entrydetail from './component/entrydetail.vue'
import log from './component/log.vue'
import entryoperate from './component/entryoperate.vue'
import BindReceivingToEntryDialog from './component/BindReceivingToEntryDialog.vue'
import UnbindReceivingToEntryDialog from './component/UnbindReceivingToEntryDialog.vue'
import ReceivingBindingDetailDialog from './component/ReceivingBindingDetailDialog.vue'
import DirectInboundLogs from './component/DirectInboundLogs.vue'
import EntryBindingRelations from './component/EntryBindingRelations.vue'
import BatchReceivingPrintDialog from '@/components/BatchReceivingPrintDialog.vue'
import AsyncExportProgressDialog from '@/components/AsyncExportProgressDialog.vue'
import { useAsyncExportTask } from '@/composables/useAsyncExportTask'
import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane'
import { useSettingsStore } from '@/stores/modules/settings'
const settingsStore = useSettingsStore()
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
const containerHeight = computed(() =>
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
)
const scanBox = ref<any>(null)
const upperTable = ref<any>(null)
const detailComponentRef = ref<{ openBatchImportDialog?: () => void; reloadAll?: () => Promise<void> } | null>(null)
const entryDetailRefreshTick = ref(0)
const {
splitStackRef,
beginSplitDrag,
lowerPaneStyle,
upperPaneStyle
} = useVerticalSplitPane({ defaultLowerPercent: 40 })
const upperPaneFullStyle = computed(() => ({
flex: '1 1 auto',
minHeight: '0',
overflow: 'hidden'
}))
const detailVisible = ref(true)
function toggleDetailVisible() {
detailVisible.value = !detailVisible.value
}
function openReceivingCompareTab() {
if (!selectedEntryId.value) {
ElMessage.warning('请先在列表中选择一个入库单')
return
}
detailVisible.value = true
activeTab.value = 'operate'
}
function openColumnConfigPanel() {
upperTable.value?.openColumnConfig?.()
}
const route = useRoute()
// 用于将初始条件传入 ScanBox(用于根据 URL 参数填充)
const initialConditions = ref<any>(null)
// 当前已规范化的 where 条件(优先使用)
const currentCondition = ref<any>(null)
const currentConditionRaw = ref<any>(null)
const presetTree = ref<any[]>([])
const availableFieldsRef = reactive(JSON.parse(JSON.stringify(availableFields)))
const addEntryFieldsRef = reactive(JSON.parse(JSON.stringify(addEntryFields)))
const activeTab = ref('details')
const list = ref<any[]>([])
const loading = ref(false)
const queryTime = ref(0)
const {
exportLoading,
exportDialogVisible,
exportTaskProgress,
exportProgressPercent,
exportProgressStatus,
exportStatusLabel,
submitExportTask
} = useAsyncExportTask({
storageKey: 'storage:entry:exportTaskId',
submitExport: (payload) => entryApi.entryExport(payload as any),
queryProgress: (params) => entryApi.entryExportTaskProgress(params)
})
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
const tableSize = ref('small')
const columns = ref(entryColums)
const selectionRows = ref<any[]>([])
const hasSelection = ref(false)
const selectedEntryId = ref<number | string | null>(null)
// ── 工具栏状态 ──
const buttonLoadingMap = computed(() => ({
loading: loading.value,
exportLoading: exportLoading.value
}))
const buttonDisabledMap = computed(() => ({
hasNoSelection: !hasSelection.value
}))
const buttonLabelMap = computed(() => ({
detailToggleLabel: detailVisible.value ? '隐藏详情' : '显示详情'
}))
const toolbarLayoutKey = computed(() =>
JSON.stringify({
loading: buttonLoadingMap.value,
disabled: buttonDisabledMap.value,
labels: buttonLabelMap.value
})
)
function resolveButtonLoading(loadingKey?: string) {
if (!loadingKey) return false
return Boolean((buttonLoadingMap.value as Record<string, boolean>)[loadingKey])
}
function resolveButtonDisabled(disabledKey?: string) {
if (!disabledKey) return false
return Boolean((buttonDisabledMap.value as Record<string, boolean>)[disabledKey])
}
function resolveButtonLabel(defaultLabel: string, dynamicLabelKey?: string) {
if (!dynamicLabelKey) return defaultLabel
return (buttonLabelMap.value as Record<string, string>)[dynamicLabelKey] || defaultLabel
}
const toolbarActionMap: Record<string, () => void> = {
loadData: () => { void loadData() },
handleExportAll: () => { void handleExportAll() },
handleExportSelected: () => { void handleExportSelected() },
openColumnConfigPanel: () => openColumnConfigPanel(),
toggleDetailVisible: () => toggleDetailVisible(),
handleImport: () => handleImport(),
handleOpenPrintDialog: () => { void handleOpenPrintDialog() },
confirmBatchCancel: () => { void confirmBatchCancel() }
}
function handleToolbarButtonClick(action: ToolbarButtonConfig['action']) {
const handler = toolbarActionMap[action]
if (!handler) return
safeInvoke(() => handler())
}
const quickSearch = ref('')
const currentSort = reactive({ prop: '', order: '' })
// 导出相关 —— 使用异步任务模式
function buildExportPayload() {
if (currentCondition.value && currentCondition.value !== 'reset') {
return { where: normalizeToWhere(currentCondition.value) }
}
return { where: normalizeToWhere({}) }
}
function buildExportSelectedPayload() {
const ids = selectionRows.value.map((item: any) => item.id)
return {
where: {
id: { operator: 'in', value: ids }
}
}
}
async function handleExportAll() {
await submitExportTask(buildExportPayload())
}
async function handleExportSelected() {
if (!selectionRows.value.length) {
ElMessage.warning('请先勾选需要导出的入库单')
return
}
await submitExportTask(buildExportSelectedPayload())
}
function handleExportCommand(command: string) {
if (command === 'handleExportSelected') {
handleExportSelected()
} else {
handleExportAll()
}
}
const componentMap: Record<string, any> = {
details: entrydetail,
bindingRelations: EntryBindingRelations,
directInboundLogs: DirectInboundLogs,
logs: log,
operate: entryoperate
}
const activeComponent = computed(() => componentMap[activeTab.value] || componentMap.details)
const selectedRow = computed(() => {
return list.value.find((i: any) => i.id === selectedEntryId.value) || null
})
const bindDialogVisible = ref(false)
const bindTargetRow = ref<any>(null)
const unbindDialogVisible = ref(false)
const unbindTargetRow = ref<any>(null)
// 收货绑定详情弹窗
const receivingBindingsDialogVisible = ref(false)
const receivingBindingsDialogData = ref<any[]>([])
const reviewDialogVisible = ref(false)
const reviewTargetRow = ref<any>(null)
const reviewSubmitting = ref(false)
const reviewCompareLoading = ref(false)
const reviewCompareRows = ref<any[]>([])
// 打印相关
const printDialogVisible = ref(false)
async function handleOpenPrintDialog() {
if (!selectionRows.value.length) {
ElMessage.warning('请先选择要打印的入库单')
return
}
printDialogVisible.value = true
}
/** 获取单个入库单的打印数据(复用 entry.get 接口) */
async function fetchEntryPrintData(row: any, _index: number): Promise<Record<string, unknown>> {
const id = Number(row?.id)
if (!id || !Number.isFinite(id)) {
throw new Error('入库单ID无效')
}
const res = await entryApi.getEntryDetail({ id })
if (res?.code !== 200 && res?.code !== undefined) {
throw new Error(res?.message || '获取入库单详情失败')
}
return buildEntryPrintFormData(res as Record<string, unknown>, row)
}
function openBindDialog(row: any) {
if (!canBindEntryOrder(row?.order_status)) return
bindTargetRow.value = row
bindDialogVisible.value = true
}
function openReceivingBindingsDialog(row: any) {
const bindings = row?.receivingBindings
if (!Array.isArray(bindings) || bindings.length === 0) {
ElMessage.info('该入库单暂无绑定的收货单')
return
}
receivingBindingsDialogData.value = bindings
receivingBindingsDialogVisible.value = true
}
function handleBindDialogClosed() {
bindTargetRow.value = null
}
async function handleBindDialogSuccess() {
bindDialogVisible.value = false
bindTargetRow.value = null
await loadData()
entryDetailRefreshTick.value += 1
}
function openUnbindDialog(row: any) {
if (!canUnbindEntryOrder(row)) return
unbindTargetRow.value = row
unbindDialogVisible.value = true
}
function handleUnbindDialogClosed() {
unbindTargetRow.value = null
}
async function handleUnbindDialogSuccess() {
unbindDialogVisible.value = false
unbindTargetRow.value = null
await loadData()
entryDetailRefreshTick.value += 1
}
function translateField(fieldValue: string, value: any) {
return translateEntryField(fieldValue, value)
}
function pad(n: number) {
return n < 10 ? '0' + n : String(n)
}
function formatTime(val: any) {
if (!val && val !== 0) return ''
const d = new Date(val)
if (isNaN(d.getTime())) return String(val)
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
/**
* 将 scan-box 返回的条件标准化为后端推荐结构:{ operator, value, type }
* 支持三种情况:
* - 已经是 {value, operator, type} 形式:原样返回
* - 是简单值(string/number/array):包装为 { operator: 'eq', value: val }
* - 空或 undefined:忽略该字段
*/
// 将 scan-box 返回的条件标准化为后端推荐结构:{ operator, value, type }
function normalizeToWhere(condition: any) {
if (!condition) return {}
// 如果是字符串或简单值,默认映射为单号模糊查询
if (typeof condition === 'string' || typeof condition === 'number') {
return { entry_order_code: { operator: 'like', value: condition, type: 'text' } }
}
const getFieldConfig = (key: string) => {
return availableFields.find((f: any) => f.value === key)
}
const mapType = (type: string, value: any) => {
if (type === 'datetimerange') return 'datetimerange'
if (type === 'daterange' || Array.isArray(value)) return 'daterange'
if (type === 'number' || typeof value === 'number') return 'number'
if (type === 'boolean' || typeof value === 'boolean') return 'boolean'
return 'text'
}
const processConditionValue = (k: string, c: any) => {
const config = getFieldConfig(k)
const fieldType = config?.type || 'text'
if (c && typeof c === 'object' && !Array.isArray(c)) {
if ('operator' in c || 'value' in c || 'type' in c) {
return {
operator: c.operator || (Array.isArray(c.value) ? 'in' : (fieldType === 'daterange' || fieldType === 'datetimerange' ? 'between' : 'eq')),
value: c.value,
type: c.type || mapType(fieldType, c.value)
}
}
}
if (c === null || c === undefined || c === '' || (Array.isArray(c) && c.length === 0)) return null
const simpleOp = (fieldType === 'daterange' || fieldType === 'datetimerange') ? 'between' : 'eq'
const simpleType = mapType(fieldType, c)
return { operator: simpleOp, value: c, type: simpleType }
}
// 如果来自 ScanBox 的 preset(包含 conditions)
if (condition.conditions && typeof condition.conditions === 'object') {
const where: any = {}
Object.keys(condition.conditions).forEach(k => {
const result = processConditionValue(k, condition.conditions[k])
if (result) where[k] = result
})
return finalizeEntryListWhere(where)
}
// 普通自定义条件对象
if (typeof condition === 'object') {
const where: any = {}
Object.keys(condition).forEach(k => {
const result = processConditionValue(k, condition[k])
if (result) where[k] = result
})
return finalizeEntryListWhere(where)
}
return finalizeEntryListWhere({})
}
function getSyncStatusType(status: string) {
const map: Record<string, string> = {
'PENDING': 'info',
'SYNCING': 'primary',
'SUCCESS': 'success',
'FAIL': 'danger',
'FAILED': 'danger',
}
return map[status] || undefined
}
function syncMessageCellClass(row: any): string {
const status = row?.sync_status
if (!status) return ''
const upper = String(status).trim().toUpperCase()
if (upper === 'FAIL' || upper === 'FAILED') return 'sync-message--fail'
if (upper === 'SUCCESS') return 'sync-message--success'
return ''
}
function syncMessageFullText(row: any): string {
const v = row?.sync_message
if (v == null) return ''
return String(v).trim()
}
/** 列表格内省略展示,完整内容见 tooltip,点击复制全文 */
function syncMessageCellText(row: any): string {
const t = syncMessageFullText(row)
if (!t) return '—'
const max = 48
return t.length > max ? `${t.slice(0, max)}…` : t
}
async function copySyncMessage(row: any) {
const text = syncMessageFullText(row)
if (!text) {
ElMessage.warning('当前行无同步信息可复制')
return
}
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
} else {
throw new Error('no clipboard api')
}
ElMessage.success('同步信息已复制到剪贴板')
} catch {
try {
const ta = document.createElement('textarea')
ta.value = text
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
document.execCommand('copy')
document.body.removeChild(ta)
ElMessage.success('同步信息已复制到剪贴板')
} catch {
ElMessage.error('复制失败,请手动选择文本复制')
}
}
}
/** 提取收货单号列表(供复制) */
function getReceivingNumbers(bindings: unknown): string[] {
if (!Array.isArray(bindings) || !bindings.length) return []
return bindings
.map((item) => {
const binding = item as Record<string, unknown>
const receiving = (binding.receiving ?? {}) as Record<string, unknown>
const number = receiving.receiving_number ?? binding.receiving_number
return number ? String(number) : ''
})
.filter(Boolean)
}
async function copyReceivingBindings(row: any) {
const numbers = getReceivingNumbers(row?.receivingBindings)
if (!numbers.length) {
ElMessage.warning('该入库单暂无绑定的收货单')
return
}
const text = numbers.join('\n')
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
} else {
throw new Error('no clipboard api')
}
ElMessage.success(`已复制 ${numbers.length} 个收货单号`)
} catch {
try {
const ta = document.createElement('textarea')
ta.value = text
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
document.execCommand('copy')
document.body.removeChild(ta)
ElMessage.success(`已复制 ${numbers.length} 个收货单号`)
} catch {
ElMessage.error('复制失败,请手动选择文本复制')
}
}
}
onMounted(() => {
// 先加载筛选相关数据(例如 store options、presetTree),保证 ScanBox options 可用
loadFilterData()
// 如果 URL 带有 id 参数,则构建初始筛选条件并应用
const idParam = route.query.id || route.query.entry_order_code || route.query.q
const id = Array.isArray(idParam) ? idParam[0] : idParam
if (id) {
// 设置 ScanBox 的初始条件以在 UI 中显示
initialConditions.value = { conditions: { entry_order_code: { operator: 'like', value: id, type: 'text' } } }
// 直接使用包含 operator 的完整条件触发搜索(避免丢失 operator)
handleConditionChange(initialConditions.value)
} else {
// 无 URL 参数时正常加载列表
loadData()
}
})
async function loadData() {
if (loading.value) return
loading.value = true
const start = Date.now()
try {
// 优先使用由 ScanBox 提交并经过规范化的条件(包含 operator 等信息)
const where = currentCondition.value || normalizeToWhere(scanBox.value?.getConditions?.() || {})
const params: StorageEntryListParams = {
pagination: {
page: pagination.currentPage,
pageSize: pagination.pageSize
},
sort: currentSort.prop ? {
sortField: currentSort.prop,
sortOrder: currentSort.order === 'ascending' ? 'ASC' : 'DESC'
} : undefined,
where: where
}
const res = await entryApi.getEntryList(params)
if (res && res.code === 200 && res.data?.list) {
list.value = res.data.list
pagination.total = res.data.pagination?.total || 0
} else {
list.value = []
pagination.total = 0
ElMessage.error(res?.message || '获取入库单列表失败')
}
} catch (e) {
console.error('加载逻辑发生严重错误', e)
ElMessage.error('加载入库单失败')
} finally {
loading.value = false
queryTime.value = Date.now() - start
}
}
async function handleDetailRefresh() {
await loadData()
entryDetailRefreshTick.value += 1
}
async function loadFilterData() {
try {
const [storesRes, presetRes]: any = await Promise.all([
indexApi.loadStores(),
indexApi.fastWhereTree('entry')
])
if (storesRes && storesRes.code === 200) {
const stores = storesRes.stores || []
const f = availableFieldsRef.find((i: any) => i.value === 'store_id')
if (f) f.options = stores
const af = addEntryFieldsRef.find((i: any) => i.prop === 'store_id')
if (af) af.options = stores
}
if (presetRes && presetRes.code === 200) {
presetTree.value = presetRes.presetTree || []
}
} catch (e) {
console.error('加载筛选配置失败', e)
}
}
function handleConditionChange(condition: any) {
// 保留原始条件供调试或后续使用
currentConditionRaw.value = condition
// 将条件规范化为后端期望的 where 结构
currentCondition.value = normalizeToWhere(condition)
pagination.currentPage = 1
loadData()
}
function handleSortChange({ prop, order }: any) {
currentSort.prop = prop
currentSort.order = order
pagination.currentPage = 1
loadData()
}
const handleConditionClear = () => {
currentCondition.value = null
pagination.currentPage = 1
loadData()
}
function handleConditionReset() {
currentCondition.value = null // 清空已保存的条件
pagination.currentPage = 1
if (scanBox.value?.reset) {
scanBox.value.reset()
} else if (scanBox.value?.clear) {
scanBox.value.clear()
}
loadData()
}
function onSelectionChange(rows: any[]) {
selectionRows.value = rows || []
hasSelection.value = selectionRows.value.length > 0
}
/** 完成入库/作废等操作的目标行:优先勾选,其次当前高亮行 */
function getActionTargetRows(): any[] {
if (selectionRows.value.length) return selectionRows.value
if (selectedEntryId.value && selectedRow.value) return [selectedRow.value]
return []
}
async function handleRowClick(row: any) {
selectedEntryId.value = row?.id || null
}
function handlePageChange(page: number) {
pagination.currentPage = page
loadData()
}
function handlePageSizeChange(size: number) {
pagination.pageSize = size
pagination.currentPage = 1
loadData()
}
function onQuickSearch() {
pagination.currentPage = 1
loadData()
}
// 新建入库单相关
const createDialogVisible = ref(false)
const createLoading = ref(false)
const createForm = reactive<any>({
order_type: '',
store_id: '',
entry_order_code: '',
purchase_order_code: '',
remark: ''
})
function handleCreateEntry() {
ElMessage.warning('接口已下线:入库单不再支持手工新建,请使用快捷入库/匹配入库流程')
}
/** 一键上架后是否通知货主:返回 0=通知、1=不通知;关闭/ESC 返回 null(取消) */
async function askOwnerNotice(actionDesc: string): Promise<number | null> {
return new Promise((resolve) => {
ElMessageBox.confirm(`${actionDesc},是否通知货主?`, '通知货主设置', {
confirmButtonText: '通知货主',
cancelButtonText: '不通知',
type: 'warning',
distinguishCancelAndClose: true
})
.then(() => resolve(0))
.catch((action: string | 'cancel' | 'close') => {
resolve(action === 'cancel' ? 1 : null)
})
})
}
async function handleRowQuickInbound(row: any) {
if (!canQuickInbound(row.order_status)) {
ElMessage.warning('仅「已创建」状态的入库单可执行一键上架')
return
}
const code = row.entry_order_code || row.id
const noNeedNotice = await askOwnerNotice(
`确认对入库单「${code}」执行一键上架(跳过收货/质检,商品直入虚拟库位并完成)`
)
if (noNeedNotice === null) return
try {
const res = await entryApi.quickInbound({ id: Number(row.id), noNeedNotice })
if (res && (res.code === 1 || res.code === 200)) {
ElMessage.success('一键上架成功')
await loadData()
entryDetailRefreshTick.value += 1
} else {
ElMessage.error(res?.message || '一键上架失败')
}
} catch (e: any) {
ElMessage.error(e?.message || '一键上架失败')
}
}
/** 构建收货对照预览行 */
function buildReviewCompareRow(record: any, index: number) {
const raw = record as Record<string, unknown>
const status = String(raw.match_status ?? '').toLowerCase()
const entryName = raw.warehouse_item_name as string || raw.receiving_product_name as string || '—'
const receivingName = raw.receiving_product_name as string || raw.warehouse_item_name as string || '—'
const entryQty = raw.entry_count ?? raw.entry_received ?? '—'
const receivingAvailable = raw.receiving_available ?? raw.receiving_actual_quantity ?? raw.receiving_allocated ?? '—'
const tagMap: Record<string, string> = {
matched: 'success',
entry_only: 'warning',
receiving_only: 'primary',
}
const labelMap: Record<string, string> = {
matched: '已匹配',
entry_only: '仅入库',
receiving_only: '仅收货',
}
return {
rowKey: `review-compare-${index}`,
matchStatus: status,
matchTagType: tagMap[status] || 'info',
matchStatusLabel: labelMap[status] || status,
entryName,
receivingName,
entryQty: entryQty === '—' ? '—' : String(entryQty),
receivingAvailable: receivingAvailable === '—' ? '—' : String(receivingAvailable),
}
}
/** 开始入库(打开确认弹窗,拉取收货对照数据) */
async function handleReviewEntry(row: any) {
reviewTargetRow.value = row
reviewDialogVisible.value = true
reviewCompareLoading.value = true
reviewCompareRows.value = []
try {
// 从 row 的 receivingBindings 中提取收货单 ID
const bindings = row.receivingBindings || []
const receivingIds = bindings
.map((item: any) => Number(item.receiving_id))
.filter((id: number) => Number.isFinite(id) && id > 0)
if (receivingIds.length > 0 && row.id) {
const res = await entryApi.receivingCompare({
entry_order_id: Number(row.id),
receiving_ids: receivingIds,
})
const payload = (res.data && typeof res.data === 'object' ? { ...res, ...res.data } : res) as any
const allRecords: any[] = []
if (Array.isArray(payload.comparison)) {
// 最新结构:合并后的逐行对照 + 合并后仍未匹配的收货商品
allRecords.push(...payload.comparison)
if (Array.isArray(payload.receiving_only)) allRecords.push(...payload.receiving_only)
} else {
// 兼容旧结构:各收货单各自对照
for (const item of (payload.comparisons ?? [])) {
allRecords.push(...(Array.isArray(item.comparison) ? item.comparison : []))
allRecords.push(...(Array.isArray(item.receiving_only) ? item.receiving_only : []))
}
}
reviewCompareRows.value = allRecords.map(buildReviewCompareRow)
}
} catch (e) {
console.warn('拉取收货对照数据失败', e)
reviewCompareRows.value = []
} finally {
reviewCompareLoading.value = false
}
}
function handleReviewDialogClosed() {
reviewTargetRow.value = null
reviewCompareRows.value = []
reviewCompareLoading.value = false
reviewSubmitting.value = false
}
/** 确定开始入库(审核入库单,CREATED → PENDING) */
async function handleReviewConfirm() {
if (!reviewTargetRow.value) return
reviewSubmitting.value = true
try {
const res = await entryApi.reviewEntry({ id: Number(reviewTargetRow.value.id) })
if (res && (res.code === 200)) {
ElMessage.success('开始入库成功')
reviewDialogVisible.value = false
await loadData()
entryDetailRefreshTick.value += 1
} else {
ElMessage.error(res?.message || '开始入库失败')
}
} catch (e: any) {
ElMessage.error(e?.message || '开始入库失败')
} finally {
reviewSubmitting.value = false
}
}
function handleCreateDialogClosed() {
Object.keys(createForm).forEach(key => createForm[key] = '')
}
async function submitCreateEntry() {
ElMessage.warning('接口已下线:storage.entry.create 不再对外开放')
}
async function confirmBatchCancel() {
if (!selectionRows.value.length) {
ElMessage.warning('请先选择要作废的入库单')
return
}
try {
await ElMessageBox.confirm(`确定要批量作废 ${selectionRows.value.length} 个入库单吗?`, '确认', { type: 'warning' })
loading.value = true
// 提取所有选中的入库单 ID
const ids = selectionRows.value.map(row => row.id)
// 调用 cancelEntry 接口,传入 ID 数组
const res = await entryApi.cancelEntry({ ids })
if (res && res.code === 200) {
ElMessage.success('批量作废成功')
loadData() // 刷新列表
} else {
ElMessage.error(res?.message || '作废失败')
}
} catch (e) {
if (e !== 'cancel') {
console.error('批量作废出错:', e)
ElMessage.error('操作失败')
}
} finally {
loading.value = false
}
}
function handleImport() {
if (!selectedEntryId.value) {
ElMessage.warning('请先在列表中选择一个入库单')
return
}
if (!isPendingEntryOrderStatus(selectedRow.value?.order_status)) {
ElMessage.warning('仅「待入库」状态可使用批量导入')
return
}
detailVisible.value = true
activeTab.value = 'details'
setTimeout(() => {
detailComponentRef.value?.openBatchImportDialog?.()
}, 0)
}
</script>
<style scoped lang="scss">
@use "../../order/orderManagement/styles/order-sub.scss";
.order-sub-container .main-content .lower-level .detail-container {
padding: 10px;
overflow: auto;
}
.empty-tip {
text-align: center;
font-size: 14px;
}
.sync-message-cell {
cursor: pointer;
color: var(--el-color-primary);
text-decoration: none;
}
.sync-message-cell:hover {
text-decoration: underline;
}
.sync-message--fail {
color: var(--el-color-danger);
}
.sync-message--success {
color: var(--el-color-success);
}
.clickable-tag {
cursor: pointer;
}
.receiving-bindings-cell {
cursor: pointer;
color: var(--el-color-primary);
text-decoration: none;
}
.receiving-bindings-cell:hover {
text-decoration: underline;
color: var(--el-color-primary-light-3);
}
</style>