391 lines
19 KiB
TypeScript
391 lines
19 KiB
TypeScript
import { createHash } from 'node:crypto'
|
||
import { z } from 'zod'
|
||
import { desktopAssert, DesktopClientError } from './contract.mjs'
|
||
|
||
const dimensions = z.object({
|
||
length: z.number().nullable(),
|
||
width: z.number().nullable(),
|
||
height: z.number().nullable(),
|
||
unit: z.string().nullable(),
|
||
})
|
||
const attributes = z.record(z.union([
|
||
z.string(), z.number(), z.boolean(), z.array(z.string()), dimensions.partial(),
|
||
]).nullable()).nullable()
|
||
const image = z.object({
|
||
url: z.string(),
|
||
kind: z.enum(['main', 'sku', 'reference', 'whiteBackground']),
|
||
signed: z.boolean().nullable(),
|
||
expiresAt: z.string().nullable(),
|
||
})
|
||
const productResponse = z.object({
|
||
success: z.literal(true),
|
||
data: z.object({
|
||
spu: z.string(),
|
||
productName: z.string().nullable(),
|
||
brandName: z.string().nullable(),
|
||
categoryName: z.string().nullable(),
|
||
seriesOrModel: z.string().nullish(),
|
||
seriesName: z.string().nullish(),
|
||
modelName: z.string().nullish(),
|
||
shared: z.object({
|
||
dimensions: dimensions.nullable(),
|
||
sizeText: z.string().nullable(),
|
||
material: z.string().nullable(),
|
||
description: z.string().nullable(),
|
||
attributes,
|
||
sellingPoints: z.array(z.string()),
|
||
}),
|
||
mainImages: z.array(image),
|
||
barcodes: z.array(z.object({
|
||
barcode: z.string(),
|
||
skuCode: z.string().nullable(),
|
||
skuName: z.string().nullable(),
|
||
colorName: z.string().nullable(),
|
||
dimensions: dimensions.nullable(),
|
||
spec: z.string().nullable(),
|
||
sizeText: z.string().nullable(),
|
||
attributes,
|
||
sellingPoints: z.array(z.string()),
|
||
images: z.array(image),
|
||
updatedAt: z.string().nullish(),
|
||
})),
|
||
}),
|
||
})
|
||
const productNotFoundResponse = z.object({
|
||
success: z.literal(false),
|
||
error: z.object({ code: z.literal('PRODUCT_001') }),
|
||
})
|
||
|
||
const timeoutMs = 15_000
|
||
const timeoutCodes = ['UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']
|
||
|
||
type Product = z.infer<typeof productResponse>['data']
|
||
type ImageKind = z.infer<typeof image>['kind']
|
||
type Group = 'material' | 'structure' | 'package' | 'other'
|
||
type Dimensions = { length: number; width: number; height: number; unit: 'mm'; display: string }
|
||
type Asset = {
|
||
id: string; url: string; kind: ImageKind; label: string; barcode: string | null; colorName: string | null
|
||
localSource: string | null; selectedForProject: boolean
|
||
}
|
||
type Barcode = {
|
||
barcode: string; skuCode: string | null; skuName: string | null; spec: string | null
|
||
dimensions: Dimensions | null; sellingPoints: string[]; attributes: { key: string; label: string; value: string }[]
|
||
imageIds: string[]
|
||
}
|
||
|
||
const placeholders = new Set(['', '-', '无', '暂无', 'n/a', '[]', '{}'])
|
||
const axes = ['length', 'width', 'height'] as const
|
||
const unitAliases = { mm: 'mm', '毫米': 'mm', cm: 'cm', '厘米': 'cm', m: 'm', '米': 'm' } as const
|
||
const unitFactors = { mm: 1, cm: 10, m: 1000 }
|
||
const imageKinds: ImageKind[] = ['whiteBackground', 'main', 'sku', 'reference']
|
||
const imageLabels = { whiteBackground: '白底图', main: '主图', sku: 'SKU 图', reference: '参考图' }
|
||
const attributeLabels: Record<string, [string, Group]> = {
|
||
material: ['材质', 'material'],
|
||
materialtype: ['材质类型', 'material'],
|
||
材质: ['材质', 'material'],
|
||
材质类型: ['材质类型', 'material'],
|
||
framematerial: ['框架材质', 'material'],
|
||
surface: ['表面工艺', 'material'],
|
||
fabric: ['面料', 'material'],
|
||
structure: ['结构', 'structure'],
|
||
spec: ['规格', 'structure'],
|
||
speccode: ['规格编码', 'structure'],
|
||
sizetext: ['尺寸规格', 'structure'],
|
||
packagedimensions: ['包装尺寸', 'package'],
|
||
packagesize: ['包装尺寸', 'package'],
|
||
包装尺寸: ['包装尺寸', 'package'],
|
||
packageweight: ['包装重量', 'package'],
|
||
packagequantity: ['包装数量', 'package'],
|
||
series: ['系列', 'other'],
|
||
seriesname: ['系列', 'other'],
|
||
model: ['型号', 'other'],
|
||
modelname: ['型号', 'other'],
|
||
seriesormodel: ['系列或型号', 'other'],
|
||
color: ['颜色', 'other'],
|
||
colorname: ['颜色', 'other'],
|
||
}
|
||
|
||
function cleanText(value: string | null | undefined) {
|
||
const trimmed = value?.trim() ?? ''
|
||
return placeholders.has(trimmed.toLowerCase()) ? null : trimmed
|
||
}
|
||
|
||
function cleanList(values: string[]) {
|
||
return Array.from(new Set(values.map(cleanText).filter((value): value is string => value !== null)))
|
||
}
|
||
|
||
function unit(value: string | null | undefined) {
|
||
const key = value?.trim().toLowerCase()
|
||
return key && Object.hasOwn(unitAliases, key) ? unitAliases[key as keyof typeof unitAliases] : null
|
||
}
|
||
|
||
function dimensionObject(value: Partial<z.infer<typeof dimensions>> | null) {
|
||
if (!value) return null
|
||
const positive = (n: number | null | undefined) => n != null && n > 0 ? n : null
|
||
const length = positive(value.length), width = positive(value.width), height = positive(value.height)
|
||
return length !== null || width !== null || height !== null ? { length, width, height, unit: unit(value.unit) } : null
|
||
}
|
||
|
||
function normalizedDimensions(value: z.infer<typeof dimensions> | string | null | undefined): Dimensions | null {
|
||
if (typeof value === 'string') {
|
||
const match = /^(\d+(?:\.\d+)?)\s*[x×*]\s*(\d+(?:\.\d+)?)\s*[x×*]\s*(\d+(?:\.\d+)?)\s*(mm|cm|m|毫米|厘米|米)$/i.exec(value.trim())
|
||
if (!match) return null
|
||
value = { length: Number(match[1]), width: Number(match[2]), height: Number(match[3]), unit: match[4] }
|
||
}
|
||
const clean = dimensionObject(value ?? null)
|
||
if (!clean?.unit || clean.length === null || clean.width === null || clean.height === null) return null
|
||
const factor = unitFactors[clean.unit]
|
||
const round = (number: number) => Number((number * factor).toFixed(3))
|
||
const length = round(clean.length), width = round(clean.width), height = round(clean.height)
|
||
if (![length, width, height].every(number => Number.isFinite(number) && number > 0)) return null
|
||
return { length, width, height, unit: 'mm', display: `${length}×${width}×${height} mm` }
|
||
}
|
||
|
||
const attributeKey = (key: string) => key.normalize('NFKC').replace(/[\s_-]+/g, '').toLowerCase()
|
||
const packageKeys = ['packagedimensions', 'packagesize', '包装尺寸']
|
||
|
||
function cleanAttributes(values: z.infer<typeof attributes>) {
|
||
const entries = Object.entries(values ?? {}).flatMap(([rawKey, rawValue]) => {
|
||
const key = cleanText(rawKey)
|
||
if (!key || attributeKey(key) === 'updatedat' || rawValue === null) return []
|
||
const value = typeof rawValue === 'string' ? cleanText(rawValue)
|
||
: Array.isArray(rawValue) ? cleanList(rawValue)
|
||
: typeof rawValue === 'object' ? dimensionObject(rawValue)
|
||
: rawValue
|
||
return value === null || (Array.isArray(value) && !value.length) ? [] : [[key, value] as const]
|
||
})
|
||
return entries.length ? Object.fromEntries(entries) : null
|
||
}
|
||
|
||
function attributeValue(value: NonNullable<ReturnType<typeof cleanAttributes>>[string]) {
|
||
if (Array.isArray(value)) return value.join('、')
|
||
if (typeof value === 'boolean') return value ? '是' : '否'
|
||
if (typeof value === 'object') {
|
||
const sizes = axes.filter(axis => value[axis] !== null)
|
||
if (sizes.length === axes.length) return normalizedDimensions(value)?.display ?? ''
|
||
const labels = { length: '长', width: '宽', height: '高' }
|
||
return sizes.map(axis => `${labels[axis]}${value[axis]}${value.unit ? ` ${value.unit}` : ''}`).join('、')
|
||
}
|
||
return String(value)
|
||
}
|
||
|
||
function normalizedAttributes(values: ReturnType<typeof cleanAttributes>) {
|
||
const seen = new Set<string>()
|
||
return Object.entries(values ?? {}).flatMap(([key, raw]) => {
|
||
const canonical = attributeKey(key)
|
||
const [label, group] = Object.hasOwn(attributeLabels, canonical) ? attributeLabels[canonical] : [key, 'other' as const]
|
||
const value = packageKeys.includes(canonical) && typeof raw === 'string'
|
||
? normalizedDimensions(raw)?.display ?? raw : attributeValue(raw)
|
||
if (!value || seen.has(canonical)) return []
|
||
seen.add(canonical)
|
||
return [{ key, label, value, group }]
|
||
})
|
||
}
|
||
|
||
function cleanRow<T extends Product['shared'] | Product['barcodes'][number]>(row: T) {
|
||
return { ...row, dimensions: dimensionObject(row.dimensions), sizeText: cleanText(row.sizeText),
|
||
attributes: cleanAttributes(row.attributes), sellingPoints: cleanList(row.sellingPoints) }
|
||
}
|
||
|
||
function canonicalImage(value: string) {
|
||
const trimmed = value.trim()
|
||
if (!URL.canParse(trimmed)) return null
|
||
const url = new URL(trimmed)
|
||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return null
|
||
url.hash = ''
|
||
for (const key of Array.from(url.searchParams.keys())) {
|
||
if (/^(?:x-amz-.+|x-oss-.+|x-goog-.+|x-cos-security-token|q-sign-.+|q-ak|q-key-time|q-header-list|q-url-param-list|q-signature|ossaccesskeyid|accesskeyid|e|expires|expiresat|expiration|token|signature|sign|sig|policy|key-pair-id|auth_key|authkey|security-token)$/i.test(key)) {
|
||
url.searchParams.delete(key)
|
||
}
|
||
}
|
||
url.searchParams.sort()
|
||
return url.toString()
|
||
}
|
||
|
||
function stableId(...parts: string[]) {
|
||
const bytes = createHash('sha256').update(JSON.stringify(parts)).digest().subarray(0, 16)
|
||
bytes[6] = (bytes[6] & 0x0f) | 0x80
|
||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||
const hex = bytes.toString('hex')
|
||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||
}
|
||
|
||
function normalizeProduct(data: Product) {
|
||
const spu = data.spu.trim()
|
||
const productName = cleanText(data.productName), brandName = cleanText(data.brandName), categoryName = cleanText(data.categoryName)
|
||
const shared = { ...cleanRow(data.shared), material: cleanText(data.shared.material), description: cleanText(data.shared.description) }
|
||
const rawFieldWarnings: string[] = []
|
||
const grouped = new Map<string, Product['barcodes']>()
|
||
for (const row of data.barcodes) {
|
||
const barcode = cleanText(row.barcode)
|
||
if (!barcode) {
|
||
rawFieldWarnings.push('已忽略空条码')
|
||
continue
|
||
}
|
||
const rows = grouped.get(barcode) ?? []
|
||
rows.push(row)
|
||
grouped.set(barcode, rows)
|
||
}
|
||
const updatedTime = (row: Product['barcodes'][number]) => {
|
||
const time = Date.parse(row.updatedAt?.trim() ?? '')
|
||
return Number.isFinite(time) ? time : -Infinity
|
||
}
|
||
const barcodes = Array.from(grouped, ([barcode, rows]) => {
|
||
if (rows.length > 1) rawFieldWarnings.push(`已合并重复条码:${barcode}`)
|
||
rows.sort((a, b) => updatedTime(b) - updatedTime(a))
|
||
const cleaned = rows.map(cleanRow)
|
||
const firstText = (key: 'skuCode' | 'skuName' | 'colorName' | 'spec' | 'sizeText') =>
|
||
cleaned.map(row => cleanText(row[key])).find(value => value !== null) ?? null
|
||
const mergedAttributes = new Map<string, [string, NonNullable<ReturnType<typeof cleanAttributes>>[string]]>()
|
||
for (const row of cleaned) {
|
||
for (const [key, value] of Object.entries(row.attributes ?? {})) {
|
||
const canonical = attributeKey(key)
|
||
if (!mergedAttributes.has(canonical)) mergedAttributes.set(canonical, [key, value])
|
||
}
|
||
}
|
||
const attributes = mergedAttributes.size ? Object.fromEntries(mergedAttributes.values()) : null
|
||
return { barcode, skuCode: firstText('skuCode'), skuName: firstText('skuName'), colorName: firstText('colorName'),
|
||
dimensions: cleaned.find(row => row.dimensions)?.dimensions ?? null, spec: firstText('spec'),
|
||
sizeText: firstText('sizeText'), attributes, sellingPoints: cleanList(cleaned.flatMap(row => row.sellingPoints)),
|
||
images: cleaned.flatMap(row => row.images) }
|
||
})
|
||
|
||
const assetsByUrl = new Map<string, Asset>()
|
||
const imagesFor = (images: Product['mainImages'], barcode: string | null, colorName: string | null) => {
|
||
const unique = new Map<string, Product['mainImages'][number]>()
|
||
for (const image of images) {
|
||
const canonical = canonicalImage(image.url)
|
||
if (!canonical) {
|
||
rawFieldWarnings.push('已忽略无效图片地址')
|
||
continue
|
||
}
|
||
const url = image.url.trim(), id = stableId(canonical)
|
||
const priority = imageKinds.indexOf(image.kind)
|
||
const current = assetsByUrl.get(canonical)
|
||
if (!current || priority < imageKinds.indexOf(current.kind)) {
|
||
assetsByUrl.set(canonical, {
|
||
id, url, kind: image.kind, label: [imageLabels[image.kind], colorName ?? barcode].filter(Boolean).join(' · '),
|
||
barcode, colorName, localSource: null, selectedForProject: false,
|
||
})
|
||
}
|
||
const previous = unique.get(canonical)
|
||
if (!previous || priority < imageKinds.indexOf(previous.kind)) unique.set(canonical, { ...image, url })
|
||
}
|
||
return { images: Array.from(unique.values()), imageIds: Array.from(unique.keys(), url => stableId(url)) }
|
||
}
|
||
const mainImages = imagesFor(data.mainImages, null, null).images
|
||
const attrs = normalizedAttributes(shared.attributes)
|
||
const sharedDimensions = normalizedDimensions(shared.dimensions) ?? normalizedDimensions(shared.sizeText)
|
||
const variantsByColor = new Map<string, { id: string; colorName: string; barcodes: Barcode[] }>()
|
||
const legacyBarcodes = barcodes.map(row => {
|
||
const color = (row.colorName ?? '').normalize('NFKC').replace(/\s+/g, ' ').trim()
|
||
const colorKey = color.toLowerCase()
|
||
let variant = variantsByColor.get(colorKey)
|
||
if (!variant) {
|
||
variant = { id: stableId(spu, colorKey), colorName: color, barcodes: [] }
|
||
variantsByColor.set(colorKey, variant)
|
||
}
|
||
const { images, imageIds } = imagesFor(row.images, row.barcode, variant.colorName || null)
|
||
const dimensions = normalizedDimensions(row.dimensions) ?? normalizedDimensions(row.sizeText) ?? normalizedDimensions(row.spec)
|
||
variant.barcodes.push({
|
||
barcode: row.barcode, skuCode: row.skuCode, skuName: row.skuName, spec: row.spec,
|
||
dimensions: dimensions?.display === sharedDimensions?.display ? null : dimensions,
|
||
sellingPoints: row.sellingPoints.filter(point => !shared.sellingPoints.includes(point)),
|
||
attributes: normalizedAttributes(row.attributes)
|
||
.filter(attr => !attrs.some(shared => attributeKey(shared.key) === attributeKey(attr.key) && shared.value === attr.value))
|
||
.map(({ key, label, value }) => ({ key, label, value })),
|
||
imageIds,
|
||
})
|
||
return { ...row, images }
|
||
})
|
||
const assets = Array.from(assetsByUrl.values()).sort((a, b) => imageKinds.indexOf(a.kind) - imageKinds.indexOf(b.kind))
|
||
.map((asset, index) => ({ ...asset, selectedForProject: index < 8 }))
|
||
const packageValue = Object.entries(shared.attributes ?? {}).find(([key]) => packageKeys.includes(attributeKey(key)))?.[1]
|
||
const packageDimensions = typeof packageValue === 'string' || (packageValue && typeof packageValue === 'object' && !Array.isArray(packageValue))
|
||
? normalizedDimensions(packageValue) : null
|
||
const seriesOrModel = cleanText(data.seriesOrModel) ?? cleanText(data.seriesName) ?? cleanText(data.modelName)
|
||
?? attrs.find(attr => ['seriesormodel', 'seriesname', 'series', 'modelname', 'model', '系列', '型号'].includes(attributeKey(attr.key)))?.value ?? null
|
||
const variants = Array.from(variantsByColor.values())
|
||
const normalizedProduct = {
|
||
identity: { spu, productName: productName ?? '', platformBrand: brandName, platformCategory: categoryName, seriesOrModel },
|
||
specs: { dimensions: sharedDimensions, packageDimensions,
|
||
materials: cleanList([shared.material ?? '', ...attrs.filter(attr => ['material', 'materialtype', '材质', '材质类型'].includes(attributeKey(attr.key))).map(attr => attr.value)]),
|
||
colors: variants.map(variant => variant.colorName).filter(Boolean), attributes: attrs },
|
||
copy: { summary: shared.description, sellingPoints: shared.sellingPoints },
|
||
variants, assets,
|
||
trace: { source: 'product_platform' as const, fetchedAt: new Date().toISOString(), upstreamSpu: spu, rawFieldWarnings: Array.from(new Set(rawFieldWarnings)) },
|
||
}
|
||
const platformFacts = {
|
||
spu, shared,
|
||
barcodes: Object.fromEntries(legacyBarcodes.map(({ barcode, images, ...facts }) => [barcode, facts])),
|
||
}
|
||
return { source: 'product_platform' as const, spu, productName, brandName, categoryName, shared, mainImages, barcodes: legacyBarcodes, platformFacts, normalizedProduct }
|
||
}
|
||
|
||
export async function desktopProductPlatformSpu(params: URLSearchParams) {
|
||
const spu = params.get('spu')?.trim()
|
||
desktopAssert(spu, '请输入商品 SPU', 400)
|
||
|
||
const origin = process.env.PRODUCT_PLATFORM_BASE_URL?.trim() ?? ''
|
||
const key = process.env.PRODUCT_PLATFORM_BY_SPU_API_KEY?.trim() ?? ''
|
||
desktopAssert(
|
||
/^https?:\/\/[^/?#@\\\s]+\/?$/i.test(origin) && URL.canParse(origin) && /^[\x20-\x7e\x80-\xff]+$/.test(key),
|
||
'产品平台联动未配置,请联系管理员', 503, 'product_platform_misconfigured',
|
||
)
|
||
|
||
const url = new URL('/api/external/products/by-spu', origin)
|
||
url.searchParams.set('spu', spu!)
|
||
const signal = AbortSignal.timeout(timeoutMs)
|
||
let response: Response
|
||
let payload: unknown
|
||
try {
|
||
response = await fetch(url, {
|
||
method: 'GET',
|
||
headers: { Accept: 'application/json', 'X-API-Key': key },
|
||
cache: 'no-store',
|
||
redirect: 'manual',
|
||
signal,
|
||
})
|
||
if (response.status === 200) {
|
||
payload = await response.json()
|
||
} else if (response.status === 404 && response.headers.get('content-type')?.toLowerCase().includes('application/json')) {
|
||
try {
|
||
payload = await response.json()
|
||
} catch {
|
||
payload = null
|
||
}
|
||
} else {
|
||
await response.body?.cancel()
|
||
}
|
||
} catch (error) {
|
||
const failure = error as { name?: string; cause?: { code?: string } } | null
|
||
if (signal.aborted || failure?.name === 'TimeoutError' || timeoutCodes.includes(failure?.cause?.code ?? '')) {
|
||
throw new DesktopClientError('产品平台请求超时,请稍后重试', 504, 'product_platform_timeout')
|
||
}
|
||
if (failure?.name === 'SyntaxError') {
|
||
throw new DesktopClientError('产品平台返回的资料格式异常,请联系管理员', 502, 'product_platform_invalid_response')
|
||
}
|
||
throw new DesktopClientError('产品平台暂时无法连接,请稍后重试', 502, 'product_platform_unreachable')
|
||
}
|
||
|
||
if (response.status === 404) {
|
||
if (productNotFoundResponse.safeParse(payload).success) {
|
||
throw new DesktopClientError('产品平台未找到该 SPU 资料', 404, 'product_not_found')
|
||
}
|
||
throw new DesktopClientError('产品平台查询接口暂不可用,请联系管理员', 502, 'product_platform_upstream_error')
|
||
}
|
||
if (response.status === 401 || response.status === 403) {
|
||
throw new DesktopClientError('产品平台鉴权失败,请联系管理员', 502, 'product_platform_auth_failed')
|
||
}
|
||
if (response.status === 504) {
|
||
throw new DesktopClientError('产品平台请求超时,请稍后重试', 504, 'product_platform_timeout')
|
||
}
|
||
desktopAssert(response.status === 200, '产品平台响应异常,请稍后重试', 502, 'product_platform_upstream_error')
|
||
|
||
const result = productResponse.safeParse(payload)
|
||
if (!result.success) {
|
||
throw new DesktopClientError('产品平台返回的资料格式异常,请联系管理员', 502, 'product_platform_invalid_response')
|
||
}
|
||
return normalizeProduct(result.data.data)
|
||
}
|