fix(clearance): bound task image loading and persist column order

Validated image-column release fixes, synchronized independently of other tasks.
This commit is contained in:
WuYongJie 2026-12-03 09:39:08 +08:00
parent 87eda0b11b
commit 6ed2cdc6a7
6 changed files with 183 additions and 3 deletions

View File

@ -0,0 +1,57 @@
import { fireEvent, render, renderHook, screen } from '@testing-library/react'
import { ClearanceTaskImageCell } from './ClearanceTaskImageCell'
import { useClearanceColumnSettings } from './useClearanceColumnSettings'
describe('clearance task images', () => {
it('loads the CDN thumbnail and waits for an explicit preview to load the original', () => {
const original = 'https://img.alicdn.com/product.jpg'
const { container } = render(<ClearanceTaskImageCell image={original} productLabel="示例商品" />)
const thumbnail = container.querySelector('img')
expect(thumbnail).toHaveAttribute('src', original + '_120x120.jpg')
expect(thumbnail).toHaveAttribute('loading', 'lazy')
const button = screen.getByRole('button', { name: '预览 示例商品 图片' })
fireEvent.focus(button)
expect(container.querySelectorAll('img')).toHaveLength(1)
fireEvent.click(button)
expect(screen.getByRole('img', { name: '示例商品 原图' })).toHaveAttribute('src', original)
fireEvent.keyDown(button, { key: 'Escape' })
expect(screen.queryByRole('img', { name: '示例商品 原图' })).toBeNull()
})
it('does not fetch an unsupported original automatically', () => {
const original = 'https://static.jiansun.vip:3333/Resource/SkuImg/product.jpg'
const { container } = render(<ClearanceTaskImageCell image={original} productLabel="示例商品" />)
expect(container.querySelector('img')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '预览 示例商品 图片' }))
expect(screen.getByRole('img', { name: '示例商品 原图' })).toHaveAttribute('src', original)
})
it('does not fall back to an original download when the thumbnail fails', () => {
const { container } = render(<ClearanceTaskImageCell image="https://img.alicdn.com/product.jpg" productLabel="示例商品" />)
fireEvent.error(container.querySelector('img')!)
expect(container.querySelector('img')).toBeNull()
expect(screen.getByText('查看')).toBeInTheDocument()
})
it('inserts the image once in legacy settings and preserves the saved order afterward', () => {
const userId = 'task-image-column-test'
const storageKey = `supply-chain.clearance.tasks-columns.v4:${userId}`
const columns = [
{ key: 'image', label: '商品图片', group: '基础信息', width: 70 },
{ key: 'spu', label: 'spu', group: '基础信息', width: 110 },
]
const storedSpu = { key: 'spu', visible: true, width: 120 }
const storedImage = { key: 'image', visible: false, width: 80 }
try {
localStorage.setItem(storageKey, JSON.stringify([storedSpu]))
const first = renderHook(() => useClearanceColumnSettings(userId, 'tasks', columns))
expect(first.result.current[0]).toEqual([{ key: 'image', visible: true, width: 70 }, storedSpu])
first.unmount()
localStorage.setItem(storageKey, JSON.stringify([storedSpu, storedImage]))
const next = renderHook(() => useClearanceColumnSettings(userId, 'tasks', columns))
expect(next.result.current[0]).toEqual([storedSpu, storedImage])
} finally {
localStorage.removeItem(storageKey)
}
})
})

View File

@ -0,0 +1,69 @@
'use client'
import { useState, type MouseEvent } from 'react'
import { getClearanceTaskThumbnail } from '@/lib/clearance-task-image'
import ui from './clearance.module.css'
export function ClearanceTaskImageCell({ image, productLabel }: { image: string; productLabel: string }) {
const [thumbnailFailed, setThumbnailFailed] = useState(false)
const [previewFailed, setPreviewFailed] = useState(false)
const [position, setPosition] = useState<{ left: number; top: number } | null>(null)
if (!image) return <span className={ui.poolImageFallback}>—</span>
const thumbnail = thumbnailFailed ? '' : getClearanceTaskThumbnail(image)
function togglePreview(event: MouseEvent<HTMLButtonElement>) {
if (position) {
setPosition(null)
return
}
const rect = event.currentTarget.getBoundingClientRect()
setPreviewFailed(false)
setPosition({
left: Math.max(12, Math.min(window.innerWidth - 332, rect.right + 14)),
top: Math.max(12, Math.min(window.innerHeight - 332, rect.top - 70)),
})
}
return (
<>
<button
type="button"
className={ui.poolImageHover}
aria-label={`预览 ${productLabel} 图片`}
aria-expanded={Boolean(position)}
onClick={togglePreview}
onBlur={() => setPosition(null)}
onKeyDown={(event) => {
if (event.key === 'Escape') setPosition(null)
}}
>
{thumbnail ? (
// eslint-disable-next-line @next/next/no-img-element
<img
className={ui.poolImage}
src={thumbnail}
alt=""
loading="lazy"
decoding="async"
referrerPolicy="no-referrer"
onError={() => setThumbnailFailed(true)}
/>
) : <span className={ui.poolImageFallback}>查看</span>}
</button>
{position && (
<span className={ui.poolImagePreview} style={position}>
{previewFailed ? <span role="status">图片暂不可用</span> : (
// eslint-disable-next-line @next/next/no-img-element
<img
src={image}
alt={`${productLabel} 原图`}
decoding="async"
referrerPolicy="no-referrer"
onError={() => setPreviewFailed(true)}
/>
)}
</span>
)}
</>
)
}

View File

@ -51,6 +51,7 @@ import {
DEFAULT_TASK_FILTER_FIELDS,
} from './clearance-filter-defaults'
import { buildClearanceTaskExportSnapshot } from './clearance-task-export-snapshot'
import { ClearanceTaskImageCell } from './ClearanceTaskImageCell'
import {
useClearanceColumnSettings,
useClearanceCompact,
@ -2417,7 +2418,9 @@ export function ClearanceView({
task: Task,
column: ClearanceColumnDefinition<ClearanceTaskColumnRow>,
) {
if (column.kind === 'image') return <PoolImageCell row={task} />
if (column.kind === 'image') {
return <ClearanceTaskImageCell key={task.image} image={task.image} productLabel={task.productName || task.barcode} />
}
if (taskEditMode && canReview && EDITABLE_TASK_FIELDS.has(column.key)) {
const draft = taskEditDrafts[task.id]
const field = column.key as keyof TaskEditDraft

View File

@ -71,7 +71,7 @@ export function useClearanceColumnSettings(
const seen = new Set(ordered.map((item) => item.key))
let merged = [...ordered, ...base.filter((item) => !seen.has(item.key))]
if (table === 'pool') merged = moveClearancePoolTaskColumnsToEnd(merged)
if (table === 'tasks') {
if (table === 'tasks' && !seen.has('image')) {
const image = merged.find((item) => item.key === 'image')
if (image) {
merged = [image, ...merged.filter((item) => item.key !== 'image')]

View File

@ -0,0 +1,50 @@
const MAX_IMAGE_URL_LENGTH = 2048
const RELATIVE_IMAGE_BASE = 'https://clearance-image.invalid'
const ALI_IMAGE_HOSTS = new Set(['img.alicdn.com', 'cbu01.alicdn.com'])
const JD_IMAGE_HOST = /^img(?:10|11|12|13|14)\.360buyimg\.com$/
const RASTER_FILE = /\.(?:avif|gif|jpe?g|png|webp)$/i
function isLocalImage(url: URL) {
return (url.pathname === '/api/storage/object' && Boolean(url.searchParams.get('key')))
|| (url.pathname.startsWith('/uploads/') && RASTER_FILE.test(url.pathname))
}
export function normalizeClearanceTaskImage(value: string | null | undefined): string {
const image = value?.trim()
if (!image || image.length > MAX_IMAGE_URL_LENGTH || /[\s\\]/.test(image)) return ''
try {
if (image.startsWith('/') && !image.startsWith('//')) {
const url = new URL(image, RELATIVE_IMAGE_BASE)
return isLocalImage(url) ? image : ''
}
const url = new URL(image)
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return ''
if (url.hostname === 'cp.jiansun.vip') {
return !url.port && isLocalImage(url) ? url.pathname + url.search : ''
}
return image
} catch {
return ''
}
}
/** Only use known CDN transformations. Never fall back to an original in the table. */
export function getClearanceTaskThumbnail(image: string): string {
try {
const url = new URL(image)
if (url.protocol !== 'https:' || url.port || url.username || url.password || url.search) return ''
if (ALI_IMAGE_HOSTS.has(url.hostname)) {
const originalPath = url.pathname.replace(/(\.(?:jpe?g|png|webp|gif))_\d+x\d+(?:q\d+)?\.(?:jpe?g|webp)\.?$/i, '$1')
if (!RASTER_FILE.test(originalPath)) return ''
url.pathname = originalPath + '_120x120.jpg'
return url.href
}
if (JD_IMAGE_HOST.test(url.hostname) && /^\/n[0-5](?:\/s\d+x\d+)?\//.test(url.pathname) && RASTER_FILE.test(url.pathname)) {
url.pathname = url.pathname.replace(/^\/n[0-5](?:\/s\d+x\d+)?\//, '/n5/')
return url.href
}
} catch {
return ''
}
return ''
}

View File

@ -3,6 +3,7 @@ import { ErrorCode } from '@/server/core/errors'
import type { AuthUser } from '@/server/core/types'
import type { Prisma } from '@prisma/client'
import { supplyChainClearanceRepository } from '@/server/repositories/supply-chain-clearance.repository'
import { normalizeClearanceTaskImage } from '@/lib/clearance-task-image'
import { supplyChainClearanceReviewSourceRepository } from '@/server/repositories/supply-chain-clearance-review-source.repository'
import { supplyChainDiscontinuationSourceRepository } from '@/server/repositories/supply-chain-discontinuation-source.repository'
import { dingtalkWorkflowMonitorRepository } from '@/server/repositories/dingtalk-workflow-monitor.repository'
@ -4428,7 +4429,7 @@ class SupplyChainClearanceService {
return {
...taskWithProgress,
taskIds: [task.id],
image: poolItem?.image || archiveItem?.image || '',
image: normalizeClearanceTaskImage(poolItem?.image) || normalizeClearanceTaskImage(archiveItem?.image),
spu: poolItem?.spu || archiveItem?.spu || '',
ownerName: taskOwnerName
|| responsibleOwnerByBarcode.get(barcode)?.effectiveOwnerName