发布小壹 1.2612.103,支持多条码表单与知识库自动授权
This commit is contained in:
parent
ed2bfbc81c
commit
4c5a76bb72
@ -366,6 +366,10 @@ npm run start
|
||||
|
||||
但当前线上环境并不只依赖容器本身,还依赖网络入口、FRP、域名与反向代理链路。因此如果要碰部署问题,建议连同项目文档一起看,而不是只看 Compose 文件。
|
||||
|
||||
### 小壹知识库自动连接
|
||||
|
||||
在素材库服务与企业知识库服务分别配置同一个 `XIAOYI_KNOWLEDGE_SESSION_SECRET`,使用独立生成且至少 32 字节的随机值。素材库按当前已授权的客户端会话签发凭据,最长有效期五分钟。企业知识库用它开放已发布的小壹知识包读取。配置先在企业知识库生效,再启用素材库签发。
|
||||
|
||||
### 发布前重点核对
|
||||
|
||||
- 登录是否正常
|
||||
|
||||
@ -34,6 +34,10 @@ async function route(request:Request,{params}:{params:{path:string[]}}){
|
||||
}else{
|
||||
const auth=await requireDesktop(request),ownerId=auth.account.id
|
||||
if(parts[0]==='session'&&parts.length===1){if(method==='GET')value={account:auth.account,expiresAt:auth.expiresAt};else if(method==='DELETE'){await revokeDesktop(auth.id,ownerId);value={revoked:true}}else throw new DesktopClientError('接口不存在',404)}
|
||||
else if(parts[0]==='knowledge'&&parts[1]==='session'&&parts.length===2&&method==='GET'){
|
||||
const {issueKnowledgeSession}=await import('@/lib/desktop-client/knowledge-session')
|
||||
value=issueKnowledgeSession(ownerId,auth.expiresAt)
|
||||
}
|
||||
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]==='tasks'){
|
||||
const tasks=await import('@/lib/desktop-client/tasks')
|
||||
|
||||
25
app/api/external/product-assets/route.ts
vendored
25
app/api/external/product-assets/route.ts
vendored
@ -168,9 +168,18 @@ export async function GET(request: NextRequest) {
|
||||
if (isXiaoyiDeliveryMaterial(material.materialType)) {
|
||||
const [delivery] = await prisma.$queryRaw<Array<{
|
||||
brandName: string; productName: string; identifierType: string; eventId: string | null; listingStatus: ListingStatus | null
|
||||
deliveryGroupId: string; relatedMaterials: Partial<Record<'detail' | 'video' | 'buyer_show', string>> | null
|
||||
}>>`
|
||||
SELECT d.brand_name AS "brandName", d.product_name AS "productName", d.identifier_type AS "identifierType",
|
||||
e.id AS "eventId", d.listing_status AS "listingStatus"
|
||||
e.id AS "eventId", d.listing_status AS "listingStatus", d.project_id AS "deliveryGroupId",
|
||||
(
|
||||
SELECT jsonb_object_agg(related.kind, related.material_id)
|
||||
FROM desktop_material_deliveries related
|
||||
JOIN materials rm ON rm.id = related.material_id AND rm."userId" = related.owner_id
|
||||
WHERE related.project_id = d.project_id AND related.owner_id = d.owner_id
|
||||
AND rm."deletedAt" IS NULL AND NOT rm.is_incomplete_shell
|
||||
AND rm.access_scope = 'general' AND NOT rm.task_detail_private
|
||||
) AS "relatedMaterials"
|
||||
FROM desktop_material_deliveries d LEFT JOIN xiaoyi_auto_listing_events e ON e.material_id = d.material_id
|
||||
WHERE d.material_id = ${material.id}
|
||||
`
|
||||
@ -195,10 +204,24 @@ export async function GET(request: NextRequest) {
|
||||
statusCode: 200, duration: Date.now() - startTime, ipAddress: getClientIp(request),
|
||||
userAgent: request.headers.get('user-agent') || undefined,
|
||||
})
|
||||
const relatedMaterial = (id?: string) => id ? {
|
||||
materialId: id,
|
||||
downloadUrl: generateDownloadUrl(baseUrl, {materialId: id, downloadType: 'all'}),
|
||||
} : null
|
||||
const response = successResponse({
|
||||
materialId: material.id, materialType: material.materialType, productModel: material.productModel,
|
||||
spu: groups.sku.some(asset => asset.barcodes.length) || delivery?.identifierType === 'spu' ? material.productModel : null,
|
||||
categoryName: material.categoryName, productCategoryName: material.productCategoryName,
|
||||
authorName: material.authorName || '',
|
||||
barcodes: Array.from(new Set<string>(groups.sku.flatMap(asset => asset.barcodes))),
|
||||
...(delivery?.deliveryGroupId && {
|
||||
deliveryGroupId: delivery.deliveryGroupId,
|
||||
relatedMaterials: {
|
||||
detail: relatedMaterial(delivery.relatedMaterials?.detail),
|
||||
video: relatedMaterial(delivery.relatedMaterials?.video),
|
||||
buyer_show: relatedMaterial(delivery.relatedMaterials?.buyer_show),
|
||||
},
|
||||
}),
|
||||
brandName: delivery?.brandName || '', productName: delivery?.productName || '', identifierType: delivery?.identifierType || '',
|
||||
isFullSet: material.materialType === '自动上架-详情' && ['main', 'sku', 'detail'].every(group => groups[group].length),
|
||||
...(delivery?.eventId && { eventId: delivery.eventId, listingStatus: delivery.listingStatus ?? pendingListingStatus }),
|
||||
|
||||
@ -796,6 +796,16 @@ export class DetailPiAgent {
|
||||
async readEnterpriseRules(workflow, productEvidence) {
|
||||
const template = workflow?.template;
|
||||
if (!workflow?.available || !template?.enterprise) return null;
|
||||
if (template.knowledgeVersion) {
|
||||
const {execution,snapshot,sources} = await openXiaoyiSkills(
|
||||
this.store,template.id,undefined,undefined,undefined,template.knowledgeVersion,true,
|
||||
);
|
||||
const rules = await Promise.all([execution.entrypoint,execution.supplement].map(async rulePath => ({
|
||||
path:rulePath,
|
||||
text:await fs.readFile(path.join(snapshot.root,rulePath),'utf8'),
|
||||
})));
|
||||
return {execution,sources,rules};
|
||||
}
|
||||
const product = productEvidence.product;
|
||||
this.enterpriseContext ??= new EnterpriseContext(this.store);
|
||||
return this.enterpriseContext.load({task:this.task || 'chat',
|
||||
|
||||
@ -336,6 +336,37 @@ export class EnterpriseTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
function intakeMetadata(value) {
|
||||
if (value === undefined || value === null) return undefined;
|
||||
if (value.version !== 1 || !Array.isArray(value.productFields) || !Array.isArray(value.barcodeFields)) {
|
||||
throw Error('小壹模板产品资料字段格式无效');
|
||||
}
|
||||
const readFields = fields => {
|
||||
const ids = new Set();
|
||||
return fields.map(field => {
|
||||
if (!field || typeof field.id !== 'string' || !field.id.trim() || typeof field.label !== 'string' || !field.label.trim() ||
|
||||
!['text','number','select','boolean'].includes(field.type) ||
|
||||
(field.required !== undefined && typeof field.required !== 'boolean') ||
|
||||
(field.help !== undefined && typeof field.help !== 'string') ||
|
||||
(field.unit !== undefined && typeof field.unit !== 'string') ||
|
||||
(field.options !== undefined && (!Array.isArray(field.options) || field.options.some(option => typeof option !== 'string'))) ||
|
||||
(field.type === 'select' && (!field.options || !field.options.length))) {
|
||||
throw Error('小壹模板产品资料字段格式无效');
|
||||
}
|
||||
if (ids.has(field.id)) throw Error('小壹模板产品资料字段编号重复');
|
||||
ids.add(field.id);
|
||||
return {
|
||||
id:field.id, label:field.label, type:field.type,
|
||||
...(field.required !== undefined && {required:field.required}),
|
||||
...(field.help !== undefined && {help:field.help}),
|
||||
...(field.unit !== undefined && {unit:field.unit}),
|
||||
...(field.options !== undefined && {options:field.options}),
|
||||
};
|
||||
});
|
||||
};
|
||||
return {version:1,productFields:readFields(value.productFields),barcodeFields:readFields(value.barcodeFields)};
|
||||
}
|
||||
|
||||
export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
|
||||
const {templateId,projectDir,cache} = input;
|
||||
const skills = await openXiaoyiSkills({dir:projectDir,xiaoyiCache:cache,xiaoyiProgress:onProgress},templateId,signal,undefined,fetch,input.knowledgeVersion,input.metadataOnly === true);
|
||||
@ -382,7 +413,8 @@ export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
|
||||
originalSha256:original.sha256,canvas:original.canvas,
|
||||
resourceSetId:templateId,componentId:component,
|
||||
mappingPath:path.join(root,binding.mapping),inventoryPath:path.join(root,binding.inventory)});
|
||||
pack.xiaoyi = skills.productionBinding;
|
||||
const intake = intakeMetadata(manifest.intake ?? input.intake);
|
||||
pack.xiaoyi = {...skills.productionBinding,...(intake && {intake})};
|
||||
packs[component] = pack;
|
||||
}
|
||||
return {packs};
|
||||
@ -402,11 +434,11 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,
|
||||
try {
|
||||
response = await fetch(new URL('/api/xiaoyi/v1/templates', origin), {method:'GET',signal});
|
||||
} catch (error) {
|
||||
if (error.category === 'credential') throw Error('请先在小壹设置中填写并保存制作 Key', {cause:error});
|
||||
if (error.category === 'credential') throw Error('小壹知识库未连接,请在小壹设置中检测连接', {cause:error});
|
||||
throw error;
|
||||
}
|
||||
if (!response.ok) {
|
||||
const messages = {401:'制作 Key 已失效或填写有误,请在小壹设置中更换',403:'制作 Key 无权读取模板目录,请联系知识库管理员'};
|
||||
const messages = {401:'小壹知识库连接已失效,请在小壹设置中检测连接',403:'当前连接无权读取模板目录,请联系知识库管理员'};
|
||||
throw Object.assign(Error(messages[response.status] ?? '模板目录读取失败(HTTP ' + response.status + ')'),{status:response.status});
|
||||
}
|
||||
const data = await response.json();
|
||||
@ -440,7 +472,8 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,
|
||||
if (input.action === 'catalog') {
|
||||
const query = input.query?.trim().toLocaleLowerCase() ?? '';
|
||||
return {items:entries.filter(item => !query || (item.name + ' ' + item.templateId).toLocaleLowerCase().includes(query))
|
||||
.map(item => ({id:item.templateId,key:item.templateId,name:item.name,brandId:input.brandId,categoryId:input.categoryId}))};
|
||||
.map(item => ({id:item.templateId,key:item.templateId,name:item.name,brandId:input.brandId,categoryId:input.categoryId,
|
||||
...(item.intake != null && {intake:intakeMetadata(item.intake)})}))};
|
||||
}
|
||||
const item = entries.find(row => row.templateId === input.resourceSetId);
|
||||
if (!item) throw Error('所选模板已不在当前发布目录,请重新选择');
|
||||
@ -455,7 +488,7 @@ export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,
|
||||
const {packs} = await xiaoyiPacks({
|
||||
templateId:item.templateId,projectDir,cache:path.join(input.root,'blobs'),
|
||||
name:item.name,brandId:input.brandId,categoryId:input.categoryId,
|
||||
knowledgeVersion:item.knowledgeVersion,metadataOnly:true,
|
||||
knowledgeVersion:item.knowledgeVersion,metadataOnly:true,intake:intakeMetadata(item.intake),
|
||||
},{signal,fetch,onProgress});
|
||||
if (!packs[component.id]) throw Error('制作包缺少所选组件,请联系知识库管理员');
|
||||
return {items:[{...component,pack:packs[component.id]}]};
|
||||
|
||||
@ -61,6 +61,7 @@ export async function runPiProductionGoal(host, text, continuation, images=[], u
|
||||
if (!continuation || !continuing || userCanvasChanges) {
|
||||
const request = JSON.stringify({request:text,...productionFacts(host.store,host.productionGoal),
|
||||
requestedOutputs:host.productionGoal.requestedOutputs,product:host.productEvidence?.product,
|
||||
...(host.productEvidence?.intake?{intake:host.productEvidence.intake,barcodeBindings:host.productEvidence.barcodeBindings}:null),
|
||||
enterpriseKnowledge:host.productionSkills?.execution,userCanvasChanges:userCanvasChanges??undefined});
|
||||
await host.session.sendCustomMessage({customType:'photocraft-goal-request',
|
||||
content:images.length?[{type:'text',text:request},...images]:request,display:false}, {triggerTurn:false});
|
||||
@ -224,7 +225,9 @@ export async function callProductionTool(host, name, args, signal) {
|
||||
const {referenceMode,mainImageAspects}=productionSettings(host.store,goal.template?.production);
|
||||
return {...productionFacts(host.store,goal),referenceMode:referenceMode??null,...(!referenceMode?{referenceNotice:'参考方式未声明'}:null),
|
||||
mainImageAspects:mainImageAspects??null,requestedOutputs:goal.requestedOutputs,pendingOutputs:goal.pendingOutputs,
|
||||
workingOutput:null,projectSlots:await projectSlotMap(host),template:{id,name,version,productionRoute},product:{...product,dimensions,note},
|
||||
workingOutput:null,projectSlots:await projectSlotMap(host),template:{id,name,version,productionRoute},
|
||||
product:{...product,dimensions,note,...(host.productEvidence?.intake?{
|
||||
intake:host.productEvidence.intake,barcodeBindings:host.productEvidence.barcodeBindings}:null)},
|
||||
...(host.productionSkills?.versionNotice?{knowledgeVersionNotice:host.productionSkills.versionNotice}:null),
|
||||
...(args.includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null)};
|
||||
}
|
||||
|
||||
@ -7,7 +7,7 @@ import path from 'node:path';
|
||||
import { CanvasOperations } from './canvas-operations.mjs';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { formatDimensionNote, parseFrontmatter, resizeImage } from '@earendil-works/pi-coding-agent';
|
||||
import { productionLedger, recordProductionInputs } from './production-repository.mjs';
|
||||
import { productionLedger, recordProductionInputs, scopedProductionBrief } from './production-repository.mjs';
|
||||
import { PresentationBatch } from './stream-presentation.mjs';
|
||||
import { candidateUsage, loadSlots, productionFacts, productionPicturePlan, productionSettings } from './production-slots.mjs';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
@ -176,8 +176,8 @@ export function productionVideoTools(host, make) {
|
||||
function productionInputs(plan,variantId){
|
||||
const brief=plan.productEvidence?.brief;
|
||||
if(!brief)return plan.revisions?.creation;
|
||||
const {variants,...shared}=brief;
|
||||
return JSON.stringify([shared,variants?.find(row=>row.id===variantId),(variants?.length??0)>1,
|
||||
const {brief:shared,variant}=scopedProductionBrief(brief,variantId);
|
||||
return JSON.stringify([shared,variant,(brief.variants?.length??0)>1,
|
||||
plan.productEvidence.sellingPoints?.selected]);
|
||||
}
|
||||
|
||||
@ -188,9 +188,10 @@ export function preparedCandidateId(intent,values,operation){
|
||||
|
||||
function changedProductionFields(previous,current,variantId){
|
||||
const inputs=value=>{
|
||||
const {variants,...brief}=value.productEvidence?.brief??{};
|
||||
return {brief,variant:variants?.find(row=>row.id===variantId)??{},
|
||||
options:{multipleVariants:(variants?.length??0)>1,
|
||||
const source=value.productEvidence?.brief??{};
|
||||
const {brief,variant}=scopedProductionBrief(source,variantId);
|
||||
return {brief,variant:variant??{},
|
||||
options:{multipleVariants:(source.variants?.length??0)>1,
|
||||
sellingPoints:value.productEvidence?.sellingPoints?.selected}};
|
||||
};
|
||||
const before=inputs(previous),after=inputs(current);
|
||||
@ -1196,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 {name,variants,dimensions,note}=plan.productEvidence?.brief??{};
|
||||
const variant=variants?.find(row=>row.id===variantId);
|
||||
const {brief,variant}=scopedProductionBrief(plan.productEvidence?.brief??{},variantId);
|
||||
const {name,dimensions,note,intake,barcodes}=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));
|
||||
@ -1216,7 +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}},
|
||||
template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName},
|
||||
...(intake?{intake,barcodes}:null)},
|
||||
candidatesPerSlot,maxCandidatesPerSlot,maxGenerationAttempts,generationLimitSource,...picturePlan,...facts(),...(productUpdate?{productUpdate}:null),pictures,
|
||||
inFlightImages:(await pendingNative()).map(row=>row.candidateId),
|
||||
...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null),
|
||||
@ -1516,6 +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),
|
||||
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'});
|
||||
@ -1842,8 +1845,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const references=()=>referenceRead??=readReferences();
|
||||
async function readReferences(){
|
||||
const inputPlan=await current();
|
||||
const {variants,...brief}=inputPlan.productEvidence?.brief??{};
|
||||
const product={...brief,variant:variants?.find(row=>row.id===variantId)??brief.variant,
|
||||
const {brief,variant}=scopedProductionBrief(inputPlan.productEvidence?.brief??{},variantId);
|
||||
const product={...brief,variant:variant??brief.variant,
|
||||
sellingPoints:inputPlan.productEvidence?.sellingPoints?.selected};
|
||||
if(!slots.length)throw Error('当前画布没有可读取本款实拍的图位');
|
||||
const {images=[],referenceCount=0}=await readImages(slots[0].id,{includeTemplateReference:false});
|
||||
|
||||
@ -38,12 +38,34 @@ export function productionLedger(store, outputId, variantId) {
|
||||
}};
|
||||
}
|
||||
|
||||
export function scopedProductionBrief(brief, variantId) {
|
||||
const { variants, intake, barcodeBindings, ...shared } = brief;
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
export function recordProductionInputs(repository, plan, slots) {
|
||||
const { productEvidence, productVariantId, revisions, template } = plan;
|
||||
let productFactsRevision;
|
||||
if (productEvidence?.brief) {
|
||||
const { variants, ...brief } = productEvidence.brief;
|
||||
const facts = { brief, variant: variants?.find(row => row.id === productVariantId),
|
||||
const { brief, variant } = scopedProductionBrief(productEvidence.brief, productVariantId);
|
||||
const facts = { brief, variant,
|
||||
facts: productEvidence.facts, sourceRevision: revisions?.creation ?? productEvidence.revision };
|
||||
productFactsRevision = digest(facts);
|
||||
repository.saveVersion('product_facts', 'product', productFactsRevision, facts);
|
||||
|
||||
@ -48,6 +48,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);
|
||||
return ids.length?[[key,ids]]:[];
|
||||
|
||||
@ -5,7 +5,7 @@ const blockedValue = /(?:data:image\/|;base64,|[a-z]:[\\/]|\\\\[^\s]+|file:\/\/|
|
||||
fields.add('screenCount');
|
||||
fields.add('persistence');
|
||||
for (const name of ['afterRevision','overlayLayers','overlayNote','hiddenRetouchLayers','mapped','bounds','overlapsSlots','group','belowSlot','coverage','opacity','blendMode']) fields.add(name);
|
||||
for (const name of ['template','enterprise','releaseId','templateVersion']) fields.add(name);
|
||||
for (const name of ['template','enterprise','releaseId','templateVersion','knowledgeVersion']) fields.add(name);
|
||||
for (const name of ['canvasFirst','subject','productVariantId','variantId','variantLabel','candidateId','parentCandidateId','adoptedCandidateId','pageId','nativeLayerId','taskId','previewId','operationId','operation','workflow','manuallyEdited','writeBlockReason']) fields.add(name);
|
||||
|
||||
/** A small data-only view. Pixels, paths, model prompts and private task bodies
|
||||
|
||||
@ -40,8 +40,8 @@ async function matches(file, item) {
|
||||
async function httpError(response) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
const messages = {
|
||||
401: '制作 Key 已失效或填写有误,请在小壹设置的企业知识库中更换制作 Key',
|
||||
403: '制作 Key 无权读取当前小壹知识,请联系知识库管理员核对权限(403)',
|
||||
401: '小壹知识库连接已失效,请在小壹设置中检测连接',
|
||||
403: '当前连接无权读取小壹知识,请联系知识库管理员',
|
||||
410: '此小壹知识版本已撤回。已完整校验的本地工程可继续使用原版本',
|
||||
};
|
||||
const message = body.code === 'not_published' ? '此模板还没有发布小壹版本'
|
||||
@ -82,7 +82,7 @@ export async function acquireXiaoyiRelease(options) {
|
||||
try {
|
||||
return await options.fetch(route, {method:'GET', headers, signal});
|
||||
} catch (error) {
|
||||
if (error.category === 'credential') throw Error('本机没有可读取的制作 Key,请在小壹设置的企业知识库中填写并保存', {cause:error});
|
||||
if (error.category === 'credential') throw Error('小壹知识库未连接,请在小壹设置中检测连接', {cause:error});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1523,6 +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 intake={templateId:'table',schema:{fields:[]},productValues:{material:'木'},
|
||||
barcodeValues:{'00123':{width:'120'},'00124':{width:'140'},'00999':{width:'160'}}};
|
||||
const submissions=[];
|
||||
let creation=1;
|
||||
const submit=Promise.withResolvers();
|
||||
@ -1532,7 +1535,8 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca
|
||||
run:'native-run',documentId:3,
|
||||
workflowRead:async()=>({available:true,canvasFirst:true,version:creation,outputId,productVariantId:variantId,
|
||||
revisions:{creation},template:{contentHash:'fixture'},totalSlots:1,slots:[{id:slotId,fieldId:'front',candidates:[]}],
|
||||
productEvidence:{brief:{name:'餐桌',dimensions,note,variants:structuredClone(variants)}}}),
|
||||
productEvidence:{brief:{name:'餐桌',dimensions,note,variants:structuredClone(variants),
|
||||
intake:structuredClone(intake),barcodeBindings:structuredClone(barcodeBindings)}}}),
|
||||
detailCopyFields:async()=>({fields:[{layer:5,field:'hero',page:'S01',label:'木纹',currentText:'木纹展示'}]}),
|
||||
read:async()=>({revision:3}),delta:async()=>{},
|
||||
async workflowExecute({operationId}){
|
||||
@ -1551,7 +1555,12 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca
|
||||
let actions=await openProductionOperations(host);
|
||||
const initialPlan=await actions.plan_production();
|
||||
assert.deepEqual(initialPlan.pendingOutputs,[nextOutput]);
|
||||
assert.deepEqual(initialPlan.product,{name:'餐桌',dimensions,note,variant:{id:variantId,colorName:'橡木色'}});
|
||||
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';
|
||||
creation++;
|
||||
assert.equal((await actions.plan_production()).productUpdate,undefined);
|
||||
creation--;
|
||||
await actions.write_copy_fields({revision:3,recordOnly:true,items:[{layer:5,text:'木纹展示',sources:[],pictures:[]}]});
|
||||
const request={slotId,source:'generate',prompt:'给商品正面留出文字区域'};
|
||||
variants[1].colorName='暖白色';
|
||||
|
||||
@ -313,6 +313,38 @@ test('P13 reloads full facts, plan, formal prompt and locked rule from stable ve
|
||||
assert.deepEqual(prepared.knowledge, draft.knowledge);
|
||||
});
|
||||
|
||||
test('production facts retain only this variant barcodes without mixing different barcode values', async t => {
|
||||
const { repo, open } = await fixture(t);
|
||||
const brief = {
|
||||
name: '餐桌',
|
||||
variants: [{ id: 'oak', colorName: '橡木' }, { id: 'white', colorName: '白色' }],
|
||||
barcodeBindings: { oak: '00123456\n00123457', white: '00999999' },
|
||||
intake: {
|
||||
templateId: 'table',
|
||||
schema: { fields: [{ id: 'width', label: '宽度', scope: 'barcode' }] },
|
||||
productValues: { material: '木' },
|
||||
barcodeValues: {
|
||||
'00123456': { width: '120 cm' },
|
||||
'00123457': { width: '140 cm' },
|
||||
'00999999': { width: '160 cm' },
|
||||
},
|
||||
},
|
||||
};
|
||||
const { productFactsRevision } = recordProductionInputs(repo, {
|
||||
productEvidence: { brief, facts: {} },
|
||||
productVariantId: 'oak', revisions: { creation: 1 }, template: {},
|
||||
}, []);
|
||||
const saved = open().readVersion('product_facts', 'product', productFactsRevision);
|
||||
assert.deepEqual(saved.brief.barcodes, ['00123456', '00123457']);
|
||||
assert.deepEqual(saved.brief.intake.barcodeValues, {
|
||||
'00123456': { width: '120 cm' },
|
||||
'00123457': { width: '140 cm' },
|
||||
});
|
||||
assert.equal(saved.brief.intake.productValues.material, '木');
|
||||
assert.equal(saved.variant.id, 'oak');
|
||||
assert.equal(saved.brief.barcodeBindings, undefined);
|
||||
});
|
||||
|
||||
test('P15 execution success and a failed pixel check remain independently traceable', async t => {
|
||||
const { open, repo } = await fixture(t);
|
||||
const draft = request('undersize', { prompt: '输出 4K,保留产品结构。' });
|
||||
|
||||
@ -14,6 +14,8 @@ import { NativeControlClient as NativeCanvas } from '../src/native-control-clien
|
||||
import { workflowContext, workflowResult } from '../src/workflow-context.mjs';
|
||||
import { executeWorkflow } from '../src/workflow-execute.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
import { openXiaoyiSkills } from '../src/xiaoyi-release.mjs';
|
||||
import { xiaoyiFixture } from './xiaoyi-fixture.mjs';
|
||||
|
||||
const scope = '8'.repeat(64);
|
||||
const binding = { brandId:'qa',shopId:'qa',categoryId:'desk',platform:'native',version:'1',source:'explicit-local-test',rules:[] };
|
||||
@ -413,3 +415,32 @@ test('a known local rejection returns the host reason and the agent decides with
|
||||
assert.ok(x.host.session.messages.some(message=>message.role==='toolResult'&&message.toolName==='workflow_execute'&&message.isError));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
|
||||
test('normal conversation reads the pinned Xiaoyi rules without the general knowledge key', async () => {
|
||||
const x = await fixture((_context, n) => n === 1 ? tool('context_read', {}) : answer('已读取本项目规则。'));
|
||||
const entry = '规则/SKILL.md';
|
||||
const supplement = '规则/补充.md';
|
||||
const fetch = xiaoyiFixture('desk', 'v1', entry, {
|
||||
[entry]: '---\nname: desk-rules\ndescription: Desk design rules.\n---\n首屏必须呈现产品全貌。',
|
||||
[supplement]: '颜色以已确认资料为准。',
|
||||
}, { supplement });
|
||||
try {
|
||||
await openXiaoyiSkills(x.store, 'desk', undefined, undefined, fetch);
|
||||
const read = x.canvas.workflowRead;
|
||||
x.canvas.workflowRead = async args => ({
|
||||
...await read(args),
|
||||
template: { id: 'desk', enterprise: true, knowledgeVersion: 'desk@v1' },
|
||||
});
|
||||
x.host.enterpriseContext = { load: async () => assert.fail('一般知识库不应被调用') };
|
||||
await x.host.prompt('请读取当前模板规则。');
|
||||
const context = x.calls[1].evidence;
|
||||
assert.equal(context.currentWorkflow.template.knowledgeVersion, 'desk@v1');
|
||||
assert.equal(context.enterpriseKnowledge.execution.knowledgeVersion, 'desk@v1');
|
||||
assert.deepEqual(context.enterpriseKnowledge.rules.map(rule => rule.path), [entry, supplement]);
|
||||
assert.match(context.enterpriseKnowledge.rules[0].text, /首屏必须呈现产品全貌/);
|
||||
assert.match(context.enterpriseKnowledge.rules[1].text, /颜色以已确认资料为准/);
|
||||
} finally {
|
||||
await x.close();
|
||||
}
|
||||
});
|
||||
|
||||
@ -14,7 +14,7 @@ import {acquireXiaoyiRelease,openXiaoyiSkills} from '../src/xiaoyi-release.mjs';
|
||||
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const describe = bytes => ({size:bytes.length,sha256:sha(bytes)});
|
||||
|
||||
async function fixture(t, {badHash = false,templateId = 'CHAIR',withBindings = false} = {}) {
|
||||
async function fixture(t, {badHash = false,templateId = 'CHAIR',withBindings = false,intake} = {}) {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-release-'));
|
||||
t.after(() => fs.rm(dir,{recursive:true,force:true}));
|
||||
const config = Buffer.from('{"productionProfiles":{"detail":{"pages":{"D01":{}}}}}');
|
||||
@ -34,6 +34,7 @@ async function fixture(t, {badHash = false,templateId = 'CHAIR',withBindings = f
|
||||
schemaVersion:1,templateId,version:'v1',knowledgeVersion:templateId+'@v1',
|
||||
entrypoint:'规则/SKILL.md',supplement:'规则/SKILL.md',
|
||||
productionConfig:'小壹/production.json',
|
||||
...(intake ? {intake} : {}),
|
||||
...(withBindings?{bindings:{detail:{mapping:'模板/mapping.json',inventory:'模板/inventory.json',original:'模板/original.psd'}}}:null),
|
||||
bundle:describe(bundle),assets:[{path:'模板/original.psd',type:'original',component:'detail',...describe(blob)}],
|
||||
files:[{path:'规则/SKILL.md',...describe(guide),...(badHash?{sha256:sha('wrong')}:null)},
|
||||
@ -90,7 +91,7 @@ test('rejects a file hash mismatch without writing a lock', async t => {
|
||||
await assert.rejects(fs.access(path.join(options.directory,'manifest.json')),{code:'ENOENT'});
|
||||
});
|
||||
|
||||
for (const [status,code,hint] of [[401,'authentication_required',/更换制作 Key/],
|
||||
for (const [status,code,hint] of [[401,'authentication_required',/检测连接/],
|
||||
[403,'forbidden',/联系知识库管理员/],[404,'not_published',/还没有发布/],[404,undefined,/没有提供小壹制作通道/],[410,'version_retired',/已撤回/]]) {
|
||||
test(`stops on HTTP ${status}`, async t => {
|
||||
const {options,pauses} = await fixture(t);
|
||||
@ -223,10 +224,12 @@ test('first production prepares the component from only manifest bindings and re
|
||||
|
||||
|
||||
test('production Key browses brands, categories, templates and component mappings without downloading originals', async t => {
|
||||
const {options,requests} = await fixture(t,{withBindings:true});
|
||||
const intake = {version:1,productFields:[{id:'material',label:'材质',type:'text',required:true}],
|
||||
barcodeFields:[{id:'color',label:'颜色',type:'select',options:['浅色','深色']}]};
|
||||
const {options,requests} = await fixture(t,{withBindings:true,intake});
|
||||
const root = path.join(options.directory,'catalog-root');
|
||||
const catalog = {items:[{templateId:'CHAIR',name:'Fixture chair',brand:'Fixture',category:'Chair',
|
||||
version:'v1',knowledgeVersion:'CHAIR@v1',components:[{id:'detail'}]}]};
|
||||
version:'v1',knowledgeVersion:'CHAIR@v1',components:[{id:'detail'}],intake}]};
|
||||
const fetch = async (url,init) => url.pathname === '/api/xiaoyi/v1/templates'
|
||||
? Response.json(catalog) : options.fetch(url.pathname,init);
|
||||
const common = {root,brandId:'ekb:brand:Fixture',brandName:'Fixture',
|
||||
@ -237,6 +240,7 @@ test('production Key browses brands, categories, templates and component mapping
|
||||
assert.equal(categories.catalog.items[0].name,'Chair');
|
||||
const list = await templateRequest({...common,action:'catalog',query:'CHAIR'},{fetch});
|
||||
assert.equal(list.items[0].id,'CHAIR');
|
||||
assert.deepEqual(list.items[0].intake,intake);
|
||||
const set = await templateRequest({...common,action:'resource-set',resourceSetId:'CHAIR'},{fetch});
|
||||
assert.equal(set.items[0].id,'detail');
|
||||
const part = await templateRequest({...common,action:'resource-component',resourceSetId:'CHAIR',componentId:'detail'},{fetch});
|
||||
@ -244,15 +248,22 @@ test('production Key browses brands, categories, templates and component mapping
|
||||
assert.equal(pack.enterprise.sourceKind,'xiaoyi-release');
|
||||
assert.equal(pack.enterprise.resourceSetId,'CHAIR');
|
||||
assert.equal(pack.enterprise.componentId,'detail');
|
||||
assert.deepEqual(pack.xiaoyi.intake,intake);
|
||||
assert.equal(pack.outputs[0].slots[0].fieldId,'D01-I01');
|
||||
assert.equal(requests.some(([route])=>route.includes('/blobs/')),false);
|
||||
assert.equal(requests.some(([route])=>route.endsWith('/bundle')),true);
|
||||
const cachedProject = path.join(root,'catalog',createHash('sha256').update(JSON.stringify(['CHAIR','v1'])).digest('hex'));
|
||||
const full = await xiaoyiPacks({templateId:'CHAIR',projectDir:cachedProject,cache:path.join(root,'blobs'),
|
||||
name:'Fixture chair',brandId:common.brandId,categoryId:common.categoryId,knowledgeVersion:'CHAIR@v1'},{fetch});
|
||||
assert.deepEqual(full.packs.detail.xiaoyi.intake,intake);
|
||||
const withoutKnowledge = value => {const copy = structuredClone(value); delete copy.xiaoyi; return copy;};
|
||||
assert.deepEqual(withoutKnowledge(full.packs.detail),withoutKnowledge(pack));
|
||||
assert.equal(requests.filter(([route])=>route.includes('/blobs/')).length,1);
|
||||
delete catalog.items[0].intake;
|
||||
const legacy = await templateRequest({...common,action:'catalog'},{fetch});
|
||||
assert.equal(legacy.items[0].intake,undefined);
|
||||
catalog.items[0].intake = {...intake,productFields:[{id:'bad',label:'错误类型',type:'unknown'}]};
|
||||
await assert.rejects(templateRequest({...common,action:'catalog'},{fetch}),/产品资料字段格式无效/);
|
||||
});
|
||||
|
||||
test('production catalog reports rejected keys without falling through to generic MCP', async t => {
|
||||
@ -261,5 +272,5 @@ test('production catalog reports rejected keys without falling through to generi
|
||||
{fetch:async url => {
|
||||
assert.equal(url.pathname,'/api/xiaoyi/v1/templates');
|
||||
return Response.json({code:'authentication_required'},{status:401});
|
||||
}}),/制作 Key 已失效/);
|
||||
}}),/知识库连接已失效/);
|
||||
});
|
||||
|
||||
@ -580,6 +580,7 @@ impl Backend {
|
||||
self.auth["account"]["id"].as_str().map(|id| hash(&format!("{}|{}", self.origin, id))).unwrap_or("guest".into())
|
||||
}
|
||||
fn revoke_access(&self, category: &str) {
|
||||
knowledge_http::clear_account(self);
|
||||
if self.access.invalidate() {
|
||||
let scope = self.scope();
|
||||
agent_daemon::revoke_scope(&scope, category);
|
||||
@ -607,6 +608,7 @@ impl Backend {
|
||||
match self.portal_json("session") {
|
||||
Ok(value) if value["account"]["id"] == account => {
|
||||
self.auth["account"] = value["account"].clone();
|
||||
knowledge_http::set_account(self);
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
@ -977,6 +979,9 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
}
|
||||
if library_status == "connected" {
|
||||
knowledge_http::set_account(self);
|
||||
}
|
||||
let mut saved = self.settings().unwrap_or_else(|_| json!({}));
|
||||
// 模型目录来自 98k,与素材库是否在线无关;已登录账户在素材库暂不可用时照常加载。
|
||||
if library_status == "connected" || library_status == "unavailable" {
|
||||
@ -1043,6 +1048,13 @@ impl Backend {
|
||||
}
|
||||
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()
|
||||
} else {
|
||||
json!({"mode":"unavailable","error":library_message})
|
||||
};
|
||||
result["xiaoyiKnowledgeMode"] = knowledge["mode"].clone();
|
||||
result["xiaoyiKnowledgeError"] = knowledge["error"].clone();
|
||||
result["accountEpoch"] = json!(self.access.epoch);
|
||||
result["origin"] = json!(self.origin);
|
||||
result["libraryStatus"] = json!(library_status);
|
||||
@ -1592,7 +1604,7 @@ impl Backend {
|
||||
"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_xiaoyi(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"]
|
||||
|| input["origin"].as_str() != Some(self.origin.as_str())
|
||||
|
||||
@ -715,9 +715,28 @@ 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(intake) = shared.get_mut("intake").and_then(Value::as_object_mut) { intake.remove("barcodeValues"); }
|
||||
shared
|
||||
}
|
||||
|
||||
fn variant_intake(brief: &Value, variant_id: &str) -> Option<Value> {
|
||||
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 mut values = serde_json::Map::new();
|
||||
for barcode in entered.split(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ',' | '、')) {
|
||||
if let Some(fields) = intake["barcodeValues"].get(barcode)
|
||||
&& fields.as_object().is_some_and(|fields| !fields.is_empty())
|
||||
{
|
||||
values.insert(barcode.to_owned(), fields.clone());
|
||||
}
|
||||
}
|
||||
(!values.is_empty()).then_some(Value::Object(values))
|
||||
}
|
||||
|
||||
fn variant_brief<'a>(brief: &'a Value, id: &str) -> &'a Value {
|
||||
brief["variants"].as_array().into_iter().flatten()
|
||||
.find(|row| row["id"] == id).unwrap_or(&Value::Null)
|
||||
@ -750,10 +769,12 @@ const VARIANT_INPUT_HASH: &str = "variant-v1:";
|
||||
fn variant_input_hash(state: &Value, creation: &Value, variant_id: &str, template: &Value, structure: &Value) -> R<String> {
|
||||
let selected = variant(state, variant_id)?;
|
||||
let live = &creation["brief"];
|
||||
let inputs = json!({"brief":shared_variant_brief(&state["brief"]),"liveBrief":shared_variant_brief(live),
|
||||
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; }
|
||||
Ok(format!("{VARIANT_INPUT_HASH}{}", hash(&inputs.to_string())))
|
||||
}
|
||||
|
||||
@ -1718,7 +1739,8 @@ fn check_image_context(dir: &Path, except: Option<&Value>, batch: Option<&Value>
|
||||
let current_variant = batch.and_then(|binding| binding["variantId"].as_str());
|
||||
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_brief(live, id) == variant_brief(saved, id)
|
||||
&& variant_intake(live, id) == variant_intake(saved, id))
|
||||
{
|
||||
return Err("当前商品或花色资料已更新,请读取新资料;原请求已保留".into());
|
||||
}
|
||||
@ -8103,6 +8125,25 @@ mod tests {
|
||||
assert_eq!(recovered["brief"]["variants"], state["variants"]);
|
||||
assert_eq!(recovered["brief"]["templateSelection"]["name"], state["template"]["name"]);
|
||||
}
|
||||
#[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"},
|
||||
"intake":{"templateId":"t","schema":{"version":1},"productValues":{},
|
||||
"barcodeValues":{"00123":{"size":"large"},"00999":{"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");
|
||||
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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_one_variant_keeps_original_requests_and_leaves_other_variant_runnable() {
|
||||
let fixture = fixture();
|
||||
|
||||
@ -40,7 +40,10 @@ pub(super) fn load(dir: &Path) -> R<Value> {
|
||||
}
|
||||
Ok(c)
|
||||
} else {
|
||||
Ok(model::empty())
|
||||
let mut creation = model::empty();
|
||||
creation["brief"]["identifierType"] = json!("spu");
|
||||
creation["brief"]["barcodeBindings"] = json!({});
|
||||
Ok(creation)
|
||||
}
|
||||
}
|
||||
pub(super) fn save(dir: &Path, c: &mut Value) -> R<()> {
|
||||
|
||||
@ -38,6 +38,60 @@ fn image_list(value: &Value) -> R<Value> {
|
||||
Ok(json!(clean))
|
||||
}
|
||||
|
||||
fn intake(value: &Value) -> R<Value> {
|
||||
let template_id = string(&value["templateId"], 120, "模板编号")?;
|
||||
if template_id.trim().is_empty() { return Err("产品资料缺少模板编号".into()); }
|
||||
let schema = &value["schema"];
|
||||
if schema["version"] != 1 { return Err("产品资料模板版本无效".into()); }
|
||||
let mut kinds = [std::collections::HashMap::new(), std::collections::HashMap::new()];
|
||||
for (index, name) in ["productFields", "barcodeFields"].iter().enumerate() {
|
||||
let fields = schema[*name].as_array().filter(|rows| rows.len() <= 100).ok_or("产品资料字段格式无效")?;
|
||||
for field in fields {
|
||||
let id = string(&field["id"], 120, "资料字段编号")?;
|
||||
let label = string(&field["label"], 200, "资料字段名称")?;
|
||||
let kind = field["type"].as_str().filter(|kind| matches!(*kind, "text" | "number" | "select" | "boolean"))
|
||||
.ok_or("资料字段类型无效")?;
|
||||
if id.trim().is_empty() || label.trim().is_empty() || kinds[index].insert(id, kind).is_some() {
|
||||
return Err("资料字段编号或名称无效".into());
|
||||
}
|
||||
if field.get("required").is_some_and(|value| !value.is_boolean()) {
|
||||
return Err("资料字段的必填标记无效".into());
|
||||
}
|
||||
for optional in ["help", "unit"] {
|
||||
if let Some(value) = field.get(optional) { string(value, 500, "资料字段说明")?; }
|
||||
}
|
||||
if let Some(options) = field.get("options") {
|
||||
let options = options.as_array().filter(|items| items.len() <= 100).ok_or("资料字段选项无效")?;
|
||||
for option in options { string(option, 200, "资料字段选项")?; }
|
||||
}
|
||||
}
|
||||
}
|
||||
let validate_values = |values: &Value, fields: &std::collections::HashMap<String, &str>| -> R<()> {
|
||||
let values = values.as_object().filter(|rows| rows.len() <= 100).ok_or("产品资料填写内容无效")?;
|
||||
for (key, value) in values {
|
||||
let kind = fields.get(key).ok_or("产品资料字段不属于当前模板")?;
|
||||
let valid = match *kind {
|
||||
"text" | "select" => value.as_str().is_some_and(|value| value.chars().count() <= 6000),
|
||||
"number" => value.is_number() || value.as_str().is_some_and(|value| value.chars().count() <= 120),
|
||||
"boolean" => value.is_boolean(),
|
||||
_ => false,
|
||||
};
|
||||
if !valid { return Err("产品资料填写内容与字段类型不符".into()); }
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
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'_')) {
|
||||
return Err("条码资料中的条码格式无效".into());
|
||||
}
|
||||
validate_values(fields, &kinds[1])?;
|
||||
}
|
||||
if value.to_string().len() > 1_000_000 { return Err("产品资料过大".into()); }
|
||||
Ok(value.clone())
|
||||
}
|
||||
|
||||
pub(super) fn brief(value: &Value) -> R<Value> {
|
||||
let mut out = empty()["brief"].clone();
|
||||
for (field, max) in [
|
||||
@ -134,6 +188,23 @@ pub(super) fn brief(value: &Value) -> R<Value> {
|
||||
out["skuBindings"] = Value::Object(clean);
|
||||
}
|
||||
}
|
||||
if 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();
|
||||
for (id, value) in rows {
|
||||
if id != "default" && Uuid::parse_str(id).is_err() {
|
||||
return Err("条码绑定的花色编号无效".into());
|
||||
}
|
||||
let codes = string(value, 24_200, "条码")?;
|
||||
if !codes.trim().is_empty() {
|
||||
clean.insert(id.clone(), json!(codes.trim()));
|
||||
}
|
||||
}
|
||||
out["barcodeBindings"] = Value::Object(clean);
|
||||
}
|
||||
if let Some(selection) = value.get("outputVariantIds") {
|
||||
let selection = selection.as_object().ok_or("出图颜色选择格式无效")?;
|
||||
let mut selected = serde_json::Map::new();
|
||||
@ -151,6 +222,9 @@ pub(super) fn brief(value: &Value) -> R<Value> {
|
||||
}
|
||||
out["outputVariantIds"] = Value::Object(selected);
|
||||
}
|
||||
if let Some(fields) = value.get("intake") {
|
||||
out["intake"] = intake(fields)?;
|
||||
}
|
||||
if let Some(selection) = value.get("templateSelection") {
|
||||
if selection.is_null() {
|
||||
out["templateSelection"] = Value::Null;
|
||||
@ -188,6 +262,12 @@ pub(super) fn brief(value: &Value) -> R<Value> {
|
||||
out["templateSelection"] = clean;
|
||||
}
|
||||
}
|
||||
if let Some(intake) = out.get("intake")
|
||||
&& let Some(template_id) = out["templateSelection"]["id"].as_str()
|
||||
&& Some(template_id) != intake["templateId"].as_str()
|
||||
{
|
||||
return Err("产品资料与所选模板不一致".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@ -459,6 +539,8 @@ pub(in super::super) fn production_brief(brief: &Value) -> Value {
|
||||
let mut brief = brief.clone();
|
||||
if let Some(fields) = brief.as_object_mut() {
|
||||
fields.remove("skuBindings");
|
||||
fields.remove("barcodeBindings");
|
||||
fields.remove("deliverySpu");
|
||||
}
|
||||
brief
|
||||
}
|
||||
@ -497,6 +579,28 @@ 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 template_intake_roundtrip_preserves_multiple_barcode_values_and_drafts() {
|
||||
let mut value = canvas_brief();
|
||||
value["intake"] = json!({
|
||||
"templateId":"chair",
|
||||
"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":"小号"}}
|
||||
});
|
||||
let clean = brief(&value).unwrap();
|
||||
assert_eq!(clean["intake"], value["intake"]);
|
||||
assert_eq!(clean["intake"]["barcodeValues"]["00123"]["size"], "大号");
|
||||
let mut changed = value.clone();
|
||||
changed["intake"]["barcodeValues"]["00123"]["unknown"] = json!("not declared");
|
||||
assert!(brief(&changed).is_err());
|
||||
changed = value;
|
||||
changed["templateSelection"] = json!({"id":"desk","version":"v1","contentHash":"a".repeat(64)});
|
||||
assert!(brief(&changed).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_map_component_selection_survives_product_brief_roundtrip() {
|
||||
let mut value = canvas_brief();
|
||||
@ -784,6 +888,19 @@ mod tests {
|
||||
assert_eq!(input_hash(stage, &changed).unwrap(), legacy, "{stage} ignores the new independent template copy contract");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn old_project_delivery_identifiers_preserve_the_production_input() {
|
||||
let original = empty()["brief"].clone();
|
||||
let mut updated = original.clone();
|
||||
updated["deliverySpu"] = json!("SPU-001");
|
||||
updated["barcodeBindings"] = json!({"default":"00123\n00456"});
|
||||
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!(production_brief(&saved), production_brief(&original));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimensions_and_sources_are_checked() {
|
||||
let mut b = empty()["brief"].clone();
|
||||
|
||||
@ -8,7 +8,7 @@ use std::{
|
||||
io::{BufReader, Read, Write},
|
||||
net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream},
|
||||
process::Command,
|
||||
sync::{Arc, LazyLock, OnceLock},
|
||||
sync::{Arc, LazyLock, Mutex, OnceLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
@ -25,6 +25,147 @@ const NETWORK: &str = "企业知识库网络不可达";
|
||||
const RESPONSE: &str = "企业知识库响应无效";
|
||||
const XIAOYI_ORIGIN_REQUIRED: &str = "请通过公司内网或 HTTPS 连接小壹制作知识库";
|
||||
|
||||
const PORTAL_UNAVAILABLE: &str = "素材库暂时无法连接,请稍后重试";
|
||||
const PORTAL_LOGIN: &str = "素材库授权已失效,请重新登录";
|
||||
const PORTAL_FORBIDDEN: &str = "当前账户无权使用小壹知识库";
|
||||
const AUTOMATIC_INVALID: &str = "小壹知识库自动授权无效,请联系管理员";
|
||||
const TOKEN_PREFIX: &str = "ekb_xiaoyi_session_";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Account {
|
||||
origin: String,
|
||||
token: String,
|
||||
account_id: String,
|
||||
access: super::AccountAccess,
|
||||
http: super::NetworkClient,
|
||||
cached: Arc<Mutex<Option<(String, std::time::Instant)>>>,
|
||||
}
|
||||
|
||||
static ACCOUNT: LazyLock<Mutex<Option<Account>>> = LazyLock::new(|| Mutex::new(None));
|
||||
|
||||
pub(super) fn set_account(backend: &super::Backend) {
|
||||
let mut current = match ACCOUNT.lock() {
|
||||
Ok(current) => current,
|
||||
Err(_) => return,
|
||||
};
|
||||
let token = backend.auth["access_token"].as_str().unwrap_or_default();
|
||||
let account_id = backend.auth["account"]["id"].as_str().unwrap_or_default();
|
||||
if token.is_empty() || account_id.is_empty() {
|
||||
*current = None;
|
||||
return;
|
||||
}
|
||||
if current.as_ref().is_some_and(|account| account.origin == backend.origin
|
||||
&& account.token == token && account.account_id == account_id
|
||||
&& account.access.epoch == backend.access.epoch)
|
||||
{
|
||||
return;
|
||||
}
|
||||
*current = Some(Account {
|
||||
origin: backend.origin.clone(),
|
||||
token: token.to_owned(),
|
||||
account_id: account_id.to_owned(),
|
||||
access: backend.access.clone(),
|
||||
http: backend.http.clone(),
|
||||
cached: Arc::new(Mutex::new(None)),
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn clear_account(backend: &super::Backend) {
|
||||
if let Ok(mut current) = ACCOUNT.lock()
|
||||
&& current.as_ref().is_some_and(|account| account.origin == backend.origin
|
||||
&& backend.auth["access_token"].as_str() == Some(account.token.as_str())
|
||||
&& account.access.epoch == backend.access.epoch)
|
||||
{
|
||||
*current = None;
|
||||
}
|
||||
}
|
||||
|
||||
enum KnowledgeCredential {
|
||||
Automatic(String),
|
||||
Manual,
|
||||
}
|
||||
|
||||
fn automatic_credential() -> R<KnowledgeCredential> {
|
||||
let account = ACCOUNT.lock().map_err(|_| PORTAL_UNAVAILABLE)?.clone().ok_or(PORTAL_LOGIN)?;
|
||||
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()));
|
||||
}
|
||||
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),
|
||||
401 => return Err(PORTAL_LOGIN.into()),
|
||||
403 => return Err(PORTAL_FORBIDDEN.into()),
|
||||
200 => {}
|
||||
_ => return Err(PORTAL_UNAVAILABLE.into()),
|
||||
}
|
||||
let token = value["token"].as_str().filter(|token| token.starts_with(TOKEN_PREFIX))
|
||||
.ok_or(AUTOMATIC_INVALID)?;
|
||||
let expiry = value["expiresAt"].as_str()
|
||||
.and_then(|expiry| chrono::DateTime::parse_from_rfc3339(expiry).ok())
|
||||
.ok_or(AUTOMATIC_INVALID)?;
|
||||
let remaining = expiry.timestamp() - chrono::Utc::now().timestamp();
|
||||
if remaining <= 5 { return Err(AUTOMATIC_INVALID.into()); }
|
||||
let token = normalize_key(token)?;
|
||||
// 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))
|
||||
}
|
||||
|
||||
fn verify_automatic_key(key: &str) -> Value {
|
||||
let mut result = match origins() {
|
||||
Ok(endpoints) => verify_xiaoyi_key(key, &endpoints, || Ok(false)),
|
||||
Err(_) => json!({"status":null,"saved":false,"error":INVALID}),
|
||||
};
|
||||
match result["status"].as_u64() {
|
||||
Some(401) => result["error"] = json!("知识库自动授权已失效,请重新登录素材库。"),
|
||||
Some(403) => result["error"] = json!("知识库拒绝了自动授权,请联系管理员。"),
|
||||
_ => {}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn automatic_status() -> Value {
|
||||
match automatic_credential() {
|
||||
Ok(KnowledgeCredential::Automatic(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}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn configure_for_account(input: &Value) -> Value {
|
||||
if input["key"].as_str().is_some_and(|key| !key.trim().is_empty()) {
|
||||
let mut result = configure_xiaoyi(input);
|
||||
result["mode"] = json!("manual");
|
||||
return result;
|
||||
}
|
||||
match automatic_credential() {
|
||||
Ok(KnowledgeCredential::Automatic(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}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn allows_xiaoyi_origin(origin: &str) -> bool {
|
||||
let Ok(url) = reqwest::Url::parse(origin) else { return false; };
|
||||
match (url.scheme(), url.host_str()) {
|
||||
@ -275,7 +416,7 @@ pub(super) fn exchange(input: &Value, mut emit: impl FnMut(Value) -> R<()>) -> R
|
||||
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);
|
||||
}
|
||||
exchange_route(route, input, credential, xiaoyi_credential, &mut emit)
|
||||
exchange_route(route, input, credential, automatic_or_manual_key, &mut emit)
|
||||
})();
|
||||
emit_error(result, &mut emit)
|
||||
}
|
||||
@ -285,6 +426,10 @@ fn emit_error(result: R<()>, emit: &mut impl FnMut(Value) -> R<()>) -> R<()> {
|
||||
let (category, message) = match error.as_str() {
|
||||
NETWORK => ("network", NETWORK),
|
||||
CREDENTIAL => ("credential", CREDENTIAL),
|
||||
PORTAL_LOGIN => ("credential", PORTAL_LOGIN),
|
||||
PORTAL_FORBIDDEN => ("credential", PORTAL_FORBIDDEN),
|
||||
PORTAL_UNAVAILABLE => ("network", PORTAL_UNAVAILABLE),
|
||||
AUTOMATIC_INVALID => ("credential", AUTOMATIC_INVALID),
|
||||
INVALID => ("boundary", INVALID),
|
||||
_ => ("response", RESPONSE),
|
||||
};
|
||||
@ -329,6 +474,13 @@ fn exchange_route(
|
||||
send(request, key.as_deref(), emit)
|
||||
}
|
||||
|
||||
fn automatic_or_manual_key() -> R<String> {
|
||||
match automatic_credential()? {
|
||||
KnowledgeCredential::Automatic(key) => Ok(key),
|
||||
KnowledgeCredential::Manual => xiaoyi_credential(),
|
||||
}
|
||||
}
|
||||
|
||||
fn xiaoyi_credential() -> R<String> {
|
||||
let key = super::vault(XIAOYI_CREDENTIAL_NAME).map_err(|_| CREDENTIAL)?
|
||||
.get_password().map_err(|_| CREDENTIAL)?;
|
||||
@ -339,13 +491,11 @@ fn xiaoyi_credential() -> R<String> {
|
||||
// workers inherit a loopback port used to relay the existing response frames.
|
||||
pub(super) fn configure_daemon(command: &mut Command) -> R<()> {
|
||||
static PORT: OnceLock<R<u16>> = OnceLock::new();
|
||||
let port = if let Some(key) = std::env::var_os(XIAOYI_OVERRIDE) {
|
||||
let port = PORT.get_or_init(|| start_override_bridge(key)).as_ref().map_err(Clone::clone)?;
|
||||
Some(*port)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
set_daemon_bridge(command, port);
|
||||
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));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -356,6 +506,37 @@ fn set_daemon_bridge(command: &mut Command, port: Option<u16>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn start_account_bridge() -> R<u16> {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|_| NETWORK)?;
|
||||
let port = listener.local_addr().map_err(|_| NETWORK)?.port();
|
||||
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<u16> {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|_| NETWORK)?;
|
||||
let port = listener.local_addr().map_err(|_| NETWORK)?.port();
|
||||
@ -469,6 +650,37 @@ mod tests {
|
||||
(origin, server)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jiansun_automatic_knowledge_is_scoped_to_current_login() {
|
||||
const TOKEN: &str = "ekb_xiaoyi_session_test-signature";
|
||||
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"));
|
||||
let expiry = (chrono::Utc::now() + chrono::Duration::seconds(300)).to_rfc3339();
|
||||
let body = json!({"token":TOKEN,"expiresAt":expiry}).to_string();
|
||||
write!(stream, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{body}", body.len()).unwrap();
|
||||
});
|
||||
let access = super::super::AccountAccess::default();
|
||||
let client = Client::builder().no_proxy().timeout(Duration::from_secs(5)).build().unwrap();
|
||||
let account = Account {
|
||||
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));
|
||||
server.join().unwrap();
|
||||
assert!(matches!(automatic_credential(), Ok(KnowledgeCredential::Automatic(token)) if token == TOKEN));
|
||||
access.invalidate();
|
||||
assert!(matches!(automatic_credential(), Err(error) if error == PORTAL_LOGIN));
|
||||
*ACCOUNT.lock().unwrap() = None;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jiansun_xiaoyi_override_reaches_current_and_stays_out_of_node_environment() {
|
||||
const KEY: &str = "synthetic-xiaoyi-override";
|
||||
|
||||
@ -28,7 +28,9 @@ impl Artifact {
|
||||
fn file_info(&self) -> Value {
|
||||
let mut file = json!({"fileName":self.name,"fileSize":self.size,"sha256":self.sha256});
|
||||
if let Some((code, barcode)) = &self.sku {
|
||||
file["skuCode"] = json!(code);
|
||||
if !code.is_empty() {
|
||||
file["skuCode"] = json!(code);
|
||||
}
|
||||
file["barcode"] = json!(barcode);
|
||||
}
|
||||
file
|
||||
@ -377,6 +379,44 @@ fn bind_sku_files(artifacts: &[Artifact], brief: &Value, variants: &[Value], cat
|
||||
}
|
||||
mappings.insert(id, bindings);
|
||||
}
|
||||
expand_barcode_files(artifacts, &mappings)
|
||||
}
|
||||
|
||||
fn bind_project_barcodes(artifacts: &[Artifact], bindings: &Value, variants: &[Value]) -> R<Vec<Artifact>> {
|
||||
let mut mappings = HashMap::new();
|
||||
let mut barcode_variants = HashMap::new();
|
||||
for variant in variants {
|
||||
let id = variant["id"].as_str().ok_or("成品花色缺少编号")?;
|
||||
if !artifacts.iter().any(|file| file.sku_variant.as_deref() == Some(id)) {
|
||||
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'_')) {
|
||||
return Err(format!("「{name}」的条码 {barcode} 格式有误,请核对后再完结"));
|
||||
}
|
||||
if barcode_variants.insert(barcode.to_ascii_lowercase(), id).is_some() {
|
||||
return Err(format!("条码 {barcode} 同时填在多个花色,请核对产品资料"));
|
||||
}
|
||||
barcodes.push((String::new(), barcode.to_owned()));
|
||||
}
|
||||
if barcodes.is_empty() {
|
||||
return Err(format!("请在产品资料中填写「{name}」的条码"));
|
||||
}
|
||||
mappings.insert(id, barcodes);
|
||||
}
|
||||
expand_barcode_files(artifacts, &mappings)
|
||||
}
|
||||
|
||||
fn expand_barcode_files(artifacts: &[Artifact], mappings: &HashMap<&str, Vec<(String, String)>>) -> R<Vec<Artifact>> {
|
||||
let mut files = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for artifact in artifacts {
|
||||
@ -395,7 +435,7 @@ fn bind_sku_files(artifacts: &[Artifact], brief: &Value, variants: &[Value], cat
|
||||
}
|
||||
}
|
||||
if seen.len() > 200 || files.len() > 500 {
|
||||
return Err("按条码展开后超过交付文件数量上限,请核对需要的 SKU".into());
|
||||
return Err("按条码展开后超过交付文件数量上限,请核对需要的条码".into());
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
@ -404,6 +444,15 @@ impl Backend {
|
||||
pub(super) fn bind_sku_delivery(&self, project: &Path, artifacts: &[Artifact]) -> R<(String, Vec<Artifact>)> {
|
||||
let creation = creation::load(project)?;
|
||||
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)
|
||||
.ok_or("请在产品资料中填写有效的 SPU 型号")?;
|
||||
return Ok((model.to_owned(), bind_project_barcodes(artifacts, bindings, 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 或条码")?;
|
||||
let lookup = |kind: &str, value: &str| {
|
||||
@ -432,8 +481,6 @@ impl Backend {
|
||||
if !catalog.iter().any(|item| item["barcodes"].is_array()) {
|
||||
return Err("素材库未返回 SKU 条码关系,请核对商品或更新素材库服务".into());
|
||||
}
|
||||
let state = canvas_workspace::load(project)?;
|
||||
let variants = state["variants"].as_array().ok_or("项目花色列表无效")?;
|
||||
let mut brief = brief.clone();
|
||||
brief["identifierType"] = json!(kind);
|
||||
Ok((spu.to_owned(), bind_sku_files(artifacts, &brief, variants, catalog)?))
|
||||
@ -602,6 +649,29 @@ impl Backend {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn project_barcodes_deliver_each_selected_identity_without_sku_numbers() {
|
||||
let image = Artifact {
|
||||
path: PathBuf::from("款式图.jpg"),
|
||||
name: "款式图.jpg".into(), group: "sku", size: 12, sha256: "checksum".into(),
|
||||
width: 900, height: 900, sku_variant: Some("white".into()), sku: None,
|
||||
};
|
||||
let variants = [json!({"id":"white","name":"白色"}), json!({"id":"black","name":"黑色"})];
|
||||
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"}),
|
||||
&variants,
|
||||
).unwrap();
|
||||
assert_eq!(files.iter().map(|file| file.name.as_str()).collect::<Vec<_>>(),
|
||||
["00123456.jpg", "00123457.jpg", "00234567.jpg"]);
|
||||
assert_eq!(files[0].path, image.path);
|
||||
assert_eq!(files[0].file_info()["barcode"], "00123456");
|
||||
assert!(files[0].file_info().get("skuCode").is_none());
|
||||
assert!(bind_project_barcodes(&[image, black], &json!({"white":"00123456","black":"00123456"}), &variants)
|
||||
.unwrap_err().contains("多个花色"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sku_delivery_expands_registered_barcodes_without_renaming_local_files() {
|
||||
let variants = [
|
||||
|
||||
@ -148,6 +148,11 @@ fn knowledge_rule(b:&Backend,doc:u64,production:bool) -> R<Option<(Option<Value>
|
||||
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":"请先选择知识库品类与模板"}))));
|
||||
}
|
||||
@ -363,6 +368,11 @@ fn project_evidence(c: &Value, scope: &str, project: &str, doc: u64, current_var
|
||||
.filter_map(|key| c["brief"].get(key).map(|value| (key.to_owned(), value.clone())))
|
||||
.collect();
|
||||
let mut brief = brief;
|
||||
for field in ["intake", "barcodeBindings", "deliverySpu"] {
|
||||
if let Some(value) = c["brief"].get(field) {
|
||||
brief.insert(field.to_owned(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(selection) = c["brief"].get("outputVariantIds") {
|
||||
brief.insert("outputVariantIds".into(), selection.clone());
|
||||
}
|
||||
|
||||
@ -171,7 +171,11 @@ impl Backend {
|
||||
pub(super) fn resource_template_choice(&self, pack: &mut Value, input: &Value) -> R<Value> {
|
||||
pack["contentHash"] = json!(template_slots::pack_hash(pack)?);
|
||||
matching_pack(pack, input["brandId"].as_str().ok_or("品牌缺失")?, input["categoryId"].as_str().ok_or("品类缺失")?)?;
|
||||
Ok(json!({"id":pack["id"],"name":pack["name"],"version":pack["version"],"contentHash":pack["contentHash"],"brandId":pack["brandId"],"categoryId":pack["categoryId"],"enterprise":pack["enterprise"],"width":pack["outputs"][0]["width"]}))
|
||||
let mut choice = json!({"id":pack["id"],"name":pack["name"],"version":pack["version"],"contentHash":pack["contentHash"],"brandId":pack["brandId"],"categoryId":pack["categoryId"],"enterprise":pack["enterprise"],"width":pack["outputs"][0]["width"]});
|
||||
if let Some(intake) = pack["xiaoyi"].get("intake") {
|
||||
choice["intake"] = intake.clone();
|
||||
}
|
||||
Ok(choice)
|
||||
}
|
||||
pub(super) fn selected_template_pack(&self, selected: &Value, brand: &str, category: &str) -> R<Value> {
|
||||
if !selected["enterprise"].is_object() { return self.template_pack(brand, category, false); }
|
||||
|
||||
@ -1 +1 @@
|
||||
1.2612.102
|
||||
1.2612.103
|
||||
|
||||
@ -1007,6 +1007,7 @@ pub struct Workspace {
|
||||
knowledge_key: String,
|
||||
xiaoyi_key: String,
|
||||
xiaoyi_key_saved: bool,
|
||||
xiaoyi_knowledge_mode: String,
|
||||
xiaoyi_key_check: Option<Result<(), String>>,
|
||||
knowledge_origin: String,
|
||||
knowledge_key_saved: bool,
|
||||
@ -1556,6 +1557,7 @@ impl Workspace {
|
||||
knowledge_key: String::new(),
|
||||
xiaoyi_key: String::new(),
|
||||
xiaoyi_key_saved: false,
|
||||
xiaoyi_knowledge_mode: "unavailable".into(),
|
||||
xiaoyi_key_check: None,
|
||||
knowledge_origin: String::new(),
|
||||
knowledge_key_saved: false,
|
||||
@ -2743,6 +2745,8 @@ impl Workspace {
|
||||
}
|
||||
if scope_changed {
|
||||
self.creation_reads_tick(app);
|
||||
self.xiaoyi_knowledge_mode = "unavailable".into();
|
||||
self.xiaoyi_key_check = None;
|
||||
}
|
||||
self.login_origin = None;
|
||||
self.projects = v["projects"].as_array().cloned().unwrap_or_default();
|
||||
@ -2757,6 +2761,12 @@ impl Workspace {
|
||||
}
|
||||
self.knowledge_key_saved = v["knowledgeKeySaved"] == true;
|
||||
self.xiaoyi_key_saved = v["xiaoyiKeySaved"] == true;
|
||||
if let Some(mode @ ("automatic" | "manual" | "unavailable")) = v["xiaoyiKnowledgeMode"].as_str() {
|
||||
self.xiaoyi_knowledge_mode = mode.to_owned();
|
||||
if let Some(error) = v["xiaoyiKnowledgeError"].as_str() {
|
||||
self.xiaoyi_key_check = if error.is_empty() { None } else { Some(Err(error.to_owned())) };
|
||||
}
|
||||
}
|
||||
self.connection_received(&v);
|
||||
self.error = v["message"].as_str().unwrap_or("").into();
|
||||
if self.error == self.library_message { self.error.clear(); }
|
||||
@ -3310,6 +3320,9 @@ impl Workspace {
|
||||
"project-delete" => self.project_deleted(app, &v),
|
||||
"select-model" => self.receive_model_preference(&v),
|
||||
"configure-xiaoyi-knowledge" => {
|
||||
if let Some(mode @ ("automatic" | "manual" | "unavailable")) = v["mode"].as_str() {
|
||||
self.xiaoyi_knowledge_mode = mode.to_owned();
|
||||
}
|
||||
self.xiaoyi_key_saved |= v["saved"] == true;
|
||||
self.xiaoyi_key_check = Some(v["error"].as_str().map_or(Ok(()), |error| Err(error.to_owned())));
|
||||
}
|
||||
@ -4774,6 +4787,11 @@ pub(crate) fn navigation(app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
app.jiansun = Some(workspace);
|
||||
}
|
||||
}
|
||||
pub(crate) fn product_form_open(app: &PhotocraftApp) -> bool {
|
||||
app.jiansun.as_ref().is_some_and(|w| w.creation_open && w.creation_step == 0 && !w.material && !w.library)
|
||||
&& app.session.active().is_some()
|
||||
}
|
||||
|
||||
pub fn center(app: &mut PhotocraftApp, ui: &mut Ui) -> bool {
|
||||
let Some(mut w) = app.jiansun.take() else {
|
||||
return false;
|
||||
|
||||
@ -3603,59 +3603,54 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
fn knowledge_settings(&mut self, ui: &mut Ui) {
|
||||
fn xiaoyi_key_input(&mut self, ui: &mut Ui) {
|
||||
use super::stitch_ui::{self, ButtonRole};
|
||||
use crate::theme::agent_scale::{space, Type};
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.label(RichText::new("企业知识库").size(Type::Title.size()).color(t.text));
|
||||
ui.label(RichText::new("Key 通过校验后保存在本机的 Windows 凭据管理器。").size(Type::Meta.size()).color(t.text_dim));
|
||||
ui.add_space(space::XS);
|
||||
ui.label(RichText::new("制作 Key(开工必需)").size(Type::Title.size()).color(t.text));
|
||||
ui.label(RichText::new("用于读取小壹制作模板和规则,由知识库管理员发放。").size(Type::Meta.size()).color(t.text_dim));
|
||||
let xiaoyi_busy = self.busy.as_deref() == Some("configure-xiaoyi-knowledge");
|
||||
knowledge_connection_status(ui, self.xiaoyi_key_saved, self.xiaoyi_key_check.as_ref(), xiaoyi_busy);
|
||||
ui.add_enabled_ui(self.busy.is_none(), |ui| {
|
||||
let id = ui.make_persistent_id("xiaoyi-knowledge-key");
|
||||
let hint = if self.xiaoyi_key_saved { "输入新的制作 Key" } else { "输入制作 Key" };
|
||||
stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add(
|
||||
stitch_ui::text_input(&mut self.xiaoyi_key, hint, false)
|
||||
.id(id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE),
|
||||
));
|
||||
let replacing = !self.xiaoyi_key.trim().is_empty();
|
||||
let label = if self.xiaoyi_key_saved && !replacing { "检测制作连接" } else { "校验并保存制作 Key" };
|
||||
if stitch_ui::action_button(ui, label, ButtonRole::Secondary, replacing || self.xiaoyi_key_saved).clicked() {
|
||||
let key = std::mem::take(&mut self.xiaoyi_key);
|
||||
self.send("configure-xiaoyi-knowledge", json!({"key":key}));
|
||||
}
|
||||
});
|
||||
let id = ui.make_persistent_id("xiaoyi-knowledge-key");
|
||||
let hint = if self.xiaoyi_key_saved { "输入新的制作 Key" } else { "输入制作 Key" };
|
||||
stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add(
|
||||
stitch_ui::text_input(&mut self.xiaoyi_key, hint, false)
|
||||
.id(id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE),
|
||||
));
|
||||
if stitch_ui::action_button(ui, "校验并保存", ButtonRole::Secondary, !self.xiaoyi_key.trim().is_empty()).clicked() {
|
||||
let key = std::mem::take(&mut self.xiaoyi_key);
|
||||
self.send("configure-xiaoyi-knowledge", json!({"key":key}));
|
||||
}
|
||||
}
|
||||
|
||||
ui.add_space(space::SM);
|
||||
let advanced_id = ui.make_persistent_id("knowledge-advanced");
|
||||
stitch_ui::disclosure(ui, advanced_id, "高级设置", false, self.reduce_motion, |ui| {
|
||||
ui.label(RichText::new("通用知识库 Key").size(Type::Title.size()).color(t.text));
|
||||
ui.label(RichText::new("用于通用知识库查询。制作项目只需上方的制作 Key。").size(Type::Meta.size()).color(t.text_dim));
|
||||
let knowledge_busy = self.busy.as_deref() == Some("configure-knowledge");
|
||||
knowledge_connection_status(ui, self.knowledge_key_saved, self.knowledge_key_check.as_ref(), knowledge_busy);
|
||||
ui.add_enabled_ui(self.busy.is_none(), |ui| {
|
||||
let id = ui.make_persistent_id("knowledge-key");
|
||||
let hint = if self.knowledge_key_saved { "输入新的通用 Key" } else { "输入通用 Key" };
|
||||
stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add(
|
||||
stitch_ui::text_input(&mut self.knowledge_key, hint, false)
|
||||
.id(id).password(true).desired_width(f32::INFINITY).frame(Frame::NONE),
|
||||
));
|
||||
ui.label(RichText::new("内网入口").size(Type::Meta.size()).color(t.text_dim));
|
||||
let id = ui.make_persistent_id("knowledge-origin");
|
||||
stitch_ui::halo_field(ui, id.with("field"), None, self.reduce_motion, |ui| ui.add(
|
||||
stitch_ui::text_input(&mut self.knowledge_origin, "使用默认地址", false)
|
||||
.id(id).desired_width(f32::INFINITY).frame(Frame::NONE),
|
||||
));
|
||||
if stitch_ui::action_button(ui, "校验并保存通用连接", ButtonRole::Quiet,
|
||||
!self.knowledge_key.trim().is_empty() || self.knowledge_key_saved).clicked()
|
||||
{
|
||||
let key = std::mem::take(&mut self.knowledge_key);
|
||||
self.send("configure-knowledge", json!({"key":key,"origin":self.knowledge_origin}));
|
||||
fn knowledge_settings(&mut self, ui: &mut Ui) {
|
||||
use super::stitch_ui::{self, ButtonRole, StatusTone, status_label};
|
||||
use crate::theme::agent_scale::Type;
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
ui.label(RichText::new("小壹知识库").size(Type::Title.size()).color(t.text));
|
||||
let checking = self.busy.as_deref() == Some("configure-xiaoyi-knowledge");
|
||||
if self.xiaoyi_knowledge_mode == "manual" {
|
||||
knowledge_connection_status(ui, self.xiaoyi_key_saved, self.xiaoyi_key_check.as_ref(), checking);
|
||||
} else {
|
||||
let (status, tone) = match (checking, self.xiaoyi_key_check.as_ref(), self.xiaoyi_knowledge_mode.as_str()) {
|
||||
(true, _, _) => ("正在连接", StatusTone::Neutral),
|
||||
(false, Some(Err(_)), _) => ("连接失败", StatusTone::Error),
|
||||
(false, _, "automatic") => ("素材库自动连接", StatusTone::Neutral),
|
||||
_ => ("等待连接", StatusTone::Neutral),
|
||||
};
|
||||
status_label(ui, status, tone);
|
||||
if let Some(Err(error)) = self.xiaoyi_key_check.as_ref().filter(|_| !checking) {
|
||||
status_label(ui, error, StatusTone::Error);
|
||||
}
|
||||
}
|
||||
ui.add_enabled_ui(self.busy.is_none(), |ui| {
|
||||
if self.xiaoyi_knowledge_mode == "manual" && !self.xiaoyi_key_saved {
|
||||
self.xiaoyi_key_input(ui);
|
||||
} else {
|
||||
if stitch_ui::action_button(ui, "检测连接", ButtonRole::Secondary, true).clicked() {
|
||||
self.send("configure-xiaoyi-knowledge", json!({"key":""}));
|
||||
}
|
||||
});
|
||||
if self.xiaoyi_knowledge_mode == "manual" {
|
||||
let id = ui.make_persistent_id("replace-xiaoyi-knowledge-key");
|
||||
stitch_ui::disclosure(ui, id, "更换制作 Key", false, self.reduce_motion, |ui| {
|
||||
self.xiaoyi_key_input(ui);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -97,36 +97,47 @@ fn structure_preview_card(ui: &mut Ui, preview: &Value, name: &str, version: &st
|
||||
});
|
||||
}
|
||||
|
||||
/// Route an OS drop only when the last painted, clipped reference target still
|
||||
/// belongs to the active account and document. Everything else retains native
|
||||
/// PhotoCraft drop behavior. The user-supplied paths use the same bounded
|
||||
/// backend import as the file picker; no file bytes are read on the UI thread.
|
||||
fn drop_contains(value: &Value, point: egui::Pos2) -> bool {
|
||||
let Some(values) = value.as_array()
|
||||
.filter(|rect| rect.len() == 4)
|
||||
.and_then(|rect| rect.iter().map(Value::as_f64).collect::<Option<Vec<_>>>()) else { return false };
|
||||
values.iter().all(|value| value.is_finite()) && values[2] > 0.0 && values[3] > 0.0
|
||||
&& egui::Rect::from_min_size(
|
||||
egui::pos2(values[0] as f32, values[1] as f32),
|
||||
vec2(values[2] as f32, values[3] as f32),
|
||||
).contains(point)
|
||||
}
|
||||
|
||||
fn reference_image_path(path: &std::path::Path) -> bool {
|
||||
path.extension().and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ["png", "jpg", "jpeg", "webp"].iter().any(|allowed| ext.eq_ignore_ascii_case(allowed)))
|
||||
}
|
||||
|
||||
/// Keep product reference drops in the current document and use the same bounded import as the picker.
|
||||
impl PhotocraftApp {
|
||||
pub(crate) fn creation_reference_drop(
|
||||
&mut self, ctx: &egui::Context, files: &[egui::DroppedFileHandle], at: Option<egui::Pos2>,
|
||||
) -> bool {
|
||||
let Some(at) = at else { return false };
|
||||
if !self.ui.dialogs.is_empty() || ctx.layer_id_at(at).is_some_and(|layer| layer.order != egui::Order::Background) {
|
||||
if !self.ui.dialogs.is_empty() || !super::product_form_open(self) {
|
||||
return false;
|
||||
}
|
||||
let Some(w) = self.jiansun.as_ref() else { return false };
|
||||
let Some(doc) = self.session.active().map(|state| state.doc.id.0) else { return false };
|
||||
let target = &w.creation_view_geometry["referenceDrop"];
|
||||
if !w.creation_open || w.creation_step != 0 || w.library || w.material || w.creation_doc != Some(doc)
|
||||
|| target["doc"].as_u64() != Some(doc) || target["accountId"] != w.account["id"] || target["origin"] != w.origin
|
||||
{
|
||||
let on_reference = target["doc"].as_u64() == Some(doc) && target["accountId"] == w.account["id"]
|
||||
&& target["origin"] == w.origin && drop_contains(&target["rect"], at)
|
||||
&& ctx.layer_id_at(at).is_none_or(|layer| layer.order == egui::Order::Background);
|
||||
if !on_reference {
|
||||
if drop_contains(&w.creation_view_geometry["product-form-viewport"], at)
|
||||
&& files.iter().any(|file| reference_image_path(file.path()))
|
||||
{
|
||||
if let Some(w) = self.jiansun.as_mut() { w.error = "请将图片拖到「产品参考图」区域".into(); }
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
let Some(rect) = target["rect"].as_array().filter(|rect| rect.len() == 4) else { return false };
|
||||
let Some(values) = rect.iter().map(Value::as_f64).collect::<Option<Vec<_>>>() else { return false };
|
||||
if values.iter().any(|value| !value.is_finite()) || values[2] <= 0.0 || values[3] <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(values[0] as f32, values[1] as f32), vec2(values[2] as f32, values[3] as f32));
|
||||
if !rect.contains(at) {
|
||||
return false;
|
||||
}
|
||||
let reject = if w.busy.is_some() {
|
||||
let reject = if w.creation_doc != Some(doc) || w.busy.is_some() {
|
||||
Some("请等待当前操作完成,再添加参考图")
|
||||
} else if w.unknown {
|
||||
Some("原请求结果待核查,请先核查后再添加参考图")
|
||||
@ -141,8 +152,7 @@ impl PhotocraftApp {
|
||||
}
|
||||
let paths = files.iter().map(|file| {
|
||||
let path = file.path();
|
||||
let valid = path.is_absolute() && path.extension().and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| ["png", "jpg", "jpeg", "webp"].iter().any(|allowed| ext.eq_ignore_ascii_case(allowed)));
|
||||
let valid = path.is_absolute() && reference_image_path(path);
|
||||
valid.then(|| path.to_str().map(str::to_owned)).flatten()
|
||||
}).collect::<Option<Vec<_>>>();
|
||||
let Some(paths) = paths else {
|
||||
@ -276,7 +286,7 @@ fn material_thumbnail(ui: &mut Ui, texture: Option<&egui::TextureHandle>, loadin
|
||||
}
|
||||
|
||||
pub(super) fn empty_brief() -> Value {
|
||||
json!({"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","variants":[],"templateSelection":null,"dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""})
|
||||
json!({"source":"upload","name":"","brandId":"","brandName":"","categoryId":"","categoryName":"","identifierType":"spu","identifier":"","barcodeBindings":{},"variant":"","colorMaterialId":"","colorName":"","variants":[],"templateSelection":null,"dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""})
|
||||
}
|
||||
|
||||
fn variant_identity(material: &str) -> String {
|
||||
@ -446,6 +456,50 @@ fn field_group<R>(ui: &mut Ui, width: f32, label: &str, contents: impl FnOnce(&m
|
||||
})
|
||||
}
|
||||
|
||||
fn intake_fields(ui: &mut Ui, scope: egui::Id, width: f32, schema: &Value, values: &mut Value, reduced: bool) -> bool {
|
||||
let mut changed = false;
|
||||
for field in schema.as_array().into_iter().flatten() {
|
||||
let Some(id) = field["id"].as_str() else { continue };
|
||||
let Some(name) = field["label"].as_str() else { continue };
|
||||
let label = format!("{}{}{}", name,
|
||||
field["unit"].as_str().map(|unit| format!("({unit})")).unwrap_or_default(),
|
||||
if field["required"] == true { " *" } else { "" });
|
||||
field_group(ui, width, &label, |ui| {
|
||||
match field["type"].as_str() {
|
||||
Some("text" | "number") => {
|
||||
let hint = if field["type"] == "number" { "输入数字" } else { "输入内容" };
|
||||
changed |= edit_named(ui, scope.with(id), &mut values[id], width, false, hint, &label);
|
||||
}
|
||||
Some("select") => {
|
||||
let selected = values[id].as_str().unwrap_or("请选择").to_owned();
|
||||
let response = stitch_ui::halo_select(ui, scope.with(id), width, &selected, reduced, |ui| {
|
||||
for option in field["options"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
if stitch_ui::select_option(ui, option, values[id] == option, true).clicked() {
|
||||
values[id] = json!(option);
|
||||
changed = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
response.response.on_hover_text(&label);
|
||||
}
|
||||
Some("boolean") => {
|
||||
let mut value = values[id].as_bool().unwrap_or(false);
|
||||
if ui.checkbox(&mut value, name).changed() {
|
||||
values[id] = json!(value);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(help) = field["help"].as_str().filter(|help| !help.is_empty()) {
|
||||
ui.weak(help);
|
||||
}
|
||||
});
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn help_icon(ui: &mut Ui, text: &str) -> egui::Response {
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click());
|
||||
let color = Tokens::get(ui.ctx()).agent().text_dim;
|
||||
@ -575,7 +629,7 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val
|
||||
let template_binding = w.template_binding(app.session.active().map(|state| state.doc.id.0));
|
||||
w.template_ui.bind_project(&template_binding);
|
||||
w.creation_read_failed = false;
|
||||
if !w.creation_dirty || !matches!(method, "creation-read" | "creation-import" | "creation-rules") {
|
||||
if !w.creation_dirty || !matches!(method, "creation-read" | "creation-import" | "creation-import-data" | "creation-import-library" | "creation-rules") {
|
||||
w.creation_brief = w.creation["brief"].clone();
|
||||
w.creation_dirty = false;
|
||||
w.creation_selected =
|
||||
@ -1200,7 +1254,7 @@ impl Workspace {
|
||||
}
|
||||
return;
|
||||
}
|
||||
egui::ScrollArea::vertical().id_salt("creation-body").show(ui, |ui| {
|
||||
let scrolled = egui::ScrollArea::vertical().id_salt("creation-body").show(ui, |ui| {
|
||||
let max_width = if self.creation_step == 0 { 900.0 } else { 840.0 };
|
||||
let width = ui.available_width().min(max_width);
|
||||
let inset = ((ui.available_width() - width) * 0.5).max(0.0);
|
||||
@ -1227,6 +1281,9 @@ impl Workspace {
|
||||
});
|
||||
});
|
||||
});
|
||||
if self.creation_step == 0 {
|
||||
self.control_geometry("product-form-viewport", scrolled.inner_rect.intersect(ui.clip_rect()));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -1294,7 +1351,7 @@ impl Workspace {
|
||||
ui.add_space(10.0);
|
||||
let columns = brief_columns(width).min(2);
|
||||
let field_width = ((width - 14.0 * (columns - 1) as f32) / columns as f32).max(130.0);
|
||||
let labels = ["产品名称 *", "产品尺寸(长 × 宽 × 高)", "产品编号与类型", "画幅导出规格"];
|
||||
let labels = ["产品名称 *", "产品尺寸(长 × 宽 × 高)", "SPU 型号", "画幅导出规格"];
|
||||
egui::Grid::new("creation-brief").num_columns(columns).spacing(vec2(14.0, 12.0)).show(ui, |ui| {
|
||||
for (index, label) in labels.iter().enumerate() {
|
||||
field_group(ui, field_width, label, |ui| match index {
|
||||
@ -1338,23 +1395,21 @@ impl Workspace {
|
||||
self.control_geometry("dimensions", dimensions.response.rect);
|
||||
}
|
||||
2 => {
|
||||
let identifier = ui.horizontal(|ui| {
|
||||
let kind = self.creation_brief["identifierType"].as_str().unwrap_or("sku");
|
||||
let label = if kind == "barcode" { "条码".into() } else { kind.to_uppercase() };
|
||||
let select = stitch_ui::halo_select(ui, "creation-id-kind", 74.0, &label, self.reduce_motion, |ui| {
|
||||
for (value, label) in [("sku", "SKU"), ("spu", "SPU"), ("barcode", "条码")] {
|
||||
let option = stitch_ui::select_option(ui, label, self.creation_brief["identifierType"] == value, true);
|
||||
self.control_geometry(&format!("identifier-option-{value}"), option.rect);
|
||||
if option.clicked() {
|
||||
self.creation_brief["identifierType"] = json!(value);
|
||||
self.creation_dirty = true;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
self.control_geometry("identifier-kind", select.response.rect);
|
||||
self.creation_dirty |= edit(ui, (field_scope, "identifier"), &mut self.creation_brief["identifier"], (field_width - 84.0).max(40.0), false, "产品编号");
|
||||
let is_spu = self.creation_brief["identifierType"] == "spu";
|
||||
let field = if is_spu { "identifier" } else { "deliverySpu" };
|
||||
let mut spu = self.creation_brief[field].clone();
|
||||
let identifier = ui.scope(|ui| {
|
||||
edit_named(ui, (field_scope, "identifier"), &mut spu, field_width, false, "输入 SPU 型号", "SPU 型号")
|
||||
});
|
||||
if identifier.inner {
|
||||
self.creation_brief[field] = spu;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
if !is_spu {
|
||||
if let Some(legacy) = self.creation_brief["identifier"].as_str().filter(|value| !value.is_empty()) {
|
||||
ui.weak(format!("原项目编号 {legacy}"));
|
||||
}
|
||||
}
|
||||
self.control_geometry("identifier", identifier.response.rect);
|
||||
}
|
||||
3 => {
|
||||
@ -1378,9 +1433,15 @@ impl Workspace {
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
field_group(ui, width, "补充资料 / 设计说明", |ui| {
|
||||
self.creation_dirty |= edit_hint(ui, (field_scope, "note"), &mut self.creation_brief["note"], width, true, "按行填写已核实的产品资料与设计说明");
|
||||
});
|
||||
let product_fields = self.creation_brief["intake"]["schema"]["productFields"].clone();
|
||||
if product_fields.is_array() {
|
||||
let mut values = self.creation_brief["intake"]["productValues"].clone();
|
||||
if !values.is_object() { values = json!({}); }
|
||||
if intake_fields(ui, field_scope.with("intake-product"), width, &product_fields, &mut values, self.reduce_motion) {
|
||||
self.creation_brief["intake"]["productValues"] = values;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
brief_section_break(ui);
|
||||
if width >= 600.0 {
|
||||
ui.horizontal_top(|ui| {
|
||||
@ -1390,13 +1451,13 @@ impl Workspace {
|
||||
let heading_width = (width - material_width - 20.0).max(100.0);
|
||||
let heading = ui.vertical(|ui| {
|
||||
ui.set_width(heading_width);
|
||||
section_heading(ui, "SKU 颜色", "先录入全部 SKU 颜色。产品图可共用,也可归属指定 SKU 颜色。");
|
||||
section_heading(ui, "产品花色", "添加花色后,可为同一花色录入多个条码。");
|
||||
});
|
||||
self.control_geometry("material-heading", heading.response.rect);
|
||||
self.material_select(app, ui, material_width);
|
||||
});
|
||||
} else {
|
||||
section_heading(ui, "SKU 颜色", "先录入全部 SKU 颜色。产品图可共用,也可归属指定 SKU 颜色。");
|
||||
section_heading(ui, "产品花色", "添加花色后,可为同一花色录入多个条码。");
|
||||
ui.add_space(6.0);
|
||||
self.material_select(app, ui, width.min(420.0));
|
||||
}
|
||||
@ -1406,18 +1467,107 @@ impl Workspace {
|
||||
if variants.is_empty() {
|
||||
variants.push(json!({"id":"default","name":"当前花色"}));
|
||||
}
|
||||
let barcode_fields = self.creation_brief["intake"]["schema"]["barcodeFields"].clone();
|
||||
for variant in variants {
|
||||
let Some(id) = variant["id"].as_str() else { continue };
|
||||
let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("当前花色");
|
||||
let label = format!("{name} · SKU 编号");
|
||||
let mut binding = self.creation_brief["skuBindings"][id].clone();
|
||||
if field_group(ui, width, &label, |ui| {
|
||||
edit_named(ui, field_scope.with(("delivery-skus", id)), &mut binding, width, false, "多个 SKU 用逗号分隔", &label)
|
||||
}).inner {
|
||||
self.creation_brief["skuBindings"][id] = binding;
|
||||
let label = if id == "default" { "条码".to_owned() } else { format!("{name} · 条码") };
|
||||
let binding = self.creation_brief["barcodeBindings"][id].as_str().unwrap_or_default();
|
||||
let mut barcodes: Vec<String> = binding.split(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ',' | '、'))
|
||||
.filter(|code| !code.is_empty()).map(str::to_owned).collect();
|
||||
let spu_field = if self.creation_brief["identifierType"] == "spu" { "identifier" } else { "deliverySpu" };
|
||||
let has_spu = self.creation_brief[spu_field].as_str().is_some_and(|value| !value.trim().is_empty());
|
||||
let draft_id = field_scope.with(("barcode-draft", id));
|
||||
let mut draft = ui.data(|data| data.get_temp::<Value>(draft_id)).unwrap_or(Value::Null);
|
||||
let mut changed = false;
|
||||
field_group(ui, width, &label, |ui| {
|
||||
ui.add_enabled_ui(has_spu, |ui| {
|
||||
let mut remove = None;
|
||||
for (index, barcode) in barcodes.iter().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
let text_width = (width - 44.0).max(40.0);
|
||||
ui.add_sized(vec2(text_width, 28.0), egui::Label::new(barcode).truncate()).on_hover_text(barcode);
|
||||
let button = stitch_ui::icon_button(ui, "x", 24.0, false, &format!("删除条码 {barcode}"));
|
||||
self.control_geometry(&format!("barcode-remove-{id}-{index}"), button.rect);
|
||||
if button.clicked() {
|
||||
remove = Some(index);
|
||||
}
|
||||
});
|
||||
if barcode_fields.is_array() {
|
||||
let mut values = self.creation_brief["intake"]["barcodeValues"][barcode.as_str()].clone();
|
||||
if !values.is_object() { values = json!({}); }
|
||||
if intake_fields(ui, field_scope.with(("intake-barcode", barcode)), width, &barcode_fields, &mut values, self.reduce_motion) {
|
||||
self.creation_brief["intake"]["barcodeValues"][barcode.as_str()] = values;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(index) = remove {
|
||||
let barcode = barcodes.remove(index);
|
||||
if let Some(values) = self.creation_brief.get_mut("intake")
|
||||
.and_then(|intake| intake.get_mut("barcodeValues"))
|
||||
.and_then(Value::as_object_mut)
|
||||
{
|
||||
values.remove(&barcode);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let hint = if has_spu { "输入条码" } else { "填写 SPU 后可录入条码" };
|
||||
let entry = ui.scope(|ui| {
|
||||
edit_named(ui, draft_id, &mut draft, (width - 86.0).max(40.0), false, hint, "新增条码")
|
||||
});
|
||||
self.control_geometry(&format!("barcode-input-{id}"), entry.response.rect);
|
||||
let text = draft.as_str().unwrap_or_default().trim();
|
||||
let valid = !text.is_empty() && text.len() <= 120
|
||||
&& text.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'));
|
||||
let duplicate = self.creation_brief["barcodeBindings"].as_object().into_iter().flatten()
|
||||
.filter_map(|(_, binding)| binding.as_str())
|
||||
.flat_map(|binding| binding.split(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ',' | '、')))
|
||||
.any(|code| !code.is_empty() && code.eq_ignore_ascii_case(text));
|
||||
let button = stitch_ui::action_button(ui, "添加条码", stitch_ui::ButtonRole::Secondary, valid && !duplicate)
|
||||
.on_disabled_hover_text(if duplicate { "此条码已录入当前项目" } else { "请输入条码" });
|
||||
self.control_geometry(&format!("barcode-add-{id}"), button.rect);
|
||||
if button.clicked() {
|
||||
barcodes.push(text.to_owned());
|
||||
draft = Value::Null;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.data_mut(|data| data.insert_temp(draft_id, draft));
|
||||
if changed {
|
||||
self.creation_brief["barcodeBindings"][id] = json!(barcodes.join("\n"));
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
if self.creation_brief.get("barcodeBindings").is_none() {
|
||||
stitch_ui::disclosure(ui, field_scope.with("legacy-sku-bindings"), "旧项目商品编号", false, self.reduce_motion, |ui| {
|
||||
let mut variants = brief_variants(&self.creation_brief);
|
||||
if variants.is_empty() {
|
||||
variants.push(json!({"id":"default","name":"当前花色"}));
|
||||
}
|
||||
for variant in variants {
|
||||
let Some(id) = variant["id"].as_str() else { continue };
|
||||
let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("当前花色");
|
||||
let label = format!("{name} · SKU 编号");
|
||||
let mut binding = self.creation_brief["skuBindings"][id].clone();
|
||||
if field_group(ui, width, &label, |ui| {
|
||||
edit_named(ui, field_scope.with(("delivery-skus", id)), &mut binding, width, false, "多个 SKU 用逗号分隔", &label)
|
||||
}).inner {
|
||||
self.creation_brief["skuBindings"][id] = binding;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
let has_note = self.creation_brief["note"].as_str().is_some_and(|note| !note.trim().is_empty());
|
||||
stitch_ui::disclosure(ui, field_scope.with("creation-note"), "补充产品资料或出图要求(选填)", has_note, self.reduce_motion, |ui| {
|
||||
self.creation_dirty |= edit_named(ui, (field_scope, "note"), &mut self.creation_brief["note"], ui.available_width(), true,
|
||||
"例如:台面为白蜡木;首屏突出可折叠;避免使用未经验证的承重数据", "补充产品资料或出图要求");
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
self.references_ui(app, ui, width);
|
||||
brief_section_break(ui);
|
||||
@ -1513,14 +1663,14 @@ impl Workspace {
|
||||
let add = ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = gap;
|
||||
let entry = ui.scope(|ui| {
|
||||
edit_named(ui, draft_id, &mut draft, width - add_width - gap, false, "输入 SKU 颜色", "新增 SKU 颜色")
|
||||
edit_named(ui, draft_id, &mut draft, width - add_width - gap, false, "输入花色", "新增花色")
|
||||
});
|
||||
self.control_geometry("sku-color-input", entry.response.rect);
|
||||
let color = draft.as_str().unwrap_or("").trim();
|
||||
let duplicate = variants.iter().any(|row| row["colorName"].as_str().is_some_and(|name| name.eq_ignore_ascii_case(color)));
|
||||
let enabled = !color.is_empty() && color.chars().count() <= 120 && !duplicate && variants.len() < 64;
|
||||
let button = stitch_ui::action_button(ui, "添加颜色", stitch_ui::ButtonRole::Secondary, enabled)
|
||||
.on_disabled_hover_text(if duplicate { "此 SKU 颜色已添加" } else { "请输入颜色名称,最多添加 64 个 SKU 颜色" });
|
||||
.on_disabled_hover_text(if duplicate { "此花色已添加" } else { "请输入颜色名称,最多添加 64 个花色" });
|
||||
self.control_geometry("sku-color-add", button.rect);
|
||||
button.clicked()
|
||||
}).inner;
|
||||
@ -1573,10 +1723,10 @@ impl Workspace {
|
||||
fn sku_output_picker(&mut self, ui: &mut Ui, width: f32, component: &str, variants: &[Value]) {
|
||||
let mut selected = self.creation_brief["outputVariantIds"][component].as_array().cloned().unwrap_or_default();
|
||||
let summary = match selected.as_slice() {
|
||||
[] if variants.is_empty() => "请先添加 SKU 颜色".into(),
|
||||
[] => format!("全部 {} 个 SKU 颜色", variants.len()),
|
||||
[] if variants.is_empty() => "请先添加花色".into(),
|
||||
[] => format!("全部 {} 个花色", variants.len()),
|
||||
[id] => variants.iter().find(|row| row["id"] == *id).and_then(|row| row["name"].as_str()).unwrap_or("已选 1 个颜色").to_owned(),
|
||||
ids => format!("已选 {} 个 SKU 颜色", ids.len()),
|
||||
ids => format!("已选 {} 个花色", ids.len()),
|
||||
};
|
||||
let picker_id = format!("sku-output-{component}");
|
||||
let mut changed = false;
|
||||
@ -1614,8 +1764,17 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn save_sku_colors(&mut self, variants: Vec<Value>) {
|
||||
if let Some(bindings) = self.creation_brief.get_mut("skuBindings").and_then(Value::as_object_mut) {
|
||||
bindings.retain(|id, _| id == "default" || variants.iter().any(|variant| variant["id"] == *id));
|
||||
for field in ["skuBindings", "barcodeBindings"] {
|
||||
if let Some(bindings) = self.creation_brief.get_mut(field).and_then(Value::as_object_mut) {
|
||||
if field == "barcodeBindings" && variants.len() == 1 {
|
||||
if let Some(default) = bindings.remove("default") {
|
||||
if let Some(id) = variants[0]["id"].as_str() {
|
||||
bindings.entry(id.to_owned()).or_insert(default);
|
||||
}
|
||||
}
|
||||
}
|
||||
bindings.retain(|id, _| id == "default" || variants.iter().any(|variant| variant["id"] == *id));
|
||||
}
|
||||
}
|
||||
set_brief_variants(&mut self.creation_brief, variants);
|
||||
if !self.creation_brief["outputVariantIds"].is_object() {
|
||||
@ -1694,8 +1853,6 @@ impl Workspace {
|
||||
let add_reference = stitch_ui::file_drop_zone(ui, egui::Id::unique("creation-reference-drop"), width, drop_pointer, enabled, self.reduce_motion)
|
||||
.on_hover_text("支持 PNG、JPG、WebP;每次最多 8 张,单张不超过 20 MB");
|
||||
self.control_geometry("reference-add", add_reference.rect);
|
||||
let visible = add_reference.rect.intersect(ui.clip_rect());
|
||||
self.creation_view_geometry["referenceDrop"] = json!({"doc":app.session.active().map(|s| s.doc.id.0),"accountId":self.account["id"],"origin":self.origin,"rect":rect_value(visible)});
|
||||
if enabled && add_reference.clicked() {
|
||||
let id = app.session.active().map(|s| s.doc.id.0);
|
||||
let account = self.account["id"].clone();
|
||||
@ -1777,19 +1934,22 @@ impl Workspace {
|
||||
let mut rows = image_rows(&self.creation_brief);
|
||||
let mut changed = false;
|
||||
let mut remove = None;
|
||||
ui.label(egui::RichText::new("产品参考图 *").size(13.0).color(t.text_dim));
|
||||
let title = ui.label(egui::RichText::new("产品参考图 *").size(13.0).color(t.text_dim));
|
||||
let mut target = title.rect;
|
||||
if rows.is_empty() {
|
||||
stitch_ui::material_frame(ui, stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Input).corner_radius(10).inner_margin(18), |ui| {
|
||||
let empty = stitch_ui::material_frame(ui, stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Input).corner_radius(10).inner_margin(18), |ui| {
|
||||
ui.set_width((width - 38.0).max(100.0));
|
||||
ui.label(egui::RichText::new("至少添加一张用途为「产品图」的参考图").size(14.0).color(t.text_dim));
|
||||
});
|
||||
self.control_geometry("reference-empty", empty.response.rect);
|
||||
target = target.union(empty.response.rect);
|
||||
} else if !rows.iter().any(|(image, _)| image["purpose"] == "product") {
|
||||
stitch_ui::status_label(ui, "请将至少一张参考图的用途设为「产品图」。", stitch_ui::StatusTone::Warning);
|
||||
}
|
||||
// Keep real purpose and ownership controls visible alongside each image.
|
||||
let columns = if width >= 780.0 { 3 } else if width >= 600.0 { 2 } else { 1 };
|
||||
let card_width = (width - 12.0 * (columns - 1) as f32) / columns as f32;
|
||||
egui::Grid::new("creation-references").num_columns(columns).spacing(vec2(12.0, 12.0)).show(ui, |ui| {
|
||||
let grid = egui::Grid::new("creation-references").num_columns(columns).spacing(vec2(12.0, 12.0)).show(ui, |ui| {
|
||||
for (index, (image, owner)) in rows.iter_mut().enumerate() {
|
||||
let source = image["source"].as_str().unwrap_or("").to_owned();
|
||||
let preview_key = super::creation_reads::reference_key(&source);
|
||||
@ -1914,6 +2074,10 @@ impl Workspace {
|
||||
}
|
||||
self.add_reference_button(app, ui, card_width - 2.0);
|
||||
});
|
||||
let visible = target.union(grid.response.rect).intersect(ui.clip_rect());
|
||||
self.creation_view_geometry["referenceDrop"] = json!({
|
||||
"doc":app.session.active().map(|state| state.doc.id.0),"accountId":self.account["id"],"origin":self.origin,"rect":rect_value(visible)
|
||||
});
|
||||
if let Some(label) = reference_import_activity(self.busy.as_deref()) {
|
||||
ui.add_space(8.0);
|
||||
let id = egui::Id::unique(("creation-reference-import", &self.origin, self.account["id"].as_str(), self.creation_doc));
|
||||
@ -1977,6 +2141,13 @@ impl Workspace {
|
||||
if active {
|
||||
continue;
|
||||
}
|
||||
if self.creation_brief["intake"]["templateId"] != row["id"] {
|
||||
self.creation_brief["intake"] = if row["intake"]["version"] == 1 {
|
||||
json!({"templateId":row["id"],"schema":row["intake"],"productValues":{},"barcodeValues":{}})
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
}
|
||||
self.creation_reads.resource_set = row.clone();
|
||||
self.creation_reads.resource_component.clear();
|
||||
self.creation_reads.resource_image = None;
|
||||
@ -2077,6 +2248,14 @@ impl Workspace {
|
||||
}
|
||||
if let Some(fields) = choice.as_object_mut() {
|
||||
fields.remove("width");
|
||||
if let Some(schema) = fields.remove("intake")
|
||||
&& schema["version"] == 1
|
||||
&& self.creation_brief["intake"]["templateId"] != fields["id"]
|
||||
{
|
||||
self.creation_brief["intake"] = json!({
|
||||
"templateId":fields["id"],"schema":schema,"productValues":{},"barcodeValues":{}
|
||||
});
|
||||
}
|
||||
}
|
||||
self.creation_brief["templateSelection"] = choice;
|
||||
self.creation_dirty = true;
|
||||
@ -2280,6 +2459,7 @@ impl Workspace {
|
||||
self.creation_brief["categoryName"] = json!("");
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); }
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.creation_catalog.remove("templates");
|
||||
self.creation_catalog.remove("categories");
|
||||
@ -2336,6 +2516,7 @@ impl Workspace {
|
||||
self.creation_brief["categoryName"] = row["name"].clone();
|
||||
self.agent_rule = Value::Null;
|
||||
self.agent_rule_state = Value::Null;
|
||||
if let Some(fields) = self.creation_brief.as_object_mut() { fields.remove("intake"); }
|
||||
self.creation_brief["templateSelection"] = Value::Null;
|
||||
self.creation_catalog.remove("templates");
|
||||
self.creation_dirty = true;
|
||||
@ -2461,11 +2642,13 @@ impl Workspace {
|
||||
);
|
||||
}
|
||||
fn product_search_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let search = stitch_ui::button(ui, "按产品编号查找", false);
|
||||
self.control_geometry("source-search", search.rect);
|
||||
let identifier = self.creation_brief["identifier"].as_str().unwrap_or_default();
|
||||
let label = if self.creation_brief["identifierType"] == "spu" { "按 SPU 查找" } else { "查找原项目产品" };
|
||||
let search = stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, !identifier.trim().is_empty());
|
||||
if search.clicked() {
|
||||
self.catalog(app, "products", self.creation_brief["identifier"].as_str().unwrap_or("").into());
|
||||
self.catalog(app, "products", identifier.to_owned());
|
||||
}
|
||||
self.control_geometry("source-search", search.rect);
|
||||
}
|
||||
fn product_select_results(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let rows = self.creation_catalog.get("products").cloned().unwrap_or_default();
|
||||
@ -3573,7 +3756,7 @@ mod tests {
|
||||
w.library = false;
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); }
|
||||
let at = control_rect(&w, "reference-add").center();
|
||||
let at = control_rect(&w, "reference-0").center();
|
||||
let before = w.creation_brief.clone();
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
app.jiansun = Some(w);
|
||||
@ -3588,6 +3771,50 @@ mod tests {
|
||||
assert!(requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_drop_accepts_the_empty_product_card() {
|
||||
let (mut w, mut app, requests) = brief_fixture();
|
||||
w.creation_open = true;
|
||||
w.library = false;
|
||||
w.creation_brief["images"] = json!([]);
|
||||
w.creation_brief["variants"] = json!([]);
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); }
|
||||
let at = control_rect(&w, "reference-empty").center();
|
||||
app.jiansun = Some(w);
|
||||
|
||||
app.open_dropped(&ctx, vec![reference_drop("D:\\photos\\oak.png")], Some(at));
|
||||
|
||||
assert!(matches!(requests.try_recv(), Ok(Request::Action(method, _)) if method == "creation-import"));
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn product_form_drop_outside_reference_cards_keeps_the_active_draft() {
|
||||
let (mut w, mut app, requests) = brief_fixture();
|
||||
w.creation_open = true;
|
||||
w.library = false;
|
||||
w.creation_brief["name"] = json!("已填写产品名称");
|
||||
w.creation_dirty = true;
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 850.0, vec![]); }
|
||||
let at = control_rect(&w, "name").center();
|
||||
w.creation_view_geometry["product-form-viewport"] = json!([0, 0, 850, 2100]);
|
||||
let before = w.creation_brief.clone();
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
app.jiansun = Some(w);
|
||||
|
||||
app.open_dropped(&ctx, vec![reference_drop("D:\\photos\\oak.png")], Some(at));
|
||||
|
||||
let workspace = app.jiansun.as_ref().unwrap();
|
||||
assert_eq!(app.session.active().unwrap().doc.id.0, doc);
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
assert_eq!(workspace.creation_brief, before);
|
||||
assert!(workspace.creation_dirty);
|
||||
assert!(workspace.error.contains("产品参考图"));
|
||||
assert!(requests.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_drop_only_intercepts_the_visible_current_project_target() {
|
||||
let (mut w, mut app, requests) = brief_fixture();
|
||||
|
||||
@ -84,7 +84,7 @@ fn rail(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &Tokens) {
|
||||
pub(crate) const DOCK_MIN_WIDTH: f32 = 250.0;
|
||||
|
||||
/// What the dock leaves the toolbar and the canvas when it is widest (points).
|
||||
const DOCK_LEAVES: f32 = 400.0;
|
||||
pub(super) const DOCK_LEAVES: f32 = 400.0;
|
||||
|
||||
/// The dock's width range (points) in a window `window_width` wide: from [`DOCK_MIN_WIDTH`] to
|
||||
/// everything but [`DOCK_LEAVES`], and never capped below the old 520, so two-column layouts can
|
||||
|
||||
@ -583,6 +583,17 @@ fn app_owned(app: &mut PhotocraftApp, command: DockCommand<String>) -> Result<Va
|
||||
crate::workspace_ui::menu(app, id, ¶ms).unwrap_or_else(|| Err(format!("`{id}` is not available")))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agent_width_range(app: &PhotocraftApp, available_width: f32) -> std::ops::RangeInclusive<f32> {
|
||||
let range = crate::panels::dock_width_range(available_width);
|
||||
if crate::jiansun::product_form_open(app) {
|
||||
let min = *range.start();
|
||||
min..=(available_width - super::dock::DOCK_LEAVES).clamp(min, *range.end())
|
||||
} else {
|
||||
range
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the layout, the canvas included, in the space `ui` has left: the customized workspace,
|
||||
/// else the native dock's arrangement.
|
||||
pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
@ -627,7 +638,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let panels: Vec<String> = app.ui.dock.visible_tabs(Group::Color, pro).iter()
|
||||
.filter_map(|(_, label)| normalize(label).map(str::to_owned)).collect();
|
||||
if let Some(active) = panels.iter().position(|id| id == "xiaoyi") {
|
||||
let range = crate::panels::dock_width_range(ui.available_width());
|
||||
let range = agent_width_range(app, ui.available_width().min(ui.ctx().content_rect().width()));
|
||||
let width = ui.ctx().data_mut(|data| data.get_persisted::<f32>(agent_width_id())).unwrap_or(520.0).clamp(*range.start(), *range.end());
|
||||
let dock = Node::Dock { side: Side::End, columns: vec![Column::new(vec![craft_ui::docking::Group::new(panels, active)], width)] };
|
||||
Layout { root: Some(with_canvas(dock, width)), floating: Vec::new() }
|
||||
@ -724,7 +735,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(width) = width {
|
||||
let range = crate::panels::dock_width_range(ui.available_width());
|
||||
let range = agent_width_range(app, ui.available_width().min(ui.ctx().content_rect().width()));
|
||||
ui.ctx().data_mut(|data| data.insert_persisted(agent_width_id(), width.clamp(*range.start(), *range.end())));
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -190,7 +190,7 @@ X-API-Key: your-api-key
|
||||
|
||||
| 类型 | 提交的 `assets` | 每个文件 |
|
||||
| --- | --- | --- |
|
||||
| `detail` | `main[]`、`sku[]`、`detail[]` | `uploadId`、`fileName`、`fileSize`、`sha256`。新版 SKU 图另传 `skuCode` 和 `barcode` |
|
||||
| `detail` | `main[]`、`sku[]`、`detail[]` | `uploadId`、`fileName`、`fileSize`、`sha256`。款式图另传 `barcode`,旧客户端可同时传 `skuCode` |
|
||||
| `video` | `files[]` | `uploadId`、`fileName`、`fileSize`、`sha256` |
|
||||
| `buyer_show` | `files[]` | `uploadId`、`fileName`、`fileSize`、`sha256` |
|
||||
|
||||
@ -199,7 +199,9 @@ X-API-Key: your-api-key
|
||||
- 在小壹产品资料中为每种花色填写对应的素材库 SKU 编号。同一张花色图对应多个 SKU 时,用逗号分隔 SKU 编号。
|
||||
- 小壹读取素材库登记的 `SPU → SKU → 条码` 关系。每个条码生成一个 `条码.jpg` 的交付条目,保留条码的前导零。入库会同时保存图的 SKU 编号和条码。
|
||||
- 同一条码有多张成品时,条目保留同一个文件名,并以 `id` 区分。整套 ZIP 将同名文件放进 `sku/{sortOrder}/` 目录,文件名仍为 `条码.jpg`。
|
||||
- 正式资源响应中的 `spu` 是已确认的 SPU。`assets.sku[]` 额外返回 `skuCode` 和 `barcodes[]`。旧交付记录若没有登记 SKU 或条码,对应字段为 `null` 或空数组。
|
||||
- 正式资源响应中的 `spu` 是商品 SPU。新项目以用户在该 SPU 下为各花色录入的条码交付款式图,同一花色可对应多个条码,前导零原样保留。`barcodes[]` 汇总当前素材的所有条码,`assets.sku[].barcodes[]` 给出每张款式图绑定的条码。`skuCode` 为兼容旧记录的可空字段。
|
||||
- `authorName` 取入库时小壹登录账户的姓名,无姓名时取用户名。
|
||||
- `deliveryGroupId` 与事件体中的 `projectId` 一致。同一小壹项目的详情、视频、买家秀共用这一编号。`relatedMaterials` 返回 `detail`、`video`、`buyer_show` 的素材 ID 和整组签名下载地址,尚未入库或不可对外提供时为 `null`。接收方可用其中的素材 ID 继续调用同一个查询接口。不同项目的同一 SPU 可以交付各自的一组素材。
|
||||
|
||||
接收方持具有产品素材读取权限的 `X-API-Key` 请求 `pullUrl`,根据返回的 `assets` 分组和 `sortOrder` 取成品。单文件使用各条目的 `downloadUrl`,整套使用 `downloadUrls.all`。下载链接已签名,过期后重新查询素材。商品型号、品类、品牌和商品名称从查询结果读取。`categoryName` 表示店铺,项目未提供时为空。
|
||||
|
||||
@ -209,7 +211,7 @@ X-API-Key: your-api-key
|
||||
|
||||
1. 自动上架系统提供可由素材库访问的 HTTPS POST 地址和回调鉴权配置。素材库管理员在「外部通知」新增目标,选中「小壹自动上架素材入库」。回调鉴权支持 Bearer 或固定自定义 Header。接收方先按 `eventId` 持久化任务并返回 `2xx`,后续异步拉取素材和处理上架。新增接收目标会收到已入库的历史通知。
|
||||
2. 管理员在「权限与凭证」创建 API Key,勾选「仅允许拉取小壹素材和回传上架状态」,通过安全渠道交给接收端。该 Key 以 `X-API-Key` 请求头发送,仅可按 `materialId` 拉取小壹交付素材和回传结果。它与接收 POST 通知使用的凭据独立。
|
||||
3. 使用 `GET pullUrl` 取 `data.spu`、`data.assets.sku[].skuCode`、`barcodes[]` 以及各图的 `downloadUrl`。条码和编号均为字符串。没有通知时,仍可按素材库提供的 `materialId` 调用同一个 GET。返回的 `data.eventId` 可用于回传。
|
||||
3. 使用 `GET pullUrl` 读取 `data.spu`、`data.barcodes` 和 `data.assets.sku[]`。按每张图的 `barcodes[]` 和 `downloadUrl` 取图,条码按字符串处理。同组其他成品可从 `data.relatedMaterials` 取整组下载地址。没有通知时,仍可按素材库提供的 `materialId` 调用同一个 GET。返回的 `data.eventId` 可用于回传。
|
||||
4. 上架处理中、成功或失败时,用同一把专用 API Key `PATCH statusUrl`。如果通知是旧版且缺少 `statusUrl`,用该通知的 `pullUrl`。回传成功后,小壹该工程的「上架状态」会显示最新结果,打开期间会自动刷新。
|
||||
|
||||
### 回传上架状态
|
||||
|
||||
61
lib/__tests__/desktop-delivery-barcode.test.ts
Normal file
61
lib/__tests__/desktop-delivery-barcode.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
/** @jest-environment node */
|
||||
import { createDesktopDelivery } from '@/lib/desktop-client/deliveries'
|
||||
import { findDetailMaterialMatches } from '@/lib/detail-generator/materials'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn() } }))
|
||||
jest.mock('@/lib/detail-generator/materials', () => ({ findDetailMaterialMatches: jest.fn() }))
|
||||
jest.mock('node:fs/promises', () => ({ ...jest.requireActual('node:fs/promises'), mkdir: jest.fn().mockRejectedValue(new Error('upload-stage')) }))
|
||||
jest.mock('@/lib/material-facets-cache', () => ({ invalidateMaterialFacetsCache: jest.fn() }))
|
||||
jest.mock('@/lib/remote-upload-sync', () => ({ syncStoredUploadFileToRemote: jest.fn() }))
|
||||
jest.mock('@/lib/upload-sessions', () => ({ getOwnedUploadSession: jest.fn() }))
|
||||
jest.mock('@/lib/upload-paths', () => ({
|
||||
getUploadRootDir: () => '/test',
|
||||
buildStoredUploadPath: jest.fn(),
|
||||
getUploadStorageExtension: jest.fn(),
|
||||
inspectUploadOutput: jest.fn(),
|
||||
}))
|
||||
jest.mock('@/lib/path-security', () => ({ resolveStrictChildPath: jest.fn() }))
|
||||
jest.mock('@/lib/detail-generator/repository', () => ({ detailTransactionLock: jest.fn() }))
|
||||
jest.mock('@/lib/external-auto-listing', () => ({
|
||||
ensureExternalNotificationTables: jest.fn(),
|
||||
queueXiaoyiAutoListingNotification: jest.fn(),
|
||||
wakeXiaoyiAutoListingNotifications: jest.fn(),
|
||||
}))
|
||||
|
||||
const file = (uploadId: string, fileName: string) => ({
|
||||
uploadId, fileName, fileSize: 1, sha256: 'a'.repeat(64),
|
||||
})
|
||||
const input = {
|
||||
projectId: 'project-1', requestId: 'request-1', kind: 'detail' as const, productModel: 'SPU-1',
|
||||
assets: {
|
||||
main: [file('upload-main', 'main.jpg')],
|
||||
detail: [file('upload-detail', 'detail.jpg')],
|
||||
sku: [{ ...file('upload-sku', '00123.jpg'), barcode: '00123' }],
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
;(prisma.$queryRawUnsafe as jest.Mock).mockResolvedValueOnce([{ id: 'project-1' }]).mockResolvedValueOnce([])
|
||||
})
|
||||
|
||||
test('未登记的条码可按用户填写入库', async () => {
|
||||
;(findDetailMaterialMatches as jest.Mock).mockResolvedValue([])
|
||||
await expect(createDesktopDelivery('owner', input, async () => {})).rejects.toThrow('upload-stage')
|
||||
expect(findDetailMaterialMatches).toHaveBeenCalledWith('owner', 'barcode', '00123', true)
|
||||
})
|
||||
|
||||
test('条码已属于另一个 SPU 时终止入库', async () => {
|
||||
;(findDetailMaterialMatches as jest.Mock).mockResolvedValueOnce([])
|
||||
.mockResolvedValueOnce([{ productModel: 'SPU-2', skuCode: 'SKU', barcodes: ['00123'] }])
|
||||
await expect(createDesktopDelivery('owner', input, async () => {})).rejects.toThrow('条码 00123 已登记在其他 SPU')
|
||||
})
|
||||
|
||||
test('该 SPU 的登记条码可继续入库', async () => {
|
||||
;(findDetailMaterialMatches as jest.Mock).mockResolvedValueOnce([
|
||||
{ productModel: 'SPU-1', skuCode: 'SKU', barcodes: ['00123'] },
|
||||
])
|
||||
await expect(createDesktopDelivery('owner', input, async () => {})).rejects.toThrow('upload-stage')
|
||||
expect(findDetailMaterialMatches).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
67
lib/__tests__/desktop-knowledge-session.test.ts
Normal file
67
lib/__tests__/desktop-knowledge-session.test.ts
Normal file
@ -0,0 +1,67 @@
|
||||
/** @jest-environment node */
|
||||
import { createHmac } from 'node:crypto'
|
||||
import { GET } from '@/app/api/desktop/[...path]/route'
|
||||
import { requireDesktop } from '@/lib/desktop-client/service'
|
||||
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
|
||||
|
||||
jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() }))
|
||||
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
|
||||
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
|
||||
|
||||
const context = { params: { path: ['knowledge', 'session'] } }
|
||||
const request = () => new Request('https://platform.test/api/desktop/knowledge/session')
|
||||
const originalSecret = process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET
|
||||
const secret = 'knowledge-session-test-secret-123456789'
|
||||
|
||||
describe('desktop knowledge session', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-12-01T08:00:00Z'))
|
||||
process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET = secret
|
||||
;(requireDesktop as jest.Mock).mockResolvedValue({
|
||||
account: { id: 'test-account' },
|
||||
expiresAt: new Date('2026-12-01T09:00:00Z'),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
if (originalSecret === undefined) delete process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET
|
||||
else process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET = originalSecret
|
||||
})
|
||||
|
||||
test('requires an active desktop session and never exposes a token on failure', async () => {
|
||||
for (const status of [401, 403]) {
|
||||
;(requireDesktop as jest.Mock).mockRejectedValueOnce(new DesktopClientError('无权访问', status, 'denied'))
|
||||
const response = await GET(request(), context)
|
||||
expect(response.status).toBe(status)
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
expect(await response.json()).not.toHaveProperty('token')
|
||||
}
|
||||
})
|
||||
|
||||
test('signs the account identity with the configured key and limits the lifetime', async () => {
|
||||
const response = await GET(request(), context)
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
||||
const result = await response.json()
|
||||
const [encoded, signature] = result.token.replace('ekb_xiaoyi_session_', '').split('.')
|
||||
expect(signature).toBe(createHmac('sha256', secret).update(encoded).digest('base64url'))
|
||||
expect(JSON.parse(Buffer.from(encoded, 'base64url').toString())).toEqual({
|
||||
sub: 'test-account', aud: 'xiaoyi-knowledge', iat: 1796112000, exp: 1796112300,
|
||||
})
|
||||
expect(result.expiresAt).toBe('2026-12-01T08:05:00.000Z')
|
||||
|
||||
;(requireDesktop as jest.Mock).mockResolvedValueOnce({
|
||||
account: { id: 'test-account' }, expiresAt: new Date('2026-12-01T08:00:45Z'),
|
||||
})
|
||||
expect((await (await GET(request(), context)).json()).expiresAt).toBe('2026-12-01T08:00:45.000Z')
|
||||
})
|
||||
|
||||
test('reports an unavailable signer without issuing a token', async () => {
|
||||
delete process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET
|
||||
const response = await GET(request(), context)
|
||||
expect(response.status).toBe(503)
|
||||
expect(await response.json()).toEqual({ error: '小壹知识库自动授权暂不可用', code: 'knowledge_session_unavailable' })
|
||||
})
|
||||
})
|
||||
@ -30,6 +30,7 @@ jest.mock('@/lib/external-api', () => {
|
||||
),
|
||||
),
|
||||
validateApiKey: jest.fn(),
|
||||
XIAOYI_LISTING_KEY_SCOPE: 'xiaoyi_auto_listing',
|
||||
API_ERROR: {
|
||||
INVALID_API_KEY: { code: 'INVALID_API_KEY', message: 'API Key 无效或缺失', status: 401 },
|
||||
TASK_NOT_FOUND: { code: 'TASK_NOT_FOUND', message: '任务号不存在', status: 404 },
|
||||
@ -44,7 +45,10 @@ jest.mock('@/lib/external-api', () => {
|
||||
})
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: { $queryRawUnsafe: jest.fn().mockResolvedValue([{ productName: '椅子', brandName: '测试品牌', identifierType: 'sku' }]) },
|
||||
prisma: { $queryRaw: jest.fn().mockResolvedValue([{
|
||||
productName: '椅子', brandName: '测试品牌', identifierType: 'spu', deliveryGroupId: 'project-1',
|
||||
relatedMaterials: { detail: '35d8644b-1e09-4ce8-9bb0-c529b39ba52e', video: '683a77e8-c567-43df-8af3-bcbae2d0010e' },
|
||||
}]) },
|
||||
}))
|
||||
|
||||
jest.mock('@/lib/product-package', () => ({
|
||||
@ -123,14 +127,14 @@ describe('external product-assets route', () => {
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
test('自动上架详情按素材 ID 返回 SPU、每张 SKU 图的编号和条码', async () => {
|
||||
test('自动上架详情返回作者、同项目成品和按条码交付的款式图', async () => {
|
||||
const id = '35d8644b-1e09-4ce8-9bb0-c529b39ba52e'
|
||||
;(getMaterialById as jest.Mock).mockResolvedValue({
|
||||
id, productModel: 'SPU-001', materialType: '自动上架-详情',
|
||||
id, productModel: 'SPU-001', materialType: '自动上架-详情', authorName: '测试作者',
|
||||
taskStatus: TASK_STATUS.COMPLETED, deletedAt: null, createdAt: new Date(), updatedAt: new Date(),
|
||||
assets: [
|
||||
{ id: 'sku-a', assetType: 'sku', fileName: '00123456.jpg', skuCode: 'SKU-D', barcodes: [{ barcode: '00123456' }], sortOrder: 1 },
|
||||
{ id: 'sku-b', assetType: 'sku', fileName: '00234567.jpg', skuCode: 'SKU-L', barcodes: [{ barcode: '00234567' }], sortOrder: 2 },
|
||||
{ id: 'sku-b', assetType: 'sku', fileName: '00234567.jpg', barcodes: [{ barcode: '00234567' }], sortOrder: 2 },
|
||||
],
|
||||
})
|
||||
const response = await GET(createRequest(`https://example.com/api/external/product-assets?materialId=${id}`))
|
||||
@ -138,9 +142,20 @@ describe('external product-assets route', () => {
|
||||
expect((await response.json()).data).toMatchObject({
|
||||
spu: 'SPU-001',
|
||||
productName: '椅子',
|
||||
authorName: '测试作者',
|
||||
barcodes: ['00123456', '00234567'],
|
||||
deliveryGroupId: 'project-1',
|
||||
relatedMaterials: {
|
||||
detail: { materialId: id, downloadUrl: 'https://download.example/' + id },
|
||||
video: {
|
||||
materialId: '683a77e8-c567-43df-8af3-bcbae2d0010e',
|
||||
downloadUrl: 'https://download.example/683a77e8-c567-43df-8af3-bcbae2d0010e',
|
||||
},
|
||||
buyer_show: null,
|
||||
},
|
||||
assets: { sku: [
|
||||
{ fileName: '00123456.jpg', skuCode: 'SKU-D', barcodes: ['00123456'], sortOrder: 1 },
|
||||
{ fileName: '00234567.jpg', skuCode: 'SKU-L', barcodes: ['00234567'], sortOrder: 2 },
|
||||
{ fileName: '00234567.jpg', skuCode: null, barcodes: ['00234567'], sortOrder: 2 },
|
||||
] },
|
||||
})
|
||||
})
|
||||
|
||||
@ -62,6 +62,7 @@ describe('小壹自动上架通知', () => {
|
||||
eventId: 'event-1', eventType: XIAOYI_AUTO_LISTING_EVENT_TYPE, ...event,
|
||||
occurredAt: '2026-11-30T12:00:00.000Z',
|
||||
pullUrl: 'https://sc.jiansun.vip/api/external/product-assets?materialId=material-1',
|
||||
statusUrl: 'https://sc.jiansun.vip/api/external/product-assets?materialId=material-1',
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@ -54,15 +54,14 @@ function normalized(input: Input) {
|
||||
const name = validateUploadFileName(file?.fileName)
|
||||
desktopAssert(name.fileName && typeof file.uploadId === 'string' && uuid.test(file.uploadId)
|
||||
&& Number.isSafeInteger(file.fileSize) && file.fileSize > 0 && sha.test(file.sha256), '交付文件信息无效')
|
||||
const identity = file.barcode === undefined && file.skuCode === undefined ? {} : {
|
||||
barcode: typeof file.barcode === 'string' ? file.barcode.trim() : '',
|
||||
skuCode: typeof file.skuCode === 'string' ? file.skuCode.trim() : '',
|
||||
}
|
||||
if ('barcode' in identity) {
|
||||
desktopAssert(group === 'sku' && identity.skuCode && identity.skuCode.length <= 200 &&
|
||||
identity.barcode && /^[a-zA-Z0-9_-]{1,120}$/.test(identity.barcode) &&
|
||||
name.fileName === identity.barcode + '.jpg', 'SKU 图文件名须为条码.jpg,并提供 SKU 编号')
|
||||
const barcode = typeof file.barcode === 'string' ? file.barcode.trim() : undefined
|
||||
const skuCode = typeof file.skuCode === 'string' ? file.skuCode.trim() : undefined
|
||||
if (file.barcode !== undefined || file.skuCode !== undefined) {
|
||||
desktopAssert(group === 'sku' && barcode && /^[a-zA-Z0-9_-]{1,120}$/.test(barcode) &&
|
||||
name.fileName === barcode + '.jpg' && (file.skuCode === undefined || (skuCode && skuCode.length <= 200)),
|
||||
'请提供条码,款式图文件名须与条码一致')
|
||||
}
|
||||
const identity = barcode ? { barcode, ...(skuCode && { skuCode }) } : {}
|
||||
files.push({ group: group === 'files' ? (input.kind === 'detail' ? 'source' : input.kind) : group,
|
||||
uploadId: file.uploadId, fileName: name.fileName!, fileSize: file.fileSize, sha256: file.sha256, ...identity })
|
||||
}
|
||||
@ -74,9 +73,9 @@ function normalized(input: Input) {
|
||||
for (const file of files) {
|
||||
const name = file.group + '\\0' + file.fileName.toLowerCase()
|
||||
if (file.barcode) {
|
||||
const sku = file.skuCode!
|
||||
const sku = file.skuCode ?? ''
|
||||
const previous = barcodeOwners.get(name)
|
||||
desktopAssert(!previous || previous === sku, '同一条码不能绑定到多个 SKU')
|
||||
desktopAssert(previous === undefined || previous === sku, '同一条码不能绑定到多个 SKU')
|
||||
barcodeOwners.set(name, sku)
|
||||
}
|
||||
const identity = file.barcode ? name + '\\0' + file.sha256 : name
|
||||
@ -143,15 +142,30 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut
|
||||
return {requestId:previous[0].requestId,materialId:previous[0].materialId,materialType:previous[0].materialType,state:previous[0].state}
|
||||
}
|
||||
|
||||
const skuFiles = request.files.filter(file => file.barcode)
|
||||
if (skuFiles.length) {
|
||||
const barcodeFiles = request.files.filter(file => file.barcode)
|
||||
if (barcodeFiles.length) {
|
||||
const catalog = await findDetailMaterialMatches(ownerId, 'spu', request.productModel, true)
|
||||
const valid = new Map<string, Set<string>>()
|
||||
const knownBarcodes = new Set<string>()
|
||||
for (const row of catalog) {
|
||||
if (!valid.has(row.skuCode)) valid.set(row.skuCode, new Set())
|
||||
for (const barcode of row.barcodes) valid.get(row.skuCode)!.add(barcode)
|
||||
for (const barcode of row.barcodes) {
|
||||
valid.get(row.skuCode)!.add(barcode)
|
||||
knownBarcodes.add(barcode)
|
||||
}
|
||||
}
|
||||
desktopAssert(barcodeFiles.every(file => !file.skuCode || valid.get(file.skuCode)?.has(file.barcode!)),
|
||||
'SKU 或条码不属于该 SPU,请核对产品资料')
|
||||
const unknownBarcodes = Array.from(new Set(barcodeFiles.map(file => file.barcode!)
|
||||
.filter(barcode => !knownBarcodes.has(barcode))))
|
||||
for (let index = 0; index < unknownBarcodes.length; index += 5) {
|
||||
const codes = unknownBarcodes.slice(index, index + 5)
|
||||
const matches = await Promise.all(codes.map(barcode => findDetailMaterialMatches(ownerId, 'barcode', barcode, true)))
|
||||
for (let offset = 0; offset < codes.length; offset++) {
|
||||
desktopAssert(matches[offset].every(row => row.productModel.toUpperCase() === request.productModel.toUpperCase()),
|
||||
'条码 ' + codes[offset] + ' 已登记在其他 SPU,请核对产品资料')
|
||||
}
|
||||
}
|
||||
desktopAssert(skuFiles.every(file => valid.get(file.skuCode!)?.has(file.barcode!)), 'SKU 或条码不属于该 SPU,请核对产品资料')
|
||||
}
|
||||
|
||||
const uploadRoot = getUploadRootDir()
|
||||
|
||||
27
lib/desktop-client/knowledge-session.ts
Normal file
27
lib/desktop-client/knowledge-session.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { createHmac } from 'node:crypto'
|
||||
import { DesktopClientError } from './contract.mjs'
|
||||
|
||||
export function issueKnowledgeSession(ownerId: string, desktopExpiresAt: Date) {
|
||||
const secret = process.env.XIAOYI_KNOWLEDGE_SESSION_SECRET
|
||||
if (!secret || Buffer.byteLength(secret, 'utf8') < 32) {
|
||||
throw new DesktopClientError('小壹知识库自动授权暂不可用', 503, 'knowledge_session_unavailable')
|
||||
}
|
||||
|
||||
const issuedAt = Math.floor(Date.now() / 1000)
|
||||
const expiresAt = Math.min(issuedAt + 300, Math.floor(new Date(desktopExpiresAt).getTime() / 1000))
|
||||
if (!Number.isFinite(expiresAt) || expiresAt <= issuedAt) {
|
||||
throw new DesktopClientError('客户端授权已过期,请重新登录', 401, 'session_expired')
|
||||
}
|
||||
|
||||
const payload = Buffer.from(JSON.stringify({
|
||||
sub: ownerId,
|
||||
aud: 'xiaoyi-knowledge',
|
||||
iat: issuedAt,
|
||||
exp: expiresAt,
|
||||
})).toString('base64url')
|
||||
const signature = createHmac('sha256', Buffer.from(secret, 'utf8')).update(payload).digest('base64url')
|
||||
return {
|
||||
token: `ekb_xiaoyi_session_${payload}.${signature}`,
|
||||
expiresAt: new Date(expiresAt * 1000).toISOString(),
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user