From 36056a9c8ea08fa36e4bc5441ea6134059de0cdc Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Tue, 1 Dec 2026 10:56:12 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=97=A7=E5=B7=A5=E7=A8=8B?= =?UTF-8?q?=E5=AE=8C=E7=BB=93=E5=B9=B6=E6=8C=89=E6=9D=A1=E7=A0=81=E4=BA=A4?= =?UTF-8?q?=E4=BB=98=20SKU=20=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/external/download/route.ts | 10 +- app/api/external/product-assets/route.ts | 5 + .../src/jiansun_canvas_workspace.rs | 30 +- .../apps/photocraft/src/jiansun_creation.rs | 1 + .../photocraft/src/jiansun_creation_model.rs | 30 +- .../apps/photocraft/src/jiansun_delivery.rs | 2 +- .../src/jiansun_material_delivery.rs | 445 +++++++++++++++++- .../apps/photocraft/src/jiansun_sync.rs | 3 +- apps/detail-photocraft/client-version.txt | 2 +- .../crates/ui-egui/src/jiansun/creation.rs | 19 + docs/自动上架平台成套入库通知接口.md | 17 + .../detail-generator-materials.test.ts | 15 + lib/__tests__/product-assets-route.test.ts | 26 + lib/desktop-client/catalog.ts | 6 +- lib/desktop-client/deliveries.ts | 52 +- lib/detail-generator/materials.ts | 31 +- lib/external-auto-listing.ts | 8 +- lib/product-package.ts | 1 + 18 files changed, 654 insertions(+), 49 deletions(-) diff --git a/app/api/external/download/route.ts b/app/api/external/download/route.ts index 9c99239b..1dbe50ae 100644 --- a/app/api/external/download/route.ts +++ b/app/api/external/download/route.ts @@ -686,10 +686,18 @@ async function downloadAsZip(assets: any[], taskNo: string, downloadType: string let successCount = 0; let failCount = 0; + const skuNames = new Map(); + for (const asset of assets) { + if (asset.assetType !== 'sku' || !asset.fileName) continue; + const name = asset.fileName.toLowerCase(); + skuNames.set(name, (skuNames.get(name) ?? 0) + 1); + } for (const asset of assets) { const fileUrl = normalizeAssetFileUrl(asset.fileUrl); const fileName = asset.fileName || path.basename(fileUrl); - const entryName = `${asset.assetType}/${fileName}`; + const group = asset.assetType === 'sku' && (skuNames.get(fileName.toLowerCase()) ?? 0) > 1 + ? `sku/${asset.sortOrder}` : asset.assetType; + const entryName = `${group}/${fileName}`; try { const localPath = resolveAssetLocalPath(fileUrl); diff --git a/app/api/external/product-assets/route.ts b/app/api/external/product-assets/route.ts index dd7920db..31c8ab6b 100644 --- a/app/api/external/product-assets/route.ts +++ b/app/api/external/product-assets/route.ts @@ -171,6 +171,10 @@ export async function GET(request: NextRequest) { fileName: asset.fileName || '', fileSize: Number(asset.fileSize || 0), sortOrder: asset.sortOrder || 0, + ...(asset.assetType === 'sku' ? { + skuCode: asset.skuCode || null, + barcodes: (asset.barcodes || []).map((entry: { barcode: string }) => entry.barcode), + } : {}), downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'single', assetId: asset.id}), }) } @@ -181,6 +185,7 @@ export async function GET(request: NextRequest) { }) const response = successResponse({ materialId: material.id, materialType: material.materialType, productModel: material.productModel, + spu: groups.sku.some(asset => asset.barcodes.length) || delivery[0]?.identifierType === 'spu' ? material.productModel : null, categoryName: material.categoryName, productCategoryName: material.productCategoryName, brandName: delivery[0]?.brandName || '', productName: delivery[0]?.productName || '', identifierType: delivery[0]?.identifierType || '', isFullSet: material.materialType === '自动上架-详情' && ['main', 'sku', 'detail'].every(group => groups[group].length), diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 8a76ec97..73c10c6a 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -713,7 +713,7 @@ fn canvas_template(previous: Option<&Value>, selected: &Value, brand: &str, cate } fn shared_variant_brief(brief: &Value) -> Value { - let mut shared = brief.clone(); + let mut shared = creation::production_brief(brief); if let Some(fields) = shared.as_object_mut() { fields.remove("variants"); } shared } @@ -2830,6 +2830,27 @@ fn stage_input_hash(state: &Value, creation: &Value, variant: &str, component: & Ok(hash(&inputs.to_string())) } +fn delivery_input_hash(state: &Value, creation: &Value, variant: &str, component: &str) -> R { + let mut inputs = creation.clone(); + if let Some(snapshot) = inputs["designSnapshot"].as_object_mut() { + snapshot.remove("rules"); + if snapshot.is_empty() { + inputs["designSnapshot"] = Value::Null; + } + } + stage_input_hash(state, &inputs, variant, component) +} + +pub(super) fn delivery_inputs_match( + state: &Value, creation: &Value, variant: &str, component: &str, receipt: &Value, +) -> bool { + if receipt["deliveryInputHash"].is_string() { + return delivery_input_hash(state, creation, variant, component) + .is_ok_and(|hash| receipt["deliveryInputHash"] == hash); + } + current_export_inputs(state, Some(creation), &creation["revision"], variant, component, receipt) +} + pub(super) fn check_delivery_export( dir: &Path, state: &Value, creation: &Value, variant: &str, component: &str, receipt: &Value, ) -> R<()> { @@ -2840,7 +2861,7 @@ pub(super) fn check_delivery_export( if receipt["templateHash"] != pack["contentHash"] { return Err("制作模板与成品回执不一致,请重新导出该组".into()); } - if !current_export_inputs(state, Some(creation), &creation["revision"], variant, component, receipt) { + if !delivery_inputs_match(state, creation, variant, component, receipt) { return Err("商品资料或制作设置与上次导出不同,请重新导出该组".into()); } if receipt_uses_retired_image(dir, receipt) { @@ -3998,6 +4019,7 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va let creation = creation::load(dir)?; result["briefRevision"] = creation["revision"].clone(); result["stageInputHash"] = json!(stage_input_hash(state, &creation, &variant_id, component)?); + result["deliveryInputHash"] = json!(delivery_input_hash(state, &creation, &variant_id, component)?); result["templateHash"] = state["template"]["contentHash"].clone(); result["imageSources"] = json!(image_sources); result["unverifiedFacts"] = json!(input["unverifiedFacts"].as_array().map_or(&[][..], Vec::as_slice)); @@ -6737,6 +6759,10 @@ mod tests { moved["editable"] = json!("old-project/plate.pcraft"); moved["sourceDocument"]["path"] = moved["editable"].clone(); check_delivery_export(&fixture.dir, &state, &creation, variant, "detail", &moved).unwrap(); + let mut refreshed = creation.clone(); + refreshed["designSnapshot"]["rules"] = json!({"refresh":"after-export"}); + assert_ne!(stage_input_hash(&state, &refreshed, variant, "detail").unwrap(), moved["stageInputHash"]); + check_delivery_export(&fixture.dir, &state, &refreshed, variant, "detail", &moved).unwrap(); let mut changed = creation.clone(); changed["sellingPoints"]["direction"] = json!("new selling point"); let reason = check_delivery_export(&fixture.dir, &state, &changed, variant, "detail", &moved).unwrap_err(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 691d83bf..e816ea91 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -4,6 +4,7 @@ use super::*; use base64::engine::general_purpose::STANDARD; #[path = "jiansun_creation_model.rs"] mod model; +pub(super) use model::production_brief; #[path = "jiansun_composer_attachments.rs"] pub(super) mod composer_attachments; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs index d6eae206..de986c11 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation_model.rs @@ -118,6 +118,22 @@ pub(super) fn brief(value: &Value) -> R { } out["variants"] = json!(clean); } + if let Some(bindings) = value.get("skuBindings") { + let rows = bindings.as_object().filter(|rows| rows.len() <= 65).ok_or("SKU 绑定格式无效")?; + let mut clean = serde_json::Map::new(); + for (id, value) in rows { + if id != "default" && Uuid::parse_str(id).is_err() { + return Err("SKU 绑定的花色编号无效".into()); + } + let codes = string(value, 4000, "SKU 编号")?; + if !codes.trim().is_empty() { + clean.insert(id.clone(), json!(codes.trim())); + } + } + if !clean.is_empty() { + out["skuBindings"] = Value::Object(clean); + } + } if let Some(selection) = value.get("outputVariantIds") { let selection = selection.as_object().ok_or("出图颜色选择格式无效")?; let mut selected = serde_json::Map::new(); @@ -176,7 +192,7 @@ pub(super) fn brief(value: &Value) -> R { } pub(super) fn facts_hash(c: &Value) -> String { - hash(&json!({"brief":c["brief"],"facts":c["facts"]}).to_string()) + hash(&json!({"brief":production_brief(&c["brief"]),"facts":c["facts"]}).to_string()) } pub(super) fn selected(c: &Value) -> R> { let selected = c["sellingPoints"]["selected"].as_array().filter(|a| a.len() <= 20).ok_or("最多选择20条卖点")?; @@ -195,7 +211,7 @@ pub(super) fn selected(c: &Value) -> R> { } pub(super) fn input_hash(stage: &str, c: &Value) -> R { - let mut input = json!({"stage":stage,"brief":c["brief"],"brand":c["designSnapshot"],"width":c["width"],"screenCount":if stage=="plan"{c["screenCount"].clone()}else{Value::Null},"facts":if stage=="facts" {Value::Null}else{c["facts"].clone()},"points":if stage=="points" {c["sellingPoints"].clone()}else{Value::Null},"selected":if stage=="plan" {json!(selected(c)?)}else{Value::Null}}); + let mut input = json!({"stage":stage,"brief":production_brief(&c["brief"]),"brand":c["designSnapshot"],"width":c["width"],"screenCount":if stage=="plan"{c["screenCount"].clone()}else{Value::Null},"facts":if stage=="facts" {Value::Null}else{c["facts"].clone()},"points":if stage=="points" {c["sellingPoints"].clone()}else{Value::Null},"selected":if stage=="plan" {json!(selected(c)?)}else{Value::Null}}); if stage == "slot-copy" { input["templateCopyInput"] = c["templateCopyInput"].clone(); input["plan"] = c["plan"].clone(); @@ -439,8 +455,16 @@ fn normalize(s: &str) -> String { s.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase).collect() } +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"); + } + brief +} + pub(super) fn invalidate(next: &mut Value, before: &Value) { - let brief_changed = next["brief"] != before["brief"]; + let brief_changed = production_brief(&next["brief"]) != production_brief(&before["brief"]); if brief_changed && next["facts"]["items"].as_array().is_some_and(|a| !a.is_empty()) { next["facts"]["status"] = json!("stale"); next["sellingPoints"]["stale"] = json!(true); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index 60de1cb1..dbd5951f 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -111,7 +111,7 @@ fn copy_artifact(root: &Path, generation: &Path, source: &Value, category: &str, Ok(record) } -fn variant_name(brief: &Value, variant: &str) -> Option { +pub(super) fn variant_name(brief: &Value, variant: &str) -> Option { let row = brief["variants"].as_array().into_iter().flatten().find(|row| row["id"] == variant); let (source, field) = row.map_or((brief, "variant"), |row| (row, "name")); [field, "colorName"].into_iter().filter_map(|key| source[key].as_str()) diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs index dc1f8d84..444e6c91 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_material_delivery.rs @@ -1,10 +1,10 @@ -use super::{Backend, R, Value, body, canvas_workspace, creation, json, read_json, write_json}; +use super::{Backend, R, Value, body, canvas_workspace, creation, json, project_file, read_json, write_json}; use std::{ - collections::HashSet, + collections::{BTreeMap, BTreeSet, HashMap, HashSet}, fs::{self, File}, io::{Read, Seek, SeekFrom}, - path::{Path, PathBuf}, + path::{Component, Path, PathBuf}, time::Duration, }; use uuid::Uuid; @@ -20,6 +20,19 @@ pub(super) struct Artifact { sha256: String, width: u32, height: u32, + sku_variant: Option, + sku: Option<(String, String)>, +} + +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); + file["barcode"] = json!(barcode); + } + file + } } pub(super) fn detail_screens(artifacts: &[Artifact]) -> R> { @@ -47,7 +60,10 @@ pub(super) fn detail_screens(artifacts: &[Artifact]) -> R> { fn artifact(generation: &Path, row: &Value, group: &'static str, name: String) -> R { let source = row["path"].as_str().and_then(|p| Path::new(p).file_name()).ok_or("成品文件路径缺失")?; - let path = generation.join(source); + verified_artifact(generation.join(source), row, group, name) +} + +fn verified_artifact(path: PathBuf, row: &Value, group: &'static str, name: String) -> R { let size = row["sizeBytes"].as_u64().filter(|size| *size > 0).ok_or("成品文件大小缺失")?; let sha256 = row["sha256"].as_str().filter(|sha| sha.len() == 64 && sha.bytes().all(|c| c.is_ascii_hexdigit())) .ok_or("成品文件校验信息缺失")?.to_ascii_lowercase(); @@ -58,16 +74,163 @@ fn artifact(generation: &Path, row: &Value, group: &'static str, name: String) - } let width = row["width"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("成品宽度缺失")?; let height = row["height"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("成品高度缺失")?; - Ok(Artifact { path, name, group, size, sha256, width, height }) + Ok(Artifact { path, name, group, size, sha256, width, height, sku_variant: None, sku: None }) +} + +fn bundle_member(root: &Path, relative: &str) -> R { + let path = Path::new(relative); + if path.as_os_str().is_empty() || !path.components().all(|part| matches!(part, Component::Normal(_))) { + return Err("旧版交付清单中的文件路径无效".into()); + } + Ok(root.join(path)) +} + +struct DeliveryBundle { + root: PathBuf, + manifest: Value, + workspace: Value, + creation: Value, + context: Value, + snapshot: Value, +} + +impl DeliveryBundle { + fn read(project: &Path, path: &Path, root: &Path, manifest: Value, local_id: &Value) -> R { + let checkpoint = read_json(path)?; + if checkpoint["localId"] != *local_id || manifest["version"] != 1 || manifest["allOutputsCompleted"] != true { + return Err("旧版交付包与当前工程不匹配,或当时尚未交付齐全".into()); + } + let files = manifest["files"].as_array().ok_or("旧版交付清单没有文件列表")?; + for category in ["详情页切片", "主图", "SKU"] { + let count = files.iter().filter(|row| row["category"] == category && row["format"] == "jpg" && row["verified"] == true).count(); + if count == 0 || manifest["counts"][category] != count { + return Err(format!("旧版交付清单中的{category}数量不匹配")); + } + } + let verify = |file: &Path| -> R<()> { + let relative = file.strip_prefix(root).map_err(|_| "旧版工程快照路径无效")?.to_string_lossy().replace('\\', "/"); + let record = files.iter().find(|row| row["relativePath"] == relative && row["verified"] == true) + .ok_or("旧版交付清单缺少工程快照记录")?; + let size = record["sizeBytes"].as_u64().ok_or("旧版工程快照大小无效")?; + if fs::metadata(file).map_err(|_| "旧版交付包中的工程快照缺失")?.len() != size + || canvas_workspace::file_digest(file).map_err(|_| "无法核对旧版工程快照")? != record["sha256"] + { + return Err("旧版交付包中的工程快照已被改动".into()); + } + Ok(()) + }; + verify(path)?; + let resource_root = project_file::resource_checkpoint(path, &checkpoint)?; + let source = checkpoint["sourceRoot"].as_str().map(Path::new).ok_or("旧版工程源目录无效")?; + let load = |logical: &str| -> R { + let file = match checkpoint.get("resourcePaths") { + Some(paths) => bundle_member(root, paths[logical].as_str().ok_or("旧版工程快照缺失")?)?, + None => resource_root.join(logical), + }; + verify(&file)?; + let mut value = read_json(&file)?; + project_file::rebase_paths(&mut value, source, project); + Ok(value) + }; + let creation = load("creation.json")?; + let workspace = load("canvas-workspace.json")?; + let context = load("context.json")?; + let outputs = canvas_workspace::production_stages(&workspace); + if manifest["completedOutputs"] != outputs.len() || manifest["totalOutputs"] != outputs.len() { + return Err("旧版交付清单与工程快照的成品范围不一致".into()); + } + Ok(Self { root: root.to_owned(), manifest, workspace, creation, context, snapshot: checkpoint["snapshot"].clone() }) + } + + fn open(project: &Path, context: &Value, creation: &Value, state: &Value) -> R> { + let Some(path) = context["projectFile"]["path"].as_str().map(Path::new) else { return Ok(None); }; + let Some(root) = path.parent().filter(|parent| parent.file_name().is_some_and(|name| name == "工程文件")) + .and_then(Path::parent) else { return Ok(None); }; + let manifest_path = root.join("交付清单.json"); + if !manifest_path.is_file() { return Ok(None); } + let bundle = Self::read(project, path, root, read_json(&manifest_path)?, &context["localId"])?; + if bundle.snapshot != context["projectFile"]["snapshot"] || bundle.workspace["id"] != state["id"] { + return Err("旧版交付包与当前工程不匹配".into()); + } + let saved = &bundle.creation; + if bundle.workspace["productTemplates"] != state["productTemplates"] + || creation::production_brief(&bundle.workspace["brief"]) != creation::production_brief(&state["brief"]) + || bundle.workspace["variants"] != state["variants"] + || creation::production_brief(&saved["brief"]) != creation::production_brief(&creation["brief"]) + || ["width", "screenCount"].iter().any(|key| saved[*key] != creation[*key]) + || saved["sellingPoints"]["selected"] != creation["sellingPoints"]["selected"] + || saved["sellingPoints"]["direction"] != creation["sellingPoints"]["direction"] + || saved["plan"]["screens"] != creation["plan"]["screens"] + { + return Err("工程的商品资料或模板已改动,请重新导出受影响的成品".into()); + } + if bundle.context["revision"] != context["revision"] { + return Err("旧版交付后画布版本已变化,请重新导出受影响的成品".into()); + } + Ok(Some(bundle)) + } + + fn last_delivery(project: &Path, context: &Value, run: &Value, state: &Value) -> Option { + let delivery = &run["productionDelivery"]; + if delivery["state"] != "bundle_saved" || run["workspaceId"] != state["id"] { return None; } + let root = Path::new(delivery["path"].as_str()?); + let manifest = read_json(&root.join("交付清单.json")).ok()?; + if manifest["deliveryId"] != run["deliveryId"] { return None; } + let entry = manifest["files"].as_array()?.iter() + .find(|row| row["category"] == "工程文件" && row["format"] == "xiaoyi")?; + let file = bundle_member(root, entry["relativePath"].as_str()?).ok()?; + let bundle = Self::read(project, &file, root, manifest, &context["localId"]).ok()?; + (bundle.workspace["id"] == state["id"]).then_some(bundle) + } + + fn confirms_generation(&self, receipt: &Value) -> bool { + self.manifest["outputEvidence"].as_array().into_iter().flatten().any(|record| + ["variantId", "outputId", "generationId"].iter().all(|key| record[*key] == receipt[*key])) + } + + fn artifacts(&self, variant: &str, component: &str, group: &'static str, index: usize) -> R> { + let category = match group { "detail" => "详情页切片", "main" => "主图", _ => "SKU" }; + let published = canvas_workspace::production_stages(&self.workspace); + let variants: HashSet<_> = published.iter().filter_map(|stage| stage["variantId"].as_str()).collect(); + let legacy_name = super::delivery::variant_name(&self.workspace["brief"], variant) + .filter(|name| variants.iter().filter(|id| super::delivery::variant_name(&self.workspace["brief"], id).as_ref() == Some(name)).count() == 1); + let mut artifacts = Vec::new(); + let mut paths = HashSet::new(); + for row in self.manifest["files"].as_array().into_iter().flatten() + .filter(|row| row["category"] == category && row["format"] == "jpg" && row["verified"] == true) + { + if row["outputId"].is_string() && row["outputId"] != component { continue; } + let relative = row["relativePath"].as_str().ok_or("旧版 JPG 缺少文件路径")?; + let selected = match row["variantId"].as_str() { + Some(saved) => saved == variant, + None if variants.len() == 1 => true, + None => Path::new(relative).parent().and_then(Path::file_name).and_then(|name| name.to_str()) + .and_then(|folder| folder.split_once(' ')) + .is_some_and(|(number, name)| !number.is_empty() && number.bytes().all(|byte| byte.is_ascii_digit()) + && legacy_name.as_deref() == Some(name)), + }; + if !selected { continue; } + if !paths.insert(relative) { return Err("旧版交付清单含重复 JPG".into()); } + let file = bundle_member(&self.root, relative)?; + let name = format!("{component}-{:03}-{:03}.jpg", index + 1, artifacts.len() + 1); + artifacts.push(verified_artifact(file, row, group, name)?); + } + if artifacts.is_empty() { + return Err("旧版交付清单缺少能对应此花色的正式 JPG".into()); + } + Ok(artifacts) + } } pub(super) fn detail_artifacts(project: &Path) -> R> { let checkpoint = project.join("production-run.json"); - if checkpoint.exists() && read_json(&checkpoint)?["active"] == true { + let run = if checkpoint.try_exists().map_err(|error| error.to_string())? { read_json(&checkpoint)? } else { Value::Null }; + if run["active"] == true { return Err("制作任务仍在运行,请完成或停止后再提交".into()); } let state = canvas_workspace::load(project)?; let creation = creation::load(project)?; + let context = read_json(&project.join("context.json"))?; let outputs = canvas_workspace::production_stages(&state); let missing: Vec<_> = [("detail", "详情页"), ("main_images", "主图"), ("sku_images", "SKU")] .into_iter().filter_map(|(id, label)| (!outputs.iter().any(|row| row["outputId"] == id)).then_some(label)) @@ -77,6 +240,8 @@ pub(super) fn detail_artifacts(project: &Path) -> R> { } let mut found = HashSet::new(); let mut artifacts = Vec::new(); + let mut bundle = None; + let mut historical = None; for (output_index, output) in outputs.iter().enumerate() { let variant = output["variantId"].as_str().filter(|v| Uuid::parse_str(v).is_ok()).ok_or("成品花色身份无效")?; let component = output["outputId"].as_str().ok_or("成品类型缺失")?; @@ -94,9 +259,21 @@ pub(super) fn detail_artifacts(project: &Path) -> R> { return Err("成品清单中存在重复输出".into()); } let pointer = canvas_workspace::receipt_path(project, variant, component); - let receipt = canvas_workspace::published_receipt(&pointer).map_err(|error| { - if pointer.exists() { issue(error) } else { issue("这组尚无正式导出回执,请先导出成品".into()) } - })?; + if !pointer.try_exists().map_err(|error| issue(error.to_string()))? { + if bundle.is_none() { + bundle = DeliveryBundle::open(project, &context, &creation, &state).map_err(&issue)?; + } + let bundle = bundle.as_ref().ok_or_else(|| issue("这组尚无正式导出回执,请先导出成品".into()))?; + let mut files = bundle.artifacts(variant, component, group, output_index).map_err(&issue)?; + if group == "sku" { + for file in &mut files { + file.sku_variant = Some(variant.to_owned()); + } + } + artifacts.extend(files); + continue; + } + let receipt = canvas_workspace::published_receipt(&pointer).map_err(&issue)?; let generation_id = receipt["generationId"].as_str() .filter(|id| id.strip_prefix("generation-").is_some_and(|v| !v.is_empty() && v.bytes().all(|c| c.is_ascii_alphanumeric()))) .ok_or_else(|| issue("成品版本无效,请重新导出该组".into()))?; @@ -109,20 +286,159 @@ pub(super) fn detail_artifacts(project: &Path) -> R> { { return Err(issue("成品版本与制作回执不一致,请重新导出该组".into())); } - canvas_workspace::check_delivery_export(project, &state, &creation, variant, component, &manifest) - .map_err(|error| issue(error))?; + let mut original_rules = None; + if manifest["deliveryInputHash"].is_null() + && !canvas_workspace::delivery_inputs_match(&state, &creation, variant, component, &manifest) + { + let archived = historical.get_or_insert_with(|| DeliveryBundle::last_delivery(project, &context, &run, &state)); + if let Some(archived) = archived.as_ref().filter(|bundle| bundle.confirms_generation(&manifest)) { + // Reconstruct only the rules that were active when these JPGs were verified. + let mut original = creation.clone(); + original["designSnapshot"]["rules"] = archived.creation["designSnapshot"]["rules"].clone(); + original_rules = Some(original); + } + } + canvas_workspace::check_delivery_export(project, &state, original_rules.as_ref().unwrap_or(&creation), variant, component, &manifest) + .map_err(&issue)?; let records = if component == "detail" { &manifest["screenFiles"] } else { &manifest["files"] }; let files = records.as_array().filter(|rows| !rows.is_empty()) .ok_or_else(|| issue("成品图片缺失,请重新导出该组".into()))?; for (index, row) in files.iter().enumerate() { - artifacts.push(artifact(generation, row, group, format!("{component}-{:03}-{:03}.jpg", output_index + 1, index + 1)) - .map_err(|error| issue(error))?); + let mut file = artifact(generation, row, group, format!("{component}-{:03}-{:03}.jpg", output_index + 1, index + 1)) + .map_err(&issue)?; + if group == "sku" { + file.sku_variant = Some(variant.to_owned()); + } + artifacts.push(file); } } Ok(artifacts) } +fn bind_sku_files(artifacts: &[Artifact], brief: &Value, variants: &[Value], catalog: &[Value]) -> R> { + let mut known = BTreeMap::<&str, BTreeSet<&str>>::new(); + for row in catalog { + let Some(code) = row["skuCode"].as_str().filter(|code| !code.is_empty()) else { continue }; + known.entry(code).or_default().extend(row["barcodes"].as_array().into_iter().flatten().filter_map(Value::as_str)); + } + let mut mappings = HashMap::new(); + let mut owners = HashMap::new(); + for variant in variants { + let id = variant["id"].as_str().ok_or("SKU 图花色缺少编号")?; + if !artifacts.iter().any(|file| file.sku_variant.as_deref() == Some(id)) { + continue; + } + let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("当前花色"); + let explicit = brief["skuBindings"][id].as_str() + .or_else(|| (variants.len() == 1).then(|| brief["skuBindings"]["default"].as_str()).flatten()); + let codes: Vec<_> = if let Some(explicit) = explicit { + explicit.split([',', ',']).map(str::trim).filter(|code| !code.is_empty()).collect() + } else if known.contains_key(name) { + vec![name] + } else if variants.len() == 1 { + match brief["identifierType"].as_str() { + Some("sku") => brief["identifier"].as_str().into_iter().collect(), + Some("barcode") => known.iter().filter_map(|(code, barcodes)| + brief["identifier"].as_str().is_some_and(|id| barcodes.contains(id)).then_some(*code)).collect(), + _ if known.len() == 1 => known.keys().copied().collect(), + _ => Vec::new(), + } + } else { + Vec::new() + }; + if codes.is_empty() || (explicit.is_none() && codes.len() != 1) { + return Err(format!("请在产品资料中给「{name}」填写素材库 SKU 编号")); + } + let mut bindings = Vec::new(); + for entered in codes.into_iter().collect::>() { + let code = if known.contains_key(entered) { + entered + } else { + let mut matches = known.keys().filter(|code| code.eq_ignore_ascii_case(entered)); + match (matches.next(), matches.next()) { + (Some(code), None) => *code, + _ => return Err(format!("「{name}」的 SKU {entered} 不属于该 SPU")), + } + }; + let barcodes = known.get(code).filter(|codes| !codes.is_empty()) + .ok_or_else(|| format!("「{name}」的 SKU {code} 在该 SPU 下没有已登记的条码"))?; + for barcode in barcodes { + if barcode.len() > 120 || !barcode.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') { + return Err(format!("SKU {code} 的条码 {barcode} 无法用作文件名,请核对素材库登记")); + } + let key = barcode.to_ascii_lowercase(); + if let Some((owner, owner_variant)) = owners.insert(key, (code, id)) { + if owner != code || owner_variant != id { + return Err(format!("条码 {barcode} 同时绑定了多个 SKU 或花色,请核对产品资料")); + } + } + bindings.push((code.to_owned(), (*barcode).to_owned())); + } + } + mappings.insert(id, bindings); + } + let mut files = Vec::new(); + let mut seen = HashSet::new(); + for artifact in artifacts { + let Some(variant) = artifact.sku_variant.as_deref() else { + files.push(artifact.clone()); + continue; + }; + for (code, barcode) in mappings.get(variant).ok_or("SKU 图缺少花色和条码的匹配")? { + if !seen.insert((barcode.to_ascii_lowercase(), artifact.sha256.as_str())) { + continue; + } + let mut file = artifact.clone(); + file.name = format!("{barcode}.jpg"); + file.sku = Some((code.clone(), barcode.clone())); + files.push(file); + } + } + if seen.len() > 200 || files.len() > 500 { + return Err("按条码展开后超过交付文件数量上限,请核对需要的 SKU".into()); + } + Ok(files) +} + impl Backend { + pub(super) fn bind_sku_delivery(&self, project: &Path, artifacts: &[Artifact]) -> R<(String, Vec)> { + let creation = creation::load(project)?; + let brief = &creation["brief"]; + 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| { + let query = url::form_urlencoded::Serializer::new(String::new()) + .append_pair("identifierType", kind) + .append_pair("identifier", value) + .append_pair("skuIdentities", "1") + .finish(); + self.json(&format!("catalog/products?{query}")) + }; + let mut kind = kind; + let mut matches = lookup(kind, identifier)?; + if kind == "sku" && matches["items"].as_array().is_some_and(Vec::is_empty) { + kind = "spu"; + matches = lookup(kind, identifier)?; + } + let items = matches["items"].as_array().ok_or("素材库未提供 SKU 与条码关系,请更新素材库服务")?; + let spus: BTreeSet<_> = items.iter().filter_map(|row| row["productModel"].as_str()).filter(|value| !value.is_empty()).collect(); + let spu = match spus.len() { + 0 => return Err("素材库未找到该商品的 SKU 和条码,请核对产品编号".into()), + 1 => spus.into_iter().next().ok_or("素材库未返回 SPU")?, + _ => return Err("该编号对应多个 SPU,请在产品资料中填写准确的 SPU".into()), + }; + let matches = if kind == "spu" { matches.clone() } else { lookup("spu", spu)? }; + let catalog = matches["items"].as_array().ok_or("素材库 SKU 列表无效")?; + 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)?)) + } + fn material_request(&self, endpoint: &str, payload: &Value) -> R { self.check_dispatch()?; let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; @@ -145,12 +461,17 @@ impl Backend { Ok(value) } - pub(super) fn upload_material_delivery(&self, project: &Path, cloud_id: &str, revision: u64, artifacts: &[Artifact]) -> R { + pub(super) fn upload_material_delivery( + &self, project: &Path, cloud_id: &str, revision: u64, artifacts: &[Artifact], spu: &str, delivery_files: &[Artifact], + ) -> R { let state_file = project.join("material-delivery.json"); let brief = creation::load(project)?["brief"].clone(); - let model = brief["identifier"].as_str().filter(|s| !s.trim().is_empty()) - .or_else(|| brief["name"].as_str().filter(|s| !s.trim().is_empty())).ok_or("产品名称或编号缺失")?; - let files = artifacts.iter().map(|file| json!({"name":file.name,"group":file.group,"size":file.size,"sha256":file.sha256})).collect::>(); + let model = spu; + let files = delivery_files.iter().map(|file| { + let mut identity = file.file_info(); + identity["group"] = json!(file.group); + identity + }).collect::>(); let identity = json!({"projectId":cloud_id,"kind":"detail","files":files, "origin":self.origin,"accountId":self.auth["account"]["id"], "productModel":model,"productName":brief["name"],"identifierType":brief["identifierType"], @@ -187,7 +508,7 @@ impl Backend { } let purpose = format!("xiaoyi:{cloud_id}:{request_id}"); let mut groups = json!({"main":[],"sku":[],"detail":[]}); - for (index, artifact) in artifacts.iter().enumerate() { + for (index, artifact) in delivery_files.iter().enumerate() { self.check_dispatch()?; let key = index.to_string(); let mut upload = state["uploads"][&key].clone(); @@ -245,8 +566,9 @@ impl Backend { state["uploads"][&key]["complete"] = json!(true); write_json(&state_file, &state)?; } - groups[artifact.group].as_array_mut().ok_or("素材分组无效")? - .push(json!({"uploadId":upload_id,"fileName":artifact.name,"fileSize":artifact.size,"sha256":artifact.sha256})); + let mut file = artifact.file_info(); + file["uploadId"] = json!(upload_id); + groups[artifact.group].as_array_mut().ok_or("素材分组无效")?.push(file); } if read_json(&project.join("context.json"))?["revision"].as_u64() != Some(revision) || detail_artifacts(project)? != artifacts @@ -280,6 +602,89 @@ impl Backend { mod tests { use super::*; + #[test] + fn sku_delivery_expands_registered_barcodes_without_renaming_local_files() { + let variants = [ + json!({"id":"dark","name":"深木色"}), + json!({"id":"light","name":"浅木色"}), + ]; + let mut files = Vec::new(); + for (variant, render, sha) in [("dark", "square", "1"), ("dark", "portrait", "2"), ("light", "square", "3")] { + files.push(Artifact { path: PathBuf::from(format!("{variant}-{render}.jpg")), name: format!("{render}.jpg"), + group: "sku", size: 100, sha256: sha.repeat(64), width: 1440, height: 1440, sku_variant: Some(variant.into()), sku: None }); + } + let brief = json!({"skuBindings":{"dark":"SKU-D,SKU-V","light":"SKU-L"}}); + let mut catalog = vec![ + json!({"skuCode":"SKU-D","barcodes":["00123456","00123457"]}), + json!({"skuCode":"SKU-V","barcodes":["00123458"]}), + json!({"skuCode":"SKU-L","barcodes":["00234567"]}), + ]; + let mapped = bind_sku_files(&files, &brief, &variants, &catalog).unwrap(); + assert_eq!(mapped.len(), 7); + assert_eq!(mapped.iter().filter(|file| file.name == "00123456.jpg").count(), 2); + assert_eq!(mapped[0].file_info()["skuCode"], "SKU-D"); + assert_eq!(mapped[0].file_info()["barcode"], "00123456"); + assert_eq!(mapped[0].path, files[0].path); + assert!(bind_sku_files(&files, &json!({}), &variants, &catalog).is_err()); + catalog[2]["barcodes"] = json!(["00123456"]); + assert!(bind_sku_files(&files, &brief, &variants, &catalog).unwrap_err().contains("同时绑定")); + } + + #[test] + #[ignore = "requires an original older .xiaoyi delivery bundle"] + fn reopened_legacy_bundle_uses_its_existing_jpgs_and_rejects_new_edits() { + let entry = PathBuf::from(std::env::var_os("XIAOYI_TEST_LEGACY_DELIVERY").expect("old .xiaoyi entry")); + let checkpoint = read_json(&entry).unwrap(); + assert!(checkpoint.get("resourcePaths").is_none(), "fixture must be an older uncompressed project"); + let directory = tempfile::tempdir().unwrap(); + let id = project_file::open(&entry, directory.path(), checkpoint["scope"].as_str().unwrap()).unwrap(); + let project = directory.path().join(id); + let path = project.as_path(); + assert!(!path.join("product-exports").exists()); + let files = detail_artifacts(path).unwrap(); + for group in ["detail", "main", "sku"] { + assert!(files.iter().any(|file| file.group == group)); + } + assert_eq!(files.len(), 32); + assert!(files.iter().all(|file| file.path.extension().unwrap() == "jpg")); + let mut current = creation::load(path).unwrap(); + current["designSnapshot"]["models"]["copy"] = json!("new-client-model"); + write_json(&path.join("creation.json"), ¤t).unwrap(); + assert_eq!(detail_artifacts(path).unwrap(), files); + + let before = current.clone(); + current["brief"]["name"] = json!("商品资料已变"); + write_json(&path.join("creation.json"), ¤t).unwrap(); + assert!(detail_artifacts(path).unwrap_err().contains("商品资料或模板已改动")); + write_json(&path.join("creation.json"), &before).unwrap(); + let mut context = read_json(&path.join("context.json")).unwrap(); + context["revision"] = json!(context["revision"].as_u64().unwrap() + 1); + write_json(&path.join("context.json"), &context).unwrap(); + assert!(detail_artifacts(path).unwrap_err().contains("画布版本已变化")); + } + + #[test] + #[ignore = "requires two original delivered projects with a later rule refresh"] + fn older_local_exports_keep_their_verified_jpgs_after_a_rule_refresh() { + let paths = std::env::var_os("XIAOYI_TEST_RULE_REFRESH_PROJECTS").expect("old project directories"); + let mut validated = 0; + for project in std::env::split_paths(&paths) { + let state = canvas_workspace::load(&project).unwrap(); + let creation = creation::load(&project).unwrap(); + for output in canvas_workspace::production_stages(&state) { + let variant = output["variantId"].as_str().unwrap(); + let component = output["outputId"].as_str().unwrap(); + let receipt = canvas_workspace::published_receipt(&canvas_workspace::receipt_path(&project, variant, component)).unwrap(); + assert!(!canvas_workspace::delivery_inputs_match(&state, &creation, variant, component, &receipt)); + } + let files = detail_artifacts(&project).unwrap(); + assert_eq!(files.len(), 26); + assert!(files.iter().all(|file| file.path.extension().unwrap() == "jpg")); + validated += 1; + } + assert_eq!(validated, 2); + } + #[test] fn registered_artifact_must_match_the_file_submitted() { let dir = tempfile::tempdir().unwrap(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs index 1bc029a9..e2e436f9 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs @@ -667,8 +667,9 @@ impl Backend { super::projects::idle(&dir)?; let artifacts = super::material_delivery::detail_artifacts(&dir)?; let creation_revision = creation::load(&dir)?["revision"].clone(); + let (spu, delivery_files) = self.bind_sku_delivery(&dir, &artifacts)?; let cloud_id = self.delivery_project_id(&dir, revision, &artifacts)?; - let mut receipt = self.upload_material_delivery(&dir, &cloud_id, revision, &artifacts)?; + let mut receipt = self.upload_material_delivery(&dir, &cloud_id, revision, &artifacts, &spu, &delivery_files)?; receipt["projectRevision"] = json!(revision); receipt["creationRevision"] = creation_revision.clone(); let context = { diff --git a/apps/detail-photocraft/client-version.txt b/apps/detail-photocraft/client-version.txt index bba03ae1..a0877ab1 100644 --- a/apps/detail-photocraft/client-version.txt +++ b/apps/detail-photocraft/client-version.txt @@ -1 +1 @@ -1.2611.3006 +1.2612.101 diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index c9b4e2c3..ac0a7cbc 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -1318,6 +1318,22 @@ impl Workspace { } ui.add_space(12.0); self.sku_colors(ui, width, field_scope); + 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); self.references_ui(app, ui, width); brief_section_break(ui); @@ -1514,6 +1530,9 @@ impl Workspace { } fn save_sku_colors(&mut self, variants: Vec) { + 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)); + } set_brief_variants(&mut self.creation_brief, variants); if !self.creation_brief["outputVariantIds"].is_object() { self.creation_brief["outputVariantIds"] = json!({}); diff --git a/docs/自动上架平台成套入库通知接口.md b/docs/自动上架平台成套入库通知接口.md index 5ce53aa3..c9df5f56 100644 --- a/docs/自动上架平台成套入库通知接口.md +++ b/docs/自动上架平台成套入库通知接口.md @@ -183,6 +183,23 @@ X-API-Key: your-api-key | `video` | 自动上架-视频 | `video` | | `buyer_show` | 自动上架-买家秀 | `buyer_show` | +### 完结上传字段 + +客户端先走分片上传,再调用 `POST /api/desktop/deliveries` 提交。三个类型共用 `projectId`、`requestId`、`kind`、`productModel`,并可附带 `productName`、`brandName`、`productCategoryName`、`categoryName`、`identifierType`。其中 `categoryName` 表示店铺。小壹三件套会将素材库核对后的 SPU 填入 `productModel`。 + +| 类型 | 提交的 `assets` | 每个文件 | +| --- | --- | --- | +| `detail` | `main[]`、`sku[]`、`detail[]` | `uploadId`、`fileName`、`fileSize`、`sha256`。新版 SKU 图另传 `skuCode` 和 `barcode` | +| `video` | `files[]` | `uploadId`、`fileName`、`fileSize`、`sha256` | +| `buyer_show` | `files[]` | `uploadId`、`fileName`、`fileSize`、`sha256` | + +### SKU 图片和条码 + +- 在小壹产品资料中为每种花色填写对应的素材库 SKU 编号。同一张花色图对应多个 SKU 时,用逗号分隔 SKU 编号。 +- 小壹读取素材库登记的 `SPU → SKU → 条码` 关系。每个条码生成一个 `条码.jpg` 的交付条目,保留条码的前导零。入库会同时保存图的 SKU 编号和条码。 +- 同一条码有多张成品时,条目保留同一个文件名,并以 `id` 区分。整套 ZIP 将同名文件放进 `sku/{sortOrder}/` 目录,文件名仍为 `条码.jpg`。 +- 正式资源响应中的 `spu` 是已确认的 SPU。`assets.sku[]` 额外返回 `skuCode` 和 `barcodes[]`。旧交付记录若没有登记 SKU 或条码,对应字段为 `null` 或空数组。 + 接收方持具有产品素材读取权限的 `X-API-Key` 请求 `pullUrl`,根据返回的 `assets` 分组和 `sortOrder` 取成品。单文件使用各条目的 `downloadUrl`,整套使用 `downloadUrls.all`。下载链接已签名,过期后重新查询素材。商品型号、品类、品牌和商品名称从查询结果读取。`categoryName` 表示店铺,项目未提供时为空。 回调由素材库服务器发起。接收方按 `eventId` 去重,并用 `materialId` 定位素材。返回 `2xx` 表示接收成功,超时或失败会重试,后台可手动补发。素材可能在收到通知后被撤回,拉取时以查询接口的当前结果为准。 diff --git a/lib/__tests__/detail-generator-materials.test.ts b/lib/__tests__/detail-generator-materials.test.ts index 5429af7e..ab774ceb 100644 --- a/lib/__tests__/detail-generator-materials.test.ts +++ b/lib/__tests__/detail-generator-materials.test.ts @@ -32,6 +32,21 @@ test('SPU and barcode matches preserve concrete white-background SKU identity', expect(canUserViewMaterial).toHaveBeenCalledWith(undefined, '', undefined, '标准模型', 'owner-1') }) +test('identity lookup returns all registered SKUs and barcode aliases without requiring source images', async () => { + const row = material() + row.skus[0].barcodes.push({ barcode: '00001234' }) + row.skus.push({ ...row.skus[0], id: 'sku-2', skuName: 'SKU-2', barcodes: [{ barcode: '00001235' }] }) + ;(prisma.material.findMany as jest.Mock).mockResolvedValue([row]) + + const identities = await findDetailMaterialMatches('owner-1', 'spu', 'SPU-1', true) + expect(identities).toEqual([ + expect.objectContaining({ skuCode: 'SKU-1', barcodes: ['00001234', 'BAR-1'] }), + expect.objectContaining({ skuCode: 'SKU-2', barcodes: ['00001235'], assets: [] }), + ]) + const pictureMatches = await findDetailMaterialMatches('owner-1', 'spu', 'SPU-1') + expect(pictureMatches.map(match => match.skuCode)).toEqual(['SKU-1']) +}) + test('private-material gate runs before type permissions and no private metadata escapes', async () => { ;(canAccessMaterialPrivacy as jest.Mock).mockResolvedValue(false) expect(await findDetailMaterialMatches('owner-1', 'spu', 'SPU-1')).toEqual([]) diff --git a/lib/__tests__/product-assets-route.test.ts b/lib/__tests__/product-assets-route.test.ts index 7af8e524..cae8333c 100644 --- a/lib/__tests__/product-assets-route.test.ts +++ b/lib/__tests__/product-assets-route.test.ts @@ -43,6 +43,10 @@ jest.mock('@/lib/external-api', () => { } }) +jest.mock('@/lib/prisma', () => ({ + prisma: { $queryRawUnsafe: jest.fn().mockResolvedValue([{ productName: '椅子', brandName: '测试品牌', identifierType: 'sku' }]) }, +})) + jest.mock('@/lib/product-package', () => ({ validateTaskNo: jest.fn((taskNo?: string | null) => Boolean(taskNo && taskNo.startsWith('TASK'))), getMaterialByTaskNo: jest.fn(), @@ -119,6 +123,28 @@ describe('external product-assets route', () => { expect(response.status).toBe(404) }) + test('自动上架详情按素材 ID 返回 SPU、每张 SKU 图的编号和条码', async () => { + const id = '35d8644b-1e09-4ce8-9bb0-c529b39ba52e' + ;(getMaterialById as jest.Mock).mockResolvedValue({ + id, productModel: 'SPU-001', materialType: '自动上架-详情', + 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 }, + ], + }) + const response = await GET(createRequest(`https://example.com/api/external/product-assets?materialId=${id}`)) + expect(response.status).toBe(200) + expect((await response.json()).data).toMatchObject({ + spu: 'SPU-001', + productName: '椅子', + assets: { sku: [ + { fileName: '00123456.jpg', skuCode: 'SKU-D', barcodes: ['00123456'], sortOrder: 1 }, + { fileName: '00234567.jpg', skuCode: 'SKU-L', barcodes: ['00234567'], sortOrder: 2 }, + ] }, + }) + }) + test('materialId 查询应返回任务详情正式资源,并为所有资源组补齐 sortOrder', async () => { ;(getMaterialById as jest.Mock).mockResolvedValue({ id: '35d8644b-1e09-4ce8-9bb0-c529b39ba52e', diff --git a/lib/desktop-client/catalog.ts b/lib/desktop-client/catalog.ts index 5a9c4a84..22835d2b 100644 --- a/lib/desktop-client/catalog.ts +++ b/lib/desktop-client/catalog.ts @@ -56,7 +56,11 @@ export async function desktopMaterialThumbnail(ownerId: string, id: string) { return { bytes, mime: imageMime(bytes) } } export async function desktopProducts(ownerId: string, params: URLSearchParams) { - const matches = await findDetailMaterialMatches(ownerId, params.get('identifierType'), params.get('identifier')) + const identities = params.get('skuIdentities') === '1' + const matches = await findDetailMaterialMatches(ownerId, params.get('identifierType'), params.get('identifier'), identities) + if (identities) { + return { items: matches.filter(item => item.skuCode).map(({ productModel, skuCode, barcodes }) => ({ productModel, skuCode, barcodes })) } + } const rows = await prisma.material.findMany({ where: { id: { in: matches.map(item => item.materialId) } }, select: { id: true, categoryName: true, productCategoryName: true } }) const names = Array.from(new Set(rows.map(row => row.productCategoryName).filter((name): name is string => !!name))) // Material stores the explicit category name; ProductCategory.name is unique. diff --git a/lib/desktop-client/deliveries.ts b/lib/desktop-client/deliveries.ts index 6e26c572..983a6aeb 100644 --- a/lib/desktop-client/deliveries.ts +++ b/lib/desktop-client/deliveries.ts @@ -11,11 +11,12 @@ import { buildStoredUploadPath, getUploadRootDir, getUploadStorageExtension, ins import { resolveStrictChildPath } from '@/lib/path-security' import { validateUploadFileName } from '@/lib/upload-file-name' import { detailTransactionLock } from '@/lib/detail-generator/repository' +import { findDetailMaterialMatches } from '@/lib/detail-generator/materials' import { ensureExternalNotificationTables, queueXiaoyiAutoListingNotification, wakeXiaoyiAutoListingNotifications } from '@/lib/external-auto-listing' import { desktopAssert, desktopId } from './contract.mjs' type DeliveryKind = 'detail' | 'video' | 'buyer_show' -type FileInput = { uploadId: string; fileName: string; fileSize: number; sha256: string } +type FileInput = { uploadId: string; fileName: string; fileSize: number; sha256: string; skuCode?: string; barcode?: string } type Input = { projectId: string; requestId: string; kind: DeliveryKind; productModel: string; categoryName?: string; productCategoryName?: string; brandName?: string; productName?: string; identifierType?: string; @@ -52,12 +53,38 @@ 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 编号') + } files.push({ group: group === 'files' ? (input.kind === 'detail' ? 'source' : input.kind) : group, - uploadId: file.uploadId, fileName: name.fileName!, fileSize: file.fileSize, sha256: file.sha256 }) + uploadId: file.uploadId, fileName: name.fileName!, fileSize: file.fileSize, sha256: file.sha256, ...identity }) } } desktopAssert(files.length > 0 && files.length <= 500 && new Set(files.map(file => file.uploadId)).size === files.length, '交付文件为空或重复') - desktopAssert(new Set(files.map(file => file.group + '\\0' + file.fileName)).size === files.length, '同一分组中有重名文件,请调整名称') + const skuFiles = files.filter(file => file.group === 'sku') + const barcodeOwners = new Map() + const filenames = new Set() + for (const file of files) { + const name = file.group + '\\0' + file.fileName.toLowerCase() + if (file.barcode) { + const sku = file.skuCode! + const previous = barcodeOwners.get(name) + desktopAssert(!previous || previous === sku, '同一条码不能绑定到多个 SKU') + barcodeOwners.set(name, sku) + } + const identity = file.barcode ? name + '\\0' + file.sha256 : name + desktopAssert(!filenames.has(identity), '同一分组中有重复文件') + filenames.add(identity) + } + if (barcodeOwners.size) { + desktopAssert(skuFiles.every(file => file.barcode), '每张 SKU 图都须提供条码') + } if (input.kind === 'detail') { desktopAssert(['main','sku','detail'].every(group => files.some(file => file.group === group)), '详情三件套需要主图、SKU 和详情图') desktopAssert(files.every(file => file.group !== 'source' && /\.(?:jpe?g|png|webp)$/i.test(file.fileName)), '详情三件套只接收主图、SKU 和详情成品图') @@ -66,7 +93,7 @@ function normalized(input: Input) { desktopAssert(files.every(file => !/\.(?:psd|psb|pcraft)$/i.test(file.fileName)), '只接收成品文件,不接收源文件') } const identity = { projectId, requestId: input.requestId, kind: input.kind, productModel, categoryName, productCategoryName, brandName, productName, identifierType, - files: files.map(({group,fileName,fileSize,sha256}) => ({group,fileName,fileSize,sha256})) } + files: files.map(({group,fileName,fileSize,sha256,barcode,skuCode}) => ({group,fileName,fileSize,sha256,...(barcode ? {barcode,skuCode} : {})})) } return { ...identity, files, fingerprint: createHash('sha256').update(JSON.stringify(identity)).digest('hex') } } @@ -113,6 +140,17 @@ 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 catalog = await findDetailMaterialMatches(ownerId, 'spu', request.productModel, true) + const valid = new Map>() + 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) + } + desktopAssert(skuFiles.every(file => valid.get(file.skuCode!)?.has(file.barcode!)), 'SKU 或条码不属于该 SPU,请核对产品资料') + } + const uploadRoot = getUploadRootDir() const owner = createHash('sha256').update(ownerId).digest('hex') const folder = path.join(uploadRoot, 'xiaoyi-deliveries', owner, request.projectId, request.requestId) @@ -177,7 +215,11 @@ export async function createDesktopDelivery(ownerId: string, input: Input, reaut userId:ownerId, authorName:user!.realName || user!.username, productModel:request.productModel, categoryName:request.categoryName, productCategoryName:request.productCategoryName, sceneName:'', materialType, previewUrl:'', taskStatus:'completed', isFullSet:request.kind === 'detail', isAiGenerated:true, - assets:{create:files.map((file,index)=>({assetType:file.group,fileUrl:file.storedPath,fileName:file.fileName,fileSize:BigInt(file.fileSize),sortOrder:index}))}, + assets: { create: files.map((file,index) => ({ + assetType: file.group, fileUrl: file.storedPath, fileName: file.fileName, + fileSize: BigInt(file.fileSize), sortOrder: index, skuCode: file.skuCode, + ...(file.barcode ? { barcodes: { create: { barcode: file.barcode } } } : {}), + })) }, },select:{id:true}}) await tx.$executeRawUnsafe( 'INSERT INTO desktop_material_deliveries (id,owner_id,project_id,request_id,kind,fingerprint,material_id,material_type,brand_name,product_name,identifier_type) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)', diff --git a/lib/detail-generator/materials.ts b/lib/detail-generator/materials.ts index b53eb474..84db3e42 100644 --- a/lib/detail-generator/materials.ts +++ b/lib/detail-generator/materials.ts @@ -1,5 +1,6 @@ import path from 'path' import { prisma } from '@/lib/prisma' +import { XIAOYI_DELIVERY_TYPES } from '@/lib/xiaoyi-delivery-material' import { canUserViewMaterial } from '@/lib/department-permission' import { canAccessMaterialPrivacy } from '@/lib/task-detail-privacy' import { getS3ObjectStream, getTrustedS3MutationKey, isS3Url } from '@/lib/s3' @@ -19,42 +20,50 @@ async function assertVisible(material: any, ownerId: string) { } } -export async function findDetailMaterialMatches(ownerId: string, identifierType: unknown, identifier: unknown) { +export async function findDetailMaterialMatches(ownerId: string, identifierType: unknown, identifier: unknown, includeSkuIdentities = false) { if (!['sku', 'spu', 'barcode'].includes(String(identifierType)) || typeof identifier !== 'string' || !identifier.trim() || identifier.length > 200) throw new DetailGeneratorError('请提供有效的产品编号') const value = identifier.trim().toUpperCase() const match = identifierType === 'spu' ? { productModel: { equals: value, mode: 'insensitive' as const } } : identifierType === 'sku' ? { OR: [{ skus: { some: { deletedAt: null, skuName: { equals: value, mode: 'insensitive' as const } } } }, { assets: { some: { skuCode: { equals: value, mode: 'insensitive' as const } } } }] } : { OR: [{ skus: { some: { deletedAt: null, barcodes: { some: { barcode: value, deletedAt: null } } } } }, { assets: { some: { barcodes: { some: { barcode: value } } } } }] } const rows = await prisma.material.findMany({ - where: { deletedAt: null, isIncompleteShell: false, ...match }, take: 30, + where: { deletedAt: null, isIncompleteShell: false, ...match, + ...(includeSkuIdentities ? { materialType: { notIn: [...XIAOYI_DELIVERY_TYPES] } } : {}) }, + ...(includeSkuIdentities ? {} : { take: 30 }), include: { assets: { include: { barcodes: true }, orderBy: { sortOrder: 'asc' } }, skus: { where: { deletedAt: null }, include: { barcodes: { where: { deletedAt: null } } }, orderBy: { sortOrder: 'asc' } } }, }) const matches: any[] = [] for (const material of rows) { try { await assertVisible(material, ownerId) } catch (error) { if (error instanceof DetailGeneratorError && error.status === 403) continue; throw error } - const candidates = new Map() - const append = (variant: string, item: any) => { - const found = candidates.get(variant) || { materialId: material.id, productModel: material.productModel, skuCode: variant, variant, assets: [] } - found.assets.push(item); candidates.set(variant, found) + const candidates = new Map; assets: any[] }>() + const append = (variant: string, barcodes: { barcode: string }[], item?: { id: string; source: string; name: string; previewUrl: string }) => { + if (!item && (!includeSkuIdentities || !variant)) return + const found = candidates.get(variant) || { materialId: material.id, productModel: material.productModel, skuCode: variant, variant, barcodes: new Set(), assets: [] } + for (const { barcode } of barcodes) { + if (barcode.trim()) found.barcodes.add(barcode.trim()) + } + if (item) found.assets.push(item) + candidates.set(variant, found) } for (const sku of material.skus) { if (identifierType === 'sku' && sku.skuName.toUpperCase() !== value) continue if (identifierType === 'barcode' && !sku.barcodes.some(code => code.barcode === value)) continue const source = sku.previewUrl && imagePath(sku.previewUrl) ? sku.previewUrl : imagePath(sku.filePath) ? sku.filePath : null - if (source) append(sku.skuName, { id: sku.id, source: 'sku', name: sku.skuName, previewUrl: `/api/detail-generator/materials/${material.id}/images/sku/${sku.id}` }) + append(sku.skuName, sku.barcodes, source ? { id: sku.id, source: 'sku', name: sku.skuName, previewUrl: `/api/detail-generator/materials/${material.id}/images/sku/${sku.id}` } : undefined) } for (const asset of material.assets) { - if (!imagePath(asset.fileUrl)) continue + const hasImage = imagePath(asset.fileUrl) + if (!hasImage && !includeSkuIdentities) continue const whiteBackground = parseStandardModelWhiteBgAssetType(asset.assetType) const linkedSku = whiteBackground ? material.skus.find(sku => sku.id === whiteBackground.skuId) : undefined const variant = asset.skuCode || linkedSku?.skuName || '' if (identifierType === 'sku' && variant.toUpperCase() !== value) continue if (identifierType === 'barcode' && !asset.barcodes.some(code => code.barcode === value) && !linkedSku?.barcodes.some(code => code.barcode === value)) continue - append(variant, { id: asset.id, source: 'asset', name: asset.fileName || asset.assetType, previewUrl: `/api/detail-generator/materials/${material.id}/images/asset/${asset.id}` }) + append(variant, [...asset.barcodes, ...(linkedSku?.barcodes || [])], hasImage ? { id: asset.id, source: 'asset', name: asset.fileName || asset.assetType, previewUrl: `/api/detail-generator/materials/${material.id}/images/asset/${asset.id}` } : undefined) } - matches.push(...Array.from(candidates.values())) + matches.push(...Array.from(candidates.values(), row => ({ ...row, barcodes: Array.from(row.barcodes).sort() }))) } - return matches.slice(0, 40) + return includeSkuIdentities ? matches : matches.slice(0, 40) } export async function readDetailMaterialImage(ownerId: string, materialId: string, source: string, sourceId: string): Promise<{ buffer: Buffer; name: string; variant: string; productModel: string; barcodes: string[] }> { diff --git a/lib/external-auto-listing.ts b/lib/external-auto-listing.ts index fc2b0faa..46b146ba 100644 --- a/lib/external-auto-listing.ts +++ b/lib/external-auto-listing.ts @@ -832,7 +832,9 @@ function scheduleDeliveryProcessing(deliveryId: string, delayMs: number) { const timer = setTimeout(() => { deliveryTimers.delete(deliveryId) - void processExternalNotificationDelivery(deliveryId) + void processExternalNotificationDelivery(deliveryId).catch((error) => { + console.error('[external-notification] 投递结果保存失败:', error) + }) }, Math.max(0, delayMs)) timer.unref?.() deliveryTimers.set(deliveryId, timer) @@ -1328,8 +1330,8 @@ export async function processExternalNotificationDelivery( last_status_code = $3, last_response_body = $4, last_error = $5, - next_retry_at = $6, - completed_at = $7, + next_retry_at = $6::timestamp, + completed_at = $7::timestamp, updated_at = NOW() WHERE id = $1 `, diff --git a/lib/product-package.ts b/lib/product-package.ts index 1bb9f86a..4037d6a2 100644 --- a/lib/product-package.ts +++ b/lib/product-package.ts @@ -269,6 +269,7 @@ export async function getMaterialById(materialId: string) { include: { assets: { orderBy: { sortOrder: 'asc' }, + include: { barcodes: { select: { barcode: true } } }, }, user: { select: {