1
This commit is contained in:
parent
00f416d847
commit
2e68b59e60
471
src/views/stock/stock/component/ImportDialog.vue
Normal file
471
src/views/stock/stock/component/ImportDialog.vue
Normal file
@ -0,0 +1,471 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
title="商品导入"
|
||||
width="80vw"
|
||||
align-center
|
||||
class="import-dialog"
|
||||
>
|
||||
<div class="import-dialog-body">
|
||||
<div class="import-toolbar">
|
||||
<input
|
||||
ref="fileInputRef"
|
||||
type="file"
|
||||
class="hidden-file-input"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
@change="handleFileChange"
|
||||
/>
|
||||
<el-button size="small" type="primary" @click="triggerFileSelect">选择文件</el-button>
|
||||
<el-button size="small" @click="downloadTemplate">下载模板</el-button>
|
||||
<el-button size="small" type="success" @click="addRow">新增行</el-button>
|
||||
<el-button size="small" type="danger" :disabled="!hasSelection" @click="deleteSelectedRows">删除行</el-button>
|
||||
<el-button size="small" @click="clearData">清空数据</el-button>
|
||||
<span class="import-file-name">{{ selectedFileName || '未选择文件' }}</span>
|
||||
</div>
|
||||
<div class="import-summary">
|
||||
汇总:共 {{ importSummary.total }} 条,新增 {{ importSummary.addCount }} 条,修改 {{ importSummary.updateCount }} 条
|
||||
</div>
|
||||
|
||||
<div class="import-table-wrap">
|
||||
<el-table :data="importRows" border size="small" height="100%" @selection-change="onSelectionChange">
|
||||
<el-table-column type="selection" width="40" fixed="left" />
|
||||
<el-table-column label="SKU" min-width="140" fixed="left">
|
||||
<template #header>
|
||||
<span>SKU <el-tooltip content="留空为新增商品" placement="top"><span style="color:#909399;font-size:11px">ⓘ</span></el-tooltip></span>
|
||||
</template>
|
||||
<template #default="{ row }"><el-input v-model="row.sku" size="small" readonly placeholder="留空为新增" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="商品编码" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.itemCode" size="small" clearable :class="requiredClass(row.itemCode)" @change="revalidateRow(row)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="商品名称" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.itemName" size="small" clearable :class="requiredClass(row.itemName)" @change="revalidateRow(row)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="货物编码" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.cargoCode" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="条码" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.barcode" size="small" clearable :class="requiredClass(row.barcode)" @change="revalidateRow(row)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="SKU规格" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.skuSpec" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="库存单位" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.stockUnit" size="small" clearable :class="requiredClass(row.stockUnit)" @change="revalidateRow(row)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="品牌" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.brand" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="毛重" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.grossWeight" size="small" clearable :class="requiredClass(row.grossWeight)" @change="revalidateRow(row)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="标价" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.tagPrice" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="零售价" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.retailPrice" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="货主" min-width="160" fixed="left">
|
||||
<template #default="{ row }">
|
||||
<el-select
|
||||
v-model="row.storeName"
|
||||
size="small"
|
||||
clearable
|
||||
filterable
|
||||
:disabled="!!row.sku.trim()"
|
||||
:placeholder="row.sku.trim() ? '已有SKU无需填写' : '请选择货主'"
|
||||
:class="requiredClass(!row.sku.trim() ? row.storeName : 'x')"
|
||||
style="width:100%"
|
||||
@change="revalidateRow(row)"
|
||||
>
|
||||
<el-option
|
||||
v-for="s in stores"
|
||||
:key="s.value"
|
||||
:label="s.label"
|
||||
:value="s.label"
|
||||
/>
|
||||
</el-select>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" min-width="180" align="center" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-tooltip v-if="row.status === 'error'" :content="row.errorMsg" placement="top">
|
||||
<el-tag type="danger" size="small" style="cursor:pointer" @click.stop="copyError(row.errorMsg)">失败</el-tag>
|
||||
</el-tooltip>
|
||||
<template v-else-if="row.status === 'invalid'">
|
||||
<el-tooltip v-if="row.missingFields" :content="'缺失:' + row.missingFields" placement="top">
|
||||
<el-tag type="warning" size="small" style="cursor:pointer;margin-right:4px" @click.stop="copyError('缺失:' + row.missingFields)">缺失数据</el-tag>
|
||||
</el-tooltip>
|
||||
<el-tooltip v-if="row.storeError" :content="row.storeError" placement="top">
|
||||
<el-tag type="danger" size="small" style="cursor:pointer" @click.stop="copyError(row.storeError)">货主异常</el-tag>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-tag v-else-if="row.status === 'success'" type="success" size="small">成功</el-tag>
|
||||
<el-tag v-else type="info" size="small">未提交</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<el-button type="primary" :loading="submitting" @click="handleSubmit">提交</el-button>
|
||||
<el-button @click="handleCloseAttempt">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import * as XLSX from 'xlsx'
|
||||
import * as stockApi from '@/api/stock/stock'
|
||||
import * as indexApi from '@/api/index/index'
|
||||
|
||||
const IMPORT_MAX_ROWS = 1000
|
||||
|
||||
type ImportRow = {
|
||||
sku: string
|
||||
itemCode: string
|
||||
itemName: string
|
||||
cargoCode: string
|
||||
barcode: string
|
||||
skuSpec: string
|
||||
stockUnit: string
|
||||
brand: string
|
||||
grossWeight: string
|
||||
tagPrice: string
|
||||
retailPrice: string
|
||||
storeName: string
|
||||
status: string
|
||||
errorMsg: string
|
||||
missingFields: string
|
||||
storeError: string
|
||||
}
|
||||
|
||||
function createEmptyImportRow(): ImportRow {
|
||||
return { sku: '', itemCode: '', itemName: '', cargoCode: '', barcode: '', skuSpec: '', stockUnit: '', brand: '', grossWeight: '', tagPrice: '', retailPrice: '', storeName: '', status: '', errorMsg: '', missingFields: '', storeError: '' }
|
||||
}
|
||||
|
||||
const props = defineProps<{ modelValue: boolean }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [boolean]; 'success': [] }>()
|
||||
|
||||
const visible = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (v) => {
|
||||
if (!v) {
|
||||
handleCloseAttempt()
|
||||
} else {
|
||||
emit('update:modelValue', true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null)
|
||||
const selectedFileName = ref('')
|
||||
const submitting = ref(false)
|
||||
const stores = ref<Array<{ value: number | string; label: string }>>([])
|
||||
const importRows = ref<ImportRow[]>([])
|
||||
const selectedRows = ref<ImportRow[]>([])
|
||||
const hasSelection = computed(() => selectedRows.value.length > 0)
|
||||
|
||||
const importSummary = computed(() => {
|
||||
const nonEmpty = importRows.value.filter(r => Object.values(r).some(v => String(v || '').trim() !== ''))
|
||||
const updateCount = nonEmpty.filter(r => String(r.sku || '').trim() !== '').length
|
||||
return { total: nonEmpty.length, addCount: nonEmpty.length - updateCount, updateCount }
|
||||
})
|
||||
|
||||
async function handleCloseAttempt() {
|
||||
const nonEmpty = importRows.value.filter(r => Object.values(r).some(v => String(v || '').trim() !== '' && v !== r.status && v !== r.errorMsg))
|
||||
if (!nonEmpty.length) { doClose(); return }
|
||||
const hasUnsubmitted = importRows.value.some(r => r.status === '')
|
||||
const hasFailed = importRows.value.some(r => r.status === 'error')
|
||||
if (hasUnsubmitted || hasFailed) {
|
||||
try {
|
||||
await ElMessageBox.confirm('有未提交或失败的数据,关闭将丢失修改,确定关闭?', '提示', { type: 'warning', confirmButtonText: '确定关闭', cancelButtonText: '取消' })
|
||||
} catch { return }
|
||||
}
|
||||
doClose()
|
||||
}
|
||||
|
||||
function doClose() {
|
||||
clearData()
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
function clearData() {
|
||||
importRows.value = []
|
||||
selectedFileName.value = ''
|
||||
selectedRows.value = []
|
||||
if (fileInputRef.value) fileInputRef.value.value = ''
|
||||
}
|
||||
|
||||
function addRow() {
|
||||
importRows.value.push(createEmptyImportRow())
|
||||
}
|
||||
|
||||
function onSelectionChange(rows: ImportRow[]) {
|
||||
selectedRows.value = rows
|
||||
}
|
||||
|
||||
function deleteSelectedRows() {
|
||||
const ids = new Set(selectedRows.value)
|
||||
importRows.value = importRows.value.filter(r => !ids.has(r))
|
||||
selectedRows.value = []
|
||||
}
|
||||
|
||||
function copyError(msg: string) {
|
||||
navigator.clipboard.writeText(msg).then(() => ElMessage.success('已复制')).catch(() => ElMessage.error('复制失败'))
|
||||
}
|
||||
|
||||
function validateRow(r: ImportRow): string[] {
|
||||
const msgs: string[] = []
|
||||
if (!r.itemCode.trim()) msgs.push('商品编码')
|
||||
if (!r.itemName.trim()) msgs.push('商品名称')
|
||||
if (!r.barcode.trim()) msgs.push('条码')
|
||||
if (!r.stockUnit.trim()) msgs.push('库存单位')
|
||||
if (!r.grossWeight.trim()) msgs.push('毛重')
|
||||
const sku = r.sku.trim()
|
||||
if (!sku && !r.storeName.trim()) msgs.push('货主')
|
||||
return msgs
|
||||
}
|
||||
|
||||
function requiredClass(val: string): string {
|
||||
return val.trim() ? '' : 'required-error'
|
||||
}
|
||||
|
||||
/** 重新校验单行并更新状态 */
|
||||
function revalidateRow(r: ImportRow) {
|
||||
// 跳过空行
|
||||
if (!Object.values(r).some(v => String(v || '').trim() !== '' && v !== r.status && v !== r.errorMsg && v !== r.missingFields && v !== r.storeError)) {
|
||||
r.status = ''; r.missingFields = ''; r.storeError = ''
|
||||
return
|
||||
}
|
||||
// 清除旧状态
|
||||
r.status = ''; r.missingFields = ''; r.storeError = ''
|
||||
// 必填字段检查
|
||||
const missing = validateRow(r)
|
||||
if (missing.length) {
|
||||
r.missingFields = missing.join('、')
|
||||
r.status = 'invalid'
|
||||
}
|
||||
// 货主匹配检查(无SKU的新增行)
|
||||
if (!r.sku.trim() && r.storeName.trim()) {
|
||||
const match = stores.value.find(s => s.label === r.storeName.trim() || String(s.value) === r.storeName.trim())
|
||||
if (!match) {
|
||||
r.storeError = '货主「' + r.storeName.trim() + '」未匹配'
|
||||
r.status = 'invalid'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function downloadTemplate() {
|
||||
const headers = ['SKU', '商品编码', '商品名称', '货物编码', '条码', 'SKU规格', '库存单位', '品牌', '毛重', '标价', '零售价', '货主']
|
||||
const ws = XLSX.utils.aoa_to_sheet([headers])
|
||||
ws['!cols'] = headers.map(() => ({ wch: 20 }))
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, '导入模板')
|
||||
XLSX.writeFile(wb, '商品导入模板.xlsx')
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (v) => { if (v) { clearData(); loadStores() } })
|
||||
|
||||
async function loadStores() {
|
||||
try {
|
||||
const res: any = await indexApi.loadStores({ type: 'stock' })
|
||||
const list = res?.stores || res?.data?.stores || res?.data || []
|
||||
stores.value = (Array.isArray(list) ? list : []).map((s: any) => ({
|
||||
value: s.id || s.store_id || s.value,
|
||||
label: s.name || s.store_name || s.label || String(s.id || '')
|
||||
}))
|
||||
} catch { stores.value = [] }
|
||||
}
|
||||
|
||||
async function triggerFileSelect() {
|
||||
if (!stores.value.length) {
|
||||
await loadStores()
|
||||
if (!stores.value.length) {
|
||||
ElMessage.warning('货主数据加载失败,请重试')
|
||||
return
|
||||
}
|
||||
}
|
||||
fileInputRef.value?.click()
|
||||
}
|
||||
|
||||
function handleFileChange(event: Event) {
|
||||
const file = (event.target as HTMLInputElement).files?.[0]
|
||||
selectedFileName.value = file?.name || ''
|
||||
if (file) void parseExcel(file)
|
||||
}
|
||||
|
||||
function pickCell(row: Record<string, any>, aliases: string[]): string {
|
||||
for (const k of aliases) {
|
||||
const v = row[k]
|
||||
if (v != null && String(v).trim() !== '') return String(v).trim()
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function mapRow(row: Record<string, any>): ImportRow {
|
||||
return {
|
||||
sku: pickCell(row, ['SKU', '商品ID', '商品id', 'sku', 'Sku']),
|
||||
itemCode: pickCell(row, ['商品编码', 'item_code', 'itemCode']),
|
||||
itemName: pickCell(row, ['商品名称', 'item_name', 'itemName', '名称']),
|
||||
cargoCode: pickCell(row, ['货物编码', '货品编码', 'cargo_code', 'cargoCode', '货号']),
|
||||
barcode: pickCell(row, ['条码', 'barcode', 'bar_code', '条形码']),
|
||||
skuSpec: pickCell(row, ['SKU规格', 'sku规格', 'sku_property', 'skuSpec', '规格']),
|
||||
stockUnit: pickCell(row, ['库存单位', 'stock_unit', 'stockUnit', '单位']),
|
||||
brand: pickCell(row, ['品牌', 'brand_name', 'brand']),
|
||||
grossWeight: pickCell(row, ['毛重', 'gross_weight', 'grossWeight']),
|
||||
tagPrice: pickCell(row, ['标价', 'tag_price', 'tagPrice']),
|
||||
retailPrice: pickCell(row, ['零售价', 'retail_price', 'retailPrice']),
|
||||
storeName: pickCell(row, ['货主', 'store_name', 'storeName', '店铺']),
|
||||
status: '',
|
||||
errorMsg: '',
|
||||
missingFields: '',
|
||||
storeError: ''
|
||||
}
|
||||
}
|
||||
|
||||
/** 对所有行做校验并标记状态,返回 invalid 行数 */
|
||||
function validateAllRows(): number {
|
||||
const storeList = stores.value
|
||||
let invalidCount = 0
|
||||
for (const r of importRows.value) {
|
||||
// 跳过空行
|
||||
if (!Object.values(r).some(v => String(v || '').trim() !== '' && v !== r.status && v !== r.errorMsg && v !== r.missingFields && v !== r.storeError)) continue
|
||||
// 清除旧状态
|
||||
r.status = ''; r.errorMsg = ''; r.missingFields = ''; r.storeError = ''
|
||||
// 必填字段检查
|
||||
const missing = validateRow(r)
|
||||
if (missing.length) {
|
||||
r.missingFields = missing.join('、')
|
||||
r.status = 'invalid'
|
||||
}
|
||||
// 货主匹配检查(无SKU的新增行)
|
||||
if (!r.sku.trim() && r.storeName.trim()) {
|
||||
const match = storeList.find(s => s.label === r.storeName.trim() || String(s.value) === r.storeName.trim())
|
||||
if (!match) {
|
||||
r.storeError = '货主「' + r.storeName.trim() + '」未匹配'
|
||||
r.status = 'invalid'
|
||||
}
|
||||
}
|
||||
if (r.status === 'invalid') invalidCount++
|
||||
}
|
||||
return invalidCount
|
||||
}
|
||||
|
||||
async function parseExcel(file: File) {
|
||||
try {
|
||||
const buf = await file.arrayBuffer()
|
||||
const wb = XLSX.read(buf, { type: 'array' })
|
||||
const ws = wb.Sheets[wb.SheetNames?.[0] || '']
|
||||
if (!ws) { ElMessage.error('未读取到工作表'); return }
|
||||
const rawRows = XLSX.utils.sheet_to_json<Record<string, any>>(ws, { defval: '' })
|
||||
const mapped = rawRows.map(mapRow).filter(r => Object.values(r).some(v => v !== ''))
|
||||
if (mapped.length > IMPORT_MAX_ROWS) { ElMessage.error(`不超过 ${IMPORT_MAX_ROWS} 行`); return }
|
||||
importRows.value = mapped.length ? mapped : []
|
||||
selectedRows.value = []
|
||||
// 导入后立即校验
|
||||
const invalidCount = validateAllRows()
|
||||
const suffix = invalidCount ? `,其中 ${invalidCount} 行数据不完整` : ''
|
||||
ElMessage.success(`已读取 ${mapped.length} 条${suffix}`)
|
||||
} catch { ElMessage.error('解析 Excel 失败') }
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
const storeList = stores.value
|
||||
|
||||
// 提交前清除状态
|
||||
importRows.value.forEach(r => { r.status = ''; r.errorMsg = '' })
|
||||
|
||||
// 预校验:标记不符合规则的行
|
||||
const invalidCount = validateAllRows()
|
||||
if (invalidCount) {
|
||||
ElMessage.warning(`共 ${invalidCount} 行数据不完整,请补全后提交`)
|
||||
return
|
||||
}
|
||||
|
||||
const payload = importRows.value
|
||||
.filter(r => Object.values(r).some(v => String(v || '').trim() !== ''))
|
||||
.map(r => {
|
||||
const sku = String(r.sku || '').trim()
|
||||
const storeName = r.storeName.trim()
|
||||
let storeId: number | undefined
|
||||
if (!sku) {
|
||||
const match = storeList.find(s => s.label === storeName || String(s.value) === storeName)
|
||||
if (match) storeId = Number(match.value)
|
||||
}
|
||||
return {
|
||||
stock_id: sku || undefined,
|
||||
item_code: r.itemCode.trim(),
|
||||
item_name: r.itemName.trim(),
|
||||
cargo_code: r.cargoCode.trim(),
|
||||
barcode: r.barcode.trim(),
|
||||
sku_property: r.skuSpec.trim(),
|
||||
stock_unit: r.stockUnit.trim(),
|
||||
brand_name: r.brand.trim(),
|
||||
gross_weight: r.grossWeight.trim(),
|
||||
tag_price: r.tagPrice.trim(),
|
||||
retail_price: r.retailPrice.trim(),
|
||||
store_id: storeId,
|
||||
action: sku ? 'update' : 'add'
|
||||
}
|
||||
})
|
||||
if (!payload.length) { ElMessage.warning('没有可提交的数据'); return }
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 提交前清除所有行的状态
|
||||
importRows.value.forEach(r => { r.status = ''; r.errorMsg = '' })
|
||||
const res: any = await stockApi.importStockWarehouse(payload)
|
||||
const total = Number(res?.total_count ?? payload.length)
|
||||
const created = Number(res?.created_count ?? 0)
|
||||
const updated = Number(res?.updated_count ?? 0)
|
||||
const fail = Number(res?.fail_count ?? 0)
|
||||
const failItems: Array<{ index: number; error: string }> = res?.fail_items || []
|
||||
|
||||
// 标记所有行状态
|
||||
const failIdxSet = new Set(failItems.map(f => f.index))
|
||||
for (let i = 0; i < importRows.value.length; i++) {
|
||||
const row = importRows.value[i]
|
||||
if (row && !failIdxSet.has(i)) {
|
||||
row.status = 'success'
|
||||
}
|
||||
}
|
||||
|
||||
// 标记失败行
|
||||
for (const item of failItems) {
|
||||
const idx = item.index
|
||||
if (idx >= 0 && idx < importRows.value.length) {
|
||||
const row = importRows.value[idx]
|
||||
if (row) {
|
||||
row.status = 'error'
|
||||
row.errorMsg = item.error || '导入失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fail === 0) {
|
||||
ElMessage.success(`导入完成:总数 ${total},新增 ${created},更新 ${updated}`)
|
||||
emit('success')
|
||||
} else {
|
||||
ElMessage.warning(`导入完成:总数 ${total},成功 ${total - fail},失败 ${fail},请查看失败行`)
|
||||
}
|
||||
} catch (e: any) { ElMessage.error(e?.message || '导入提交失败') }
|
||||
finally { submitting.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.hidden-file-input { display: none; }
|
||||
:deep(.import-dialog.el-dialog) { max-width: none; height: 80vh; display: flex; flex-direction: column; }
|
||||
:deep(.import-dialog .el-dialog__body) { flex: 1; min-height: 0; padding: 12px 16px; overflow: hidden; }
|
||||
.import-dialog-body { height: 100%; display: flex; flex-direction: column; gap: 10px; min-height: 0; overflow: hidden; }
|
||||
.import-toolbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.import-file-name { color: #606266; font-size: 12px; }
|
||||
.import-summary { color: #606266; font-size: 13px; }
|
||||
.import-table-wrap { flex: 1; min-height: 0; overflow: hidden; }
|
||||
.import-table-wrap :deep(.el-table) { height: 100%; }
|
||||
.required-error :deep(.el-input__wrapper) { box-shadow: 0 0 0 1px #f56c6c inset !important; }
|
||||
</style>
|
||||
@ -70,6 +70,15 @@
|
||||
</el-dropdown>
|
||||
</template>
|
||||
|
||||
<el-button
|
||||
size="small"
|
||||
type="warning"
|
||||
@click="handleClearData"
|
||||
title="清空当前筛选数据"
|
||||
>
|
||||
清空数据
|
||||
</el-button>
|
||||
|
||||
<el-button
|
||||
v-if="hasPermission('warehouseExport')"
|
||||
type="success"
|
||||
@ -288,73 +297,13 @@
|
||||
</div>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog
|
||||
v-model="importDialogVisible"
|
||||
title="商品导入"
|
||||
width="80vw"
|
||||
align-center
|
||||
class="import-dialog"
|
||||
>
|
||||
<div class="import-dialog-body">
|
||||
<div class="import-toolbar">
|
||||
<input
|
||||
ref="importFileInputRef"
|
||||
type="file"
|
||||
class="hidden-file-input"
|
||||
@change="handleImportFileChange"
|
||||
/>
|
||||
<el-button size="small" type="primary" @click="triggerImportFileSelect">选择文件</el-button>
|
||||
<span class="import-file-name">{{ selectedImportFileName || '未选择文件' }}</span>
|
||||
</div>
|
||||
<div class="import-summary">
|
||||
汇总:共 {{ importSummary.total }} 条,新增 {{ importSummary.addCount }} 条,修改 {{ importSummary.updateCount }} 条
|
||||
</div>
|
||||
|
||||
<div class="import-table-wrap">
|
||||
<el-table :data="importRows" border size="small" height="100%">
|
||||
<el-table-column label="SKU" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.sku" size="small" readonly /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="商品编码" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.itemCode" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="货物编码" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.cargoCode" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="SKU规格" min-width="140">
|
||||
<template #default="{ row }"><el-input v-model="row.skuSpec" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="库存单位" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.stockUnit" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="品牌" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.brand" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="毛重" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.grossWeight" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="标价" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.tagPrice" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="零售价" min-width="120">
|
||||
<template #default="{ row }"><el-input v-model="row.retailPrice" size="small" clearable /></template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<el-button type="primary" :loading="importSubmitting" @click="handleImportSubmit">提交</el-button>
|
||||
<el-button @click="closeImportDialog">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
<ImportDialog v-model="importDialogVisible" @success="handleImportSuccess" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, computed, onMounted, onBeforeUnmount, shallowRef, markRaw } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import * as XLSX from 'xlsx'
|
||||
import {
|
||||
Refresh, Plus, Delete, DeleteFilled, Edit, Download, Upload,
|
||||
ArrowDown, User, InfoFilled
|
||||
@ -371,6 +320,7 @@ import Barcode from './component/barcode.vue'
|
||||
import Log from './component/log.vue'
|
||||
import Add from './component/add.vue'
|
||||
import Recycle from './component/recycle.vue'
|
||||
import ImportDialog from './component/ImportDialog.vue'
|
||||
import { stockColumns, availableFields as stockAvailableFields, stockBatchConfig } from './stock-config'
|
||||
|
||||
// API
|
||||
@ -458,54 +408,6 @@ const pagination = reactive({
|
||||
const batchConfig = reactive(JSON.parse(JSON.stringify(stockBatchConfig)))
|
||||
const exportDialogVisible = ref(false)
|
||||
const importDialogVisible = ref(false)
|
||||
const selectedImportFileName = ref('')
|
||||
const importSubmitting = ref(false)
|
||||
const IMPORT_MAX_ROWS = 1000
|
||||
|
||||
type ImportRow = {
|
||||
sku: string
|
||||
itemCode: string
|
||||
cargoCode: string
|
||||
skuSpec: string
|
||||
stockUnit: string
|
||||
brand: string
|
||||
grossWeight: string
|
||||
tagPrice: string
|
||||
retailPrice: string
|
||||
}
|
||||
|
||||
function createEmptyImportRow(): ImportRow {
|
||||
return {
|
||||
sku: '',
|
||||
itemCode: '',
|
||||
cargoCode: '',
|
||||
skuSpec: '',
|
||||
stockUnit: '',
|
||||
brand: '',
|
||||
grossWeight: '',
|
||||
tagPrice: '',
|
||||
retailPrice: ''
|
||||
}
|
||||
}
|
||||
|
||||
const importRows = ref<ImportRow[]>([
|
||||
createEmptyImportRow(),
|
||||
createEmptyImportRow(),
|
||||
createEmptyImportRow(),
|
||||
createEmptyImportRow(),
|
||||
createEmptyImportRow()
|
||||
])
|
||||
|
||||
const importSummary = computed(() => {
|
||||
const nonEmptyRows = importRows.value.filter((row) => Object.values(row).some((v) => String(v || '').trim() !== ''))
|
||||
const updateCount = nonEmptyRows.filter((row) => String(row.sku || '').trim() !== '').length
|
||||
const addCount = nonEmptyRows.length - updateCount
|
||||
return {
|
||||
total: nonEmptyRows.length,
|
||||
addCount,
|
||||
updateCount
|
||||
}
|
||||
})
|
||||
const exportTaskProgress = reactive({
|
||||
taskId: '',
|
||||
status: 'submitted' as 'submitted' | 'running' | 'success' | 'failed' | 'not_found',
|
||||
@ -802,6 +704,15 @@ const confirmBatchDialog = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const handleClearData = () => {
|
||||
currentConditions.value = {}
|
||||
loadData()
|
||||
}
|
||||
|
||||
const handleImportSuccess = () => {
|
||||
loadData()
|
||||
}
|
||||
|
||||
const handleExport = () => {
|
||||
if (exportLoading.value) return
|
||||
void submitExportTask()
|
||||
@ -811,142 +722,7 @@ const handleTabChange = () => {
|
||||
//
|
||||
}
|
||||
|
||||
const openImportDialog = () => {
|
||||
importDialogVisible.value = true
|
||||
}
|
||||
|
||||
const closeImportDialog = () => {
|
||||
importDialogVisible.value = false
|
||||
}
|
||||
|
||||
const triggerImportFileSelect = () => {
|
||||
importFileInputRef.value?.click()
|
||||
}
|
||||
|
||||
const handleImportFileChange = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement
|
||||
const file = target?.files?.[0]
|
||||
selectedImportFileName.value = file?.name || ''
|
||||
if (file) {
|
||||
void parseImportExcel(file)
|
||||
}
|
||||
}
|
||||
|
||||
function pickExcelCellValue(row: Record<string, any>, aliases: string[]) {
|
||||
for (const key of aliases) {
|
||||
if (!Object.prototype.hasOwnProperty.call(row, key)) continue
|
||||
const val = row[key]
|
||||
if (val === null || val === undefined) continue
|
||||
const text = String(val).trim()
|
||||
if (text !== '') return text
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function mapExcelRowToImportRow(row: Record<string, any>): ImportRow {
|
||||
return {
|
||||
sku: pickExcelCellValue(row, ['SKU', '商品ID', '商品id', 'sku', 'Sku']),
|
||||
itemCode: pickExcelCellValue(row, ['商品编码', 'item_code', 'itemCode']),
|
||||
cargoCode: pickExcelCellValue(row, ['货物编码', '货品编码', 'cargo_code', 'cargoCode', '货号']),
|
||||
skuSpec: pickExcelCellValue(row, ['SKU规格', 'sku规格', 'sku_property', 'skuSpec', '规格']),
|
||||
stockUnit: pickExcelCellValue(row, ['库存单位', 'stock_unit', 'stockUnit', '单位']),
|
||||
brand: pickExcelCellValue(row, ['品牌', 'brand_name', 'brand']),
|
||||
grossWeight: pickExcelCellValue(row, ['毛重', 'gross_weight', 'grossWeight']),
|
||||
tagPrice: pickExcelCellValue(row, ['标价', 'tag_price', 'tagPrice']),
|
||||
retailPrice: pickExcelCellValue(row, ['零售价', 'retail_price', 'retailPrice'])
|
||||
}
|
||||
}
|
||||
|
||||
async function parseImportExcel(file: File) {
|
||||
try {
|
||||
const buf = await file.arrayBuffer()
|
||||
const wb = XLSX.read(buf, { type: 'array' })
|
||||
const firstSheetName = wb.SheetNames?.[0]
|
||||
if (!firstSheetName) {
|
||||
ElMessage.error('未读取到工作表')
|
||||
return
|
||||
}
|
||||
const ws = wb.Sheets[firstSheetName]
|
||||
if (!ws) {
|
||||
ElMessage.error('未读取到工作表内容')
|
||||
return
|
||||
}
|
||||
const rawRows = XLSX.utils.sheet_to_json<Record<string, any>>(ws, { defval: '' })
|
||||
const mappedRows = rawRows
|
||||
.map(mapExcelRowToImportRow)
|
||||
.filter((row) => Object.values(row).some((v) => String(v || '').trim() !== ''))
|
||||
|
||||
if (mappedRows.length > IMPORT_MAX_ROWS) {
|
||||
ElMessage.error(`导入数据不能超过 ${IMPORT_MAX_ROWS} 行`)
|
||||
return
|
||||
}
|
||||
|
||||
importRows.value = mappedRows.length ? mappedRows : [createEmptyImportRow()]
|
||||
ElMessage.success(`已读取 ${mappedRows.length} 条数据`)
|
||||
} catch (error) {
|
||||
console.error('解析导入模板失败:', error)
|
||||
ElMessage.error('解析 Excel 失败,请检查模板格式')
|
||||
}
|
||||
}
|
||||
|
||||
function buildImportPayload() {
|
||||
return importRows.value
|
||||
.filter((row) => Object.values(row).some((v) => String(v || '').trim() !== ''))
|
||||
.map((row) => {
|
||||
const sku = String(row.sku || '').trim()
|
||||
return {
|
||||
stock_id: sku || undefined,
|
||||
item_code: String(row.itemCode || '').trim(),
|
||||
cargo_code: String(row.cargoCode || '').trim(),
|
||||
sku_property: String(row.skuSpec || '').trim(),
|
||||
stock_unit: String(row.stockUnit || '').trim(),
|
||||
brand_name: String(row.brand || '').trim(),
|
||||
gross_weight: String(row.grossWeight || '').trim(),
|
||||
tag_price: String(row.tagPrice || '').trim(),
|
||||
retail_price: String(row.retailPrice || '').trim(),
|
||||
action: sku ? 'update' : 'add'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function handleImportSubmit() {
|
||||
const payload = buildImportPayload()
|
||||
if (!payload.length) {
|
||||
ElMessage.warning('没有可提交的导入数据')
|
||||
return
|
||||
}
|
||||
if (payload.length > IMPORT_MAX_ROWS) {
|
||||
ElMessage.error(`导入数据不能超过 ${IMPORT_MAX_ROWS} 行`)
|
||||
return
|
||||
}
|
||||
|
||||
importSubmitting.value = true
|
||||
try {
|
||||
const res: any = await stockApi.importStockWarehouse(payload)
|
||||
const totalCount = Number(res?.total_count ?? payload.length)
|
||||
const createdCount = Number(res?.created_count ?? 0)
|
||||
const updatedCount = Number(res?.updated_count ?? 0)
|
||||
const failCount = Number(res?.fail_count ?? 0)
|
||||
const failItems = Array.isArray(res?.fail_items) ? res.fail_items : []
|
||||
|
||||
ElMessage.success(`导入完成:总数 ${totalCount},新增 ${createdCount},更新 ${updatedCount},失败 ${failCount}`)
|
||||
|
||||
if (failItems.length > 0) {
|
||||
console.log('stockImportFailItems', failItems)
|
||||
ElMessage.warning(`存在 ${failItems.length} 条失败明细,已输出到控制台`)
|
||||
}
|
||||
|
||||
if (failCount === 0) {
|
||||
closeImportDialog()
|
||||
loadData()
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('stockImportError', error)
|
||||
ElMessage.error(error?.message || '导入提交失败')
|
||||
} finally {
|
||||
importSubmitting.value = false
|
||||
}
|
||||
}
|
||||
const openImportDialog = () => { importDialogVisible.value = true }
|
||||
|
||||
onMounted(async () => {
|
||||
// Load stores, prohibited types etc.
|
||||
@ -1310,54 +1086,4 @@ function formatDateTime(value: string | number | null | undefined) {
|
||||
.hidden-file-input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:deep(.import-dialog.el-dialog) {
|
||||
max-width: none;
|
||||
height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
:deep(.import-dialog .el-dialog__body) {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 12px 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.import-dialog-body {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.import-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.import-file-name {
|
||||
color: #606266;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.import-summary {
|
||||
color: #606266;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.import-table-wrap {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.import-table-wrap :deep(.el-table) {
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
Loading…
x
Reference in New Issue
Block a user