feat(warehouse): 批量修改弹窗、库位类型接口化、储位列表添加库位类型列

This commit is contained in:
liufumingren 2026-04-29 17:35:25 +08:00
parent d022634749
commit 42bf6c7bfa
4 changed files with 630 additions and 17 deletions

View File

@ -157,7 +157,7 @@ import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import { orderDeliveryOrder } from '@/api/order.deliveryorder/orderdeliveryOrder'
import { orderDeliveryOrder } from '@/api/order.deliveryOrder/orderdeliveryOrder'
import {
deliveryAvailableFields,

View File

@ -55,8 +55,8 @@
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="仓位类型" prop="location_type_id">
<el-select v-model="formData.location_type_id" placeholder="请选择仓位类型" style="width: 100%;"
<el-form-item label="库位类型" prop="location_type_id">
<el-select v-model="formData.location_type_id" placeholder="请选择库位类型" style="width: 100%;"
:loading="typeLoading">
<el-option v-for="type in locationTypes" :key="type.id" :label="type.type_name" :value="type.id" />
</el-select>
@ -95,6 +95,7 @@
import { ref, reactive, watch, onMounted, onBeforeUnmount, getCurrentInstance, } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as warehouseApi from '@/api/warehouse/warehouse'
import * as indexApi from '@/api/index/index'
const props = defineProps({
title: { type: String, default: '仓位属性管理' },
@ -143,7 +144,7 @@ const formRules = {
{ max: 100, message: '长度不能超过100个字符', trigger: 'blur' },
{ validator: (rule:any, value:any, callback:any) => validateBarcode(rule, value, callback), trigger: 'blur' }
],
location_type_id: [{ required: true, message: '请选择仓位类型', trigger: 'change' }],
location_type_id: [{ required: true, message: '请选择库位类型', trigger: 'change' }],
pick_sequence: [{ type: 'number', min: 0, max: 9999, message: '拣货顺序必须在0-9999之间', trigger: 'blur' }]
}
@ -248,13 +249,16 @@ async function loadSpaceData(spaceId: any) {
async function loadLocationTypes() {
typeLoading.value = true
try {
locationTypes.value = [
{ id: 1, type_name: '普通仓位' },
{ id: 2, type_name: '拣货仓位' },
{ id: 3, type_name: '存储仓位' }
]
const res: any = await indexApi.getLocationTypeList()
const data = res && (res.data || res.list || res)
const arr = Array.isArray(data) ? data : []
locationTypes.value = arr.map((lt: any) => ({
id: lt.id,
type_name: lt.type_name ?? lt.name ?? String(lt.id)
}))
} catch (error) {
console.error('加载仓位类型失败:', error)
console.error('加载库位类型失败:', error)
locationTypes.value = []
} finally {
typeLoading.value = false
}

View File

@ -20,7 +20,7 @@
<el-button type="link" size="small" :loading="exportLoading" @click="handleExportRackSpaces">
导出
</el-button>
<el-button type="link" size="small" @click="handleAddSpace">
<el-button type="link" size="small" @click="openBulkModify">
导入批量修改
</el-button>
</span>
@ -45,6 +45,11 @@
</template>
</el-table-column>
<el-table-column sortable prop="pick_sequence" label="拣货顺序" width="100" fixed="right" />
<el-table-column label="库位类型" width="110" fixed="right">
<template #default="{ row }">
{{ getLocationTypeName(row.location_type_id) }}
</template>
</el-table-column>
</el-table>
<div class="info">
@ -56,13 +61,16 @@
<div v-else class="empty-rack-container">
<el-empty description="选择货架后查看信息" />
</div>
<RackBulkModifyDialog ref="bulkDialog" @success="onBulkSuccess" />
</div>
</template>
<script setup lang="ts">
import { ref, watch, computed, } from 'vue'
import { ref, watch, computed, onMounted } from 'vue'
import * as warehouseApi from '@/api/warehouse/warehouse'
import * as indexApi from '@/api/index/index'
import { ElMessage } from 'element-plus'
import RackBulkModifyDialog from './components/RackBulkModifyDialog.vue'
const props = defineProps({
rack: { type: Object, default: null },
@ -78,6 +86,40 @@ const exportLoading = ref(false)
const useSpaceCount = ref(0)
const canUseSpacecCount = ref(0)
const canNotUseSpace = ref(0)
const bulkDialog = ref<any>(null)
const locationTypes = ref<any[]>([])
async function loadLocationTypes() {
try {
const res: any = await indexApi.getLocationTypeList()
const data = res && (res.data || res.list || res)
locationTypes.value = Array.isArray(data) ? data : []
} catch { locationTypes.value = [] }
}
function getLocationTypeName(id: any) {
if (id == null || id === '') return '-'
const found = locationTypes.value.find((lt: any) => lt.id == id)
return found ? (found.type_name ?? found.name ?? id) : id
}
onMounted(() => { loadLocationTypes() })
function openBulkModify() {
try {
const id = props.rack?.id ?? null
if (bulkDialog.value && typeof bulkDialog.value.open === 'function') {
bulkDialog.value.open(id)
}
} catch (e) {
console.error('打开批量修改对话框失败', e)
}
}
async function onBulkSuccess() {
await loadRackSpaces()
emit('refresh')
}
watch(() => props.rack, (newVal) => {
console.log('货架信息', newVal)
@ -191,6 +233,32 @@ function normalizeDownloadUrl(fileUrl: string) {
return `${window.location.origin}${normalizedPath}`
}
function base64ToBlob(base64: string, mime = 'application/octet-stream') {
const pure = base64.trim()
const binary = window.atob(pure)
const buf = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
buf[i] = binary.charCodeAt(i)
}
return new Blob([buf], { type: mime })
}
function saveBlob(blob: Blob, fileName: string) {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = fileName || `warehouse-rack-spaces-${Date.now()}.xlsx`
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
}
function ensureXlsxFileName(fileName: string) {
const name = String(fileName || '').trim() || `warehouse-rack-spaces-${Date.now()}.xlsx`
return name.toLowerCase().endsWith('.xlsx') ? name : `${name}.xlsx`
}
async function handleExportRackSpaces() {
if (exportLoading.value) return
exportLoading.value = true
@ -199,22 +267,33 @@ async function handleExportRackSpaces() {
ElMessage.warning('未获取到货架信息,无法导出')
return
}
const response: any = await warehouseApi.exportRackSpaces(props.rack.id)
const isSuccess = response && (response.code === 200 || response.flag === 'success')
if (!isSuccess) {
const ok = response && (response.code === 1 || response.code === 200 || response.flag === 'success')
if (!ok) {
ElMessage.error(response?.message || '导出失败')
return
}
const fileUrl = String(response?.fileUrl || '').trim()
// 优先处理 base64 返回(兼容 order.pendingOrder.downloadCreateTemplate 的实现)
const base64 = String(response?.base64 || response?.data?.base64 || '').trim()
if (base64) {
const mime = String(response?.mime || response?.data?.mime || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
const filename = ensureXlsxFileName(String(response?.filename || response?.data?.filename || `warehouse-rack-spaces-${Date.now()}.xlsx`))
const blob = base64ToBlob(base64, mime)
saveBlob(blob, filename)
ElMessage.success(response?.message || '导出成功')
return
}
// 回退到 fileUrl 下载
const fileUrl = String(response?.fileUrl || response?.data?.fileUrl || '').trim()
if (!fileUrl) {
ElMessage.error('导出文件地址为空')
return
}
const downloadUrl = normalizeDownloadUrl(fileUrl)
const fileName = String(response?.fileName || `warehouse-rack-spaces-${Date.now()}.xlsx`).trim()
const fileName = ensureXlsxFileName(String(response?.fileName || response?.data?.fileName || `warehouse-rack-spaces-${Date.now()}.xlsx`))
const link = document.createElement('a')
link.href = downloadUrl
link.download = fileName

View File

@ -0,0 +1,530 @@
<template>
<el-dialog
v-model="visible"
title="导入批量修改"
width="1000px"
top="calc(50% - 250px)"
:close-on-click-modal="false"
destroy-on-close
append-to-body
@close="close"
:show-close="true"
>
<div class="bulk-dialog" style="display:flex;flex-direction:column;">
<div v-if="!loaded" class="empty-container">
<input ref="fileInputRef" type="file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="display:none" @change="onFileChange" />
<el-button type="primary" @click="triggerFileSelect">选择 Excel 文件</el-button>
</div>
<div v-else class="content-container" style="display:flex;flex-direction:column;flex:1;">
<div class="toolbar" style="display:flex;align-items:center;gap:8px;padding:8px;">
<el-button size="small" @click="triggerFileSelect">导入文件</el-button>
<el-button size="small" @click="clearData">清空</el-button>
<el-button size="small" type="primary" :loading="submitLoading" :disabled="hasErrors || items.length===0" @click="submit">提交</el-button>
<el-button size="small" @click="validateAll">校验</el-button>
<div style="flex:1"></div>
<el-tag type="info">总行: {{ items.length }}</el-tag>
<el-tag type="danger" v-if="errorCount>0">错误: {{ errorCount }}</el-tag>
</div>
<div style="flex:1;overflow:auto;padding:8px;">
<el-table :data="items" stripe size="small" border style="width:100%" :row-class-name="rowClassName">
<el-table-column prop="space_code" label="仓位编码" width="160">
<template #default="{ row }">
<div>{{ getRowValue(row, 'space_code') }}</div>
</template>
</el-table-column>
<el-table-column prop="custom_name" label="自定义名称" width="160">
<template #default="{ row, $index }">
<el-input :model-value="getRowValue(row, 'custom_name')" clearable @update:modelValue="(val: any) => (setRowValue(row, 'custom_name', val), onRowChange($index))"></el-input>
</template>
</el-table-column>
<el-table-column prop="custom_barcode" label="自定义条码" width="120">
<template #default="{ row, $index }">
<el-input :model-value="getRowValue(row, 'custom_barcode')" clearable @update:modelValue="(val: any) => (setRowValue(row, 'custom_barcode', val), onRowChange($index))"></el-input>
</template>
</el-table-column>
<el-table-column prop="pick_sequence" label="拣货顺序" width="120">
<template #default="{ row, $index }">
<el-input-number :model-value="getRowValue(row, 'pick_sequence')" :min="0" :controls="false" @change="(val: any) => (setRowValue(row, 'pick_sequence', val), onRowChange($index))"></el-input-number>
</template>
</el-table-column>
<el-table-column prop="location_type_name" label="库位类型" width="120">
<template #default="{ row, $index }">
<el-select :model-value="getRowValue(row, 'location_type_name')" placeholder="请选择" filterable clearable @change="(val: any) => (setRowValue(row, 'location_type_name', val), onRowChange($index))">
<el-option
v-for="(lt, idx) in locationTypes"
:key="lt.id ?? idx"
:label="lt.label"
:value="lt.value"
/>
</el-select>
</template>
</el-table-column>
<el-table-column label="错误" width="160">
<template #default="{ row, $index }">
<div v-if="errors[$index]">
<el-tooltip :content="errors[$index]" placement="top">
<el-tag type="danger">{{ errors[$index] }}</el-tag>
</el-tooltip>
</div>
</template>
</el-table-column>
<el-table-column label="操作" width="120">
<template #default="{ row, $index }">
<el-button link type="primary" size="small" @click="removeRow($index)">移除</el-button>
<el-button link type="primary" size="small" @click="validateRow($index)">校验</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
</div>
<template #footer>
<el-button @click="close">关闭</el-button>
<el-button type="primary" :loading="submitLoading" :disabled="hasErrors || items.length===0" @click="submit">提交</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import * as XLSX from 'xlsx'
import * as warehouseApi from '@/api/warehouse/warehouse'
import * as indexApi from '@/api/index/index'
import { ElMessage } from 'element-plus'
const visible = ref(false)
const loaded = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)
const items = ref<any[]>([])
const submitLoading = ref(false)
const rackId = ref<number | null>(null)
const locationTypes = ref<any[]>([])
const errors = reactive<Record<number, string>>({})
const parsedHeaderMap = ref<Record<string, string>>({})
const parsedHeaderKeys = ref<string[]>([])
const emit = defineEmits(['success'])
// 归一化用于匹配的字符串(去空格、去非中英数字、转小写)
const normalizeKey = (s: any) => String(s ?? '').toLowerCase().replace(/\s+/g, '').replace(/[^a-z0-9\u4e00-\u9fa5]/g, '')
function findHeaderKeyForField(field: string) {
for (const [hk, f] of Object.entries(parsedHeaderMap.value || {})) {
if (f === field) return hk
}
return undefined
}
function getRowValue(row: any, field: string) {
if (!row) return undefined
if (row[field] !== undefined) return row[field]
const hk = findHeaderKeyForField(field)
if (hk && row[hk] !== undefined) return row[hk]
return undefined
}
function setRowValue(row: any, field: string, value: any) {
if (!row) return
if (row[field] !== undefined) { row[field] = value; return }
const hk = findHeaderKeyForField(field)
if (hk) { row[hk] = value; return }
row[field] = value
}
function open(id?: number | null) {
rackId.value = id ?? null
visible.value = true
loadLocationTypes()
}
function close() {
visible.value = false
clearData()
}
defineExpose({ open })
function triggerFileSelect() {
fileInputRef.value?.click()
}
async function onFileChange(e: Event) {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
if (!file) return
if (!file.name.toLowerCase().endsWith('.xlsx')) {
ElMessage.warning('仅支持 .xlsx 文件')
input.value = ''
return
}
try {
const arr = await file.arrayBuffer()
const wb = XLSX.read(arr, { type: 'array' })
const sheetName = Array.isArray(wb.SheetNames) && wb.SheetNames.length ? wb.SheetNames[0] : undefined
if (!sheetName) {
ElMessage.error('Excel 文件不包含工作表')
input.value = ''
return
}
const firstSheet = wb.Sheets[sheetName]
if (!firstSheet) {
ElMessage.error('选择的工作表为空')
input.value = ''
return
}
// read as array of arrays to preserve column order
const matrix: any[] = XLSX.utils.sheet_to_json(firstSheet, { header: 1, defval: '' })
if (!matrix || matrix.length === 0) {
ElMessage.error('空的表格')
input.value = ''
return
}
const headerRow: any[] = matrix[0]
const dataRows = matrix.slice(1)
// build objects preserving header order
const rows: any[] = dataRows.map(r => {
const obj: Record<string, any> = {}
for (let i = 0; i < headerRow.length; i++) {
const key = headerRow[i] ?? `col${i}`
obj[key] = r[i]
}
return obj
})
// 打印调试信息,便于排查列映射问题(只打印前几行)
try {
console.log('RackBulkModifyDialog headerRow:', headerRow)
console.log('RackBulkModifyDialog matrix sample:', matrix.slice(0, Math.min(5, matrix.length)))
console.log('RackBulkModifyDialog dataRows sample:', dataRows.slice(0, Math.min(5, dataRows.length)))
console.log('RackBulkModifyDialog parsed rows sample:', rows.slice(0, Math.min(5, rows.length)))
console.log('RackBulkModifyDialog locationTypes:', locationTypes.value)
} catch (e) {
// ignore
}
// pass both rows objects and original matrix rows so parser can force A 列为 space_code
parseRowsToItems(rows, headerRow as string[])
input.value = ''
} catch (err) {
console.error(err)
ElMessage.error('解析文件失败')
}
}
function parseRowsToItems(rows: any[], headerOrder?: string[]) {
const mapped: any[] = []
// build header -> field map using explicit headerOrder (preserves A列顺序) or fallback to object keys
const headerKeys = headerOrder && headerOrder.length ? headerOrder : (rows.length > 0 ? Object.keys(rows[0]) : [])
const normalize = normalizeKey
const candidates: Record<string, string[]> = {
space_code: ['spacecode', 'space_code', '仓位编码', '库位编码', '库位编号', '仓位编号', '库位', '仓位', '库位名称', '仓位名称', '编码', '编号', 'code'],
custom_name: ['customname', 'custom_name', '自定义名称', '自定义名', '名称', 'name'],
custom_barcode: ['custombarcode', 'custom_barcode', '自定义条码', '条码', 'barcode'],
pick_sequence: ['picksequence', 'pick_sequence', '拣货顺序', '拣货', 'pick'],
location_type_name: ['locationtypename', 'location_type_name', '库位类型名称', '库位类型', '仓位类型', '仓位类型名称']
}
// scoring match: exact -> 100, includes -> 80
const headerMap: Record<string, string> = {}
for (const hk of headerKeys) {
const nh = normalize(hk)
let bestField: string | null = null
let bestScore = -1
for (const [field, pats] of Object.entries(candidates)) {
for (const p of pats) {
const np = normalize(p)
let score = -1
if (nh === np) score = 100
else if (nh.includes(np) || np.includes(nh)) score = 80
if (score > bestScore) {
bestScore = score
bestField = field
}
}
}
if (bestField && bestScore > 0) {
headerMap[hk] = bestField
}
}
try {
console.log('RackBulkModifyDialog headerMap:', headerMap, 'headerKeys:', headerKeys)
} catch (e) {}
// fallback: if no space_code mapped, pick header with most non-empty values (excluding barcode-like headers)
if (!Object.values(headerMap).includes('space_code')) {
let bestHeader: string | null = null
let bestCount = -1
const sampleSize = Math.min(rows.length, 20)
for (const hk of headerKeys) {
const nh = normalize(hk)
if (/barcode|条码/.test(nh)) continue
let count = 0
for (let i = 0; i < sampleSize; i++) {
const v = String(rows[i][hk] ?? '').trim()
if (v !== '') count++
}
if (count > bestCount) { bestCount = count; bestHeader = hk }
}
if (bestHeader) {
headerMap[bestHeader] = 'space_code'
// notify user that a fallback was used
ElMessage.info(`未检测到明确的“仓位编码”表头,已使用 "${bestHeader}" 作为仓位编码列。`)
}
}
// 强制将第一列(A 列)映射为仓位编码,符合模板要求
if (headerKeys.length > 0) {
const firstKey = headerKeys[0]!
headerMap[firstKey] = 'space_code'
}
// 保存解析出的 headerMap 与 headerKeys,items 直接使用解析得到的 rows(不再转换字段)
parsedHeaderMap.value = headerMap
parsedHeaderKeys.value = headerKeys
items.value = rows
loaded.value = true
// 如果已有库位类型,把名称转换为 id 再校验;否则直接校验
if (locationTypes.value && locationTypes.value.length) {
remapItemsLocationTypes()
nextTick(() => validateAll())
} else {
nextTick(() => validateAll())
}
}
function remapItemsLocationTypes() {
if (!items.value || !items.value.length) return
// 找到源文件中对应的列名
const hk = findHeaderKeyForField('location_type_name')
items.value.forEach((r: any) => {
const rawStr = String(getRowValue(r, 'location_type_name') ?? '').trim()
// 用名称/id 进行归一化匹配,转换为数字 id;无匹配则设为 null
const rawNorm = normalizeKey(rawStr)
const found = rawStr ? locationTypes.value.find((lt: any) => {
try {
if (normalizeKey(lt.id) === rawNorm) return true
if (normalizeKey(lt.label) === rawNorm) return true
} catch (e) {}
return false
}) : undefined
const mapped = found != null ? found.id : null
if (hk !== undefined) r[hk] = mapped
else r.location_type_name = mapped
})
}
function removeRow(index: number) {
items.value.splice(index, 1)
nextTick(() => validateAll())
}
function clearData() {
items.value = []
loaded.value = false
Object.keys(errors).forEach(k => delete errors[Number(k)])
}
function onRowChange(index: number) {
validateRow(index)
}
function rowClassName({ row, rowIndex }: any) {
return errors[rowIndex] ? 'row-error' : ''
}
const errorCount = computed(() => Object.keys(errors).length)
const hasErrors = computed(() => errorCount.value > 0)
async function loadLocationTypes() {
try {
const res: any = await indexApi.getLocationTypeList()
const data = res && (res.data || res.list || res)
const arr = Array.isArray(data) ? data : []
// normalize to { id, label, value } to avoid undefined in template
// prefer numeric id as value when available so imported numeric ids map to the dropdown
// Always normalize option `value` to string to avoid type mismatch in v-model comparisons
// value 直接用数字 id,便于提交时直接取到 id
locationTypes.value = arr.map((lt: any, idx: number) => {
const id = lt?.id ?? lt?.code ?? idx
const label = String(lt?.type_name ?? lt?.name ?? lt?.location_type_name ?? lt?.label ?? id ?? '').trim()
return { id, label, value: id }
})
// 如果已有解析后的 items,尝试把 items 中的库位类型名称映射为 id 并重新校验
if (items.value && items.value.length) {
remapItemsLocationTypes()
nextTick(() => validateAll())
}
} catch (e) {
locationTypes.value = []
}
}
async function validateAll() {
// clear
Object.keys(errors).forEach(k => delete errors[Number(k)])
// basic checks
const codeCounts: Record<string, number> = {}
items.value.forEach((r, i) => {
const code = String(getRowValue(r, 'space_code') ?? '').trim()
if (!code) {
errors[i] = '缺失仓位编码'
}
codeCounts[code] = (codeCounts[code] || 0) + 1
// pick_sequence check
const pickVal = getRowValue(r, 'pick_sequence')
if (pickVal !== null && pickVal !== undefined && pickVal !== '') {
const n = Number(pickVal)
if (isNaN(n) || n < 0 || !Number.isInteger(n)) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '拣货顺序必须为非负整数'
}
}
// location_type_name 校验:此时存储的应为数字 id 或 null
const locVal = getRowValue(r, 'location_type_name')
if (locVal !== null && locVal !== undefined && String(locVal).trim() !== '') {
const ok = locationTypes.value.some(lt => lt.id === locVal || String(lt.id) === String(locVal))
if (!ok) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '库位类型无效'
}
}
})
// duplicates within batch
for (const [code, cnt] of Object.entries(codeCounts)) {
if (!code) continue
if (cnt > 1) {
items.value.forEach((r, i) => {
if (String(getRowValue(r, 'space_code') ?? '').trim() === code) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位编码在批次内重复'
}
})
}
}
// remote checks: rack membership or existence
if (rackId.value) {
try {
const resp: any = await warehouseApi.getSpacesByRack(rackId.value)
const allowed = Array.isArray(resp.spaces) ? resp.spaces.map((s:any) => String(s.space_code || '').trim()) : []
const allowSet = new Set(allowed)
items.value.forEach((r, i) => {
const code = String(getRowValue(r, 'space_code') ?? '').trim()
if (code && !allowSet.has(code)) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位不属于当前货架'
}
})
} catch (e) {
// ignore
}
} else {
// validate existence by searchSpace
const uniques = Array.from(new Set(items.value.map(r => String(r.space_code || '').trim()).filter(Boolean)))
await Promise.all(uniques.map(async (code) => {
try {
const res: any = await indexApi.searchSpace({ keyword: code })
const data = res && (res.data || res.list || res)
const item = Array.isArray(data) ? (data[0] || null) : data
if (!item) {
// mark all rows with this code
items.value.forEach((r, i) => {
if (String(getRowValue(r, 'space_code') ?? '').trim() === code) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位不存在'
}
})
} else {
// if item has zone/type info and not rack, try to detect
const zoneType = item.zone?.zone_type || item.zone_type || item.type || item.parent_type || ''
if (zoneType && String(zoneType) !== 'rack') {
items.value.forEach((r, i) => {
if (String(getRowValue(r, 'space_code') ?? '').trim() === code) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位不属于货架类型'
}
})
}
}
} catch (e) {
items.value.forEach((r, i) => {
if (String(r.space_code || '').trim() === code) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位校验失败'
}
})
}
}))
}
}
async function validateRow(index: number) {
// re-run validateAll for simplicity
await validateAll()
}
async function submit() {
await validateAll()
if (hasErrors.value) {
ElMessage.warning('请先修正错误后再提交')
return
}
if (!items.value.length) {
ElMessage.warning('没有数据可提交')
return
}
submitLoading.value = true
try {
const payload: any = { items: items.value.map((r: any) => {
const spaceCode = String(getRowValue(r, 'space_code') ?? '').trim()
const customName = getRowValue(r, 'custom_name')
const customBarcode = getRowValue(r, 'custom_barcode')
const pickSeq = getRowValue(r, 'pick_sequence')
const locId = getRowValue(r, 'location_type_name') // 已经是数字 id 或 null
return {
space_code: spaceCode,
custom_name: customName != null ? String(customName) : undefined,
custom_barcode: customBarcode != null ? String(customBarcode) : undefined,
pick_sequence: pickSeq === null || pickSeq === undefined || pickSeq === '' ? undefined : Number(pickSeq),
location_type_id: locId != null && String(locId).trim() !== '' ? Number(locId) : undefined
}
}) }
if (rackId.value) payload.id = rackId.value
const res: any = await warehouseApi.batchUpdateSpaceInfo(payload)
const ok = res && (res.code === 1 || res.code === 200 || res.flag === 'success')
if (!ok) {
ElMessage.error(res?.message || '批量修改失败')
return
}
ElMessage.success(res?.message || '批量修改成功')
emit('success')
close()
} catch (e:any) {
console.error('批量修改失败', e)
ElMessage.error(e?.message || '批量修改失败')
} finally {
submitLoading.value = false
}
}
</script>
<style scoped>
.empty-container {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.row-error td {
background: #fff6f6 !important;
}
</style>