修复小壹四图验收模板并新增超管测试商品预设
This commit is contained in:
parent
794be1c34f
commit
623b4ec73e
@ -3,6 +3,7 @@ import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { desktopAssert, desktopPortal, DesktopClientError, DESKTOP_CLIENT_ID } from '@/lib/desktop-client/contract.mjs'
|
||||
import {isAllowedCorsOrigin} from '@/lib/cors-origin'
|
||||
import {isSuperAdmin} from '@/lib/department-permission'
|
||||
import { approveDesktop, desktopUser, exchangeDesktop, getDesktopAsset, getDesktopProject, listDesktopDevices, listDesktopProjects, putDesktopAsset, putDesktopProject, requireDesktop, revokeDesktop, deleteDesktopProject } from '@/lib/desktop-client/service'
|
||||
export const runtime='nodejs'
|
||||
export const dynamic='force-dynamic'
|
||||
@ -42,6 +43,11 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
|
||||
const {desktopProductPlatformSpu}=await import('@/lib/desktop-client/product-platform')
|
||||
value=await desktopProductPlatformSpu(url.searchParams)
|
||||
}
|
||||
else if(parts[0]==='test-product-presets'&&parts.length===1&&method==='GET'){
|
||||
desktopAssert(await isSuperAdmin(ownerId),'无权读取测试商品资料',403,'forbidden')
|
||||
const {desktopTestProductPresets}=await import('@/lib/desktop-client/test-presets')
|
||||
value=desktopTestProductPresets()
|
||||
}
|
||||
else if(parts[0]==='capabilities'&&parts.length===1&&method==='GET')value={documentVersions:[1,2,3],projectDeletion:true,nativeFiles:{streaming:true,maxFileBytes:536870912,maxProjectBytes:1073741824,source:'sha256',range:true},catalog:{brands:true,materials:true,products:true},modelExecution:'client',creationTasks:{version:1,leases:true,recovery:'read-only'}}
|
||||
else if(parts[0]==='feedback'&&parts.length===1&&method==='POST'){
|
||||
const {submitDesktopFeedback}=await import('@/lib/desktop-client/feedback')
|
||||
|
||||
@ -64,12 +64,9 @@ function componentPack(manifest, revision, mappings, binding) {
|
||||
const mapping = mappings[component.component];
|
||||
if (!mapping || mapping.template_id !== manifest.template.templateId || mapping.mapping_version !== component.mappingVersion) throw Error('模板组件或映射版本不一致');
|
||||
if (mapping.skill_sources !== undefined) pack.skillSources = mapping.skill_sources;
|
||||
if(component.component==='detail'){
|
||||
const original=asset(manifest,component.originalAssetIds[0]);
|
||||
Object.assign(pack.enterprise,{mappingAssetId:component.mappingAssetId,inventoryAssetId:component.sourceInventoryAssetId,
|
||||
originalAssetId:original.assetId,originalRevision:original.revision,originalSha256:original.sha256,canvas:mapping.canvas});
|
||||
}
|
||||
const sources = component.component === 'detail'
|
||||
const isDetail = component.component === 'detail';
|
||||
const singleDetailOriginal = isDetail && component.originalAssetIds.length === 1;
|
||||
const sources = singleDetailOriginal
|
||||
? [{assetId:component.originalAssetIds[0],canvas:mapping.canvas,sha256:mapping.source.sha256}]
|
||||
: mapping.source.assets.map(source => {
|
||||
const original = component.originalAssetIds.map(id=>asset(manifest,id)).find(item=>item.declaredId===source.asset_id);
|
||||
@ -77,23 +74,37 @@ function componentPack(manifest, revision, mappings, binding) {
|
||||
return {assetId:original.assetId,sourceId:source.asset_id,canvas:source.canvas_px,sha256:source.ps_sha256};
|
||||
});
|
||||
if (sources.length !== component.originalAssetIds.length) throw Error('模板组件原稿清单不完整');
|
||||
if (component.component !== 'detail') {
|
||||
if (!singleDetailOriginal) {
|
||||
const pageAssetIds = [...new Set(mapping.screens.map(screen => screen.asset_id))];
|
||||
const pageOrder = new Map(pageAssetIds.map((id, index) => [id, index]));
|
||||
const unreferenced = pageOrder.size;
|
||||
sources.sort((a, b) => (pageOrder.get(a.sourceId) ?? unreferenced) - (pageOrder.get(b.sourceId) ?? unreferenced));
|
||||
}
|
||||
if (isDetail) {
|
||||
const [source] = sources;
|
||||
const original = asset(manifest, source.assetId);
|
||||
Object.assign(pack.enterprise,{mappingAssetId:component.mappingAssetId,inventoryAssetId:component.sourceInventoryAssetId,
|
||||
originalAssetId:original.assetId,originalRevision:original.revision,originalSha256:original.sha256,canvas:source.canvas});
|
||||
}
|
||||
pack.enterprise.components[component.component] = {
|
||||
mappingAssetId:component.mappingAssetId,inventoryAssetId:component.sourceInventoryAssetId,
|
||||
originals:sources.map(source=>({...source,revision:asset(manifest,source.assetId).revision}))
|
||||
};
|
||||
const detailSourceTops = new Map();
|
||||
if (isDetail && !singleDetailOriginal) {
|
||||
let offset = 0;
|
||||
for (const source of sources) {
|
||||
detailSourceTops.set(source.assetId, offset);
|
||||
offset += source.canvas[1];
|
||||
}
|
||||
}
|
||||
let top = 0;
|
||||
const outputs = mapping.screens.map(screen => {
|
||||
const source = sources.find(item=>component.component==='detail' || item.sourceId===screen.asset_id);
|
||||
const source = sources.find(item=>singleDetailOriginal || item.sourceId===screen.asset_id);
|
||||
if (!source) throw Error('模板页面缺少对应原稿');
|
||||
const [left,nativeTop,right,bottom] = screen.bounds;
|
||||
const slots = mapping.fields.filter(field=>field.screen_id===screen.screen_id).map(field=>{
|
||||
if (component.component!=='detail' && field.asset_id!==source.sourceId) throw Error('字段不属于当前页面原稿');
|
||||
if (!singleDetailOriginal && field.asset_id!==source.sourceId) throw Error('字段不属于当前页面原稿');
|
||||
const [l,t,r,b]=field.ps_style.coverage_rect;
|
||||
const x=Math.max(left,l),y=Math.max(nativeTop,t),x2=Math.min(right,r),y2=Math.min(bottom,b);
|
||||
if(x2<=x||y2<=y)throw Error(`字段 ${field.field_id} 不在所属页面`);
|
||||
@ -126,7 +137,7 @@ function componentPack(manifest, revision, mappings, binding) {
|
||||
maxChars:field.maxChars??Math.max(1,Array.from(text).length),maxLines:field.maxLines??Math.max(1,text.split(/\r\n|\r|\n/).length)}:{})};
|
||||
});
|
||||
const output={id:screen.screen_id,name:screen.title,component:component.component,width:right-left,height:bottom-nativeTop,
|
||||
top:component.component==='detail'?nativeTop:top,originalAssetId:source.assetId,slots};
|
||||
top:isDetail ? nativeTop + (detailSourceTops.get(source.assetId) ?? 0) : top,originalAssetId:source.assetId,slots};
|
||||
top+=source.canvas[1];
|
||||
return output;
|
||||
});
|
||||
@ -411,8 +422,14 @@ export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
|
||||
const inventoryFile = itemAt(files,binding.inventory,'inventory');
|
||||
const raw = await jsonAt(mappingFile);
|
||||
const inventory = await jsonAt(inventoryFile);
|
||||
if (inventory.template_id !== templateId || (inventory.component ?? 'detail') !== component ||
|
||||
inventory.mapping_version !== raw.mapping_version) throw Error('小壹图层清单与组件映射不一致');
|
||||
const location = `${manifest.knowledgeVersion} / ${component}`;
|
||||
if (inventory.template_id !== templateId || (inventory.component ?? 'detail') !== component) {
|
||||
throw Error(`小壹图层清单与组件映射不一致(${location}):${binding.inventory} 的模板或组件标识不符`);
|
||||
}
|
||||
if (inventory.mapping_version !== raw.mapping_version) {
|
||||
const version = value => value === undefined ? '未填写' : JSON.stringify(value);
|
||||
throw Error(`小壹图层清单与组件映射不一致(${location}):${binding.inventory} 版本 ${version(inventory.mapping_version)},${binding.mapping} 版本 ${version(raw.mapping_version)}`);
|
||||
}
|
||||
const pages = Object.entries(binding.pages ?? {});
|
||||
const references = binding.original ? [{original:binding.original,assetId:raw.source?.assets?.[0]?.asset_id ?? 'original'}]
|
||||
: [...new Map(pages.map(([,page])=>[page.assetId,page])).values()];
|
||||
|
||||
44
apps/detail-agent-pi/test/test-product-presets.test.mts
Normal file
44
apps/detail-agent-pi/test/test-product-presets.test.mts
Normal file
@ -0,0 +1,44 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { createRequire } from 'node:module'
|
||||
import { test } from 'node:test'
|
||||
import type * as PresetsModule from '../../../lib/desktop-client/test-presets'
|
||||
import { intakeMetadata } from '../src/enterprise-templates.mjs'
|
||||
import { briefBarcodeBindings, canonicalProductBrief, detailBarcode } from '../src/product-brief.mjs'
|
||||
|
||||
const { desktopTestProductPresets } = createRequire(import.meta.url)('../../../lib/desktop-client/test-presets.ts') as typeof PresetsModule
|
||||
|
||||
test('test presets feed the same intake, project and SKU contract as a saved brief', () => {
|
||||
for (const { productBrief: brief, imageAssets } of desktopTestProductPresets().presets) {
|
||||
const canon = canonicalProductBrief(brief)
|
||||
assert.equal(canon.spu, brief.identifier)
|
||||
assert.equal(canon.name, brief.name)
|
||||
assert.equal(canon.brand, brief.brandName)
|
||||
assert.equal(canon.category, brief.categoryName)
|
||||
assert.equal(detailBarcode(brief), brief.detailBarcode)
|
||||
assert.deepEqual(briefBarcodeBindings(brief), brief.barcodeBindings)
|
||||
assert.deepEqual(canon.intake, brief.intake)
|
||||
assert.deepEqual(intakeMetadata(brief.intake.schema), brief.intake.schema)
|
||||
assert.deepEqual(Object.keys(brief.intake.productValues), brief.intake.schema.productFields.map(field => field.id))
|
||||
assert.equal(canon.images.length, imageAssets.length)
|
||||
|
||||
for (const entry of brief.barcodeEntries) {
|
||||
assert.match(entry.barcode, /^\d{13}$/)
|
||||
assert.match(entry.variantId, /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/)
|
||||
assert.deepEqual(brief.barcodeBindings[entry.variantId], [entry.barcode])
|
||||
assert.deepEqual(canon.barcodeEntries.filter(row => row.barcode === entry.barcode), [{
|
||||
barcode: entry.barcode, colorName: entry.colorName, dimensions: entry.dimensions,
|
||||
material: entry.material, boardType: entry.boardType,
|
||||
}])
|
||||
const values = brief.intake.barcodeValues[entry.barcode]
|
||||
assert.deepEqual(Object.keys(values).sort(), brief.intake.schema.barcodeFields.map(field => field.id).sort())
|
||||
for (const axis of ['length', 'width', 'height'] as const) {
|
||||
assert.equal(values[axis], entry.dimensions[axis])
|
||||
assert.ok(Number(values[axis]) > 0)
|
||||
}
|
||||
const scoped = canonicalProductBrief(brief, { variantId: entry.variantId, barcodes: [entry.barcode] })
|
||||
assert.deepEqual(scoped.barcodeEntries.map(row => row.barcode), [entry.barcode])
|
||||
assert.deepEqual(scoped.images.map(image => image.barcode), [entry.barcode])
|
||||
assert.match(scoped.images[0].source, /^local:[a-f0-9]{64}$/)
|
||||
}
|
||||
}
|
||||
})
|
||||
@ -61,6 +61,81 @@ async function fixture(t, {badHash = false,templateId = 'CHAIR',withBindings = f
|
||||
return {options,manifest,requests,pauses,bundle,blob};
|
||||
}
|
||||
|
||||
async function fastTemplate(t, inventoryVersion) {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-fast-template-'));
|
||||
t.after(() => fs.rm(root,{recursive:true,force:true}));
|
||||
const templateId = 'QA-FAST-001';
|
||||
const version = '2026-12-01.2';
|
||||
const knowledgeVersion = `${templateId}@${version}`;
|
||||
const components = {detail:[['S01','D01',640],['S02','D02',640]],main_images:[['M01','M01',512]],sku_images:[['K01','K01',512]]};
|
||||
const entries = {'SKILL.md':Buffer.from('---\nname: fast\ndescription: Fixture template.\n---\n指南')};
|
||||
const put = (name, value) => { entries[name] = Buffer.from(JSON.stringify(value)); };
|
||||
const bindings = {}, assets = [];
|
||||
const blobs = new Map();
|
||||
put('production.json', {productionProfiles:{detail:{},main_images:{},sku_images:{}}});
|
||||
for (const [component, pages] of Object.entries(components)) {
|
||||
const files = pages.map(([screen, assetId, height]) => {
|
||||
const original = `${component}/${assetId}.psd`;
|
||||
const blob = Buffer.from(original);
|
||||
const content = describe(blob);
|
||||
blobs.set(content.sha256, blob);
|
||||
assets.push({path:original, type:'original', component, ...content});
|
||||
return {screen, assetId, height, original, sha256:content.sha256};
|
||||
});
|
||||
const source = {assets:files.map(({assetId,height,sha256}) => ({asset_id:assetId, ps_sha256:sha256, canvas_px:[512,height]}))};
|
||||
const mapping = `${component}/mapping.json`, inventory = `${component}/inventory.json`;
|
||||
const identity = {template_id:templateId,component};
|
||||
put(mapping, {...identity,source,mapping_version:'20261201.1',
|
||||
screens:files.map(({screen,assetId,height}) => ({screen_id:screen,asset_id:assetId,title:screen,bounds:[0,0,512,height]})),
|
||||
fields:files.map(({screen,assetId,height}) => ({field_id:screen+'-I01',type:'图片',name:'商品',screen_id:screen,
|
||||
ps_location:{asset_id:assetId,path:'商品',name:'商品'},ps_style:{coverage_rect:[0,0,512,height]}})),
|
||||
});
|
||||
put(inventory, {...identity,source,mapping_version:component==='sku_images' ? inventoryVersion : '20261201.1'});
|
||||
bindings[component] = {mapping,inventory,...(files.length === 1 ? {original:files[0].original} :
|
||||
{pages:Object.fromEntries(files.map(({screen,assetId,original}) => [screen,{assetId,original}]))})};
|
||||
}
|
||||
const bundle = Buffer.from(zipSync(entries));
|
||||
const files = Object.entries(entries).map(([path,data]) => ({path,...describe(data),type:path.split('/').at(-1).split('.')[0]}));
|
||||
const manifest = Buffer.from(JSON.stringify({schemaVersion:1,templateId,version,knowledgeVersion,
|
||||
entrypoint:'SKILL.md',supplement:'SKILL.md',productionConfig:'production.json',bundle:describe(bundle),bindings,files,assets}));
|
||||
const fetch = async url => {
|
||||
const route = new URL(url).pathname;
|
||||
if (route.endsWith('/current')) return Response.json({version,manifestSha256:sha(manifest)});
|
||||
if (route.endsWith('/manifest')) return new Response(manifest,{headers:{etag:`"${sha(manifest)}"`}});
|
||||
if (route.endsWith('/bundle')) return new Response(bundle);
|
||||
const data = blobs.get(route.split('/').at(-1));
|
||||
assert.ok(data,route);
|
||||
return new Response(data);
|
||||
};
|
||||
return {input:{templateId,projectDir:path.join(root,'project'),cache:path.join(root,'blobs')},fetch};
|
||||
}
|
||||
|
||||
test('the four-image template keeps both detail originals and the main and SKU outputs', async t => {
|
||||
const {input,fetch} = await fastTemplate(t, '20261201.1');
|
||||
const {packs} = await xiaoyiPacks(input,{fetch});
|
||||
assert.deepEqual(Object.keys(packs), ['detail','main_images','sku_images']);
|
||||
assert.deepEqual(packs.detail.outputs.map(({id,originalAssetId,top}) => [id,originalAssetId,top]), [['S01','D01',0],['S02','D02',640]]);
|
||||
assert.deepEqual(packs.detail.enterprise.components.detail.originals.map(({assetId}) => assetId), ['D01','D02']);
|
||||
assert.deepEqual(packs.main_images.outputs.map(({id,originalAssetId}) => [id,originalAssetId]), [['M01','M01']]);
|
||||
assert.deepEqual(packs.sku_images.outputs.map(({id,originalAssetId}) => [id,originalAssetId]), [['K01','K01']]);
|
||||
for (const pack of Object.values(packs)) {
|
||||
for (const output of pack.outputs) {
|
||||
assert.equal(output.slots[0].fieldId, `${output.id}-I01`);
|
||||
assert.equal(output.slots[0].kind, 'image');
|
||||
assert.equal(output.slots[0].psLayer.asset_id, output.originalAssetId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (const version of [undefined, 20261201.1, '20261201.2']) {
|
||||
test(`rejects an inconsistent SKU inventory version (${version}) with precise diagnostics`, async t => {
|
||||
const {input,fetch} = await fastTemplate(t, version);
|
||||
await assert.rejects(xiaoyiPacks(input,{fetch}), {
|
||||
message: `小壹图层清单与组件映射不一致(QA-FAST-001@2026-12-01.2 / sku_images):sku_images/inventory.json 版本 ${JSON.stringify(version) ?? '未填写'},sku_images/mapping.json 版本 "20261201.1"`,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('locks a verified release, resumes offline and repairs from the same bundle', async t => {
|
||||
const {options,requests} = await fixture(t);
|
||||
const first = await acquireXiaoyiRelease(options);
|
||||
|
||||
98
lib/__tests__/desktop-test-product-presets-route.test.ts
Normal file
98
lib/__tests__/desktop-test-product-presets-route.test.ts
Normal file
@ -0,0 +1,98 @@
|
||||
/** @jest-environment node */
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
import sharp from 'sharp'
|
||||
import { GET, POST } from '@/app/api/desktop/[...path]/route'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import type { desktopTestProductPresets } from '@/lib/desktop-client/test-presets'
|
||||
|
||||
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
|
||||
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
|
||||
jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn(), user: { findUnique: jest.fn() } } }))
|
||||
jest.mock('@/lib/detail-generator/repository', () => ({}))
|
||||
jest.mock('@/lib/detail-generator/storage', () => ({}))
|
||||
jest.mock('@/lib/desktop-client/project-lifecycle', () => ({}))
|
||||
|
||||
const querySession = jest.mocked(prisma.$queryRawUnsafe)
|
||||
const findUser = prisma.user.findUnique as jest.Mock
|
||||
const context = { params: { path: ['test-product-presets'] } }
|
||||
const originalEnv = process.env
|
||||
const account = { username: 'owner', isActive: true, status: 'active', archivedAt: null }
|
||||
|
||||
function request(method = 'GET', token = `Bearer dcs_${'a'.repeat(64)}`) {
|
||||
return new Request('https://materials.test/api/desktop/test-product-presets', { method, headers: { authorization: token } })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...originalEnv, DETAIL_GENERATOR_ENABLED: 'true' }
|
||||
querySession.mockReset().mockResolvedValue([{ id: 'device', ownerId: 'owner', expiresAt: new Date(Date.now() + 25 * 86400000) }])
|
||||
findUser.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
})
|
||||
|
||||
test('only a valid Bearer session reaches the role check', async () => {
|
||||
expect((await GET(request('GET', ''), context)).status).toBe(401)
|
||||
expect(querySession).not.toHaveBeenCalled()
|
||||
querySession.mockResolvedValueOnce([])
|
||||
const revoked = await GET(request(), context)
|
||||
expect(revoked.status).toBe(401)
|
||||
expect(await revoked.json()).toHaveProperty('code', 'session_expired')
|
||||
expect(findUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each(['USER', 'DEPT_ADMIN', 'ADMIN', 'SYSTEM_ADMIN'])('does not disclose presets to %s', async role => {
|
||||
findUser.mockResolvedValue({ ...account, role, isSuperAdmin: false })
|
||||
const response = await GET(request(), context)
|
||||
expect(response.status).toBe(403)
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
expect(await response.json()).toEqual({ error: '无权读取测试商品资料', code: 'forbidden' })
|
||||
expect(findUser).toHaveBeenLastCalledWith({ where: { id: 'owner' }, select: { isSuperAdmin: true } })
|
||||
})
|
||||
|
||||
test('checks the current super-admin flag before reading presets', async () => {
|
||||
findUser.mockResolvedValueOnce({ ...account, isSuperAdmin: true }).mockResolvedValueOnce({ isSuperAdmin: false })
|
||||
expect((await GET(request(), context)).status).toBe(403)
|
||||
})
|
||||
|
||||
test('does not serve presets for other methods or subpaths', async () => {
|
||||
findUser.mockResolvedValue({ ...account, isSuperAdmin: true })
|
||||
expect((await POST(request('POST'), context)).status).toBe(404)
|
||||
expect((await GET(request(), { params: { path: ['test-product-presets', 'images'] } })).status).toBe(404)
|
||||
})
|
||||
|
||||
test('super admins get three complete presets with four decodable, content-addressed product photos', async () => {
|
||||
findUser.mockResolvedValue({ ...account, isSuperAdmin: true })
|
||||
const response = await GET(request(), context)
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
const { presets } = await response.json() as ReturnType<typeof desktopTestProductPresets>
|
||||
expect(presets.map(preset => preset.productBrief.barcodeEntries.length)).toEqual([1, 2, 1])
|
||||
expect(new Set(presets.map(preset => preset.id)).size).toBe(3)
|
||||
const sources = new Set<string>()
|
||||
for (const { label, productBrief: brief, imageAssets } of presets) {
|
||||
expect(label).toBeTruthy()
|
||||
expect(brief).toMatchObject({ name: expect.any(String), brandId: 'ekb:brand:小壹测试', brandName: '小壹测试',
|
||||
categoryId: 'ekb:category:链路验收', identifierType: 'spu', identifier: expect.stringMatching(/^XYQA-/),
|
||||
intake: { templateId: 'QA-FAST-001', productValues: {
|
||||
productBrand: expect.stringContaining('演示'), sellingPoints: expect.any(String), specifications: expect.any(String),
|
||||
} } })
|
||||
expect(brief.images).toHaveLength(brief.barcodeEntries.length)
|
||||
expect(imageAssets).toHaveLength(brief.images.length)
|
||||
for (const image of imageAssets) {
|
||||
const bytes = Buffer.from(image.base64, 'base64')
|
||||
expect(image.contentType).toBe('image/jpeg')
|
||||
expect(image.source).toBe(`local:${createHash('sha256').update(bytes).digest('hex')}`)
|
||||
expect(brief.images).toContainEqual(expect.objectContaining({ source: image.source, name: image.name, purpose: 'product' }))
|
||||
const { info } = await sharp(bytes).raw().toBuffer({ resolveWithObject: true })
|
||||
expect(info.width).toBeGreaterThanOrEqual(640)
|
||||
expect(info.height).toBeGreaterThanOrEqual(640)
|
||||
sources.add(image.source)
|
||||
}
|
||||
}
|
||||
expect(sources.size).toBe(4)
|
||||
expect(presets[2].productBrief.intake.productValues.sellingPoints.length).toBeGreaterThan(180)
|
||||
expect(presets[2].productBrief.intake.productValues.specifications.split('\n')).toHaveLength(12)
|
||||
})
|
||||
18
lib/desktop-client/test-preset-images.json
Normal file
18
lib/desktop-client/test-preset-images.json
Normal file
File diff suppressed because one or more lines are too long
17
lib/desktop-client/test-preset-intake.json
Normal file
17
lib/desktop-client/test-preset-intake.json
Normal file
@ -0,0 +1,17 @@
|
||||
{
|
||||
"version": 1,
|
||||
"productFields": [
|
||||
{ "id": "productBrand", "label": "商品品牌", "type": "text" },
|
||||
{ "id": "description", "label": "商品说明", "type": "text", "multiline": true },
|
||||
{ "id": "sellingPoints", "label": "卖点", "type": "text", "multiline": true },
|
||||
{ "id": "specifications", "label": "规格参数", "type": "text", "multiline": true }
|
||||
],
|
||||
"barcodeFields": [
|
||||
{ "id": "colorName", "label": "花色", "type": "text" },
|
||||
{ "id": "length", "label": "长", "type": "number", "unit": "mm" },
|
||||
{ "id": "width", "label": "宽", "type": "number", "unit": "mm" },
|
||||
{ "id": "height", "label": "高", "type": "number", "unit": "mm" },
|
||||
{ "id": "material", "label": "材质", "type": "text" },
|
||||
{ "id": "boardType", "label": "板材类型", "type": "text" }
|
||||
]
|
||||
}
|
||||
119
lib/desktop-client/test-presets.ts
Normal file
119
lib/desktop-client/test-presets.ts
Normal file
@ -0,0 +1,119 @@
|
||||
import imageData from './test-preset-images.json'
|
||||
import intakeSchema from './test-preset-intake.json'
|
||||
|
||||
const template = {
|
||||
id: 'QA-FAST-001',
|
||||
brandId: 'ekb:brand:小壹测试',
|
||||
brandName: '小壹测试',
|
||||
categoryId: 'ekb:category:链路验收',
|
||||
categoryName: '链路验收',
|
||||
} as const
|
||||
|
||||
type PresetVariant = {
|
||||
id: string
|
||||
barcode: string
|
||||
name: string
|
||||
colorName: string
|
||||
size: [length: string, width: string, height: string]
|
||||
material: string
|
||||
boardType: string
|
||||
photo: keyof typeof imageData
|
||||
}
|
||||
|
||||
type Preset = {
|
||||
id: string
|
||||
label: string
|
||||
spu: string
|
||||
name: string
|
||||
productBrand: string
|
||||
description: string
|
||||
sellingPoints: string[]
|
||||
specifications: string[]
|
||||
variants: [PresetVariant, ...PresetVariant[]]
|
||||
}
|
||||
|
||||
const presets: Preset[] = [
|
||||
{
|
||||
id: 'oak-entryway-stool', label: '单条码 · 橡木换鞋凳', spu: 'XYQA-ST-001', name: '圆角橡木换鞋凳',
|
||||
productBrand: '栖序家居(演示)',
|
||||
description: '适合窄玄关的矮凳,四脚略向外张,保留浅橡木的天然色差与纹理。',
|
||||
sellingPoints: ['40 cm 宽的座面,可沿玄关墙摆放', '圆角座面,边缘打磨顺滑', '开箱即用,凳脚配防滑垫'],
|
||||
specifications: ['成品尺寸:400 × 280 × 420 mm', '材质:橡木拼板与橡木凳脚', '表面:哑光清漆', '净重:3.6 kg', '安装:整装'],
|
||||
variants: [{ id: 'dd6f9c0b-6f6a-4a0e-9fb2-88d50aa7d001', barcode: '0200000010010', name: '原木色 · 标准款',
|
||||
colorName: '浅橡木色', size: ['400', '280', '420'], material: '橡木', boardType: '橡木实木拼板', photo: 'oak-stool' }],
|
||||
},
|
||||
{
|
||||
id: 'linen-storage-ottoman', label: '双花色 · 亚麻储物凳', spu: 'XYQA-OT-002', name: '翻盖亚麻储物凳',
|
||||
productBrand: '栖序家居(演示)',
|
||||
description: '同款软包储物凳分窄版和宽版。掀起坐盖可收纳毯子、靠垫或入户杂物。',
|
||||
sellingPoints: ['软包坐盖可开启,合上后可作换鞋凳', '粗织纹理在近景中可辨识', '燕麦米窄版与岩灰宽版各有独立条码'],
|
||||
specifications: ['燕麦米窄版:480 × 380 × 420 mm', '岩灰宽版:600 × 400 × 420 mm',
|
||||
'面料:亚麻混纺', '填充:聚氨酯海绵', '底脚:黑色聚丙烯脚垫'],
|
||||
variants: [
|
||||
{ id: 'dd6f9c0b-6f6a-4a0e-9fb2-88d50aa7d002', barcode: '0200000020019', name: '燕麦米 · 48 cm',
|
||||
colorName: '燕麦米', size: ['480', '380', '420'], material: '亚麻混纺、木质框架', boardType: '多层胶合板', photo: 'linen-sand' },
|
||||
{ id: 'dd6f9c0b-6f6a-4a0e-9fb2-88d50aa7d003', barcode: '0200000020026', name: '岩灰 · 60 cm',
|
||||
colorName: '岩灰', size: ['600', '400', '420'], material: '亚麻混纺、木质框架', boardType: '多层胶合板', photo: 'linen-charcoal' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'electric-standing-desk', label: '长卖点与规格表 · 电动升降桌', spu: 'XYQA-SD-003', name: '双电机电动升降桌',
|
||||
productBrand: '衡间工位(演示)',
|
||||
description: '面向家庭办公的坐站两用桌。胡桃木纹桌面配黑色钢架,升降手控器安装在右前方。',
|
||||
sellingPoints: [
|
||||
'两侧桌腿由双电机同步驱动,切换坐姿与站姿时,可让显示器、键盘和桌面收纳用品随桌面一同升降。',
|
||||
'手控器提供三组高度记忆,共用工位的人可以分别记录坐姿和站姿的高度,也可用按键微调。',
|
||||
'后侧理线托盘集中容纳插线板和电源适配器,预留随桌面运动的线缆长度,便于离地清理。',
|
||||
'桌面前角采用圆角,胡桃木纹饰面便于日常擦拭。钢制 T 形底脚可微调,以适应轻微不平的地面。',
|
||||
'遇阻检测用于升降过程中降低夹碰风险,摆放时仍需在桌面上下留出移动空间。',
|
||||
],
|
||||
specifications: [
|
||||
'桌面:1200 × 600 mm,厚 25 mm', '高度:720–1180 mm', '升降速度:25 mm/s', '额定均布负载:70 kg',
|
||||
'驱动:双电机,两节升降立柱', '手控器:数显,3 组高度记忆', '电源:AC 220 V / 50 Hz', '饰面:胡桃木纹三聚氰胺饰面',
|
||||
'桌架:黑色粉末涂层冷轧钢', '净重:30.5 kg', '包装:桌板和桌架分箱,需组装', '随箱配件:理线托盘、紧固件、内六角扳手',
|
||||
],
|
||||
variants: [{ id: 'dd6f9c0b-6f6a-4a0e-9fb2-88d50aa7d004', barcode: '0200000030018', name: '胡桃木纹 · 120 cm',
|
||||
colorName: '胡桃木色/黑色', size: ['1200', '600', '720'], material: '饰面板、冷轧钢', boardType: '三聚氰胺饰面刨花板', photo: 'standing-desk' }],
|
||||
},
|
||||
]
|
||||
|
||||
export function desktopTestProductPresets() {
|
||||
return {
|
||||
presets: presets.map(({ id, label, spu, name, productBrand, description, sellingPoints, specifications, variants }) => {
|
||||
const { id: templateId, ...catalog } = template
|
||||
const barcodeEntries = variants.map(({ id, barcode, colorName, material, boardType, size: [length, width, height] }) => ({
|
||||
id: barcode, variantId: id, barcode, colorName, material, boardType,
|
||||
dimensions: { length, width, height, unit: 'mm' as const },
|
||||
}))
|
||||
const [primary] = barcodeEntries
|
||||
const imageAssets = variants.map(({ photo, colorName }) => ({
|
||||
source: `local:${imageData[photo].sha256}`, name: `${name} ${colorName}.jpg`,
|
||||
contentType: 'image/jpeg' as const, base64: imageData[photo].base64,
|
||||
}))
|
||||
|
||||
return {
|
||||
id, label, imageAssets,
|
||||
productBrief: {
|
||||
...catalog, source: 'upload' as const, name, identifierType: 'spu' as const, identifier: spu,
|
||||
variant: variants[0].name, colorName: primary.colorName, colorMaterialId: '',
|
||||
dimensions: primary.dimensions, note: description, detailBarcode: primary.barcode,
|
||||
variants: variants.map(({ id, name, colorName }) => ({ id, name, colorName, colorMaterialId: '', images: [] })),
|
||||
barcodeBindings: Object.fromEntries(barcodeEntries.map(({ variantId, barcode }) => [variantId, [barcode]])),
|
||||
barcodeEntries,
|
||||
// Import each imageAsset into the project and replace this transport reference
|
||||
// with the local source returned by the existing image import.
|
||||
images: imageAssets.map(({ source, name }, index) => ({
|
||||
source, name, purpose: 'product' as const, kind: 'whiteBackground' as const, barcode: barcodeEntries[index].barcode,
|
||||
})),
|
||||
intake: {
|
||||
templateId, schema: intakeSchema,
|
||||
productValues: { productBrand, description, sellingPoints: sellingPoints.join('\n'), specifications: specifications.join('\n') },
|
||||
barcodeValues: Object.fromEntries(barcodeEntries.map(({ barcode, colorName, material, boardType, dimensions }) => [
|
||||
barcode, { colorName, material, boardType, length: dimensions.length, width: dimensions.width, height: dimensions.height },
|
||||
])),
|
||||
},
|
||||
},
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
136
scripts/repair-qa-fast-template-release.py
Normal file
136
scripts/repair-qa-fast-template-release.py
Normal file
@ -0,0 +1,136 @@
|
||||
"""Build a local replacement for QA-FAST-001@2026-12-01.1 from its verified release bundle."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
TEMPLATE = "QA-FAST-001"
|
||||
OLD_VERSION = "2026-12-01.1"
|
||||
OLD_BUNDLE_SHA = "2e276b3d336f0e049739348fd5dc7150c40cb1d5d139a7f0e9c035805f9a9db3"
|
||||
PAGES = {
|
||||
"detail": [("S01", "D01"), ("S02", "D02")],
|
||||
"main_images": [("M01", "M01")],
|
||||
"sku_images": [("K01", "K01")],
|
||||
}
|
||||
|
||||
|
||||
def fingerprint(data):
|
||||
return {"size": len(data), "sha256": hashlib.sha256(data).hexdigest()}
|
||||
|
||||
|
||||
def json_bytes(value):
|
||||
return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def repair_component(manifest, files, payload, component, pages):
|
||||
binding = manifest["bindings"][component]
|
||||
mapping_path, inventory_path = binding["mapping"], binding["inventory"]
|
||||
require(files[mapping_path]["type"] == "mapping" and files[inventory_path]["type"] == "inventory", component)
|
||||
mapping, inventory = (json.loads(payload[path]) for path in (mapping_path, inventory_path))
|
||||
require(all(x["template_id"] == TEMPLATE and x["component"] == component for x in (mapping, inventory)),
|
||||
f"{component}: template or component mismatch")
|
||||
require(mapping["mapping_version"] == "20261201.1" and "mapping_version" not in inventory,
|
||||
f"{component}: unexpected mapping versions")
|
||||
require([(screen["screen_id"], screen["asset_id"]) for screen in mapping["screens"]] == pages,
|
||||
f"{component}: unexpected pages")
|
||||
|
||||
sources = mapping["ps_assets"]
|
||||
require(sources == inventory["ps_assets"] and [source["asset_id"] for source in sources] == [item[1] for item in pages],
|
||||
f"{component}: original references disagree")
|
||||
originals = {asset["path"]: asset for asset in manifest["assets"]
|
||||
if asset["type"] == "original" and asset["component"] == component}
|
||||
require(set(originals) == {source["ps_asset_path"] for source in sources}, f"{component}: originals missing")
|
||||
for source, (page, asset_id) in zip(sources, pages):
|
||||
path = source["ps_asset_path"]
|
||||
if len(pages) == 1:
|
||||
require(binding["original"] == path, f"{component}: original binding mismatch")
|
||||
else:
|
||||
require(binding["pages"][page] == {"original": path, "assetId": asset_id}, f"{page}: original binding mismatch")
|
||||
require((originals[path]["sha256"], originals[path]["size"]) == (source["ps_sha256"], source["ps_size_bytes"]),
|
||||
f"{page}: original hash or size mismatch")
|
||||
fields = [field for field in mapping["fields"] if field["screen_id"] == page]
|
||||
require(len(fields) == 1 and fields[0]["type"] == "图片", f"{page}: expected one image slot")
|
||||
field = fields[0]
|
||||
location = field["ps_location"]
|
||||
require(field["asset_id"] == location["asset_id"] == asset_id and sum(
|
||||
row["asset_id"] == asset_id and row["id"] == location["layer_id"] and row["path"] == location["path"]
|
||||
for row in inventory["rows"]
|
||||
) == 1, f"{page}: image layer binding mismatch")
|
||||
|
||||
for document in (mapping, inventory):
|
||||
require("source" not in document, f"{component}: unexpected source metadata")
|
||||
document["source"] = {"assets": document["ps_assets"]}
|
||||
inventory["mapping_version"] = mapping["mapping_version"]
|
||||
for path, document in ((mapping_path, mapping), (inventory_path, inventory)):
|
||||
payload[path] = json_bytes(document)
|
||||
files[path].update(fingerprint(payload[path]))
|
||||
|
||||
|
||||
def repair(manifest, bundle, new_version):
|
||||
require((manifest["schemaVersion"], manifest["templateId"], manifest["version"], manifest["visibility"])
|
||||
== (1, TEMPLATE, OLD_VERSION, "super_admin_only"), "Unexpected input release")
|
||||
require(new_version != OLD_VERSION and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,79}", new_version),
|
||||
"Choose a new release version")
|
||||
require(manifest["bundle"] == fingerprint(bundle) and manifest["bundle"]["sha256"] == OLD_BUNDLE_SHA,
|
||||
"Input is not the verified QA release bundle")
|
||||
require(manifest["bindings"].keys() == PAGES.keys(), "Expected detail, main_images and sku_images")
|
||||
files = {item["path"]: item for item in manifest["files"]}
|
||||
with zipfile.ZipFile(io.BytesIO(bundle)) as archive:
|
||||
require(len(archive.namelist()) == len(files) and set(archive.namelist()) == set(files), "Bundle file list mismatch")
|
||||
payload = {name: archive.read(name) for name in files}
|
||||
for name, data in payload.items():
|
||||
require(all(files[name][field] == value for field, value in fingerprint(data).items()), f"{name}: file hash or size mismatch")
|
||||
for component, pages in PAGES.items():
|
||||
repair_component(manifest, files, payload, component, pages)
|
||||
|
||||
intake_path = Path(__file__).resolve().parents[1] / "lib" / "desktop-client" / "test-preset-intake.json"
|
||||
config_path = manifest["productionConfig"]
|
||||
config = json.loads(payload[config_path])
|
||||
require("intake" not in config and manifest.get("intake") is None, "Unexpected existing intake schema")
|
||||
manifest["intake"] = config["intake"] = json.loads(intake_path.read_bytes())
|
||||
payload[config_path] = json_bytes(config)
|
||||
files[config_path].update(fingerprint(payload[config_path]))
|
||||
|
||||
output = io.BytesIO()
|
||||
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
for name, data in payload.items():
|
||||
archive.writestr(name, data)
|
||||
repaired_bundle = output.getvalue()
|
||||
manifest.pop("publishedAt", None)
|
||||
manifest.pop("bundlePath", None)
|
||||
manifest.update(version=new_version, knowledgeVersion=f"{TEMPLATE}@{new_version}",
|
||||
builtAt=datetime.now(timezone.utc).isoformat(), bundle=fingerprint(repaired_bundle))
|
||||
return repaired_bundle
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
parser.add_argument("--bundle", type=Path, required=True)
|
||||
parser.add_argument("--version", required=True, help="Unused knowledge release version, e.g. 2026-12-01.2")
|
||||
parser.add_argument("--output", type=Path, required=True, help="New local directory for manifest.json and bundle.zip")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
manifest = json.loads(args.manifest.read_bytes())
|
||||
bundle = repair(manifest, args.bundle.read_bytes(), args.version)
|
||||
args.output.mkdir()
|
||||
(args.output / "bundle.zip").write_bytes(bundle)
|
||||
(args.output / "manifest.json").write_bytes(json_bytes(manifest))
|
||||
except (OSError, ValueError, KeyError, zipfile.BadZipFile) as error:
|
||||
parser.exit(1, f"{error}\n")
|
||||
print(f"{manifest['knowledgeVersion']} | detail: S01,S02 | main_images: M01 | sku_images: K01")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
x
Reference in New Issue
Block a user