feat(supply-chain): 产品全量档案导出字段勾选与图片URL导出修复
This commit is contained in:
parent
c0e7a8d606
commit
5fc195d9fe
@ -48,6 +48,8 @@ export async function POST(request: NextRequest) {
|
||||
)
|
||||
const blockedFields = await productArchiveFieldPermissionService.getBlockedFields(ctx.user)
|
||||
params.fieldBlocks = [...blockedFields]
|
||||
// 图片列相对路径归一成绝对 URL 用的站点 Origin,同样在创建时快照。
|
||||
params.siteOrigin = request.nextUrl.origin
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -26,6 +26,10 @@ async function createExportResponse(params: {
|
||||
blockedFields: ReadonlySet<string>
|
||||
includeImage?: boolean
|
||||
columnSet?: 'archive' | 'limit'
|
||||
/** 自定义导出字段(列 prop 清单):仅产品档案列单生效,全勾/未传=全部列。 */
|
||||
fields?: string[]
|
||||
/** 图片列相对路径归一成绝对 URL 用的站点 Origin。 */
|
||||
siteOrigin?: string
|
||||
requestId: string
|
||||
signal: AbortSignal
|
||||
}) {
|
||||
@ -34,6 +38,8 @@ async function createExportResponse(params: {
|
||||
blockedFields: params.blockedFields,
|
||||
includeImage: params.includeImage,
|
||||
columnSet: params.columnSet,
|
||||
fields: params.fields,
|
||||
siteOrigin: params.siteOrigin,
|
||||
})
|
||||
|
||||
result.completion.catch((error) => {
|
||||
@ -88,12 +94,21 @@ export async function GET(request: NextRequest) {
|
||||
includeImage: request.nextUrl.searchParams.get('includeImage') !== '0',
|
||||
// 限价管理页导出用「限价界面抬头」列单。
|
||||
columnSet: isLimitExport ? 'limit' : 'archive',
|
||||
fields: parseExportFields(request.nextUrl.searchParams.get('fields')),
|
||||
siteOrigin: request.nextUrl.origin,
|
||||
requestId: ctx.requestId,
|
||||
signal: request.signal,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** fields=spu,barcode,costPrice(逗号分隔的列 prop);仅接受字符串,未知项由服务端过滤。 */
|
||||
function parseExportFields(raw: string | null): string[] | undefined {
|
||||
if (!raw) return undefined
|
||||
const fields = raw.split(',').map((field) => field.trim()).filter(Boolean)
|
||||
return fields.length > 0 ? fields : undefined
|
||||
}
|
||||
|
||||
// Same export with the filters carried in the body for large multi-selects
|
||||
// that would exceed the URL length limit.
|
||||
export async function POST(request: NextRequest) {
|
||||
@ -120,8 +135,19 @@ export async function POST(request: NextRequest) {
|
||||
blockedFields,
|
||||
includeImage: body?.includeImage !== false,
|
||||
columnSet: body?.columnSet === 'limit' ? 'limit' : 'archive',
|
||||
fields: parseExportFieldsBody(body?.fields),
|
||||
siteOrigin: request.nextUrl.origin,
|
||||
requestId: ctx.requestId,
|
||||
signal: request.signal,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** POST 体里的字段勾选清单:字符串数组;未知项由服务端按列单过滤。 */
|
||||
function parseExportFieldsBody(raw: unknown): string[] | undefined {
|
||||
if (!Array.isArray(raw)) return undefined
|
||||
const fields = raw.filter((field): field is string => typeof field === 'string')
|
||||
.map((field) => field.trim())
|
||||
.filter(Boolean)
|
||||
return fields.length > 0 ? fields : undefined
|
||||
}
|
||||
|
||||
@ -0,0 +1,243 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
import { ARCHIVE_COLUMNS } from './columns'
|
||||
|
||||
const STORAGE_KEY = 'product-archive-export-fields-v1'
|
||||
|
||||
type ProductArchiveExportFieldsDialogProps = {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
/** 字段权限屏蔽的列 prop:不出现在勾选清单里。 */
|
||||
blockedFields: ReadonlySet<string>
|
||||
/** 当前页面列设置里勾显的列 prop,供「按当前显示列」快捷键。 */
|
||||
visibleProps: string[]
|
||||
/** 确认导出:回传勾选的列 prop 清单(全选=全部列)。 */
|
||||
onExport: (fields: string[]) => void
|
||||
}
|
||||
|
||||
function loadSavedSelection(): string[] | null {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return null
|
||||
const list = JSON.parse(raw)
|
||||
if (!Array.isArray(list)) return null
|
||||
const fields = list.filter((field): field is string => typeof field === 'string')
|
||||
.map((field) => field.trim())
|
||||
.filter((field) => field.length > 0)
|
||||
return fields.length > 0 ? fields : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出资料前的字段勾选弹窗:按分组勾选,快捷键 全选/清空/按当前显示列,
|
||||
* 上次选择本地记住;全勾=全量导出,勾部分=只导该部分。
|
||||
*/
|
||||
export function ProductArchiveExportFieldsDialog({
|
||||
open,
|
||||
onClose,
|
||||
blockedFields,
|
||||
visibleProps,
|
||||
onExport,
|
||||
}: ProductArchiveExportFieldsDialogProps) {
|
||||
const groups = useMemo(
|
||||
() => ARCHIVE_COLUMNS.map((group) => ({
|
||||
group: group.group,
|
||||
columns: group.columns.filter((column) => !blockedFields.has(column.prop)),
|
||||
})).filter((group) => group.columns.length > 0),
|
||||
[blockedFields],
|
||||
)
|
||||
const allProps = useMemo(
|
||||
() => groups.flatMap((group) => group.columns.map((column) => column.prop)),
|
||||
[groups],
|
||||
)
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set(allProps))
|
||||
|
||||
// 每次打开时初始化:记住的上次选择 > 全选(首次打开=全量口径)
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const saved = loadSavedSelection()
|
||||
const valid = saved ? saved.filter((field) => allProps.includes(field)) : allProps
|
||||
setSelected(new Set(valid.length > 0 ? valid : allProps))
|
||||
}, [open, allProps])
|
||||
|
||||
const toggle = (prop: string) => {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current)
|
||||
if (next.has(prop)) next.delete(prop)
|
||||
else next.add(prop)
|
||||
return next
|
||||
})
|
||||
}
|
||||
const setGroupAll = (props: string[], checked: boolean) => {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current)
|
||||
props.forEach((prop) => (checked ? next.add(prop) : next.delete(prop)))
|
||||
return next
|
||||
})
|
||||
}
|
||||
const applyVisible = () => {
|
||||
const visible = new Set(visibleProps.filter((prop) => allProps.includes(prop)))
|
||||
setSelected(visible.size > 0 ? visible : new Set(allProps))
|
||||
}
|
||||
const startExport = () => {
|
||||
if (selected.size === 0) return
|
||||
// 按分组顺序回传,导出列顺序稳定
|
||||
const ordered = allProps.filter((prop) => selected.has(prop))
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(ordered))
|
||||
} catch {
|
||||
/* 本地记住失败不阻断导出 */
|
||||
}
|
||||
onExport(ordered)
|
||||
onClose()
|
||||
}
|
||||
|
||||
// 样式块常驻渲染、弹窗主体条件渲染:避免弹窗开关伴随样式挂载/卸载带来的布局闪动
|
||||
return (
|
||||
<>
|
||||
{!open ? null : (
|
||||
<>
|
||||
<div className="aefd-overlay" onClick={onClose} />
|
||||
<div className="aefd-dialog" role="dialog" aria-modal="true" aria-label="选择导出字段">
|
||||
<div className="aefd-head">
|
||||
<div>
|
||||
<div className="aefd-title">选择导出字段</div>
|
||||
<div className="aefd-sub">全选即导出全量字段;勾选部分则只导出勾选列(上次选择已自动恢复)</div>
|
||||
</div>
|
||||
<button type="button" className="aefd-close" onClick={onClose} aria-label="关闭"><X size={18} strokeWidth={1.8} /></button>
|
||||
</div>
|
||||
|
||||
<div className="aefd-actions">
|
||||
<button type="button" className="aefd-quick" onClick={() => setGroupAll(allProps, true)}>全选</button>
|
||||
<button type="button" className="aefd-quick" onClick={() => setGroupAll(allProps, false)}>清空</button>
|
||||
<button type="button" className="aefd-quick" onClick={applyVisible}>按当前显示列</button>
|
||||
<span className="aefd-count">已选 {selected.size} / {allProps.length} 个字段</span>
|
||||
</div>
|
||||
|
||||
<div className="aefd-list">
|
||||
{groups.map((group) => {
|
||||
const props = group.columns.map((column) => column.prop)
|
||||
const checkedCount = props.filter((prop) => selected.has(prop)).length
|
||||
return (
|
||||
<div key={group.group} className="aefd-group">
|
||||
<div className="aefd-group-head">
|
||||
<span className="aefd-group-name">{group.group}</span>
|
||||
<span className="aefd-group-count">{checkedCount}/{props.length}</span>
|
||||
</div>
|
||||
<div className="aefd-group-cols">
|
||||
{group.columns.map((column) => (
|
||||
<label key={column.prop} className="aefd-check">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.has(column.prop)}
|
||||
onChange={() => toggle(column.prop)}
|
||||
/>
|
||||
<span>{column.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="aefd-foot">
|
||||
<span className="aefd-hint">开始导出后进入下载中心队列,完成后在右上角下载</span>
|
||||
<div className="aefd-foot-btns">
|
||||
<button type="button" className="aefd-cancel" onClick={onClose}>取消</button>
|
||||
<button type="button" className="aefd-submit" onClick={startExport} disabled={selected.size === 0}>
|
||||
开始导出{selected.size > 0 ? `(${selected.size} 列)` : ''}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<style jsx global>{`
|
||||
.aefd-overlay {
|
||||
position: fixed; inset: 0; background: rgba(0,0,0,0.25); z-index: 210;
|
||||
}
|
||||
.aefd-dialog {
|
||||
position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%);
|
||||
width: min(720px, calc(100vw - 48px)); height: min(680px, calc(100vh - 64px));
|
||||
background: #fff; border-radius: 10px; box-shadow: 0 16px 40px rgba(0,0,0,0.16);
|
||||
z-index: 211; display: flex; flex-direction: column; overflow: hidden;
|
||||
}
|
||||
.aefd-head {
|
||||
display: flex; align-items: flex-start; justify-content: space-between;
|
||||
padding: 16px 20px 12px; border-bottom: 1px solid #f4f4f5;
|
||||
}
|
||||
.aefd-title { font-size: 15px; font-weight: 600; color: #27272a; }
|
||||
.aefd-sub { font-size: 12px; color: #a1a1aa; margin-top: 3px; }
|
||||
.aefd-close {
|
||||
border: none; background: transparent; color: #a1a1aa; cursor: pointer;
|
||||
padding: 2px; border-radius: 4px;
|
||||
}
|
||||
.aefd-close:hover { color: #27272a; background: #f4f4f5; }
|
||||
.aefd-actions {
|
||||
display: flex; align-items: center; gap: 8px; padding: 10px 20px;
|
||||
border-bottom: 1px solid #f4f4f5;
|
||||
}
|
||||
.aefd-quick {
|
||||
padding: 5px 10px; background: #fff; border: 1px solid #e4e4e7; border-radius: 6px;
|
||||
font-size: 12px; color: #52525b; cursor: pointer;
|
||||
}
|
||||
.aefd-quick:hover { background: #f4f4f5; }
|
||||
.aefd-count { margin-left: auto; font-size: 12px; color: #a1a1aa; }
|
||||
.aefd-list {
|
||||
flex: 1 1 0; min-height: 120px; overflow-y: auto; padding: 12px 20px;
|
||||
display: flex; flex-direction: column; gap: 12px;
|
||||
scrollbar-width: auto;
|
||||
}
|
||||
.aefd-list::-webkit-scrollbar { width: 10px; }
|
||||
.aefd-list::-webkit-scrollbar-track { background: #f4f4f5; border-radius: 5px; }
|
||||
.aefd-list::-webkit-scrollbar-thumb { background: #a1a1aa; border-radius: 5px; }
|
||||
.aefd-list::-webkit-scrollbar-thumb:hover { background: #71717a; }
|
||||
.aefd-group { border: 1px solid #f4f4f5; border-radius: 8px; overflow: hidden; flex: 0 0 auto; }
|
||||
.aefd-group-head {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 7px 10px; background: #fafafa; border-bottom: 1px solid #f4f4f5;
|
||||
}
|
||||
.aefd-group-name { font-size: 13px; font-weight: 600; color: #3f3f46; }
|
||||
.aefd-group-count { font-size: 11px; color: #a1a1aa; }
|
||||
.aefd-group-cols {
|
||||
display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 2px 12px; padding: 8px 10px;
|
||||
}
|
||||
@media (max-width: 720px) { .aefd-group-cols { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.aefd-check {
|
||||
display: inline-flex; align-items: center; gap: 6px; cursor: pointer;
|
||||
font-size: 13px; color: #27272a; padding: 3px 0; min-width: 0;
|
||||
}
|
||||
.aefd-check span {
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.aefd-check input {
|
||||
appearance: none; width: 15px; height: 15px; flex: none; margin: 0;
|
||||
border: 1.5px solid #d4d4d8; border-radius: 3px; background: #fff; cursor: pointer; position: relative;
|
||||
}
|
||||
.aefd-check input:checked { background: #27272a; border-color: #27272a; }
|
||||
.aefd-foot {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 12px 20px; border-top: 1px solid #f4f4f5;
|
||||
}
|
||||
.aefd-hint { font-size: 12px; color: #a1a1aa; }
|
||||
.aefd-foot-btns { display: flex; gap: 8px; }
|
||||
.aefd-cancel, .aefd-submit {
|
||||
padding: 7px 16px; border-radius: 6px; font-size: 13px; cursor: pointer;
|
||||
}
|
||||
.aefd-cancel { border: 1px solid #d4d4d8; background: #fff; color: #52525b; }
|
||||
.aefd-cancel:hover { background: #f4f4f5; }
|
||||
.aefd-submit {
|
||||
border: 1px solid #27272a; background: #27272a; color: #fff;
|
||||
}
|
||||
.aefd-submit:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.aefd-submit:not(:disabled):hover { background: #3f3f46; }
|
||||
`}</style>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@ -20,6 +20,7 @@ import { ProductArchiveDetailDialog } from './ProductArchiveDetailDialog'
|
||||
import { ProductArchiveChangeLogDialog } from './ProductArchiveChangeLogDialog'
|
||||
import { useProductArchivePageImages } from './useProductArchivePageImages'
|
||||
import { useProductArchiveImageExport } from './useProductArchiveImageExport'
|
||||
import { ProductArchiveExportFieldsDialog } from './ProductArchiveExportFieldsDialog'
|
||||
import { ProductArchiveThemeStyles } from './ProductArchiveThemeStyles'
|
||||
import { ProductArchiveSalesPeriodFilter } from './ProductArchiveSalesPeriodFilter'
|
||||
import { ProductArchiveFilterBar } from './ProductArchiveFilterBar'
|
||||
@ -128,6 +129,7 @@ export function ProductArchiveView({
|
||||
&& (Array.isArray(value) ? value.length > 0 : Boolean(value)),
|
||||
).length
|
||||
const { exporting, exportImages } = useProductArchiveImageExport(filters)
|
||||
const [exportFieldsOpen, setExportFieldsOpen] = useState(false)
|
||||
const [creatingArchiveTask, setCreatingArchiveTask] = useState(false)
|
||||
const [archiveTaskMessage, setArchiveTaskMessage] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
@ -135,14 +137,14 @@ export function ProductArchiveView({
|
||||
const timer = setTimeout(() => setArchiveTaskMessage(null), 5000)
|
||||
return () => clearTimeout(timer)
|
||||
}, [archiveTaskMessage])
|
||||
const createArchiveExportTask = useCallback(async () => {
|
||||
const createArchiveExportTask = useCallback(async (fields: string[]) => {
|
||||
setCreatingArchiveTask(true)
|
||||
setArchiveTaskMessage(null)
|
||||
try {
|
||||
const response = await fetch('/api/downloads', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'archive-export', params: { filters } }),
|
||||
body: JSON.stringify({ type: 'archive-export', params: { filters, fields } }),
|
||||
})
|
||||
const payload = await response.json().catch(() => null)
|
||||
if (!response.ok || !payload?.success) {
|
||||
@ -180,7 +182,8 @@ export function ProductArchiveView({
|
||||
label: creatingArchiveTask ? '导出资料(加入队列中…)' : '导出资料',
|
||||
icon: <FileDown size={14} strokeWidth={1.8} />,
|
||||
disabled: creatingArchiveTask,
|
||||
onClick: () => void createArchiveExportTask(),
|
||||
// 先弹「选择导出字段」:全勾=全量,勾部分=只导该部分
|
||||
onClick: () => setExportFieldsOpen(true),
|
||||
},
|
||||
// 图片列被屏蔽时,图片导出入口一并隐藏(服务端同样拒绝)
|
||||
...(blockedFieldSet.has('image') ? [] : [{
|
||||
@ -495,6 +498,15 @@ export function ProductArchiveView({
|
||||
onClose={() => setChangeLogBarcode(null)}
|
||||
/>
|
||||
)}
|
||||
{canDownload && (
|
||||
<ProductArchiveExportFieldsDialog
|
||||
open={exportFieldsOpen}
|
||||
onClose={() => setExportFieldsOpen(false)}
|
||||
blockedFields={blockedFieldSet}
|
||||
visibleProps={effectiveColumns.flatMap((group) => group.columns.map((column) => column.prop))}
|
||||
onExport={(fields) => void createArchiveExportTask(fields)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<style jsx>{`
|
||||
.archive-page {
|
||||
|
||||
@ -115,6 +115,80 @@ describe('product archive full export', () => {
|
||||
expect(result.fieldCount).toBe(ARCHIVE_COLUMNS.flatMap((group) => group.columns).length - 3)
|
||||
})
|
||||
|
||||
// 自定义字段导出:只导勾选列、未知 prop 忽略、保持分组列顺序;全勾/未传=全量。
|
||||
it('exports only the selected fields and keeps archive column order', async () => {
|
||||
const { service } = createService(1)
|
||||
|
||||
const result = await service.openWorkbook({
|
||||
filters: {},
|
||||
fields: ['spu', 'image', 'barcode', 'not-a-field'],
|
||||
})
|
||||
const bytes = await drain(result)
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.load(bytes)
|
||||
const headers = (workbook.getWorksheet(PRODUCT_ARCHIVE_EXPORT_SHEET_NAME)!.getRow(1).values as unknown[]).slice(1)
|
||||
|
||||
expect(headers).toEqual(['图片', 'SPU', '条码'])
|
||||
expect(result.fieldCount).toBe(3)
|
||||
})
|
||||
|
||||
it('exports every column when fields is an empty list', async () => {
|
||||
const { service } = createService(1)
|
||||
|
||||
const result = await service.openWorkbook({ filters: {}, fields: [] })
|
||||
await drain(result)
|
||||
|
||||
expect(result.fieldCount).toBe(ARCHIVE_COLUMNS.flatMap((group) => group.columns).length)
|
||||
})
|
||||
|
||||
// 图片列与页面同口径:缓存 > 定厂 > 聚水潭 > 原始列兜底,相对路径归一成站点绝对 URL。
|
||||
it('writes the resolved absolute image URL instead of the raw column', async () => {
|
||||
const rows = [
|
||||
{
|
||||
...ARCHIVE_ROW,
|
||||
id: 'row-rel',
|
||||
firstSourceCode: 'PRODUCT_DEVELOPMENT',
|
||||
image: '/api/storage/object?key=sku-1.jpeg',
|
||||
},
|
||||
{
|
||||
...ARCHIVE_ROW,
|
||||
id: 'row-cache',
|
||||
image: 'https://images.example.com/legacy.webp',
|
||||
imageCache: {
|
||||
previewUrl: 'https://images.example.com/material.webp',
|
||||
source: 'barcode',
|
||||
viewKey: 'latest',
|
||||
status: 'RESOLVED',
|
||||
},
|
||||
},
|
||||
]
|
||||
const repository = {
|
||||
openRowSource: jest.fn().mockResolvedValue({
|
||||
total: 2,
|
||||
batches: async function* batches() { yield rows },
|
||||
}),
|
||||
}
|
||||
const service = new SupplyChainProductArchiveExportService(
|
||||
repository as never,
|
||||
{ listActive: jest.fn().mockResolvedValue([]) },
|
||||
() => new Date('2026-08-31T12:00:00Z'),
|
||||
)
|
||||
|
||||
const result = await service.openWorkbook({
|
||||
filters: {},
|
||||
fields: ['spu', 'image'],
|
||||
siteOrigin: 'http://localhost:3001',
|
||||
})
|
||||
const bytes = await drain(result)
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.load(bytes)
|
||||
const worksheet = workbook.getWorksheet(PRODUCT_ARCHIVE_EXPORT_SHEET_NAME)!
|
||||
|
||||
expect(worksheet.getCell(2, 1).value).toBe('http://localhost:3001/api/storage/object?key=sku-1.jpeg')
|
||||
expect(worksheet.getCell(2, 2).value).toBe('SPU-001')
|
||||
expect(worksheet.getCell(3, 1).value).toBe('https://images.example.com/material.webp')
|
||||
})
|
||||
|
||||
it('streams rows in batches instead of materialising them all', async () => {
|
||||
const batchCalls: number[] = []
|
||||
const repository = {
|
||||
|
||||
@ -76,6 +76,17 @@ describe('product archive image export', () => {
|
||||
},
|
||||
}))).toBe('')
|
||||
|
||||
// 兜底:缓存视图不可导出、行上也没有字段级来源标记,但 image 列本身有值 → 直接导出该值
|
||||
expect(resolveProductArchiveImageExportUrl(record({
|
||||
imageCache: {
|
||||
previewUrl: 'https://cp.jiansun.vip/api/storage/object?key=product.webp',
|
||||
source: 'product',
|
||||
viewKey: 'product-catalog-wide-product',
|
||||
status: 'RESOLVED',
|
||||
},
|
||||
image: 'https://images.example.com/legacy.webp',
|
||||
}))).toBe('https://images.example.com/legacy.webp')
|
||||
|
||||
expect(resolveProductArchiveImageExportUrl(record({
|
||||
firstSourceCode: 'PRODUCT_DEVELOPMENT',
|
||||
image: 'https://images.example.com/new-sku.webp',
|
||||
|
||||
@ -58,6 +58,16 @@ function asBlockedFields(params: Record<string, unknown>): ReadonlySet<string> {
|
||||
return new Set(list.filter(isProductArchiveFieldKey))
|
||||
}
|
||||
|
||||
/** 自定义导出字段清单(列 prop):老任务/全量导出没有该参数。 */
|
||||
function asExportFields(params: Record<string, unknown>): string[] | undefined {
|
||||
const list = params.fields
|
||||
if (!Array.isArray(list)) return undefined
|
||||
const fields = list.filter((field): field is string => typeof field === 'string')
|
||||
.map((field) => field.trim())
|
||||
.filter(Boolean)
|
||||
return fields.length > 0 ? fields : undefined
|
||||
}
|
||||
|
||||
/** 把「已处理行数 / 总行数」映射成 5~95 的进度:剩下 5% 留给落盘与收尾。 */
|
||||
function rowProgress(processedRows: number, totalRows: number) {
|
||||
if (!Number.isFinite(totalRows) || totalRows <= 0) return 5
|
||||
@ -86,6 +96,8 @@ const archiveExportExecutor: DownloadExecutor = {
|
||||
const result = await supplyChainProductArchiveExportService.openWorkbook({
|
||||
filters: stripProductArchiveBlockedFilters(parsed.data, blockedFields),
|
||||
blockedFields,
|
||||
fields: asExportFields(params),
|
||||
siteOrigin: typeof params.siteOrigin === 'string' && params.siteOrigin ? params.siteOrigin : undefined,
|
||||
onProgress: (processedRows, totalRows) => onProgress?.(rowProgress(processedRows, totalRows)),
|
||||
})
|
||||
const filePath = path.join(taskDir, path.basename(result.fileName))
|
||||
|
||||
@ -9,6 +9,10 @@ import {
|
||||
} from '@/app/supply-chain/management/custom-table/limit-table-columns'
|
||||
import type { ProductArchiveFilters, SupplyChainProductArchiveRow } from '@/lib/supply-chain-product-archive'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import {
|
||||
resolveProductArchiveImageExportUrl,
|
||||
resolveProductArchiveImageExportUrlForSite,
|
||||
} from '@/server/services/supply-chain-product-archive-image-export.service'
|
||||
import {
|
||||
PRODUCT_ARCHIVE_EXPORT_BATCH_SIZE,
|
||||
supplyChainProductArchiveExportRepository,
|
||||
@ -262,6 +266,10 @@ export class SupplyChainProductArchiveExportService {
|
||||
includeImage?: boolean
|
||||
/** 列单:archive=产品档案列(默认);limit=限价界面抬头列(限价管理页导出用)。 */
|
||||
columnSet?: 'archive' | 'limit'
|
||||
/** 自定义导出字段(列 prop 清单):仅 archive 列单生效,按勾选过滤列并保持分组顺序;空/未传=全部列。 */
|
||||
fields?: readonly string[]
|
||||
/** 站点 Origin:图片列相对路径(/api/storage/object?...)归一成可访问的绝对 URL 用。 */
|
||||
siteOrigin?: string
|
||||
/** 每写完一批回调一次已写行数 / 总行数,供下载中心显示进度。 */
|
||||
onProgress?: (processedRows: number, totalRows: number) => void
|
||||
}): Promise<ProductArchiveExportStream> {
|
||||
@ -270,13 +278,19 @@ export class SupplyChainProductArchiveExportService {
|
||||
const rowSource = await this.repository.openRowSource(params.filters)
|
||||
const isLimitSet = params.columnSet === 'limit'
|
||||
const mapRow = await this.createRowMapper({ withInspectionReport: isLimitSet })
|
||||
// 自定义字段导出:交集过滤(不认识的 prop 直接忽略),保持 ARCHIVE_COLUMNS 里的分组顺序。
|
||||
const customFields = !isLimitSet && params.fields && params.fields.length > 0
|
||||
? new Set(params.fields.map((field) => String(field).trim()).filter(Boolean))
|
||||
: null
|
||||
const columns = (isLimitSet
|
||||
? LIMIT_TABLE_COLUMNS.map((column) => ({ prop: column.key, label: column.label, width: column.width }))
|
||||
: ARCHIVE_COLUMNS.flatMap((group) => group.columns)
|
||||
.filter((column) => !customFields || customFields.has(column.prop))
|
||||
)
|
||||
.filter((column) => params.includeImage !== false || column.prop !== 'image')
|
||||
// 字段权限:被屏蔽的列不进表头、不写值
|
||||
.filter((column) => !params.blockedFields?.has(column.prop))
|
||||
const hasImageColumn = columns.some((column) => column.prop === 'image')
|
||||
// 限价列单的取值复用界面格式化逻辑(包装尺寸 / 整装组装 / 材质等级 / 时间格式等)。
|
||||
const readValue = (row: SupplyChainProductArchiveRow, prop: string) => {
|
||||
if (!isLimitSet) return row[prop as keyof SupplyChainProductArchiveRow] ?? ''
|
||||
@ -329,6 +343,14 @@ export class SupplyChainProductArchiveExportService {
|
||||
const values = Object.fromEntries(
|
||||
columns.map((column) => [column.prop, readValue(row, column.prop)]),
|
||||
)
|
||||
// 图片列与页面显示同口径:缓存 > 定厂 > 聚水潭 > 原始列兜底,相对路径归一成站点绝对 URL,
|
||||
// 不再直接写主表 image 原始值(很多行为空,导出会大片空白)。
|
||||
if (hasImageColumn) {
|
||||
values.image = resolveProductArchiveImageExportUrlForSite(
|
||||
resolveProductArchiveImageExportUrl(record),
|
||||
params.siteOrigin ?? '',
|
||||
)
|
||||
}
|
||||
worksheet.addRow(values).commit()
|
||||
}
|
||||
processedRows += batch.length
|
||||
|
||||
@ -42,7 +42,9 @@ export function resolveProductArchiveImageExportUrl(
|
||||
? sourceImage
|
||||
: ''
|
||||
|
||||
return cacheImage || jstSkuImage || productDevelopmentSkuImage || ''
|
||||
// 兜底:存量行没有字段级来源标记时,缓存和来源分支全落空,但 image 列本身有值——
|
||||
// 直接导出该值(调用方会把相对路径归一成当前站绝对 URL),避免导出大片空白。
|
||||
return cacheImage || jstSkuImage || productDevelopmentSkuImage || sourceImage
|
||||
}
|
||||
|
||||
export function resolveProductArchiveImageExportUrlForSite(
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user