库存导入

master
lion 2 days ago
parent 79f4e138f3
commit f16919e138

@ -34,7 +34,6 @@ export function show(params) {
})
}
export function del(params) {
return request({
url: '/api/admin/book_detail/destroy',
@ -42,3 +41,11 @@ export function del(params) {
params
})
}
export function previewImport(rows) {
return request({ url: '/api/admin/book_detail/import-preview', method: 'post', data: { rows }, timeout: 120000, isLoading: false })
}
export function commitImport(token) {
return request({ url: '/api/admin/book_detail/import-commit', method: 'post', data: { token }, timeout: 120000, isLoading: false })
}

@ -0,0 +1,49 @@
import * as XLSX from 'xlsx'
const columns = {
'库存编号': 'no', '图书分类': 'category', '图书': 'book_name', '作者': 'author',
'装订方式': 'bind_way', '所在位置': 'location', '入库日期': 'enter_date', '备注': 'remark'
}
export function parseInventoryWorkbook(workbook, sheetName) {
const sheet = workbook.Sheets[sheetName]
if (!sheet || !sheet['!ref']) throw new Error('工作表没有数据')
const range = XLSX.utils.decode_range(sheet['!ref'])
if (range.e.r > 10000 || range.e.c > 100) throw new Error('工作表范围过大,请删除多余空行和空列后重试')
const grid = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: true, defval: '', blankrows: true, range: 0 })
const headerRow = grid.findIndex(row => row.some(value => String(value).trim()))
if (headerRow < 0) throw new Error('工作表没有数据')
const header = grid[headerRow].map(value => String(value).trim())
Object.keys(columns).forEach(name => {
if (header.filter(value => value === name).length !== 1) throw new Error(`必须且只能包含一个“${name}”列,请使用库存导出文件`)
})
const rows = []
for (let index = headerRow + 1; index < grid.length; index++) {
const source = grid[index]
if (!source.some(value => String(value).trim())) continue
const row = { row_number: index + 1 }
Object.keys(columns).concat(header.includes('借阅状态') ? ['借阅状态'] : []).forEach(name => {
const col = header.indexOf(name)
const cell = sheet[XLSX.utils.encode_cell({ r: index, c: col })]
if (cell && cell.f) throw new Error(`第 ${index + 1} 行“${name}”为公式,请先粘贴为值`)
let value = source[col] === undefined ? '' : source[col]
if (name === '入库日期') {
if (typeof value === 'number') {
const date = XLSX.SSF.parse_date_code(value, { date1904: !!workbook.Workbook?.WBProps?.date1904 })
if (!date || date.y < 1900 || date.m < 1 || date.d < 1) throw new Error(`第 ${index + 1} 行入库日期无效`)
value = `${date.y}-${String(date.m).padStart(2, '0')}-${String(date.d).padStart(2, '0')}`
} else {
const match = String(value).trim().match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/)
if (match) value = `${match[1]}-${match[2].padStart(2, '0')}-${match[3].padStart(2, '0')}`
}
} else if (name === '库存编号' && cell && cell.t === 'n') {
value = XLSX.utils.format_cell(cell)
}
row[name === '借阅状态' ? 'borrow_status' : columns[name]] = String(value).trim()
})
rows.push(row)
if (rows.length > 5000) throw new Error('每次最多导入 5000 条库存')
}
if (!rows.length) throw new Error('工作表没有库存明细')
return rows
}

@ -0,0 +1,149 @@
<template>
<el-dialog title="导入库存记录" :visible.sync="visible" width="94%" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy" :before-close="beforeClose">
<el-alert type="warning" :closable="false" show-icon title="按库存编号更新已有记录;空位置会清空书架、列、行,空备注会清除原备注。" />
<p>同时更新图书分类、书名、作者、装订方式(作者和装订方式留空也会清空)。同书所有库存共用图书资料;未列出的库存保留,借阅状态、创建时间及系统排序保持原样。</p>
<p>使用库存导出的 .xlsx 文件,分类需与系统已有分类匹配。每次最多 5,000 条、10 MB。校验预览 15 分钟内有效。</p>
<input ref="file" type="file" accept=".xlsx" :disabled="busy" aria-label="选择库存 Excel 文件" @change="selectFile">
<el-select v-if="sheetNames.length > 1" v-model="sheetName" :disabled="busy" placeholder="选择工作表" @change="result = null">
<el-option v-for="name in sheetNames" :key="name" :label="name" :value="name" />
</el-select>
<el-button type="primary" :disabled="!workbook || busy" :loading="checking" @click="preview">校验并预览</el-button>
<el-alert v-if="error" type="error" :closable="false" :title="error" style="margin-top: 12px" />
<template v-if="result">
<p>共 {{ result.total }} 条;库存信息变更 {{ result.update_count }} 条;图书资料变更 {{ result.book_update_count }} 种(关联库存共 {{ result.affected_inventory_count }} 条)。错误 {{ result.errors.length }} 项,借阅状态提示 {{ result.warnings.length }} 项。</p>
<el-tabs v-model="tab">
<el-tab-pane :label="`更新预览(${result.items.length})`" name="preview">
<el-table :data="previewItems" height="390" border>
<el-table-column prop="row_number" label="Excel行" width="80" />
<el-table-column prop="no" label="库存编号" width="115" />
<el-table-column label="图书资料:原值 → 新值" min-width="300">
<template slot-scope="scope">
<div>书名:{{ scope.row.before_book_name }} → {{ scope.row.book_name }}</div>
<div>分类:{{ scope.row.before_category || '(空)' }} → {{ scope.row.after_category }}</div>
<div>作者:{{ scope.row.before_author || '(空)' }} → {{ scope.row.after_author || '(清空)' }}</div>
<div>装订:{{ scope.row.before_bind_way || '(空)' }} → {{ scope.row.after_bind_way || '(清空)' }}</div>
</template>
</el-table-column>
<el-table-column label="位置:原值 → 新值" min-width="250">
<template slot-scope="scope">{{ scope.row.before_location || '(空)' }} → {{ scope.row.after_location || '(清空)' }}</template>
</el-table-column>
<el-table-column label="备注:原值 → 新值" min-width="240">
<template slot-scope="scope">{{ scope.row.before_remark || '(空)' }} → {{ scope.row.after_remark || '(清空)' }}</template>
</el-table-column>
<el-table-column label="入库日期:原值 → 新值" min-width="215">
<template slot-scope="scope">{{ scope.row.before_date }} → {{ scope.row.after_date }}</template>
</el-table-column>
</el-table>
<el-pagination :current-page.sync="page" :page-size="50" :total="result.items.length" layout="total, prev, pager, next" />
</el-tab-pane>
<el-tab-pane v-if="result.errors.length" :label="`错误(${result.errors.length})`" name="errors">
<el-table :data="result.errors" height="390" border><el-table-column prop="row_number" label="Excel行" width="80" /><el-table-column prop="no" label="库存编号" width="120" /><el-table-column prop="message" label="错误原因" /></el-table>
</el-tab-pane>
<el-tab-pane v-if="result.warnings.length" :label="`借阅状态提示(${result.warnings.length})`" name="warnings">
<el-table :data="result.warnings" height="390" border><el-table-column prop="row_number" label="Excel行" width="80" /><el-table-column prop="no" label="库存编号" width="120" /><el-table-column prop="message" label="提示" /></el-table>
</el-tab-pane>
</el-tabs>
<el-checkbox v-if="result.token" v-model="confirmed" :disabled="busy" style="margin-top: 16px">已核对预览,确认清空表内空位置、空备注,并更新共用图书资料;借阅状态保持原样。</el-checkbox>
</template>
<span slot="footer">
<el-button :disabled="busy" @click="visible = false">关闭</el-button>
<el-button type="primary" :loading="submitting" :disabled="!canCommit" @click="commit">确认导入</el-button>
</span>
</el-dialog>
</template>
<script>
import { previewImport, commitImport } from '@/api/bookStore/storeList'
import { parseInventoryWorkbook } from '@/utils/inventoryImport'
export default {
data() {
return { visible: false, workbook: null, sheetNames: [], sheetName: '', checking: false, submitting: false, result: null, error: '', confirmed: false, page: 1, tab: 'preview' }
},
computed: {
busy() { return this.checking || this.submitting },
canCommit() { return !!(this.result && this.result.token && !this.result.errors.length && this.confirmed && !this.busy) },
previewItems() { return this.result ? this.result.items.slice((this.page - 1) * 50, this.page * 50) : [] }
},
methods: {
open() {
this.visible = true
this.workbook = null
this.result = null
this.error = ''
this.confirmed = false
this.sheetNames = []
this.sheetName = ''
this.$nextTick(() => { if (this.$refs.file) this.$refs.file.value = '' })
},
beforeClose(done) { if (!this.busy) done() },
async selectFile(event) {
this.result = null
this.workbook = null
this.sheetNames = []
this.error = ''
this.confirmed = false
const file = event.target.files[0]
if (!file) return
if (!/\.xlsx$/i.test(file.name) || file.size > 10 * 1024 * 1024) {
this.error = '请选择不超过 10 MB 的 .xlsx 文件'
return
}
this.checking = true
try {
const XLSX = await import('xlsx')
const data = await new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result)
reader.onerror = () => reject(new Error('读取文件失败'))
reader.readAsArrayBuffer(file)
})
// Workbook 不放入 Vue 深层响应式观察,避免大文件遍历开销。
this.workbook = Object.freeze(XLSX.read(data, { type: 'array' }))
this.sheetNames = this.workbook.SheetNames
this.sheetName = this.sheetNames[0]
} catch (e) {
this.error = '无法读取 Excel,请确认文件完整且未加密'
} finally {
this.checking = false
}
},
async preview() {
if (this.busy || !this.workbook) return
this.checking = true
this.error = ''
this.result = null
this.confirmed = false
try {
const rows = parseInventoryWorkbook(this.workbook, this.sheetName)
this.result = await previewImport(rows)
this.page = 1
this.tab = this.result.errors.length ? 'errors' : 'preview'
} catch (e) {
this.error = e.message || '校验失败,请稍后重试'
} finally {
this.checking = false
}
},
async commit() {
if (!this.canCommit) return
this.submitting = true
this.error = ''
try {
const result = await commitImport(this.result.token)
this.$Message.success(`导入成功:库存更新 ${result.updated} 条,图书更新 ${result.books_updated} 种`)
this.visible = false
this.result = null
this.$emit('refresh')
} catch (e) {
this.error = e.message || '导入失败,请重新校验后重试'
// 超时可能已提交,禁止沿用旧预览重试;重新校验实际状态。
this.result = null
this.confirmed = false
} finally {
this.submitting = false
}
}
}
}
</script>

@ -23,6 +23,7 @@
</Button>
<Button style="margin-left: 10px" type="primary" @click="doSearch">查询</Button>
<Button style="margin-left: 10px" type="primary" @click="doExport" :loading="exportLoading">导出</Button>
<Button style="margin-left: 10px" type="primary" @click="$refs.importInventory.open()">导入</Button>
<Button style="margin-left: 10px" type="primary" @click="doPrint">打印</Button>
</div>
</slot>
@ -34,6 +35,7 @@
</xy-table>
<putIn ref="putIn" @refresh="load()"></putIn>
<importInventory ref="importInventory" @refresh="load()" />
</div>
</template>
@ -51,8 +53,10 @@
} from '@/utils/exportExcel'
import putIn from '@/views/bookStore/components/putIn'
import importInventory from '@/views/bookStore/components/importInventory'
export default {
components: {
importInventory,
putIn
},
data() {

@ -0,0 +1,48 @@
import * as XLSX from 'xlsx'
import { parseInventoryWorkbook } from '@/utils/inventoryImport'
const headers = ['库存编号', '图书分类', '图书', '作者', '装订方式', '所在位置', '入库日期', '备注', '借阅状态']
function workbook(rows = [['0000001', '综合类', '测试图书', '', '', '', '2026-11-27', '', '在库']]) {
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet([headers, ...rows]), '库存')
return wb
}
describe('inventory import workbook', () => {
it('keeps blank fields explicit and inventory numbers as text', () => {
const rows = parseInventoryWorkbook(workbook(), '库存')
expect(rows[0]).toMatchObject({ no: '0000001', location: '', remark: '', author: '', bind_way: '', row_number: 2 })
})
it('supports Excel dates and numeric inventory numbers with a zero format', () => {
const wb = workbook()
wb.Sheets['库存'].A2 = { t: 'n', v: 123, z: '0000000' }
wb.Sheets['库存'].G2 = { t: 'n', v: 46353, z: 'yyyy-mm-dd' }
const row = parseInventoryWorkbook(wb, '库存')[0]
expect(row.no).toBe('0000123')
expect(row.enter_date).toBe('2026-11-27')
})
it('rejects missing and duplicate required columns', () => {
const wb = workbook()
wb.Sheets['库存'].H1.v = '其他'
expect(() => parseInventoryWorkbook(wb, '库存')).toThrow('备注')
wb.Sheets['库存'].H1.v = '库存编号'
expect(() => parseInventoryWorkbook(wb, '库存')).toThrow('库存编号')
})
it('rejects formulas instead of importing stale cached values', () => {
const wb = workbook()
wb.Sheets['库存'].H2 = { t: 's', v: '', f: 'A2' }
expect(() => parseInventoryWorkbook(wb, '库存')).toThrow('公式')
})
it('skips empty rows and preserves actual Excel row numbers', () => {
const wb = workbook([[], ['1234567', '综合类', '测试', '', '', '', '2026/1/2', '']])
const row = parseInventoryWorkbook(wb, '库存')[0]
expect(row.row_number).toBe(3)
expect(row.enter_date).toBe('2026-01-02')
})
it('rejects empty and oversized sheets', () => {
expect(() => parseInventoryWorkbook(workbook([]), '库存')).toThrow('没有库存明细')
const wb = workbook()
wb.Sheets['库存']['!ref'] = 'A1:J20000'
expect(() => parseInventoryWorkbook(wb, '库存')).toThrow('范围过大')
})
})

@ -0,0 +1,60 @@
import ImportInventory from '@/views/bookStore/components/importInventory.vue'
import { previewImport, commitImport } from '@/api/bookStore/storeList'
import { parseInventoryWorkbook } from '@/utils/inventoryImport'
jest.mock('@/api/bookStore/storeList', () => ({ previewImport: jest.fn(), commitImport: jest.fn() }))
jest.mock('@/utils/inventoryImport', () => ({ parseInventoryWorkbook: jest.fn() }))
function instance() {
const vm = { ...ImportInventory.data(), ...ImportInventory.methods, $Message: { success: jest.fn() }, $emit: jest.fn() }
Object.keys(ImportInventory.computed).forEach(key => Object.defineProperty(vm, key, { get: () => ImportInventory.computed[key].call(vm) }))
return vm
}
const valid = () => ({ token: 'test-token', errors: [], warnings: [], items: [], total: 1 })
describe('inventory import dialog', () => {
beforeEach(() => jest.clearAllMocks())
it('requires successful preview and explicit confirmation to commit', async() => {
const vm = instance()
await vm.commit()
expect(commitImport).not.toHaveBeenCalled()
vm.result = valid()
expect(vm.canCommit).toBe(false)
vm.confirmed = true
expect(vm.canCommit).toBe(true)
vm.result.errors = [{ message: 'error' }]
expect(vm.canCommit).toBe(false)
})
it('clears an old token when validation fails', async() => {
const vm = instance()
vm.workbook = {}; vm.result = valid(); vm.confirmed = true
parseInventoryWorkbook.mockReturnValue([{ no: '0000001' }])
previewImport.mockRejectedValueOnce(new Error('invalid workbook'))
await vm.preview()
expect(vm.result).toBe(null)
expect(vm.confirmed).toBe(false)
expect(vm.error).toBe('invalid workbook')
expect(vm.busy).toBe(false)
})
it('refreshes the inventory after a successful import', async() => {
const vm = instance()
vm.result = valid(); vm.confirmed = true; vm.visible = true
commitImport.mockResolvedValueOnce({ updated: 543, books_updated: 0 })
await vm.commit()
expect(commitImport).toHaveBeenCalledWith('test-token')
expect(vm.$emit).toHaveBeenCalledWith('refresh')
expect(vm.visible).toBe(false)
expect(vm.busy).toBe(false)
})
it('discards the token after a failed or uncertain commit and requires a fresh preview', async() => {
const vm = instance()
vm.result = valid(); vm.confirmed = true
commitImport.mockRejectedValueOnce(new Error('timeout'))
await vm.commit()
expect(vm.canCommit).toBe(false)
expect(vm.result).toBe(null)
expect(vm.error).toBe('timeout')
expect(vm.$emit).not.toHaveBeenCalled()
expect(vm.busy).toBe(false)
})
})
Loading…
Cancel
Save