parent
79f4e138f3
commit
f16919e138
@ -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,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…
Reference in new issue