fix(clearance): 修正外采导入错误反馈并增加交互自检

This commit is contained in:
居居 2026-11-11 10:15:37 +08:00
parent cf4624f61c
commit 72cc83ddce
4 changed files with 158 additions and 6 deletions

View File

@ -43,3 +43,14 @@
- 绕开组件库另造一套新平台视觉
- 明显只是补丁式修复
- 没做最小验证就宣称完成
## 5. 前端弹窗与导入交互固定自检
涉及导入、下载模板、批量操作、审核弹窗等交互时,提交前必须额外完成:
1. 点击入口能实际打开目标弹窗,关闭和重新打开正常。
2. 模板下载失败、文件格式错误、导入提交失败必须在当前弹窗内显示原因,不能只显示在被遮罩层挡住的页面区域。
3. 失败后更换修正文件可以重新提交;重新打开弹窗会清空上一次错误。
4. 弹窗打开期间,后台列表或轮询刷新不得清空当前弹窗错误。
5. 模板下载、文件选择、开始导入、成功关闭弹窗等完整路径都有回归测试。
6. 固定验证命令:`npm run verify:clearance-import-dialogs`,并同时执行类型检查和生产构建。

View File

@ -10,6 +10,7 @@
"start": "next start",
"lint": "eslint",
"test": "jest",
"verify:clearance-import-dialogs": "jest --runInBand src/app/supply-chain/management/clearance/ClearancePricePushView.test.tsx src/app/supply-chain/management/clearance/ClearancePricePushFeedback.test.tsx src/app/supply-chain/management/clearance/ExternalOrderCostView.test.tsx src/app/supply-chain/management/clearance/ExternalOrderCostFeedback.test.tsx",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"clean:local": "node scripts/cleanup-local-artifacts.js",

View File

@ -0,0 +1,134 @@
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { ExternalOrderCostView } from './ExternalOrderCostView'
const rows = {
rows: [{
id: 'row-1',
onlineOrderNo: '4777990',
internalOrderNo: '',
orderIdentifierType: 'ONLINE',
productCode: 'A01',
styleCode: '',
shopProductCode: '',
shopStyleCode: '',
productIdentifierType: 'PRODUCT',
productName: 'a商品',
costPrice: 16.99,
freightExpenditure: 8,
remark: '',
sourceFileName: '成本.xlsx',
importedByName: '经管',
createdAt: '2026-11-07T00:00:00.000Z',
}],
total: 1,
page: 1,
pageSize: 50,
totalPages: 1,
}
function success(data: unknown) {
return Promise.resolve({
ok: true,
json: async () => ({ success: true, data }),
} as Response)
}
function failure(message: string) {
return Promise.resolve({
ok: false,
json: async () => ({ success: false, error: { message } }),
} as Response)
}
async function openImport() {
render(<ExternalOrderCostView canWrite />)
await screen.findByText('4777990')
fireEvent.click(screen.getByRole('button', { name: '导入外采订单成本' }))
return screen.getByRole('dialog')
}
function selectFiles(dialog: HTMLElement, name = '成本1.xlsx') {
fireEvent.change(within(dialog).getByLabelText('选择外采订单成本 Excel'), {
target: { files: [new File(['xlsx'], name)] },
})
}
describe('外采订单成本导入弹窗操作反馈', () => {
beforeEach(() => {
jest.clearAllMocks()
global.fetch = jest.fn(() => success(rows)) as jest.Mock
})
it('shows import validation errors in the dialog and allows corrected files to retry', async () => {
let imports = 0
;(global.fetch as jest.Mock).mockImplementation((url: string, init?: RequestInit) => {
if (String(url).includes('/external-order-cost/import') && init?.method === 'POST') {
imports += 1
return imports === 1
? failure('第 2 行成本价不能为空')
: success({ importedCount: 1, fileCount: 1, fileResults: [] })
}
return success(rows)
})
const dialog = await openImport()
selectFiles(dialog, '错误成本.xlsx')
fireEvent.click(within(dialog).getByRole('button', { name: '开始导入' }))
expect(await within(dialog).findByRole('alert')).toHaveTextContent('第 2 行成本价不能为空')
expect(within(dialog).getByText('错误成本.xlsx')).toBeInTheDocument()
selectFiles(dialog, '修正成本.xlsx')
expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument()
fireEvent.click(within(dialog).getByRole('button', { name: '开始导入' }))
expect(await screen.findByText(/已导入 1 个文件,共 1 条订单成本/)).toBeInTheDocument()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(imports).toBe(2)
})
it('keeps template download failures inside the dialog and clears them when reopened', async () => {
;(global.fetch as jest.Mock).mockImplementation((url: string) => (
String(url).includes('/external-order-cost/template')
? failure('模板生成失败,请稍后重试')
: success(rows)
))
const dialog = await openImport()
fireEvent.click(within(dialog).getByRole('button', { name: '导入模板下载' }))
expect(await within(dialog).findByRole('alert')).toHaveTextContent('模板生成失败,请稍后重试')
fireEvent.click(within(dialog).getByRole('button', { name: '关闭外采订单成本导入' }))
fireEvent.click(screen.getByRole('button', { name: '导入外采订单成本' }))
expect(within(screen.getByRole('dialog')).queryByRole('alert')).not.toBeInTheDocument()
})
it('does not clear an import error when the background list reload completes', async () => {
let finishList: ((result: Response) => void) | undefined
let listRequests = 0
;(global.fetch as jest.Mock).mockImplementation((url: string, init?: RequestInit) => {
if (String(url).includes('/external-order-cost/import') && init?.method === 'POST') {
return failure('同一个文件中商品标识只能使用一种类型')
}
listRequests += 1
return listRequests === 1
? success(rows)
: new Promise<Response>((resolve) => { finishList = resolve })
})
render(<ExternalOrderCostView canWrite />)
await screen.findByText('4777990')
fireEvent.click(screen.getByRole('button', { name: '刷新' }))
fireEvent.click(screen.getByRole('button', { name: '导入外采订单成本' }))
const dialog = screen.getByRole('dialog')
selectFiles(dialog)
fireEvent.click(within(dialog).getByRole('button', { name: '开始导入' }))
expect(await within(dialog).findByRole('alert')).toHaveTextContent(
'同一个文件中商品标识只能使用一种类型',
)
finishList?.({
ok: true,
json: async () => ({ success: true, data: rows }),
} as Response)
await waitFor(() => expect(screen.getByRole('button', { name: '刷新' })).toBeEnabled())
expect(within(dialog).getByRole('alert')).toHaveTextContent(
'同一个文件中商品标识只能使用一种类型',
)
})
})

View File

@ -137,6 +137,7 @@ export function ExternalOrderCostView({
const [refreshKey, setRefreshKey] = useState(0)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [dialogError, setDialogError] = useState('')
const [message, setMessage] = useState('')
const [importDialogOpen, setImportDialogOpen] = useState(false)
const [pendingImportFiles, setPendingImportFiles] = useState<File[]>([])
@ -170,7 +171,7 @@ export function ExternalOrderCostView({
const importFiles = useCallback(async (files: File[]) => {
if (!canWrite || !files.length || importing) return
setImporting(true)
setError('')
setDialogError('')
setMessage('')
try {
const form = new FormData()
@ -191,7 +192,7 @@ export function ExternalOrderCostView({
setPage(1)
setRefreshKey((value) => value + 1)
} catch (reason) {
setError(reason instanceof Error ? reason.message : '导入失败')
setDialogError(reason instanceof Error ? reason.message : '导入失败')
} finally {
setImporting(false)
if (importRef.current) importRef.current.value = ''
@ -201,7 +202,7 @@ export function ExternalOrderCostView({
const downloadTemplate = useCallback(async () => {
if (downloadingTemplate) return
setDownloadingTemplate(true)
setError('')
setDialogError('')
try {
await downloadResponse(
await fetch('/api/supply-chain/clearance/external-order-cost/template', {
@ -210,7 +211,7 @@ export function ExternalOrderCostView({
'外采订单成本导入模板.xlsx',
)
} catch (reason) {
setError(reason instanceof Error ? reason.message : '模板下载失败')
setDialogError(reason instanceof Error ? reason.message : '模板下载失败')
} finally {
setDownloadingTemplate(false)
}
@ -262,7 +263,10 @@ export function ExternalOrderCostView({
className={limitStyles.primaryButton}
type="button"
disabled={importing}
onClick={() => setImportDialogOpen(true)}
onClick={() => {
setDialogError('')
setImportDialogOpen(true)
}}
>
<Upload size={14} aria-hidden="true" />导入外采订单成本
</button>
@ -291,6 +295,7 @@ export function ExternalOrderCostView({
aria-label="关闭外采订单成本导入"
onClick={() => {
setImportDialogOpen(false)
setDialogError('')
setPendingImportFiles([])
if (importRef.current) importRef.current.value = ''
}}
@ -316,7 +321,7 @@ export function ExternalOrderCostView({
{downloadingTemplate ? '模板下载中…' : '导入模板下载'}
</button>
</div>
{error && <div className={styles.error} role="alert">{error}</div>}
{dialogError && <div className={styles.error} role="alert">{dialogError}</div>}
<div className={styles.importFileBar}>
<input
ref={importRef}
@ -325,6 +330,7 @@ export function ExternalOrderCostView({
multiple
hidden
onChange={(event) => {
setDialogError('')
setPendingImportFiles(Array.from(event.target.files ?? []))
}}
aria-label="选择外采订单成本 Excel"