2026-07-30 18:12:43 +08:00

659 lines
21 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

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

<template>
<div class="order-sub-container" :style="{ height: containerHeight }">
<scan-box
ref="scanBox"
cache-key="storage-inventory"
width="250px"
:tree-props="{ children: 'children', label: 'label' }"
:auto-submit="false"
:preset-tree="presetTree"
:available-fields="availableFieldsRef"
@condition-change="handleConditionChange"
@reset="handleConditionReset"
@condition-clear="handleConditionClear"
@field-action="handleScanBoxFieldAction"
/>
<div class="main-content">
<div class="toolbar">
<div class="toolbar-left">
<el-button size="small" type="primary" @click="loadData">刷新</el-button>
<!-- <el-button size="small" @click="handleCreateEntry">新建入库单</el-button> -->
<el-button size="small" :disabled="!hasSelection" @click="confirmBatchCancel">批量作废</el-button>
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
<el-button size="small" @click="handleImport">导入</el-button>
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
<!-- <el-button>是否按批次显示</el-button> -->
</div>
<div class="toolbar-right">
<span class="toolbar-label"></span>
<el-select v-model="groupByBatch" size="small" style="width:120px" @change="handleGroupByBatchChange">
<el-option label="汇总查询" :value="false" />
<el-option label="批次查询" :value="true" />
</el-select>
</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-inventory-list"
:enable-column-config="true"
:data="list"
:columns="columns"
:table-size="tableSize"
:pagination="pagination"
:show-index="true"
:show-actions="true"
:show-selection="true"
:loading="loading"
:queryTime="queryTime"
@current-change="handleRowClick"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
@refresh="loadData"
@selection-change="onSelectionChange"
>
<template #column-expiry_date="{ row }">
<span :class="{ 'expiry-date-expired': row.is_shelf_life_warning_triggered }">
{{ row.expiry_date || '--' }}
</span>
</template>
<template #column-is_batch_mgmt_enabled="{ row }">
<div style="text-align:center">
<el-tag :type="isInventoryFlagEnabled(row.is_batch_mgmt_enabled) ? 'success' : 'info'" size="small">
{{ formatInventoryFlagLabel(row.is_batch_mgmt_enabled) }}
</el-tag>
</div>
</template>
<template #column-is_shelf_life_mgmt="{ row }">
<div style="text-align:center">
<el-tag :type="isInventoryFlagEnabled(row.is_shelf_life_mgmt) ? 'success' : 'info'" size="small">
{{ formatInventoryFlagLabel(row.is_shelf_life_mgmt) }}
</el-tag>
</div>
</template>
<template #column-remaining_threshold_days="{ row }">
<span>{{ formatInventoryOptionalText(row.remaining_threshold_days) }}</span>
</template>
<template #column-first_inbound_time="{ row }">
<span>{{ row.first_inbound_time || '--' }}</span>
</template>
<template #column-batch_count="{ row }">
<div style="text-align:center">{{ row.batch_count || 0 }}</div>
</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="details" />
<!-- <el-tab-pane label="操作日志" name="logs" /> -->
</el-tabs>
</div>
<div class="detail-container">
<KeepAlive>
<component
:is="activeComponent"
:id="selectedEntryId"
:row="selectedRow"
:group-by-batch="groupByBatch"
@refresh="loadData"
/>
</KeepAlive>
</div>
</div>
<div v-else class="no-selection" :style="lowerPaneStyle">
<div class="empty-tip">
<p>请从上方列表中选择一项查看详情</p>
</div>
</div>
</template>
</div>
</div>
<InventoryStockPickerDialog
v-model="stockPickerVisible"
:store-id="stockPickerStoreId"
:selected-items="stockPickerSelectedItems"
@confirm="handleStockPickerConfirm"
/>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import * as indexApi from '@/api/index/index'
// import * as entryApi from '@/api/storage.entry/entry'
import * as inventoryApi from '@/api/storage.inventory/inventory'
import {
availableFields,
formatInventoryBarcodes,
formatInventoryFlagLabel,
formatInventoryOptionalText,
inventoryExportColumns,
isInventoryFlagEnabled,
productstockColums,
} from './inventory-config'
import { exportUpperTableRows } from '@/views/order/orderManagement/utils/export'
import entrydetail from './component/panelstockdetail.vue'
import log from './component/log.vue'
import InventoryStockPickerDialog from './component/InventoryStockPickerDialog.vue'
import type { InventoryStockPickerItem } from './component/InventoryStockPickerDialog.vue'
import ExportModeDropdown from '@/components/ExportModeDropdown.vue'
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 stockPickerVisible = ref(false)
const stockPickerStoreId = ref<number | undefined>(undefined)
const stockPickerSelectedItems = ref<InventoryStockPickerItem[]>([])
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 openColumnConfigPanel() {
upperTable.value?.openColumnConfig?.()
}
const presetTree = ref<any[]>([])
const availableFieldsRef = reactive(JSON.parse(JSON.stringify(availableFields)))
const activeTab = ref('details')
const list = ref<any[]>([])
const loading = ref(false)
const exportLoading = ref(false)
const queryTime = ref(0)
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
const tableSize = ref('small')
const groupByBatch = ref(false)
const columns = computed(() => {
const cols: any[] = JSON.parse(JSON.stringify(productstockColums))
if (groupByBatch.value) {
if (!cols.find((c: any) => c.prop === 'batch_no')) {
const batchCol = { prop: 'batch_no', label: '批次号', width: '120' }
const idx = cols.findIndex((c: any) => c.prop === 'item_name')
if (idx >= 0) cols.splice(idx + 1, 0, batchCol)
else cols.push(batchCol)
}
const warningColumns = [
{ prop: 'expiry_remaining_days', label: '剩余有效期', width: '110' },
{ prop: 'inventory_warning_level', label: '预警等级', width: '110' },
{ prop: 'inventory_warning_tip_text', label: '预警提示', width: '160' }
]
const expiryIdx = cols.findIndex((x: any) => x.prop === 'expiry_date')
for (let i = warningColumns.length - 1; i >= 0; i--) {
const c = warningColumns[i]
if (!c) continue
if (cols.find((x: any) => x.prop === c.prop)) continue
if (expiryIdx >= 0) cols.splice(expiryIdx + 1, 0, c)
else cols.push(c)
}
return cols
}
return cols.filter(
(col: any) =>
![
'production_date',
'expiry_date',
'shelf_life_days',
'sale_ban_period',
'expiry_remaining_days',
'inventory_warning_level',
'inventory_warning_tip_text'
].includes(col.prop)
)
})
const selectionRows = ref<any[]>([])
const hasSelection = ref(false)
const selectedEntryId = ref<number | string | null>(null)
const componentMap: Record<string, any> = {
details: entrydetail,
logs: log
}
const activeComponent = computed(() => componentMap[activeTab.value] || componentMap.details)
const selectedRow = computed(() => {
return list.value.find((i: any) => i.id === selectedEntryId.value) || null
})
onMounted(() => {
loadData()
loadFilterData()
})
async function loadData() {
if (loading.value) return
loading.value = true
const start = Date.now()
try {
const rawWhere = scanBox.value?.getConditions?.() || {}
const where: Record<string, unknown> = { ...rawWhere }
// 解析库位关键字 → 库位ID
const rawSpaceVal = where.space_keyword
delete where.space_keyword
const spaceKeyword = rawSpaceVal && typeof rawSpaceVal === 'object'
? String((rawSpaceVal as any).value ?? '').trim()
: String(rawSpaceVal ?? '').trim()
if (spaceKeyword) {
try {
const spaceRes: any = await indexApi.searchSpace({ keyword: spaceKeyword, page: 1, pageSize: 20 })
const spaceData = spaceRes && (spaceRes.data || spaceRes.list || spaceRes)
const spaceList = Array.isArray(spaceData?.list) ? spaceData.list : Array.isArray(spaceData) ? spaceData : []
if (spaceList.length) {
const spaceIds = spaceList.map((s: any) => Number(s.id)).filter((id: number) => Number.isFinite(id) && id > 0)
if (spaceIds.length === 1) {
where.space_id = spaceIds[0]
} else if (spaceIds.length > 1) {
where.space_id = spaceIds
}
} else {
// 未匹配到任何库位,设一个不可能的值使结果为空
where.space_id = -1
}
} catch {
where.space_id = -1
}
}
const params: any = {
pagination: { page: pagination.currentPage, pageSize: pagination.pageSize },
where,
group_by_batch: groupByBatch.value
}
const res: any = await inventoryApi.getInventoryList(params)
if (res && (res.code === 200 || res.code === 1 || res.flag === 'success')) {
const data = res.data || res
const rows = Array.isArray(data.list) ? data.list : []
list.value = rows.map((item: any) => {
const rowId = `${item.stock_id}`
return {
id: rowId,
stock_id: item.stock_id,
item_code: item.stock?.item_code || '',
item_name: item.stock?.item_name || '',
barcodes: formatInventoryBarcodes(item.stock?.barcodes),
sku_property: formatInventoryOptionalText(item.stock?.sku_property),
stock_unit: formatInventoryOptionalText(item.stock?.stock_unit),
production_date: item.production_date || '',
expiry_date: item.expiry_date || '',
is_shelf_life_warning_triggered: Boolean(item.is_shelf_life_warning_triggered),
store_name: item.store_name || item.stock?.store_name || '',
quantity: item.quantity,
available_quantity: item.available_quantity,
locked_quantity: item.locked_quantity,
first_inbound_time: item.first_inbound_time || '',
last_inbound_time: item.last_inbound_time,
batch_count: Number(item.batch_count || 0),
is_shelf_life_mgmt: item.stock?.is_shelf_life_mgmt ?? '',
remaining_threshold_days: item.stock?.remaining_threshold_days ?? '',
is_batch_mgmt_enabled: item.stock?.is_batch_mgmt_enabled,
// preserve original structures for child components that need full network shape
stock: item.stock || null,
space: item.space || null,
storage_id: item.storage_id ?? null,
space_id: item.space_id ?? item.space?.id ?? null,
__raw: item
}
})
const pager = data.pagination || {}
pagination.total = pager.total || data.total || list.value.length
} else {
list.value = []
pagination.total = 0
}
} catch (e) {
console.error('获取库存列表失败', e)
ElMessage.error('加载库存列表失败')
list.value = []
pagination.total = 0
} finally {
loading.value = false
queryTime.value = Date.now() - start
}
}
async function loadFilterData() {
try {
const [storesRes, presetRes]: any = await Promise.all([
indexApi.loadStores(),
indexApi.fastWhereTree('entry')
])
if (storesRes && storesRes.code === 200) {
const f = availableFieldsRef.find((i: any) => i.value === 'store_id')
if (f) f.options = storesRes.stores || []
}
if (presetRes && presetRes.code === 200) {
presetTree.value = presetRes.presetTree || []
}
} catch (e) {
console.error('加载筛选配置失败', e)
}
}
function handleConditionChange(condition: any) {
pagination.currentPage = 1
loadData()
}
const handleConditionClear = () => {
pagination.currentPage = 1
loadData()
}
function handleConditionReset() {
pagination.currentPage = 1
if (scanBox.value?.reset) {
scanBox.value.reset()
}
loadData()
}
function parseStockIdDraftValue(raw: unknown): number[] {
if (raw === undefined || raw === null || raw === '') return []
const values = Array.isArray(raw)
? raw
: String(raw).split(/[,,\s]+/)
return values
.map((item) => Number(String(item).trim()))
.filter((id) => Number.isInteger(id) && id > 0)
}
function resolveStoreIdFromScanBox(): number | undefined {
const draft = scanBox.value?.getFieldDraft?.('store_id')
const val = draft?.value
if (Array.isArray(val)) {
if (val.length === 1) {
const storeId = Number(val[0])
return Number.isInteger(storeId) && storeId > 0 ? storeId : undefined
}
return undefined
}
const storeId = Number(val)
return Number.isInteger(storeId) && storeId > 0 ? storeId : undefined
}
function buildStockPickerSelectedItems(ids: number[]): InventoryStockPickerItem[] {
return ids.map((itemId) => ({
item_id: itemId,
item_code: '',
item_name: '',
barcode: ''
}))
}
function handleScanBoxFieldAction(fieldKey: string) {
if (fieldKey !== 'stock_id') return
stockPickerStoreId.value = resolveStoreIdFromScanBox()
const existingIds = parseStockIdDraftValue(scanBox.value?.getFieldDraft?.('stock_id')?.value)
stockPickerSelectedItems.value = buildStockPickerSelectedItems(existingIds)
stockPickerVisible.value = true
}
async function handleStockPickerConfirm(items: InventoryStockPickerItem[]) {
const pickedIds = items
.map((item) => Number(item.item_id))
.filter((id) => Number.isInteger(id) && id > 0)
if (!pickedIds.length) {
ElMessage.warning('未获取到有效商品ID')
return
}
const operator = pickedIds.length > 1 ? 'in' : 'eq'
const value = pickedIds.join(',')
scanBox.value?.setFieldCondition?.('stock_id', { operator, value }, { autoSubmit: false })
await nextTick()
scanBox.value?.submit?.()
}
function onSelectionChange(rows: any[]) {
selectionRows.value = rows || []
hasSelection.value = selectionRows.value.length > 0
}
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 handleGroupByBatchChange() {
pagination.currentPage = 1
selectedEntryId.value = null
loadData()
}
function handleCreateEntry() {
ElMessage.info('新建入库单')
}
async function confirmBatchCancel() {
if (!selectionRows.value.length) {
ElMessage.warning('请先选择要作废的入库单')
return
}
try {
await ElMessageBox.confirm(`确定要批量作废 ${selectionRows.value.length} 个入库单吗?`, '确认', { type: 'warning' })
// 调用作废 API
ElMessage.success('操作成功')
loadData()
} catch (e) {}
}
async function handleExport(mode: 'waybill' | 'item' = 'waybill') {
exportLoading.value = true
try {
if (mode === 'waybill') {
const sourceRows = selectionRows.value.length ? selectionRows.value : list.value
if (!sourceRows.length) {
ElMessage.warning('当前无数据可导出')
return
}
exportUpperTableRows({
rows: sourceRows,
columns: inventoryExportColumns,
fileName: `库存列表-${Date.now()}.xlsx`,
transformCell: (prop, value) => {
if (prop === 'is_shelf_life_mgmt') return formatInventoryFlagLabel(value)
if (prop === 'remaining_threshold_days') return formatInventoryOptionalText(value)
return value
}
})
ElMessage.success('导出成功')
return
}
const params: any = {
pagination: { page: 1, pageSize: 10000 },
where: scanBox.value?.getConditions?.() || {},
group_by_batch: true
}
const res: any = await inventoryApi.getInventoryList(params)
if (!(res && (res.code === 200 || res.code === 1 || res.flag === 'success'))) {
ElMessage.error('获取库存明细失败')
return
}
const data = res.data || res
const rawRows = Array.isArray(data.list) ? data.list : []
let exportRows = rawRows.map((item: any) => {
return {
store_name: item.store_name || item.stock?.store_name || '',
item_code: item.stock?.item_code || '',
item_name: item.stock?.item_name || '',
barcodes: formatInventoryBarcodes(item.stock?.barcodes),
sku_property: formatInventoryOptionalText(item.stock?.sku_property),
stock_unit: formatInventoryOptionalText(item.stock?.stock_unit),
production_date: item.production_date || '',
expiry_date: item.expiry_date || '',
quantity: item.quantity,
available_quantity: item.available_quantity,
locked_quantity: item.locked_quantity,
first_inbound_time: item.first_inbound_time || '',
last_inbound_time: item.last_inbound_time,
batch_count: Number(item.batch_count || 0),
is_shelf_life_mgmt: item.stock?.is_shelf_life_mgmt ?? '',
remaining_threshold_days: item.stock?.remaining_threshold_days ?? '',
is_batch_mgmt_enabled: item.stock?.is_batch_mgmt_enabled
}
})
if (selectionRows.value.length) {
const selectedKeys = new Set(
selectionRows.value.map((row: any) => row.stock_id)
)
exportRows = exportRows.filter((row: any) =>
selectedKeys.has(row.stock_id)
)
}
if (!exportRows.length) {
ElMessage.warning('未获取到可导出的库存明细')
return
}
exportUpperTableRows({
rows: exportRows,
columns: productstockColums,
fileName: `库存明细-${Date.now()}.xlsx`,
transformCell: (prop, value) => {
if (prop === 'is_shelf_life_mgmt' || prop === 'is_batch_mgmt_enabled') {
return formatInventoryFlagLabel(value)
}
if (prop === 'remaining_threshold_days') return formatInventoryOptionalText(value)
return value
}
})
ElMessage.success('导出成功')
} catch (e) {
console.error('导出 Excel 失败:', e)
ElMessage.error('导出失败')
} finally {
exportLoading.value = false
}
}
function handleExportAction(action: string) {
void handleExport(action === 'handleExportItem' ? 'item' : 'waybill')
}
function handleImport() {
ElMessage.info('导入功能')
}
</script>
<style scoped lang="scss">
@use "../../order/orderManagement/styles/order-sub.scss";
.order-sub-container .main-content {
.toolbar-right {
display: flex;
flex-direction: row;
gap: 8px;
align-items: center;
.toolbar-label {
font-size: 12px;
color: #606266;
}
}
.expiry-date-expired {
color: #f56c6c;
font-weight: 600;
}
.inventory-warning-level {
font-weight: 600;
}
}
.order-sub-container .main-content .lower-level .detail-container {
padding: 10px;
overflow: auto;
}
.empty-tip {
text-align: center;
font-size: 14px;
}
</style>