From 8f56e16f84abcf54d601d4a624cbe41e65cdf906 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Tue, 1 Dec 2026 15:39:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B6=E5=8F=A3=E5=B0=8F=E5=A3=B9=E6=9D=A1?= =?UTF-8?q?=E7=A0=81=E5=88=B6=E4=BD=9C=E5=A5=91=E7=BA=A6=E5=92=8C=E7=9F=A5?= =?UTF-8?q?=E8=AF=86=E5=BA=93=E8=87=AA=E5=8A=A8=E6=8E=88=E6=9D=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripts/import-enterprise-rules.mjs | 1 + .../detail-agent-pi/scripts/prepare-rules.mjs | 18 +- apps/detail-agent-pi/src/enterprise-rules.mjs | 8 +- .../src/native-knowledge-http.mjs | 11 +- apps/detail-agent-pi/src/product-brief.mjs | 21 ++ .../src/production-operations.mjs | 18 +- .../src/production-repository.mjs | 43 +-- apps/detail-agent-pi/src/project-context.mjs | 24 +- .../test/enterprise-rules.test.mjs | 2 +- .../test/native-knowledge-http.test.mjs | 30 ++ .../test/product-brief.test.mjs | 45 +++ .../test/production-operations.test.mjs | 8 +- apps/detail-photocraft/Cargo.lock | 1 - .../apps/photocraft/Cargo.toml | 3 - .../apps/photocraft/src/jiansun_backend.rs | 11 - .../src/jiansun_canvas_workspace.rs | 97 ++++-- .../apps/photocraft/src/jiansun_creation.rs | 2 +- .../photocraft/src/jiansun_creation_model.rs | 139 ++++++++- .../photocraft/src/jiansun_knowledge_http.rs | 288 ++++++++---------- .../src/jiansun_material_delivery.rs | 61 ++-- .../apps/photocraft/src/jiansun_pi_runtime.rs | 8 +- .../apps/photocraft/src/main.rs | 11 - docs/自动上架平台成套入库通知接口.md | 6 +- 23 files changed, 527 insertions(+), 329 deletions(-) create mode 100644 apps/detail-agent-pi/src/product-brief.mjs create mode 100644 apps/detail-agent-pi/test/product-brief.test.mjs diff --git a/apps/detail-agent-pi/scripts/import-enterprise-rules.mjs b/apps/detail-agent-pi/scripts/import-enterprise-rules.mjs index c02aea9f..504e9c80 100644 --- a/apps/detail-agent-pi/scripts/import-enterprise-rules.mjs +++ b/apps/detail-agent-pi/scripts/import-enterprise-rules.mjs @@ -6,6 +6,7 @@ import { importEnterpriseRules } from '../src/enterprise-rules.mjs'; const [platformFile, knowledgeRoot, output] = process.argv.slice(2); if (!platformFile || !knowledgeRoot || !output) throw Error('用法:<素材库目录快照> <知识库详情页技能目录> <本地规则包路径>'); const platform = JSON.parse(await fs.readFile(platformFile, 'utf8')); +// brandRuleSources 可按店铺 ID 指定知识库根目录下的独立规范文件。 const catalog = await importEnterpriseRules(platform, knowledgeRoot); await atomic(path.resolve(output), catalog); console.log(JSON.stringify({ revision: catalog.revision, brands: catalog.brands.map(b => b.name), ready: catalog.bindings.map(b => ({ template: b.id, shop: catalog.shops.find(s => s.id === b.shopId).name, category: catalog.categories.find(c => c.id === b.categoryId).name })), sourceFiles: catalog.sourceFiles.length, productionWrites: 0 })); diff --git a/apps/detail-agent-pi/scripts/prepare-rules.mjs b/apps/detail-agent-pi/scripts/prepare-rules.mjs index 5bc0da94..90a80dc5 100644 --- a/apps/detail-agent-pi/scripts/prepare-rules.mjs +++ b/apps/detail-agent-pi/scripts/prepare-rules.mjs @@ -2,20 +2,22 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import { resolveRules } from '../src/rules.mjs'; import { atomic, digest } from '../src/store.mjs'; -const configFile = process.argv[2]; +const [configFile, packFile, brandName] = process.argv.slice(2); +if (!configFile || !packFile || !brandName) throw Error('用法:<本地 QA 配置> <离线规则包路径> <品牌名称>'); const config = JSON.parse(await fs.readFile(configFile, 'utf8')); -const packPath = path.resolve('lib/detail-generator/knowledge/enterprise-20261013.json'); +const packPath = path.resolve(packFile); const bytes = await fs.readFile(packPath, 'utf8'), pack = JSON.parse(bytes); -const profile = pack.brands.find(b => b.name === '顾家'); -if (!profile) throw Error('现有顾家导入快照不存在'); +const profile = pack.brands.find(b => b.name === brandName); +if (!profile) throw Error(`离线规则包没有品牌「${brandName}」`); +const brandId = 'local-import:' + digest(brandName); const catalog = { - brands: [{ id: 'local-import-gujia', name: '顾家', profile, revision: pack.version, source: 'repository-import:enterprise-20261013.json (draft)' }], - shops: [{ id: 'QA-A店', brandId: 'local-import-gujia', platform: 'local-qa', revision: 'qa-1', source: 'explicit-qa-fixture', rules: ['A店书桌规则口令:晨雾-2168'] }, { id: 'QA-B店', brandId: 'local-import-gujia', platform: 'local-qa', revision: 'qa-1', source: 'explicit-qa-fixture', rules: ['B店餐椅规则口令:海盐-7391'] }], + brands: [{ id: brandId, name: brandName, profile, revision: pack.version, source: 'local-import:' + path.basename(packPath) }], + shops: [{ id: 'QA-A店', brandId, platform: 'local-qa', revision: 'qa-1', source: 'explicit-qa-fixture', rules: ['A店书桌规则口令:晨雾-2168'] }, { id: 'QA-B店', brandId, platform: 'local-qa', revision: 'qa-1', source: 'explicit-qa-fixture', rules: ['B店餐椅规则口令:海盐-7391'] }], categories: [{ id: 'QA-书桌', revision: 'qa-1', source: 'explicit-qa-fixture', rules: ['没有承重或检测报告时不编造相应参数'] }, { id: 'QA-餐椅', revision: 'qa-1', source: 'explicit-qa-fixture', rules: ['不能把另一产品的尺寸与材质用于当前餐椅'] }], bindings: [{ id: 'QA-A-desk', shopId: 'QA-A店', categoryId: 'QA-书桌', revision: 'qa-1', source: 'explicit-qa-fixture', state: 'ready', rules: [] }, { id: 'QA-B-chair', shopId: 'QA-B店', categoryId: 'QA-餐椅', revision: 'qa-1', source: 'explicit-qa-fixture', state: 'ready', rules: [] }], }; -config.canvasBinding = resolveRules({ brandId: 'local-import-gujia', shopId: 'QA-A店', categoryId: 'QA-书桌' }, catalog); -config.otherBinding = resolveRules({ brandId: 'local-import-gujia', shopId: 'QA-B店', categoryId: 'QA-餐椅' }, catalog); +config.canvasBinding = resolveRules({ brandId, shopId: 'QA-A店', categoryId: 'QA-书桌' }, catalog); +config.otherBinding = resolveRules({ brandId, shopId: 'QA-B店', categoryId: 'QA-餐椅' }, catalog); await atomic(configFile, config); await atomic(path.join(config.output, 'rule-source-manifest.json'), { brandSource: packPath, importedVersion: pack.version, hash: digest(bytes), status: profile.status, shopsAndCategories: 'explicit-local-qa-fixtures', productionCatalog: 'GET currently unavailable; no automatic fallback or deployment performed' }); console.log('Selected the existing local enterprise import explicitly; shop/category rules are labelled QA fixtures.'); diff --git a/apps/detail-agent-pi/src/enterprise-rules.mjs b/apps/detail-agent-pi/src/enterprise-rules.mjs index 6fb1bbe8..d4f63182 100644 --- a/apps/detail-agent-pi/src/enterprise-rules.mjs +++ b/apps/detail-agent-pi/src/enterprise-rules.mjs @@ -76,15 +76,15 @@ export async function importEnterpriseRules(platform, sourceRoot) { return text; } const styles = await read('references/brand-style-prompts.md'); - const gujia = await read('references/gujia-visual-style.md'); const templateCatalog = JSON.parse(await read('template-adapter/references/template-catalog.json')); const catalog = { schemaVersion: 1, source: 'enterprise-knowledge-offline-import', platformCapturedAt: platform.capturedAt, brands: [], shops: [], categories: platform.categories.map(c => ({ ...c, revision: digest(c), source: `material-platform:product_categories:${c.id}`, rules: [`当前品类为「${c.name}」;只使用精确登记的模板和本款产品资料。`] })), bindings: [] }; for (const shop of platform.shops) { const name = shop.name; - if (!markdownSections(styles).some(section => section.title === name)) continue; - const sourceFile = name === '顾家' ? 'references/gujia-visual-style.md' : 'references/brand-style-prompts.md'; - const source = name === '顾家' ? gujia : brandSection(styles, name); + const dedicatedSource = platform.brandRuleSources?.[shop.id]; + if (!dedicatedSource && !markdownSections(styles).some(section => section.title === name)) continue; + const sourceFile = dedicatedSource ?? 'references/brand-style-prompts.md'; + const source = dedicatedSource ? await read(sourceFile) : brandSection(styles, name); const sections = selectSections(source, title => brandRule.test(title)); if (!sections.some(({ title, lines }) => (brandRule.test(title) && /[::]\s*\S/.test(title)) || lines.slice(1).some(line => line.trim()) diff --git a/apps/detail-agent-pi/src/native-knowledge-http.mjs b/apps/detail-agent-pi/src/native-knowledge-http.mjs index 3f923537..dc1d3604 100644 --- a/apps/detail-agent-pi/src/native-knowledge-http.mjs +++ b/apps/detail-agent-pi/src/native-knowledge-http.mjs @@ -1,6 +1,12 @@ import { spawn } from 'node:child_process'; +// Keep the daemon capability out of the environment inherited by unrelated workers. +const bridgeToken = process.env.PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN; +delete process.env.PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN; + const errors = { + 'session-missing': '素材库未部署小壹知识库签发接口(HTTP 404),请联系管理员', + 'session-unavailable': '素材库小壹知识库签发服务不可用(HTTP 503),请联系管理员核对配置', unconfigured: '企业知识库宿主未配置', network: '企业知识库网络不可达', credential: '企业知识库用户凭据未配置或不可读取', @@ -46,7 +52,10 @@ export function createNativeKnowledgeFetch({ cleanup(); try { if (!host) { - const child = spawnProcess(binary, ['--jiansun-pi-rpc'], {windowsHide:true,stdio:['pipe','pipe','ignore']}); + const child = spawnProcess(binary, ['--jiansun-pi-rpc'], { + windowsHide:true, stdio:['pipe','pipe','ignore'], + ...(bridgeToken ? {env:{...process.env, PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN:bridgeToken}} : {}), + }); const current = {child, output:frames(child.stdout), busy:false}; host = current; hosts.add(current); diff --git a/apps/detail-agent-pi/src/product-brief.mjs b/apps/detail-agent-pi/src/product-brief.mjs new file mode 100644 index 00000000..b30f1bc3 --- /dev/null +++ b/apps/detail-agent-pi/src/product-brief.mjs @@ -0,0 +1,21 @@ +export function splitBarcodes(input) { + return [...new Set(input.split(/[\r\n,,、;;]+/u).map(barcode => barcode.trim()).filter(Boolean))]; +} + +export function projectSpu(brief) { + return (brief.identifierType === 'spu' ? brief.identifier : brief.deliverySpu)?.trim() || undefined; +} + +export function detailBarcode(brief) { + const barcodes = new Set(Object.values(brief.barcodeBindings ?? {}).flatMap(splitBarcodes)); + const selected = brief.detailBarcode ?? (barcodes.size === 1 ? barcodes.values().next().value : undefined); + if (selected !== undefined && (!/^[a-zA-Z0-9_-]{1,120}$/u.test(selected) || !barcodes.has(selected))) { + throw Error('详情主条码必须属于当前项目'); + } + return selected; +} + +export function variantBarcodes(brief, variantId) { + const { barcodeBindings, variants = [] } = brief; + return splitBarcodes(barcodeBindings?.[variantId] ?? (variants.length <= 1 ? barcodeBindings?.default : undefined) ?? ''); +} diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 7759007b..169667f1 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -176,7 +176,7 @@ export function productionVideoTools(host, make) { function productionInputs(plan,variantId){ const brief=plan.productEvidence?.brief; if(!brief)return plan.revisions?.creation; - const {brief:shared,variant}=scopedProductionBrief(brief,variantId); + const {brief:shared,variant}=scopedProductionBrief(brief,variantId,plan.outputId); return JSON.stringify([shared,variant,(brief.variants?.length??0)>1, plan.productEvidence.sellingPoints?.selected]); } @@ -189,7 +189,7 @@ export function preparedCandidateId(intent,values,operation){ function changedProductionFields(previous,current,variantId){ const inputs=value=>{ const source=value.productEvidence?.brief??{}; - const {brief,variant}=scopedProductionBrief(source,variantId); + const {brief,variant}=scopedProductionBrief(source,variantId,value.outputId); return {brief,variant:variant??{}, options:{multipleVariants:(source.variants?.length??0)>1, sellingPoints:value.productEvidence?.sellingPoints?.selected}}; @@ -1197,8 +1197,8 @@ export async function openProductionOperations(host,{target=host.productionGoal, await current(); if(!canvasReady)recordProductionInputs(repository,plan,slots); const {requested,matched,unmatched}=readSelection(slotIds); - const {brief,variant}=scopedProductionBrief(plan.productEvidence?.brief??{},variantId); - const {name,dimensions,note,intake,barcodes}=brief; + const {brief,variant}=scopedProductionBrief(plan.productEvidence?.brief??{},variantId,outputId); + const {name,spu,dimensions,note,intake,barcodes,detailBarcode}=brief; const settings=productionSettings(store,plan.template.production); const {plannedSlots,...picturePlan}=productionPicturePlan(outputId,await liveSlots(),settings); const selected=plannedSlots.filter(slot=>!requested.size||matched.has(slot.id)); @@ -1217,8 +1217,8 @@ export async function openProductionOperations(host,{target=host.productionGoal, const {outputId:workingOutputId,variantId:workingVariantId}=host.productionGoal; return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null, fieldConflicts:await fieldConflicts(await copySnapshot(),plan),fieldRequirements:fieldRequirements(plan), - template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName}, - ...(intake?{intake,barcodes}:null)}, + template,product:{name,dimensions,note,...(spu?{spu}:null),variant:variant&&{id:variant.id,colorName:variant.colorName}, + ...(intake?{intake}:null),...(barcodes?{barcodes}:null),...(detailBarcode?{detailBarcode}:null)}, candidatesPerSlot,maxCandidatesPerSlot,maxGenerationAttempts,generationLimitSource,...picturePlan,...facts(),...(productUpdate?{productUpdate}:null),pictures, inFlightImages:(await pendingNative()).map(row=>row.candidateId), ...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null), @@ -1518,7 +1518,7 @@ export async function openProductionOperations(host,{target=host.productionGoal, delegateSignal.throwIfAborted(); await runDetailAgent(slot.id,instructions, JSON.stringify({rework,goal,referenceMode,screenCopy,pendingCopyFields,target:slotTarget(live), - product:scopedProductionBrief((await current()).productEvidence?.brief??{},variantId), + product:scopedProductionBrief((await current()).productEvidence?.brief??{},variantId,outputId), productReferences:productIds,layoutCount,layoutIssue,templatePrompt,outputSpec,referenceError:unavailable,...status,...(grouped?{groupTargets}:null),field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...workerTools], attachments,productRequestScope('slot',slot.id),captions,delegateSignal); if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'}); @@ -1845,8 +1845,8 @@ export async function openProductionOperations(host,{target=host.productionGoal, const references=()=>referenceRead??=readReferences(); async function readReferences(){ const inputPlan=await current(); - const {brief,variant}=scopedProductionBrief(inputPlan.productEvidence?.brief??{},variantId); - const product={...brief,variant:variant??brief.variant, + const {brief,variant}=scopedProductionBrief(inputPlan.productEvidence?.brief??{},variantId,outputId); + const product={...brief,variant, sellingPoints:inputPlan.productEvidence?.sellingPoints?.selected}; if(!slots.length)throw Error('当前画布没有可读取本款实拍的图位'); const {images=[],referenceCount=0}=await readImages(slots[0].id,{includeTemplateReference:false}); diff --git a/apps/detail-agent-pi/src/production-repository.mjs b/apps/detail-agent-pi/src/production-repository.mjs index e0d49fa0..5eee6723 100644 --- a/apps/detail-agent-pi/src/production-repository.mjs +++ b/apps/detail-agent-pi/src/production-repository.mjs @@ -2,6 +2,7 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import { ProjectRepository } from './project-repository.mjs'; import { atomic, digest } from './store.mjs'; +import { detailBarcode, projectSpu, variantBarcodes } from './product-brief.mjs'; export function productionRepository(store, outputId, variantId) { const { scope: accountId, project: projectId } = store.identity; @@ -38,33 +39,35 @@ export function productionLedger(store, outputId, variantId) { }}; } -export function scopedProductionBrief(brief, variantId) { - const { variants, intake, barcodeBindings, ...shared } = brief; +export function scopedProductionBrief(source, variantId, outputId) { + const { variants, intake, barcodeBindings, detailBarcode: selectedBarcode, deliverySpu, ...brief } = source; + const spu = projectSpu(source); + if (spu) brief.spu = spu; const variant = variants?.find(row => row.id === variantId); - if (!intake) return { brief: shared, variant }; - - const binding = barcodeBindings?.[variantId] - ?? ((variants?.length ?? 0) <= 1 ? barcodeBindings?.default : undefined) - ?? ''; - const barcodes = [...new Set(binding.split(/[\s,,、]+/u).filter(Boolean))]; - const barcodeValues = Object.fromEntries(barcodes - .filter(barcode => Object.hasOwn(intake.barcodeValues ?? {}, barcode)) - .map(barcode => [barcode, intake.barcodeValues[barcode]])); - return { - brief: { - ...shared, - intake: { ...intake, barcodeValues }, - barcodes, - }, - variant, - }; + const selected = outputId === 'detail' ? detailBarcode(source) : undefined; + const boundBarcodes = variantBarcodes(source, variantId); + if (outputId === 'detail' && !selected && boundBarcodes.length) { + throw Error('请在产品资料中选择制作详情页的主条码'); + } + if (selected && !boundBarcodes.includes(selected)) throw Error('当前详情花色不包含选定的主条码'); + const barcodes = selected ? [selected] : boundBarcodes; + if (selected) brief.detailBarcode = selected; + if (barcodeBindings) brief.barcodes = barcodes; + if (intake) { + const values = intake.barcodeValues ?? {}; + const barcodeValues = Object.fromEntries(barcodes + .filter(barcode => Object.hasOwn(values, barcode)) + .map(barcode => [barcode, values[barcode]])); + brief.intake = { ...intake, barcodeValues }; + } + return { brief, variant }; } export function recordProductionInputs(repository, plan, slots) { const { productEvidence, productVariantId, revisions, template } = plan; let productFactsRevision; if (productEvidence?.brief) { - const { brief, variant } = scopedProductionBrief(productEvidence.brief, productVariantId); + const { brief, variant } = scopedProductionBrief(productEvidence.brief, productVariantId, plan.outputId); const facts = { brief, variant, facts: productEvidence.facts, sourceRevision: revisions?.creation ?? productEvidence.revision }; productFactsRevision = digest(facts); diff --git a/apps/detail-agent-pi/src/project-context.mjs b/apps/detail-agent-pi/src/project-context.mjs index 1c200d80..07aefe93 100644 --- a/apps/detail-agent-pi/src/project-context.mjs +++ b/apps/detail-agent-pi/src/project-context.mjs @@ -1,4 +1,5 @@ import { digest } from './store.mjs'; +import { detailBarcode, projectSpu, variantBarcodes } from './product-brief.mjs'; const text=value=>typeof value==="string"?value:""; const list=value=>Array.isArray(value)?value:[]; @@ -48,22 +49,17 @@ export function productContext(value,identity){ factsStatus:text(facts.status),facts:list(facts.items).map(f=>({text:text(f.text),source:text(f.source)})), missing:list(facts.missing).map(v=>text(v)),selectedSellingPoints:selling.stale?[]:selected, plan:{status:text(plan.status),screens:list(plan.screens).map(s=>({name:text(s.name||s.title),body:text(s.body)}))}}; - if(brief.intake && typeof brief.intake==='object' && !Array.isArray(brief.intake)){ - result.intake=brief.intake; - } - if(brief.barcodeBindings && typeof brief.barcodeBindings==='object' && !Array.isArray(brief.barcodeBindings)){ - result.barcodeBindings=brief.barcodeBindings; - } - if(typeof brief.deliverySpu==='string' && brief.deliverySpu.trim()){ - result.product.spu=brief.deliverySpu; - } else if(brief.intake && brief.identifierType==='spu' && typeof brief.identifier==='string' && brief.identifier.trim()){ - result.product.spu=brief.identifier; - } - if(skuPlan)result.references.outputVariantIds=Object.fromEntries(['detail','main_images'].flatMap(key=>{ - const ids=list(brief.outputVariantIds[key]).map(safeId).filter(Boolean); + if(brief.intake) result.intake=brief.intake; + if(brief.barcodeBindings) result.barcodeBindings=brief.barcodeBindings; + const selectedBarcode=detailBarcode(brief), spu=projectSpu(brief); + if(selectedBarcode) result.detailBarcode=selectedBarcode; + if(spu) result.product.spu=spu; + const detailVariant=selectedBarcode&&variants.find(variant=>variantBarcodes(brief,variant.id).includes(selectedBarcode)); + if(skuPlan||detailVariant)result.references.outputVariantIds=Object.fromEntries(['detail','main_images'].flatMap(key=>{ + const ids=key==='detail'&&detailVariant?[detailVariant.id]:list(brief.outputVariantIds?.[key]).map(safeId).filter(Boolean); return ids.length?[[key,ids]]:[]; })); - else if(brief.outputColors)result.product.outputColors=outputColors(brief.outputColors); + if(!skuPlan&&brief.outputColors)result.product.outputColors=outputColors(brief.outputColors); result.contentHash=digest(result); return result; } diff --git a/apps/detail-agent-pi/test/enterprise-rules.test.mjs b/apps/detail-agent-pi/test/enterprise-rules.test.mjs index c7d7f0ff..6ed748b1 100644 --- a/apps/detail-agent-pi/test/enterprise-rules.test.mjs +++ b/apps/detail-agent-pi/test/enterprise-rules.test.mjs @@ -16,7 +16,7 @@ async function fixture() { await write('template-adapter/references/template-catalog.json', JSON.stringify({ templates: [template] })); await write('template-adapter/references/guide.md', '## 屏号和固定元素\n模板事实不是新产品事实\n## 主图组件\n不在详情范围\n'); await write('template-adapter/assets/mapping.json', JSON.stringify({ template_id: 'T', brand: '顾家', category: '电脑桌', screens: [{ screen_id: 'S01', title: '首屏', purpose: '展示当前产品', page_role: 'content' }] })); - const platform = { capturedAt: '2026-01-01', shops: [{ id: 's1', name: '顾家' }, { id: 's2', name: '欧意朗' }, { id: 's3', name: '未知店' }], categories: [{ id: 'c1', name: '电脑桌' }, { id: 'c2', name: '书桌' }] }; + const platform = { brandRuleSources: { s1: 'references/gujia-visual-style.md' }, capturedAt: '2026-01-01', shops: [{ id: 's1', name: '顾家' }, { id: 's2', name: '欧意朗' }, { id: 's3', name: '未知店' }], categories: [{ id: 'c1', name: '电脑桌' }, { id: 'c2', name: '书桌' }] }; return { dir, root, write, platform, template }; } test('enterprise import uses exact real catalog identities and sourced category bindings without inventing coverage', async () => { diff --git a/apps/detail-agent-pi/test/native-knowledge-http.test.mjs b/apps/detail-agent-pi/test/native-knowledge-http.test.mjs index 0d0c631c..62b48ade 100644 --- a/apps/detail-agent-pi/test/native-knowledge-http.test.mjs +++ b/apps/detail-agent-pi/test/native-knowledge-http.test.mjs @@ -96,6 +96,36 @@ test('知识库通道只返回固定错误文案,取消时终止等待中的 }); +test('签发端缺失或不可用时保留固定的 HTTP 诊断', async () => { + for (const [category, status] of [['session-missing', 404], ['session-unavailable', 503]]) { + const host = fixture(async write => { + write({ type: 'error', category, error: 'synthetic raw upstream text' }); + }); + await assert.rejects(host.fetch('http://knowledge.test/api/xiaoyi/v1/templates', { method: 'GET' }), + error => error.category === category && error.network === false && error.message.includes(`HTTP ${status}`)); + await host.produced; + } +}); + +test('回环 Token 只传给知识库宿主子进程', async () => { + const name = 'PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN'; + process.env[name] = 'synthetic-bridge-token'; + const { createNativeKnowledgeFetch: createFetch } = await import('../src/native-knowledge-http.mjs?bridge-test'); + assert.equal(process.env[name], undefined); + const child = Object.assign(new EventEmitter(), { stdin: new PassThrough(), stdout: new PassThrough() }); + child.stdin.once('data', bytes => { + assert.ok(!bytes.includes('synthetic-bridge-token')); + child.stdout.end('{"type":"headers","status":200,"headers":{}}\n{"type":"result"}\n'); + }); + const fetch = createFetch({ binary: 'fake-host.exe', spawnProcess(binary, args, options) { + assert.equal(options.env[name], 'synthetic-bridge-token'); + return child; + } }); + const response = await fetch('http://knowledge.test/api/xiaoyi/v1/templates', { method: 'GET' }); + assert.equal(response.status, 200); + await response.text(); +}); + test('完整响应之后,同一宿主继续接收下一次请求', async () => { const child = Object.assign(new EventEmitter(), {stdin:new PassThrough(),stdout:new PassThrough()}); const requests = []; diff --git a/apps/detail-agent-pi/test/product-brief.test.mjs b/apps/detail-agent-pi/test/product-brief.test.mjs new file mode 100644 index 00000000..d970bbe4 --- /dev/null +++ b/apps/detail-agent-pi/test/product-brief.test.mjs @@ -0,0 +1,45 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { detailBarcode, projectSpu, splitBarcodes } from '../src/product-brief.mjs'; +import { scopedProductionBrief } from '../src/production-repository.mjs'; +import { productContext } from '../src/project-context.mjs'; + +const white = 'DNZ030516N717V01'; +const other = 'CY001307N35V01'; +const black = 'cy001301N35'; +const brief = { + identifierType: 'spu', identifier: 'DNZ030516', deliverySpu: 'old-spu', + variants: [{ id: 'white', images: [] }, { id: 'black', images: [] }], + barcodeBindings: { white: `${white};${other}\n${white}`, black }, + detailBarcode: other, outputVariantIds: { detail: ['black'], main_images: ['black'] }, + intake: { productValues: { title: '共用名称' }, barcodeValues: { + [white]: { size: '小' }, [other]: { size: '大' }, [black]: { size: '中' }, + } }, +}; + +test('barcode split follows the upload form and preserves original case and spelling', () => { + assert.deepEqual(splitBarcodes(` ${white},${black}、${white};CY001301N35\r\n`), [white, black, 'CY001301N35']); + assert.equal(projectSpu(brief), brief.identifier); + assert.equal(projectSpu({ ...brief, identifierType: 'sku' }), brief.deliverySpu); + assert.equal(detailBarcode({ barcodeBindings: { default: black } }), black); + assert.throws(() => detailBarcode({ ...brief, detailBarcode: black.toUpperCase() }), /必须属于/); +}); + +test('project context sees all barcodes and the detail stage uses only the selected barcode', () => { + const context = productContext({ accountScope: 'a', project: 'p', documentId: 1, brief }, { scope: 'a', project: 'p', documentId: 1 }); + assert.equal(context.product.spu, brief.identifier); + assert.equal(context.detailBarcode, other); + assert.deepEqual(context.references.outputVariantIds, { detail: ['white'], main_images: ['black'] }); + assert.deepEqual(context.barcodeBindings, brief.barcodeBindings); + assert.deepEqual(context.intake, brief.intake); + const detail = scopedProductionBrief(brief, 'white', 'detail').brief; + assert.equal(detail.detailBarcode, other); + assert.deepEqual(detail.barcodes, [other]); + assert.deepEqual(detail.intake, { productValues: brief.intake.productValues, barcodeValues: { [other]: { size: '大' } } }); + assert.throws(() => scopedProductionBrief(brief, 'black', 'detail'), /不包含选定的主条码/); + assert.throws(() => scopedProductionBrief({ ...brief, detailBarcode: undefined }, 'white', 'detail'), /选择制作详情页的主条码/); + const sku = scopedProductionBrief(brief, 'white', 'sku_images').brief; + assert.deepEqual(sku.barcodes, [white, other]); + assert.deepEqual(Object.keys(sku.intake.barcodeValues), [white, other]); + assert.equal(sku.detailBarcode, undefined); +}); diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index 69706c66..9fdf7cba 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -1523,9 +1523,9 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca const variants=[{id:'wood',colorName:'橡木色'},{id:'white',colorName:'米白色'}]; const dimensions={length:'1200',width:'600',height:'740',unit:'mm'}; const note='桌面为橡胶木,图片只参考模板构图。'; - const barcodeBindings={wood:'00123,00124',white:'00999'}; + const barcodeBindings={wood:'DNZ030516N717V01,CY001307N35V01',white:'SG008839N1049V01'}; const intake={templateId:'table',schema:{fields:[]},productValues:{material:'木'}, - barcodeValues:{'00123':{width:'120'},'00124':{width:'140'},'00999':{width:'160'}}}; + barcodeValues:{'DNZ030516N717V01':{width:'120'},'CY001307N35V01':{width:'140'},'SG008839N1049V01':{width:'160'}}}; const submissions=[]; let creation=1; const submit=Promise.withResolvers(); @@ -1556,8 +1556,8 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca const initialPlan=await actions.plan_production(); assert.deepEqual(initialPlan.pendingOutputs,[nextOutput]); assert.deepEqual(initialPlan.product,{name:'餐桌',dimensions,note,variant:{id:variantId,colorName:'橡木色'}, - barcodes:['00123','00124'],intake:{...intake,barcodeValues:{'00123':{width:'120'},'00124':{width:'140'}}}}); - intake.barcodeValues['00999'].width='170'; + barcodes:['DNZ030516N717V01','CY001307N35V01'],intake:{...intake,barcodeValues:{'DNZ030516N717V01':{width:'120'},'CY001307N35V01':{width:'140'}}}}); + intake.barcodeValues['SG008839N1049V01'].width='170'; creation++; assert.equal((await actions.plan_production()).productUpdate,undefined); creation--; diff --git a/apps/detail-photocraft/Cargo.lock b/apps/detail-photocraft/Cargo.lock index 0b7c142e..759d2b36 100644 --- a/apps/detail-photocraft/Cargo.lock +++ b/apps/detail-photocraft/Cargo.lock @@ -5056,7 +5056,6 @@ dependencies = [ "url", "uuid", "winit", - "winreg", "winresource", "winsafe", "wl-clipboard-rs", diff --git a/apps/detail-photocraft/apps/photocraft/Cargo.toml b/apps/detail-photocraft/apps/photocraft/Cargo.toml index 8095b51b..7a89009f 100644 --- a/apps/detail-photocraft/apps/photocraft/Cargo.toml +++ b/apps/detail-photocraft/apps/photocraft/Cargo.toml @@ -61,9 +61,6 @@ image = { workspace = true } keyring = { version = "3", features = ["windows-native"] } memchr = "2" -[target.'cfg(windows)'.dependencies] -winreg = "0.55" - [target.'cfg(target_os = "macos")'.dependencies] # Safe CoreGraphics bindings, compatible with the existing macOS 11 deployment target. # `event` (CGEventSource) is used for the Caps Lock poll (#1758). diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index aac87ec9..401b092c 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -149,15 +149,6 @@ pub fn pi_rpc() -> R<()> { pi::run_rpc() } -#[cfg(windows)] -pub fn import_ekb_key(name: &std::ffi::OsStr) -> R<()> { - use winreg::{RegKey, enums::HKEY_CURRENT_USER}; - let key: String = RegKey::predef(HKEY_CURRENT_USER).open_subkey("Environment") - .and_then(|env| env.get_value(name)) - .map_err(|_| "无法读取指定的用户环境变量")?; - knowledge_http::save_key(&key) -} - /// One-time, stdin-only migration from this project's existing OS-encrypted client. /// No secret is accepted in a command-line argument or written to an intermediate file. pub fn import_existing() -> R { @@ -1046,7 +1037,6 @@ impl Backend { if let Ok([intranet, _]) = knowledge_http::origins() { result["knowledgeOrigin"] = json!(intranet); } - result["knowledgeKeySaved"] = json!(knowledge_http::credential().is_ok()); result["xiaoyiKeySaved"] = json!(knowledge_http::xiaoyi_key_saved()); let knowledge = if library_status == "connected" { knowledge_http::automatic_status() @@ -1603,7 +1593,6 @@ impl Backend { "project-sync" => self.sync_project(input), "delivery-status" => self.delivery_status(input), "project-state" => self.project_state(input), - "configure-knowledge" => knowledge_http::configure(input), "configure-xiaoyi-knowledge" => Ok(knowledge_http::configure_for_account(input)), "select-model" => { if self.auth["account"]["id"].is_null() || input["accountId"] != self.auth["account"]["id"] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 1d413c72..80524abb 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -92,6 +92,10 @@ fn variant<'a>(state: &'a Value, id: &str) -> R<&'a Value> { state["variants"].as_array().into_iter().flatten().find(|v| v["id"] == id).ok_or_else(|| "花色不属于此项目".into()) } fn output_uses_variant(brief: &Value, component: &str, id: &str) -> bool { + if component == "detail" && let Some(selected) = creation::detail_barcode(brief) { + let count = brief["variants"].as_array().map_or(0, Vec::len); + return creation::variant_barcodes(brief, id, count).any(|barcode| barcode == selected); + } brief["outputVariantIds"][component].as_array().is_none_or(|ids| ids.iter().any(|value| value == id)) } @@ -124,6 +128,9 @@ fn runnable_stages(state: &Value, mut remaining: Vec) -> Vec { } fn production_output_state(mut state: Value, output: &str, variant_id: &str) -> R { + if output == "detail" { + creation::require_detail_barcode(&state["brief"])?; + } variant(&state, variant_id)?; if !output_uses_variant(&state["brief"], output, variant_id) { return Err("花色不属于所选成品".into()); @@ -164,14 +171,17 @@ fn image_output_state(state: Value, binding: &Value) -> R { fn output_variant<'a>(state: &'a Value, component: &str, requested: Option<&'a str>) -> R<&'a str> { if let Some(id) = requested { variant(state, id)?; - return Ok(id); + if output_uses_variant(&state["brief"], component, id) { + return Ok(id); + } + return Err("当前花色不属于此输出".into()); } let active = state["activeVariantId"].as_str().ok_or("当前花色缺失")?; if output_uses_variant(&state["brief"], component, active) { return Ok(active); } - state["brief"]["outputVariantIds"][component].as_array().into_iter().flatten() - .filter_map(Value::as_str).find(|id| variant(state, id).is_ok()) + state["variants"].as_array().into_iter().flatten() + .filter_map(|row| row["id"].as_str()).find(|id| output_uses_variant(&state["brief"], component, id)) .ok_or_else(|| "请在产品资料选择此类图片的 SKU 颜色".into()) } @@ -714,20 +724,21 @@ fn canvas_template(previous: Option<&Value>, selected: &Value, brand: &str, cate fn shared_variant_brief(brief: &Value) -> Value { let mut shared = creation::production_brief(brief); - if let Some(fields) = shared.as_object_mut() { fields.remove("variants"); } + if let Some(fields) = shared.as_object_mut() { + fields.remove("variants"); + fields.remove("detailBarcode"); + } if let Some(intake) = shared.get_mut("intake").and_then(Value::as_object_mut) { intake.remove("barcodeValues"); } shared } -fn variant_intake(brief: &Value, variant_id: &str) -> Option { +fn variant_intake(brief: &Value, variant_id: &str, component: &str) -> Option { let intake = brief.get("intake")?; - let bindings = &brief["barcodeBindings"]; - let entered = bindings[variant_id].as_str().or_else(|| { - (brief["variants"].as_array().is_none_or(|rows| rows.len() <= 1)) - .then(|| bindings["default"].as_str()).flatten() - }).unwrap_or_default(); + let count = brief["variants"].as_array().map_or(0, Vec::len); + let detail_barcode = (component == "detail").then(|| creation::detail_barcode(brief)).flatten(); let mut values = serde_json::Map::new(); - for barcode in entered.split(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ',' | '、')) { + for barcode in creation::variant_barcodes(brief, variant_id, count) + .filter(|barcode| detail_barcode.is_none_or(|selected| selected == *barcode)) { if let Some(fields) = intake["barcodeValues"].get(barcode) && fields.as_object().is_some_and(|fields| !fields.is_empty()) { @@ -766,20 +777,24 @@ pub(super) fn apply_saved_variant_edits(dir: &Path) -> R<()> { const VARIANT_INPUT_HASH: &str = "variant-v1:"; -fn variant_input_hash(state: &Value, creation: &Value, variant_id: &str, template: &Value, structure: &Value) -> R { +fn variant_input_hash(state: &Value, creation: &Value, variant_id: &str, component: &str, template: &Value, structure: &Value) -> R { let selected = variant(state, variant_id)?; let live = &creation["brief"]; let mut inputs = json!({"brief":shared_variant_brief(&state["brief"]),"liveBrief":shared_variant_brief(live), "liveVariant":variant_brief(live, variant_id),"variant":selected, "multiVariant":state["variants"].as_array().is_some_and(|rows| rows.len() > 1), "templateHash":template,"structureHash":structure,"rules":creation["designSnapshot"]}); - if let Some(fields) = variant_intake(&state["brief"], variant_id) { inputs["variantIntake"] = fields; } - if let Some(fields) = variant_intake(live, variant_id) { inputs["liveVariantIntake"] = fields; } + if component == "detail" && (state["brief"].get("detailBarcode").is_some() || live.get("detailBarcode").is_some()) { + inputs["detailBarcode"] = json!(creation::detail_barcode(&state["brief"])); + inputs["liveDetailBarcode"] = json!(creation::detail_barcode(live)); + } + if let Some(fields) = variant_intake(&state["brief"], variant_id, component) { inputs["variantIntake"] = fields; } + if let Some(fields) = variant_intake(live, variant_id, component) { inputs["liveVariantIntake"] = fields; } Ok(format!("{VARIANT_INPUT_HASH}{}", hash(&inputs.to_string()))) } fn input_hash(dir: &Path, state: &Value, variant_id: &str) -> R { - variant_input_hash(state, &creation::load(dir)?, variant_id, &state["template"]["contentHash"], &state["structureHash"]) + variant_input_hash(state, &creation::load(dir)?, variant_id, state["activeOutput"].as_str().unwrap_or("detail"), &state["template"]["contentHash"], &state["structureHash"]) } fn candidate_uses_current_inputs(dir: &Path, state: &Value, record: &Value, variant_id: &str) -> R { @@ -1740,7 +1755,8 @@ fn check_image_context(dir: &Path, except: Option<&Value>, batch: Option<&Value> if live != saved && !current_variant.is_some_and(|id| state["productTemplates"].is_object() && shared_variant_brief(live) == shared_variant_brief(saved) && variant_brief(live, id) == variant_brief(saved, id) - && variant_intake(live, id) == variant_intake(saved, id)) + && creation::detail_barcode(live) == creation::detail_barcode(saved) + && variant_intake(live, id, "detail") == variant_intake(saved, id, "detail")) { return Err("当前商品或花色资料已更新,请读取新资料;原请求已保留".into()); } @@ -2845,7 +2861,7 @@ fn approved_structure_guides(recipe: &Value, item: &Value, candidate: &str) -> R fn stage_input_hash(state: &Value, creation: &Value, variant: &str, component: &str) -> R { let template = &state["productTemplates"][component]["contentHash"]; let structure = json!(hash(&json!([template,state["width"]]).to_string())); - let inputs = json!({"variant":variant_input_hash(state, creation, variant, template, &structure)?, + let inputs = json!({"variant":variant_input_hash(state, creation, variant, component, template, &structure)?, "width":creation["width"],"screenCount":creation["screenCount"], "selected":creation["sellingPoints"]["selected"],"direction":creation["sellingPoints"]["direction"], "screens":creation["plan"]["screens"]}); @@ -4815,6 +4831,9 @@ impl Backend { let start_product = !browsing && (input["generateProduct"] == true || input["resumeProduct"] == true); if start_product { let stages = resumable_stages(&dir, &state, &creation::load(&dir)?["revision"], true); + if stages.iter().any(|stage| stage["outputId"] == "detail") { + creation::require_detail_barcode(&state["brief"])?; + } if stages.is_empty() { let blocked = blocked_production_stages(&state); if blocked.is_empty() { return Err("已选成品均已在项目中保存".into()); } @@ -8125,23 +8144,51 @@ mod tests { assert_eq!(recovered["brief"]["variants"], state["variants"]); assert_eq!(recovered["brief"]["templateSelection"]["name"], state["template"]["name"]); } + #[test] + fn selected_detail_barcode_controls_only_detail_variant_and_intake() { + let mut brief = json!({ + "variants":[{"id":"white"},{"id":"black"}], + "barcodeBindings":{"white":"DNZ030516N717V01;CY001307N35V01","black":"cy001301N35"}, + "detailBarcode":"CY001307N35V01", + "outputVariantIds":{"detail":["black"],"main_images":["black"]}, + "intake":{"productValues":{"title":"共用"},"barcodeValues":{ + "DNZ030516N717V01":{"size":"小"},"CY001307N35V01":{"size":"大"},"cy001301N35":{"size":"中"} + }} + }); + assert!(output_uses_variant(&brief, "detail", "white")); + assert!(!output_uses_variant(&brief, "detail", "black")); + assert!(output_uses_variant(&brief, "main_images", "black")); + assert_eq!(variant_intake(&brief, "white", "detail"), Some(json!({"CY001307N35V01":{"size":"大"}}))); + let old_sku = variant_intake(&brief, "white", "sku_images"); + let saved = json!({"brief":brief,"variants":brief["variants"]}); + let mut creation = json!({"brief":brief}); + let hash = |creation: &Value, output| variant_input_hash(&saved, creation, "white", output, &json!("template"), &json!("structure")).unwrap(); + let old_detail = hash(&creation, "detail"); + let old_sku_hash = hash(&creation, "sku_images"); + brief["detailBarcode"] = json!("DNZ030516N717V01"); + creation["brief"] = brief.clone(); + assert_ne!(hash(&creation, "detail"), old_detail); + assert_eq!(hash(&creation, "sku_images"), old_sku_hash); + assert_eq!(variant_intake(&brief, "white", "sku_images"), old_sku); + } + #[test] fn barcode_intake_only_changes_its_own_variant_input() { let mut state = json!({ "brief":{"variants":[{"id":"oak"},{"id":"white"}], - "barcodeBindings":{"oak":"00123\n00456","white":"00999"}, + "barcodeBindings":{"oak":"DNZ030516N717V01\nCY001307N35V01","white":"SG008839N1049V01"}, "intake":{"templateId":"t","schema":{"version":1},"productValues":{}, - "barcodeValues":{"00123":{"size":"large"},"00999":{"size":"small"}}}}, + "barcodeValues":{"DNZ030516N717V01":{"size":"large"},"SG008839N1049V01":{"size":"small"}}}}, "variants":[{"id":"oak"},{"id":"white"}] }); let mut creation = json!({"brief":state["brief"],"designSnapshot":null}); - let before_oak = variant_input_hash(&state, &creation, "oak", &json!("template"), &json!("structure")).unwrap(); - let before_white = variant_input_hash(&state, &creation, "white", &json!("template"), &json!("structure")).unwrap(); - creation["brief"]["intake"]["barcodeValues"]["00123"]["size"] = json!("extra large"); + let before_oak = variant_input_hash(&state, &creation, "oak", "sku_images", &json!("template"), &json!("structure")).unwrap(); + let before_white = variant_input_hash(&state, &creation, "white", "sku_images", &json!("template"), &json!("structure")).unwrap(); + creation["brief"]["intake"]["barcodeValues"]["DNZ030516N717V01"]["size"] = json!("extra large"); state["brief"] = creation["brief"].clone(); - assert_ne!(variant_input_hash(&state, &creation, "oak", &json!("template"), &json!("structure")).unwrap(), before_oak); - assert_eq!(variant_input_hash(&state, &creation, "white", &json!("template"), &json!("structure")).unwrap(), before_white); - assert!(variant_intake(&creation["brief"], "white").unwrap().get("00123").is_none()); + assert_ne!(variant_input_hash(&state, &creation, "oak", "sku_images", &json!("template"), &json!("structure")).unwrap(), before_oak); + assert_eq!(variant_input_hash(&state, &creation, "white", "sku_images", &json!("template"), &json!("structure")).unwrap(), before_white); + assert!(variant_intake(&creation["brief"], "white", "sku_images").unwrap().get("DNZ030516N717V01").is_none()); } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 863c9440..67e02f82 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -4,7 +4,7 @@ use super::*; use base64::engine::general_purpose::STANDARD; #[path = "jiansun_creation_model.rs"] mod model; -pub(super) use model::production_brief; +pub(super) use model::{delivery_spu, detail_barcode, production_brief, require_detail_barcode, valid_delivery_barcode, variant_barcodes}; #[path = "jiansun_composer_attachments.rs"] pub(super) mod composer_attachments; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs index f7bf77b8..9809cdf1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs @@ -38,6 +38,51 @@ fn image_list(value: &Value) -> R { Ok(json!(clean)) } +pub(in super::super) fn valid_delivery_barcode(barcode: &str) -> bool { + !barcode.is_empty() && barcode.len() <= 120 + && barcode.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) +} + +pub(in super::super) fn split_barcodes(input: &str) -> impl Iterator { + let mut seen = std::collections::HashSet::new(); + input.split(['\r', '\n', ',', ',', '、', ';', ';']).map(str::trim) + .filter(move |barcode| !barcode.is_empty() && seen.insert(*barcode)) +} + +pub(in super::super) fn variant_barcodes<'a>( + brief: &'a Value, variant_id: &str, variant_count: usize, +) -> impl Iterator { + let bindings = &brief["barcodeBindings"]; + let entered = bindings[variant_id].as_str().or_else(|| { + if variant_count <= 1 { bindings["default"].as_str() } else { None } + }); + split_barcodes(entered.unwrap_or_default()) +} + +pub(in super::super) fn detail_barcode(brief: &Value) -> Option<&str> { + if let Some(selected) = brief["detailBarcode"].as_str() { + return Some(selected); + } + let mut barcodes = brief["barcodeBindings"].as_object()?.values() + .filter_map(Value::as_str).flat_map(split_barcodes); + let first = barcodes.next()?; + barcodes.all(|barcode| barcode == first).then_some(first) +} + +pub(in super::super) fn require_detail_barcode(brief: &Value) -> R<()> { + if detail_barcode(brief).is_none() && brief["barcodeBindings"].as_object().is_some_and(|rows| { + rows.values().filter_map(Value::as_str).flat_map(split_barcodes).next().is_some() + }) { + return Err("请在产品资料中选择制作详情页的主条码".into()); + } + Ok(()) +} + +pub(in super::super) fn delivery_spu(brief: &Value) -> Option<&str> { + let value = if brief["identifierType"] == "spu" { &brief["identifier"] } else { &brief["deliverySpu"] }; + value.as_str().map(str::trim).filter(|spu| !spu.is_empty()) +} + fn intake(value: &Value) -> R { let template_id = string(&value["templateId"], 120, "模板编号")?; if template_id.trim().is_empty() { return Err("产品资料缺少模板编号".into()); } @@ -83,7 +128,7 @@ fn intake(value: &Value) -> R { validate_values(&value["productValues"], &kinds[0])?; let barcode_values = value["barcodeValues"].as_object().filter(|rows| rows.len() <= 200).ok_or("条码资料格式无效")?; for (barcode, fields) in barcode_values { - if barcode.is_empty() || barcode.len() > 120 || !barcode.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) { + if !valid_delivery_barcode(barcode) { return Err("条码资料中的条码格式无效".into()); } validate_values(fields, &kinds[1])?; @@ -188,22 +233,56 @@ pub(super) fn brief(value: &Value) -> R { out["skuBindings"] = Value::Object(clean); } } - if let Some(spu) = value.get("deliverySpu") { + if out["identifierType"] != "spu" && let Some(spu) = value.get("deliverySpu") { out["deliverySpu"] = json!(string(spu, 120, "SPU 型号")?.trim()); } if let Some(bindings) = value.get("barcodeBindings") { let rows = bindings.as_object().filter(|rows| rows.len() <= 65).ok_or("条码绑定格式无效")?; let mut clean = serde_json::Map::new(); + let variants = out["variants"].as_array().map(Vec::as_slice).unwrap_or_default(); + let mut owners = std::collections::HashSet::new(); for (id, value) in rows { - if id != "default" && Uuid::parse_str(id).is_err() { - return Err("条码绑定的花色编号无效".into()); - } + let id = if id == "default" { + match variants { + [] => id.as_str(), + [variant] => variant["id"].as_str().ok_or("条码绑定的花色编号无效")?, + _ => return Err("多花色项目须分别填写条码".into()), + } + } else { + if !variants.iter().any(|variant| variant["id"] == *id) { + return Err("条码绑定的花色编号无效".into()); + } + id.as_str() + }; let codes = string(value, 24_200, "条码")?; - if !codes.trim().is_empty() { - clean.insert(id.clone(), json!(codes.trim())); + let barcodes = split_barcodes(&codes).collect::>(); + for barcode in &barcodes { + if !valid_delivery_barcode(barcode) { + return Err(format!("条码 {barcode} 格式无效")); + } + if !owners.insert(barcode.to_string()) { + return Err(format!("条码 {barcode} 同时填在多个花色")); + } + } + if !barcodes.is_empty() && clean.insert(id.to_owned(), json!(barcodes.join("\n"))).is_some() { + return Err("同一花色的条码绑定重复".into()); } } + if owners.len() > 200 { return Err("最多填写 200 个条码".into()); } out["barcodeBindings"] = Value::Object(clean); + if let Some(selected) = value.get("detailBarcode").filter(|barcode| !barcode.is_null()) { + let selected = string(selected, 120, "详情主条码")?; + let selected = selected.trim(); + if !selected.is_empty() { + if !owners.contains(selected) { return Err("详情主条码必须属于当前项目".into()); } + out["detailBarcode"] = json!(selected); + } + } + if let Some(selected) = detail_barcode(&out) { + out["detailBarcode"] = json!(selected); + } + } else if !value["detailBarcode"].is_null() { + return Err("详情主条码必须属于当前项目".into()); } if let Some(selection) = value.get("outputVariantIds") { let selection = selection.as_object().ok_or("出图颜色选择格式无效")?; @@ -579,22 +658,56 @@ mod tests { value["templateSelection"] = json!({"id":"GJ-NATIVE","name":"顾家原生详情模板","version":"20261023.1","contentHash":"a".repeat(64),"brandId":value["brandId"],"categoryId":value["categoryId"]}); value } + #[test] + fn delivery_spu_prefers_canonical_identifier_and_reads_legacy_projects() { + assert_eq!(delivery_spu(&json!({"identifierType":"spu","identifier":" DNZ030516 ","deliverySpu":"legacy"})), Some("DNZ030516")); + assert_eq!(delivery_spu(&json!({"identifierType":"barcode","identifier":"DNZ030516N717V01","deliverySpu":" DNZ030516 "})), Some("DNZ030516")); + assert_eq!(delivery_spu(&json!({"identifierType":"spu","identifier":"","deliverySpu":"legacy"})), None); + } + + #[test] + fn detail_barcode_is_validated_against_the_original_case_and_bound_color() { + let white = Uuid::new_v4().to_string(); + let black = Uuid::new_v4().to_string(); + let mut source = empty()["brief"].clone(); + source["variants"] = json!([{"id":white,"images":[]},{"id":black,"images":[]}]); + source["barcodeBindings"] = json!({ + (&white):"DNZ030516N717V01;DNZ030516N717V01,CY001307N35V01", + (&black):"cy001301N35", + }); + source["outputVariantIds"] = json!({"detail":[white],"main_images":[white,black]}); + assert!(require_detail_barcode(&brief(&source).unwrap()).is_err()); + source["detailBarcode"] = json!("CY001301N35"); + assert!(brief(&source).is_err()); + source["detailBarcode"] = json!("cy001301N35"); + let clean = brief(&source).unwrap(); + assert_eq!(detail_barcode(&clean), Some("cy001301N35")); + assert_eq!(clean["outputVariantIds"]["main_images"], json!([white,black])); + assert_eq!(variant_barcodes(&clean, &white, 2).collect::>(), ["DNZ030516N717V01", "CY001307N35V01"]); + assert_eq!(split_barcodes("cy001301N35,CY001301N35、cy001301N35").collect::>(), ["cy001301N35","CY001301N35"]); + source["detailBarcode"] = Value::Null; + source["barcodeBindings"] = json!({(&black):"cy001301N35"}); + assert_eq!(brief(&source).unwrap()["detailBarcode"], "cy001301N35"); + source["barcodeBindings"][black.as_str()] = json!("cy001301N35 /"); + assert!(brief(&source).is_err()); + } + #[test] fn template_intake_roundtrip_preserves_multiple_barcode_values_and_drafts() { let mut value = canvas_brief(); value["intake"] = json!({ - "templateId":"chair", + "templateId":value["templateSelection"]["id"], "schema":{"version":1, "productFields":[{"id":"length","label":"长度","type":"number","unit":"cm"}], "barcodeFields":[{"id":"size","label":"规格","type":"text"}]}, "productValues":{"length":"1e"}, - "barcodeValues":{"00123":{"size":"大号"},"00456":{"size":"小号"}} + "barcodeValues":{"DNZ030516N717V01":{"size":"大号"},"CY001307N35V01":{"size":"小号"}} }); let clean = brief(&value).unwrap(); assert_eq!(clean["intake"], value["intake"]); - assert_eq!(clean["intake"]["barcodeValues"]["00123"]["size"], "大号"); + assert_eq!(clean["intake"]["barcodeValues"]["DNZ030516N717V01"]["size"], "大号"); let mut changed = value.clone(); - changed["intake"]["barcodeValues"]["00123"]["unknown"] = json!("not declared"); + changed["intake"]["barcodeValues"]["DNZ030516N717V01"]["unknown"] = json!("not declared"); assert!(brief(&changed).is_err()); changed = value; changed["templateSelection"] = json!({"id":"desk","version":"v1","contentHash":"a".repeat(64)}); @@ -893,11 +1006,11 @@ mod tests { let original = empty()["brief"].clone(); let mut updated = original.clone(); updated["deliverySpu"] = json!("SPU-001"); - updated["barcodeBindings"] = json!({"default":"00123\n00456"}); + updated["barcodeBindings"] = json!({"default":"DNZ030516N717V01\nCY001307N35V01"}); let saved = brief(&updated).unwrap(); assert_eq!(saved["identifierType"], "sku"); assert_eq!(saved["deliverySpu"], "SPU-001"); - assert_eq!(saved["barcodeBindings"]["default"], "00123\n00456"); + assert_eq!(saved["barcodeBindings"]["default"], "DNZ030516N717V01\nCY001307N35V01"); assert_eq!(production_brief(&saved), production_brief(&original)); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs index 7d2badc5..5a5177a3 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs @@ -12,9 +12,9 @@ use std::{ time::Duration, }; -const CREDENTIAL_NAME: &str = "knowledge:enterprise-knowledge-base"; const XIAOYI_CREDENTIAL_NAME: &str = "企业知识库/小壹"; const XIAOYI_OVERRIDE: &str = "EKB_XIAOYI_READ_KEY"; +const BRIDGE_TOKEN: &str = "PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN"; const XIAOYI_BRIDGE: &str = "PHOTOCRAFT_XIAOYI_OVERRIDE_PORT"; // 校验钥匙用一个不属于任何业务的模板标识:鉴权通过时返回 200,或 404(模板不存在、未发布);钥匙无效时返回 401/403。 const XIAOYI_CURRENT: &str = "/api/xiaoyi/v1/templates/key-check/current"; @@ -29,6 +29,8 @@ const PORTAL_UNAVAILABLE: &str = "素材库暂时无法连接,请稍后重试" const PORTAL_LOGIN: &str = "素材库授权已失效,请重新登录"; const PORTAL_FORBIDDEN: &str = "当前账户无权使用小壹知识库"; const AUTOMATIC_INVALID: &str = "小壹知识库自动授权无效,请联系管理员"; +const SESSION_MISSING: &str = "素材库未部署小壹知识库签发接口(HTTP 404),请联系管理员"; +const SESSION_UNAVAILABLE: &str = "素材库小壹知识库签发服务不可用(HTTP 503),请联系管理员核对配置"; const TOKEN_PREFIX: &str = "ekb_xiaoyi_session_"; #[derive(Clone)] @@ -80,32 +82,32 @@ pub(super) fn clear_account(backend: &super::Backend) { } } -enum KnowledgeCredential { - Automatic(String), - Manual, +fn automatic_credential() -> R { + let account = ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or(PORTAL_LOGIN)?; + account_credential(&account) } -fn automatic_credential() -> R { - let account = ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or(PORTAL_LOGIN)?; +fn account_credential(account: &Account) -> R { account.access.check().map_err(|_| PORTAL_LOGIN)?; let mut cache = account.cached.lock().map_err(|_| PORTAL_UNAVAILABLE)?; if let Some((token, expires)) = cache.as_ref() && std::time::Instant::now() < *expires { account.access.check().map_err(|_| PORTAL_LOGIN)?; - return Ok(KnowledgeCredential::Automatic(token.clone())); + return Ok(token.clone()); } let response = account.http.get(format!("{}/api/desktop/knowledge/session", account.origin)) .bearer_auth(&account.token).send().map_err(|_| PORTAL_UNAVAILABLE)?; let status = response.status().as_u16(); - let (_, value) = super::body(response, super::MAX_JSON).map_err(|_| PORTAL_UNAVAILABLE)?; account.access.check().map_err(|_| PORTAL_LOGIN)?; match status { - 404 => return Ok(KnowledgeCredential::Manual), - 503 if value["code"] == "knowledge_session_unavailable" => return Ok(KnowledgeCredential::Manual), + 404 => return Err(SESSION_MISSING.into()), + 503 => return Err(SESSION_UNAVAILABLE.into()), 401 => return Err(PORTAL_LOGIN.into()), 403 => return Err(PORTAL_FORBIDDEN.into()), 200 => {} _ => return Err(PORTAL_UNAVAILABLE.into()), } + let (_, value) = super::body(response, super::MAX_JSON).map_err(|_| AUTOMATIC_INVALID)?; + account.access.check().map_err(|_| PORTAL_LOGIN)?; let token = value["token"].as_str().filter(|token| token.starts_with(TOKEN_PREFIX)) .ok_or(AUTOMATIC_INVALID)?; let expiry = value["expiresAt"].as_str() @@ -117,7 +119,7 @@ fn automatic_credential() -> R { // Refresh frequently so remotely revoked access stops within 30 seconds. let lifetime = u64::try_from((remaining - 5).min(30)).map_err(|_| AUTOMATIC_INVALID)?; *cache = Some((token.clone(), std::time::Instant::now() + Duration::from_secs(lifetime))); - Ok(KnowledgeCredential::Automatic(token)) + Ok(token) } fn verify_automatic_key(key: &str) -> Value { @@ -135,11 +137,10 @@ fn verify_automatic_key(key: &str) -> Value { pub(super) fn automatic_status() -> Value { match automatic_credential() { - Ok(KnowledgeCredential::Automatic(key)) => { + Ok(key) => { let result = verify_automatic_key(&key); json!({"mode":"automatic","error":result["error"].as_str().unwrap_or_default()}) } - Ok(KnowledgeCredential::Manual) => json!({"mode":"manual","error":""}), Err(error) => json!({"mode":"unavailable","error":error}), } } @@ -151,16 +152,11 @@ pub(super) fn configure_for_account(input: &Value) -> Value { return result; } match automatic_credential() { - Ok(KnowledgeCredential::Automatic(key)) => { + Ok(key) => { let mut result = verify_automatic_key(&key); result["mode"] = json!("automatic"); result } - Ok(KnowledgeCredential::Manual) => { - let mut result = configure_xiaoyi(input); - result["mode"] = json!("manual"); - result - } Err(error) => json!({"mode":"unavailable","status":null,"saved":false,"error":error}), } } @@ -194,58 +190,6 @@ pub(super) fn origins() -> R<[String; 2]> { Ok(origins) } -pub(super) fn configure(input: &Value) -> R { - let mut endpoints = origins()?; - let previous_origin = endpoints[0].clone(); - let origin = input["origin"].as_str().unwrap_or_default().trim(); - if !origin.is_empty() { - let parsed = reqwest::Url::parse(origin).map_err(|_| "请输入完整的内网入口地址")?; - if !matches!(parsed.scheme(), "http" | "https") || parsed.host().is_none() - || parsed.path() != "/" || parsed.query().is_some() || parsed.fragment().is_some() - || !parsed.username().is_empty() || parsed.password().is_some() - { - return Err("内网入口只填写协议、主机和端口".into()); - } - endpoints[0] = parsed.origin().ascii_serialization(); - } - let candidate = input["key"].as_str().filter(|key| !key.trim().is_empty()); - let key = match candidate { Some(key) => normalize_key(key)?, None => credential()? }; - let probe = HEALTH_CLIENT.as_ref().map_err(|_| NETWORK)?; - let origin = endpoints.iter().find(|origin| { - probe.get(format!("{origin}/healthz")).send().ok() - .filter(|reply| reply.status().is_success()) - .and_then(|reply| reply.json::().ok()) - .is_some_and(|health| health["service"] == "enterprise-knowledge-base" && health["status"] == "ok") - }).ok_or(NETWORK)?; - let response = MCP_CLIENT.as_ref().map_err(|_| NETWORK)?.post(format!("{origin}/mcp")) - .bearer_auth(&key).header("accept", "application/json, text/event-stream") - .header("mcp-protocol-version", "2025-11-25") - .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_libraries","arguments":{}}})) - .send().map_err(|_| NETWORK)?; - let status = response.status(); - match status.as_u16() { - 401 => return Err("通用 Key 已失效或填写有误,请更换后重试。".into()), - 403 => return Err("通用 Key 没有访问权限,请联系知识库管理员。".into()), - _ if !status.is_success() => return Err(format!("通用知识库校验失败(HTTP {})", status.as_u16())), - _ => {} - } - let body = response.text().map_err(|_| NETWORK)?; - let body = body.lines().find_map(|line| line.strip_prefix("data:")).unwrap_or(&body); - let reply: Value = serde_json::from_str(body).map_err(|_| RESPONSE)?; - if !reply["error"].is_null() || !reply["result"].is_object() || reply["result"]["isError"] == true { - let reason = reply["result"]["structuredContent"]["error"].as_str() - .or_else(|| reply["error"]["message"].as_str()) - .filter(|reason| !reason.contains(key.as_str())); - return Err(reason.unwrap_or("企业知识库无法列出可访问的库").to_owned()); - } - if candidate.is_some() { save_key(&key)?; } - let origin_changed = endpoints[0] != previous_origin; - if origin_changed { - super::write_json(&config_path().ok_or("本机设置目录不可用")?, &json!(endpoints[0]))?; - } - Ok(json!({"origin":endpoints[0],"originChanged":origin_changed})) -} - pub(super) fn configure_xiaoyi(input: &Value) -> Value { let endpoints = match origins() { Ok(endpoints) => endpoints, @@ -317,19 +261,6 @@ pub(super) fn xiaoyi_key_saved() -> bool { xiaoyi_credential().is_ok() } -#[cfg(windows)] -pub(super) fn credential() -> R { - let key = super::vault(CREDENTIAL_NAME).map_err(|_| CREDENTIAL)? - .get_password().map_err(|_| CREDENTIAL)?; - normalize_key(&key) -} - -pub(super) fn save_key(key: &str) -> R<()> { - let key = normalize_key(key)?; - super::vault(CREDENTIAL_NAME).map_err(|_| CREDENTIAL)? - .set_password(&key).map_err(|_| CREDENTIAL.into()) -} - fn normalize_key(key: &str) -> R { let key = key.trim(); if key.is_empty() || reqwest::header::HeaderValue::from_str(key).is_err() { @@ -338,11 +269,6 @@ fn normalize_key(key: &str) -> R { Ok(key.to_owned()) } -#[cfg(not(windows))] -pub(super) fn credential() -> R { - Err(CREDENTIAL.into()) -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Route { Health, @@ -414,9 +340,10 @@ pub(super) fn exchange(input: &Value, mut emit: impl FnMut(Value) -> R<()>) -> R let result = (|| { let route = Route::parse(input)?; if route == Route::Xiaoyi && let Some(port) = std::env::var_os(XIAOYI_BRIDGE) { - return relay_override(port.to_str().ok_or(INVALID)?.parse().map_err(|_| INVALID)?, input, &mut emit); + let token = std::env::var(BRIDGE_TOKEN).map_err(|_| INVALID)?; + return relay_bridge(port.to_str().ok_or(INVALID)?.parse().map_err(|_| INVALID)?, &token, input, &mut emit); } - exchange_route(route, input, credential, automatic_or_manual_key, &mut emit) + exchange_route(route, input, || Err(CREDENTIAL.into()), automatic_credential, &mut emit) })(); emit_error(result, &mut emit) } @@ -429,6 +356,8 @@ fn emit_error(result: R<()>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { PORTAL_LOGIN => ("credential", PORTAL_LOGIN), PORTAL_FORBIDDEN => ("credential", PORTAL_FORBIDDEN), PORTAL_UNAVAILABLE => ("network", PORTAL_UNAVAILABLE), + SESSION_MISSING => ("session-missing", SESSION_MISSING), + SESSION_UNAVAILABLE => ("session-unavailable", SESSION_UNAVAILABLE), AUTOMATIC_INVALID => ("credential", AUTOMATIC_INVALID), INVALID => ("boundary", INVALID), _ => ("response", RESPONSE), @@ -474,106 +403,84 @@ fn exchange_route( send(request, key.as_deref(), emit) } -fn automatic_or_manual_key() -> R { - match automatic_credential()? { - KnowledgeCredential::Automatic(key) => Ok(key), - KnowledgeCredential::Manual => xiaoyi_credential(), - } -} - fn xiaoyi_credential() -> R { let key = super::vault(XIAOYI_CREDENTIAL_NAME).map_err(|_| CREDENTIAL)? .get_password().map_err(|_| CREDENTIAL)?; normalize_key(&key) } -// Only the desktop host holds the override. The Node daemon and its RPC -// workers inherit a loopback port used to relay the existing response frames. +// The daemon gets a fresh bridge capability. It never receives the upstream credential. pub(super) fn configure_daemon(command: &mut Command) -> R<()> { - static PORT: OnceLock> = OnceLock::new(); - let port = PORT.get_or_init(|| match std::env::var_os(XIAOYI_OVERRIDE) { - Some(key) => start_override_bridge(key), - None => start_account_bridge(), - }).as_ref().map_err(Clone::clone)?; - set_daemon_bridge(command, Some(*port)); + static BRIDGE: OnceLock>)>> = OnceLock::new(); + let (port, current_token) = BRIDGE.get_or_init(|| start_bridge(std::env::var_os(XIAOYI_OVERRIDE))) + .as_ref().map_err(Clone::clone)?; + let token = super::Uuid::new_v4().simple().to_string(); + *current_token.lock().map_err(|_| NETWORK)? = token.clone(); + set_daemon_bridge(command, *port, &token); Ok(()) } -fn set_daemon_bridge(command: &mut Command, port: Option) { - command.env_remove(XIAOYI_OVERRIDE).env_remove(XIAOYI_BRIDGE); - if let Some(port) = port { - command.env(XIAOYI_BRIDGE, port.to_string()); - } +fn set_daemon_bridge(command: &mut Command, port: u16, token: &str) { + command.env_remove(XIAOYI_OVERRIDE) + .env(XIAOYI_BRIDGE, port.to_string()) + .env(BRIDGE_TOKEN, token); } -fn start_account_bridge() -> R { +fn start_bridge(key: Option) -> R<(u16, Arc>)> { let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|_| NETWORK)?; let port = listener.local_addr().map_err(|_| NETWORK)?.port(); + let token = Arc::new(Mutex::new(String::new())); + let current_token = Arc::clone(&token); std::thread::spawn(move || { - for stream in listener.incoming().map_while(Result::ok) { - std::thread::spawn(move || { - let _ = serve_account(stream); - }); - } - }); - Ok(port) -} - -fn serve_account(mut stream: TcpStream) -> R<()> { - stream.set_read_timeout(Some(Duration::from_secs(5))).map_err(|_| NETWORK)?; - let result = (|| { - let Some(Ok(line)) = super::pi::bounded_line(&mut BufReader::new(&stream))? else { - return Err(INVALID.into()); - }; - let input: Value = serde_json::from_slice(&line).map_err(|_| INVALID)?; - let route = Route::parse(&input)?; - if route != Route::Xiaoyi { - return Err(INVALID.into()); - } - exchange_route(route, &input, || Err(INVALID.into()), automatic_or_manual_key, &mut |frame| { - writeln!(stream, "{frame}").map_err(|_| NETWORK.into()) - }) - })(); - emit_error(result, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into())) -} - -fn start_override_bridge(key: OsString) -> R { - let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|_| NETWORK)?; - let port = listener.local_addr().map_err(|_| NETWORK)?.port(); - let key = Arc::new(key); - std::thread::spawn(move || { + let key = Arc::new(key); for stream in listener.incoming().map_while(Result::ok) { let key = Arc::clone(&key); + let token = Arc::clone(¤t_token); std::thread::spawn(move || { - let _ = serve_override(stream, &key, origins); + let _ = serve_bridge(stream, &token, key.as_deref(), origins); }); } }); - Ok(port) + Ok((port, token)) } -fn serve_override(mut stream: TcpStream, key: &OsStr, allowed_origins: impl FnOnce() -> R<[String; 2]>) -> R<()> { +fn serve_bridge( + mut stream: TcpStream, + token: &Mutex, + key: Option<&OsStr>, + allowed_origins: impl FnOnce() -> R<[String; 2]>, +) -> R<()> { stream.set_read_timeout(Some(Duration::from_secs(5))).map_err(|_| NETWORK)?; let result = (|| { let Some(Ok(line)) = super::pi::bounded_line(&mut BufReader::new(&stream))? else { return Err(INVALID.into()); }; - let input: Value = serde_json::from_slice(&line).map_err(|_| INVALID)?; - let route = Route::parse_with_origins(&input, &allowed_origins()?)?; + let envelope: Value = serde_json::from_slice(&line).map_err(|_| INVALID)?; + { + let expected = token.lock().map_err(|_| NETWORK)?; + let presented = envelope["authorization"].as_str().ok_or(INVALID)?; + let different = presented.bytes().zip(expected.bytes()) + .fold(0, |difference, (a, b)| difference | (a ^ b)); + if expected.is_empty() || presented.len() != expected.len() || different != 0 { + return Err(INVALID.into()); + } + } + let input = &envelope["request"]; + let route = Route::parse_with_origins(input, &allowed_origins()?)?; if route != Route::Xiaoyi { return Err(INVALID.into()); } - exchange_route(route, &input, || Err(INVALID.into()), - || normalize_key(key.to_str().ok_or(CREDENTIAL)?), &mut |frame| { - writeln!(stream, "{frame}").map_err(|_| NETWORK.into()) - }) + exchange_route(route, input, || Err(INVALID.into()), || match key { + Some(key) => normalize_key(key.to_str().ok_or(CREDENTIAL)?), + None => automatic_credential(), + }, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into())) })(); emit_error(result, &mut |frame| writeln!(stream, "{frame}").map_err(|_| NETWORK.into())) } -fn relay_override(port: u16, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { +fn relay_bridge(port: u16, token: &str, input: &Value, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> { let mut stream = TcpStream::connect(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)).map_err(|_| NETWORK)?; - writeln!(stream, "{input}").map_err(|_| NETWORK)?; + writeln!(stream, "{}", json!({"authorization":token,"request":input})).map_err(|_| NETWORK)?; let mut reader = BufReader::new(stream); while let Some(Ok(line)) = super::pi::bounded_line(&mut reader)? { let frame: Value = serde_json::from_slice(&line).map_err(|_| RESPONSE)?; @@ -672,35 +579,86 @@ mod tests { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: access.clone(), http: client.into(), cached: Arc::new(Mutex::new(None)), }; - *ACCOUNT.lock().unwrap() = Some(account); - assert!(matches!(automatic_credential(), Ok(KnowledgeCredential::Automatic(token)) if token == TOKEN)); + assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN)); server.join().unwrap(); - assert!(matches!(automatic_credential(), Ok(KnowledgeCredential::Automatic(token)) if token == TOKEN)); + assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN)); access.invalidate(); - assert!(matches!(automatic_credential(), Err(error) if error == PORTAL_LOGIN)); - *ACCOUNT.lock().unwrap() = None; + assert!(matches!(account_credential(&account), Err(error) if error == PORTAL_LOGIN)); + } + + #[test] + fn jiansun_missing_knowledge_signer_returns_http_diagnostics() { + for (status, body, code, message) in [ + (404, r#"{"code":"not_found"}"#, "session-missing", SESSION_MISSING), + (503, r#"{"code":"knowledge_session_unavailable"}"#, "session-unavailable", SESSION_UNAVAILABLE), + ] { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut lines = BufReader::new(&mut stream).lines(); + assert_eq!(lines.next().unwrap().unwrap(), "GET /api/desktop/knowledge/session HTTP/1.1"); + assert!(lines.map(Result::unwrap).take_while(|line| !line.is_empty()) + .any(|line| line == "authorization: Bearer synthetic-desktop-session")); + write!(stream, "HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\n\r\n{body}", body.len()).unwrap(); + }); + let account = Account { + origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), + access: super::super::AccountAccess::default(), http: client(5).unwrap().into(), + cached: Arc::new(Mutex::new(None)), + }; + let error = account_credential(&account).unwrap_err(); + assert_eq!(error, message); + emit_error(Err(error), &mut |frame| { + assert_eq!(frame, json!({"type":"error","category":code,"error":message})); + Ok(()) + }).unwrap(); + server.join().unwrap(); + } + } + + #[test] + fn jiansun_generic_key_has_no_configuration_or_import_entry() { + let backend = include_str!("jiansun_backend.rs"); + let entrypoint = include_str!("main.rs"); + assert!(!backend.contains("configure-knowledge")); + assert!(!backend.contains("knowledgeKeySaved")); + assert!(!entrypoint.contains("--import-ekb-key-from-env")); } #[test] fn jiansun_xiaoyi_override_reaches_current_and_stays_out_of_node_environment() { const KEY: &str = "synthetic-xiaoyi-override"; + const BRIDGE: &str = "synthetic-bridge-token"; let (origin, upstream) = current_fixture(200, r#"{"version":"v1"}"#, KEY); let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let port = listener.local_addr().unwrap().port(); let allowed = origin.clone(); let host = std::thread::spawn(move || { - let (stream, _) = listener.accept().unwrap(); - serve_override(stream, OsStr::new(KEY), || Ok([allowed, String::new()])).unwrap(); + let token = Mutex::new(BRIDGE.to_owned()); + for _ in 0..3 { + let (stream, _) = listener.accept().unwrap(); + serve_bridge(stream, &token, Some(OsStr::new(KEY)), || Ok([allowed.clone(), String::new()])).unwrap(); + } }); let mut node = Command::new("node"); node.env(XIAOYI_OVERRIDE, KEY).arg("-e").arg( - "process.exit(Number('EKB_XIAOYI_READ_KEY' in process.env || !process.env.PHOTOCRAFT_XIAOYI_OVERRIDE_PORT))", + "process.exit(Number('EKB_XIAOYI_READ_KEY' in process.env || !process.env.PHOTOCRAFT_XIAOYI_OVERRIDE_PORT || !process.env.PHOTOCRAFT_XIAOYI_BRIDGE_TOKEN))", ); - set_daemon_bridge(&mut node, Some(port)); + set_daemon_bridge(&mut node, port, BRIDGE); assert!(node.status().unwrap().success()); let input = json!({"origin":origin,"path":XIAOYI_CURRENT,"httpMethod":"GET","headers":{}}); let mut frames = Vec::new(); - relay_override(port, &input, &mut |frame| { + let mut unauthorized = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); + writeln!(unauthorized, "{}", json!({"request":input})).unwrap(); + let rejected: Value = serde_json::from_reader(BufReader::new(unauthorized)).unwrap(); + assert_eq!(rejected["category"], "boundary"); + relay_bridge(port, "incorrect", &input, &mut |frame| { + assert_eq!(frame["category"], "boundary"); + Ok(()) + }).unwrap(); + relay_bridge(port, BRIDGE, &input, &mut |frame| { assert!(!frame.to_string().contains(KEY)); frames.push(frame); Ok(()) diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs index c3df2635..bd552cfb 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs @@ -232,6 +232,7 @@ pub(super) fn detail_artifacts(project: &Path) -> R> { } let state = canvas_workspace::load(project)?; let creation = creation::load(project)?; + creation::require_detail_barcode(&creation["brief"])?; let context = read_json(&project.join("context.json"))?; let outputs = canvas_workspace::production_stages(&state); let missing: Vec<_> = [("detail", "详情页"), ("main_images", "主图"), ("sku_images", "SKU")] @@ -365,11 +366,10 @@ fn bind_sku_files(artifacts: &[Artifact], brief: &Value, variants: &[Value], cat let barcodes = known.get(code).filter(|codes| !codes.is_empty()) .ok_or_else(|| format!("「{name}」的 SKU {code} 在该 SPU 下没有已登记的条码"))?; for barcode in barcodes { - if barcode.len() > 120 || !barcode.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') { + if !creation::valid_delivery_barcode(barcode) { return Err(format!("SKU {code} 的条码 {barcode} 无法用作文件名,请核对素材库登记")); } - let key = barcode.to_ascii_lowercase(); - if let Some((owner, owner_variant)) = owners.insert(key, (code, id)) { + if let Some((owner, owner_variant)) = owners.insert(*barcode, (code, id)) { if owner != code || owner_variant != id { return Err(format!("条码 {barcode} 同时绑定了多个 SKU 或花色,请核对产品资料")); } @@ -382,7 +382,7 @@ fn bind_sku_files(artifacts: &[Artifact], brief: &Value, variants: &[Value], cat expand_barcode_files(artifacts, &mappings) } -fn bind_project_barcodes(artifacts: &[Artifact], bindings: &Value, variants: &[Value]) -> R> { +fn bind_project_barcodes(artifacts: &[Artifact], brief: &Value, variants: &[Value]) -> R> { let mut mappings = HashMap::new(); let mut barcode_variants = HashMap::new(); for variant in variants { @@ -391,19 +391,12 @@ fn bind_project_barcodes(artifacts: &[Artifact], bindings: &Value, variants: &[V continue; } let name = variant["name"].as_str().unwrap_or("当前花色"); - let entered = bindings[id].as_str() - .or_else(|| (variants.len() == 1).then(|| bindings["default"].as_str()).flatten()) - .unwrap_or_default(); let mut barcodes = Vec::new(); - let mut seen = HashSet::new(); - for barcode in entered.split(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ',' | '、')) { - if barcode.is_empty() || !seen.insert(barcode.to_ascii_lowercase()) { - continue; - } - if barcode.len() > 120 || !barcode.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) { + for barcode in creation::variant_barcodes(brief, id, variants.len()) { + if !creation::valid_delivery_barcode(barcode) { return Err(format!("「{name}」的条码 {barcode} 格式有误,请核对后再完结")); } - if barcode_variants.insert(barcode.to_ascii_lowercase(), id).is_some() { + if barcode_variants.insert(barcode, id).is_some() { return Err(format!("条码 {barcode} 同时填在多个花色,请核对产品资料")); } barcodes.push((String::new(), barcode.to_owned())); @@ -419,13 +412,20 @@ fn bind_project_barcodes(artifacts: &[Artifact], bindings: &Value, variants: &[V fn expand_barcode_files(artifacts: &[Artifact], mappings: &HashMap<&str, Vec<(String, String)>>) -> R> { let mut files = Vec::new(); let mut seen = HashSet::new(); + let mut filename_spellings = HashMap::new(); for artifact in artifacts { let Some(variant) = artifact.sku_variant.as_deref() else { files.push(artifact.clone()); continue; }; for (code, barcode) in mappings.get(variant).ok_or("SKU 图缺少花色和条码的匹配")? { - if !seen.insert((barcode.to_ascii_lowercase(), artifact.sha256.as_str())) { + // The delivery service checks filename collisions without regard to case. + if let Some(previous) = filename_spellings.insert(barcode.to_ascii_lowercase(), barcode) + && previous != barcode + { + return Err(format!("条码 {previous} 与 {barcode} 的交付文件名冲突,请核对产品资料")); + } + if !seen.insert((barcode.as_str(), artifact.sha256.as_str())) { continue; } let mut file = artifact.clone(); @@ -446,12 +446,11 @@ impl Backend { let brief = &creation["brief"]; let state = canvas_workspace::load(project)?; let variants = state["variants"].as_array().ok_or("项目花色列表无效")?; - if let Some(bindings) = brief.get("barcodeBindings") { - let model = if brief["identifierType"] == "spu" { &brief["identifier"] } else { &brief["deliverySpu"] }; - let model = model.as_str().map(str::trim) - .filter(|value| !value.is_empty() && value.chars().count() <= 120) + if brief.get("barcodeBindings").is_some() { + let model = creation::delivery_spu(brief) + .filter(|value| value.chars().count() <= 120) .ok_or("请在产品资料中填写有效的 SPU 型号")?; - return Ok((model.to_owned(), bind_project_barcodes(artifacts, bindings, variants)?)); + return Ok((model.to_owned(), bind_project_barcodes(artifacts, brief, variants)?)); } let kind = brief["identifierType"].as_str().ok_or("商品编号类型缺失")?; let identifier = brief["identifier"].as_str().filter(|value| !value.trim().is_empty()).ok_or("请先填写 SPU、SKU 或条码")?; @@ -660,15 +659,17 @@ mod tests { let black = Artifact { sku_variant: Some("black".into()), ..image.clone() }; let files = bind_project_barcodes( &[image.clone(), black.clone()], - &json!({"white":"00123456\n00123457,00123456","black":"00234567"}), + &json!({"barcodeBindings":{"white":"DNZ030516N717V01\nCY001307N35V01,DNZ030516N717V01","black":"cy001301N35"}}), &variants, ).unwrap(); assert_eq!(files.iter().map(|file| file.name.as_str()).collect::>(), - ["00123456.jpg", "00123457.jpg", "00234567.jpg"]); + ["DNZ030516N717V01.jpg", "CY001307N35V01.jpg", "cy001301N35.jpg"]); assert_eq!(files[0].path, image.path); - assert_eq!(files[0].file_info()["barcode"], "00123456"); + assert_eq!(files[0].file_info()["barcode"], "DNZ030516N717V01"); assert!(files[0].file_info().get("skuCode").is_none()); - assert!(bind_project_barcodes(&[image, black], &json!({"white":"00123456","black":"00123456"}), &variants) + assert!(bind_project_barcodes(&[image.clone(), black.clone()], &json!({"barcodeBindings":{"white":"DNZ030516N717V01","black":"dnz030516N717V01"}}), &variants) + .unwrap_err().contains("文件名冲突")); + assert!(bind_project_barcodes(&[image, black], &json!({"barcodeBindings":{"white":"DNZ030516N717V01","black":"DNZ030516N717V01"}}), &variants) .unwrap_err().contains("多个花色")); } @@ -685,18 +686,18 @@ mod tests { } let brief = json!({"skuBindings":{"dark":"SKU-D,SKU-V","light":"SKU-L"}}); let mut catalog = vec![ - json!({"skuCode":"SKU-D","barcodes":["00123456","00123457"]}), - json!({"skuCode":"SKU-V","barcodes":["00123458"]}), - json!({"skuCode":"SKU-L","barcodes":["00234567"]}), + json!({"skuCode":"SKU-D","barcodes":["DNZ030516N717V01","CY001307N35V01"]}), + json!({"skuCode":"SKU-V","barcodes":["SG008839N1049V01"]}), + json!({"skuCode":"SKU-L","barcodes":["SJ021613N16V01"]}), ]; let mapped = bind_sku_files(&files, &brief, &variants, &catalog).unwrap(); assert_eq!(mapped.len(), 7); - assert_eq!(mapped.iter().filter(|file| file.name == "00123456.jpg").count(), 2); + assert_eq!(mapped.iter().filter(|file| file.name == "DNZ030516N717V01.jpg").count(), 2); assert_eq!(mapped[0].file_info()["skuCode"], "SKU-D"); - assert_eq!(mapped[0].file_info()["barcode"], "00123456"); + assert_eq!(mapped[0].file_info()["barcode"], "CY001307N35V01"); assert_eq!(mapped[0].path, files[0].path); assert!(bind_sku_files(&files, &json!({}), &variants, &catalog).is_err()); - catalog[2]["barcodes"] = json!(["00123456"]); + catalog[2]["barcodes"] = json!(["DNZ030516N717V01"]); assert!(bind_sku_files(&files, &brief, &variants, &catalog).unwrap_err().contains("同时绑定")); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index 9928fe77..2c2d712f 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -148,11 +148,6 @@ fn knowledge_rule(b:&Backend,doc:u64,production:bool) -> R let category=creation["brief"]["categoryId"].as_str().unwrap_or(""); let workspace = production.then(|| super::canvas_workspace::load(&dir)).transpose()?; let selected = workspace.as_ref().map_or(&creation["brief"]["templateSelection"], |state| &state["template"]); - if production && let Some(intake) = creation["brief"].get("intake") - && intake["templateId"] != selected["id"] - { - return Err("产品资料对应的模板与当前画布不一致,请核对模板".into()); - } if category.is_empty() || !selected["enterprise"].is_object() { return Ok(Some((None,json!({"state":"needs-template","reason":"请先选择知识库品类与模板"})))); } @@ -373,6 +368,9 @@ fn project_evidence(c: &Value, scope: &str, project: &str, doc: u64, current_var brief.insert(field.to_owned(), value.clone()); } } + if let Some(barcode) = super::creation::detail_barcode(&c["brief"]) { + brief.insert("detailBarcode".into(), json!(barcode)); + } if let Some(selection) = c["brief"].get("outputVariantIds") { brief.insert("outputVariantIds".into(), selection.clone()); } diff --git a/apps/detail-photocraft/apps/photocraft/src/main.rs b/apps/detail-photocraft/apps/photocraft/src/main.rs index 5f5f5006..7308f7ec 100644 --- a/apps/detail-photocraft/apps/photocraft/src/main.rs +++ b/apps/detail-photocraft/apps/photocraft/src/main.rs @@ -352,17 +352,6 @@ fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup } fn main() -> eframe::Result { - #[cfg(windows)] - if std::env::args_os().any(|arg| arg == "--import-ekb-key-from-env") { - let result = std::env::args_os().skip_while(|arg| arg != "--import-ekb-key-from-env") - .nth(1).ok_or_else(|| "请指定用户环境变量名".to_owned()) - .and_then(|name| jiansun_backend::import_ekb_key(&name)); - if let Err(error) = result { - eprintln!("{error}"); - std::process::exit(2); - } - return Ok(()); - } if std::env::args_os().any(|a| a == "--jiansun-pi-rpc") { if let Err(error) = jiansun_backend::pi_rpc() { eprintln!("{error}"); diff --git a/docs/自动上架平台成套入库通知接口.md b/docs/自动上架平台成套入库通知接口.md index 26a59899..9ccd7610 100644 --- a/docs/自动上架平台成套入库通知接口.md +++ b/docs/自动上架平台成套入库通知接口.md @@ -186,7 +186,7 @@ X-API-Key: your-api-key ### 完结上传字段 -客户端先走分片上传,再调用 `POST /api/desktop/deliveries` 提交。三个类型共用 `projectId`、`requestId`、`kind`、`productModel`,并可附带 `productName`、`brandName`、`productCategoryName`、`categoryName`、`identifierType`。其中 `categoryName` 表示店铺。小壹三件套会将素材库核对后的 SPU 填入 `productModel`。 +客户端先走分片上传,再调用 `POST /api/desktop/deliveries` 提交。三个类型共用 `projectId`、`requestId`、`kind`、`productModel`,并可附带 `productName`、`brandName`、`productCategoryName`、`categoryName`、`identifierType`。其中 `categoryName` 表示店铺。小壹三件套会将项目的商品 SPU 填入 `productModel`。如果条码已登记在其他 SPU 下,入库会拒绝该提交。 | 类型 | 提交的 `assets` | 每个文件 | | --- | --- | --- | @@ -196,8 +196,8 @@ X-API-Key: your-api-key ### SKU 图片和条码 -- 在小壹产品资料中为每种花色填写对应的素材库 SKU 编号。同一张花色图对应多个 SKU 时,用逗号分隔 SKU 编号。 -- 小壹读取素材库登记的 `SPU → SKU → 条码` 关系。每个条码生成一个 `条码.jpg` 的交付条目,保留条码的前导零。入库会同时保存图的 SKU 编号和条码。 +- 在小壹产品资料中填写商品 SPU,再为每种花色填写对应的产品条码,例如 `DNZ030516N717V01` 或 `CY001307N35V01`。同一花色的多个条码可用换行、逗号、顿号或分号分隔。条码按原文匹配,保留大小写和前导零。历史记录中的无 V 段条码可正常使用。 +- 条码交付字段接受 1–120 个英文字母、数字、下划线或连字符。每个条码生成一个 `条码.jpg` 交付条目,仅大小写不同的文件名会发生冲突。只有一个条码时默认用它制作详情页。有多个条码时由用户选择详情主条码 `brief.detailBarcode`,SKU 图仍按各花色的全部绑定条码交付。 - 同一条码有多张成品时,条目保留同一个文件名,并以 `id` 区分。整套 ZIP 将同名文件放进 `sku/{sortOrder}/` 目录,文件名仍为 `条码.jpg`。 - 正式资源响应中的 `spu` 是商品 SPU。新项目以用户在该 SPU 下为各花色录入的条码交付款式图,同一花色可对应多个条码,前导零原样保留。`barcodes[]` 汇总当前素材的所有条码,`assets.sku[].barcodes[]` 给出每张款式图绑定的条码。`skuCode` 为兼容旧记录的可空字段。 - `authorName` 取入库时小壹登录账户的姓名,无姓名时取用户名。