提交详情成品到素材库

This commit is contained in:
WuYongJie 2026-11-30 21:10:03 +08:00
parent 53712220f0
commit 71eecd09d6
6 changed files with 328 additions and 6 deletions

View File

@ -91,6 +91,8 @@ mod context_usage;
mod prompt_library;
#[path = "jiansun_delivery.rs"]
mod delivery;
#[path = "jiansun_material_delivery.rs"]
mod material_delivery;
#[path = "jiansun_project_file.rs"]
mod project_file;
#[path = "jiansun_transfer.rs"]

View File

@ -95,7 +95,7 @@ fn output_uses_variant(brief: &Value, component: &str, id: &str) -> bool {
brief["outputVariantIds"][component].as_array().is_none_or(|ids| ids.iter().any(|value| value == id))
}
fn production_stages(state: &Value) -> Vec<Value> {
pub(super) fn production_stages(state: &Value) -> Vec<Value> {
if !state["productTemplates"].is_object() { return Vec::new(); }
let outputs: std::collections::BTreeSet<_> = ["productTemplates", "productTemplateIssues"].into_iter()
.flat_map(|key| state[key].as_object().into_iter().flat_map(|rows| rows.keys().map(String::as_str)))
@ -2826,7 +2826,7 @@ fn stage_input_hash(state: &Value, creation: &Value, variant: &str, component: &
Ok(hash(&inputs.to_string()))
}
fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_editable: bool) -> Vec<Value> {
pub(super) fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_editable: bool) -> Vec<Value> {
let creation = creation::load(dir);
production_stages(state).into_iter().filter(|stage| {
let (Some(variant), Some(component)) = (stage["variantId"].as_str(), stage["outputId"].as_str()) else { return true };

View File

@ -0,0 +1,272 @@
use super::{Backend, R, Value, body, canvas_workspace, creation, json, read_json, write_json};
use std::{
collections::HashSet,
fs::{self, File},
io::{Read, Seek, SeekFrom},
path::{Path, PathBuf},
time::Duration,
};
use uuid::Uuid;
const CHUNK_SIZE: u64 = 10 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Artifact {
path: PathBuf,
name: String,
group: &'static str,
size: u64,
sha256: String,
}
fn artifact(generation: &Path, row: &Value, group: &'static str, name: String) -> R<Artifact> {
let source = row["path"].as_str().and_then(|p| Path::new(p).file_name()).ok_or("成品文件路径缺失")?;
let path = generation.join(source);
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();
if fs::metadata(&path).map_err(|_| "已登记成品文件不存在")?.len() != size
|| canvas_workspace::file_digest(&path).map_err(|_| "已登记成品文件无法读取")? != sha256
{
return Err("成品文件与已登记版本不一致,请重新导出成品".into());
}
Ok(Artifact { path, name, group, size, sha256 })
}
pub(super) fn detail_artifacts(project: &Path) -> R<Vec<Artifact>> {
let checkpoint = read_json(&project.join("production-run.json"))
.map_err(|_| "请先完成详情页、主图和 SKU 的制作并导出成品")?;
if checkpoint["active"] == true {
return Err("制作任务仍在运行,请完成或停止后再提交".into());
}
let state = canvas_workspace::load(project)?;
let creation = creation::load(project)?;
if !canvas_workspace::remaining_stages(project, &state, &creation["revision"], true).is_empty()
{
return Err("项目资料或画布已变化,请先重新导出对应成品".into());
}
let outputs = canvas_workspace::production_stages(&state);
if outputs.is_empty() { return Err("没有可提交的已导出成品,请先完成制作".into()); }
let mut found = HashSet::new();
let mut artifacts = Vec::new();
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("成品类型缺失")?;
let group = match component {
"detail" => "detail",
"main_images" => "main",
"sku_images" => "sku",
_ => return Err("此制作结果暂不支持详情三件套提交".into()),
};
if !found.insert((variant.to_owned(), component.to_owned())) {
return Err("成品清单中存在重复输出".into());
}
let pointer = canvas_workspace::receipt_path(project, variant, component);
let receipt = canvas_workspace::published_receipt(&pointer)?;
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("成品版本无效")?;
let manifest_path = pointer.with_file_name(canvas_workspace::manifest_path(generation_id));
let generation = manifest_path.parent().ok_or("成品目录无效")?;
let manifest = read_json(&manifest_path)?;
if manifest["generationId"] != generation_id || manifest["variantId"] != variant
|| manifest["outputId"] != component || manifest["workspaceId"] != state["id"]
|| manifest["validation"]["mode"] != "full"
{
return Err("成品版本与制作回执不一致,请重新导出".into());
}
let files = manifest["files"].as_array().filter(|rows| !rows.is_empty()).ok_or("成品图片缺失")?;
let screens = manifest["screenFiles"].as_array().filter(|rows| !rows.is_empty());
let image_group = if component == "detail" && screens.is_some() { "files" } else { group };
for (index, row) in files.iter().enumerate() {
artifacts.push(artifact(generation, row, image_group, format!("{component}-{:03}-{:03}.jpg", output_index + 1, index + 1))?);
}
if component == "detail" {
for (index, row) in screens.into_iter().flatten().enumerate() {
artifacts.push(artifact(generation, row, group, format!("detail-screen-{:03}-{:03}.jpg", output_index + 1, index + 1))?);
}
}
let layered = &manifest["layeredDocument"];
let format = layered["format"].as_str().filter(|v| matches!(*v, "psd" | "psb")).ok_or("成品分层文件缺失")?;
artifacts.push(artifact(generation, layered, "files", format!("{component}-{:03}.{format}", output_index + 1))?);
}
for component in ["detail", "main_images", "sku_images"] {
if !found.iter().any(|(_, item)| item == component) {
return Err("详情页、主图或 SKU 成品尚未全部导出".into());
}
}
Ok(artifacts)
}
impl Backend {
fn material_request(&self, endpoint: &str, payload: &Value) -> R<Value> {
self.check_dispatch()?;
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
let response = self.http.post(format!("{}/api/{endpoint}", self.origin))
.bearer_auth(token).json(payload).timeout(Duration::from_secs(300)).send()
.map_err(|_| "素材库连接中断,请重新点击完结继续提交")?;
self.check_cloud_authority(response.status().as_u16())?;
let (status, value) = body(response, 2 * 1024 * 1024)?;
if status == 404 && endpoint == "materials/upload/complete" {
return Err("素材上传会话已失效".into());
}
if status == 409 && endpoint == "desktop/deliveries"
&& matches!(value["code"].as_str(), Some("upload_mismatch" | "upload_incomplete"))
{
return Err("素材上传记录已失效".into());
}
if status != 200 {
return Err(value["error"].as_str().unwrap_or("素材库提交失败,请重新点击完结继续提交").to_owned());
}
Ok(value)
}
pub(super) fn upload_material_delivery(&self, project: &Path, cloud_id: &str, revision: u64, artifacts: &[Artifact]) -> R<Value> {
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::<Vec<_>>();
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"],
"brandName":brief["brandName"],"productCategoryName":brief["categoryName"]});
let mut state = if state_file.exists() { read_json(&state_file)? } else { Value::Null };
if state["identity"] != identity {
state = json!({"identity":identity,"requestId":Uuid::new_v4().to_string(),"uploads":{}});
write_json(&state_file, &state)?;
}
let request_id = state["requestId"].as_str().filter(|id| Uuid::parse_str(id).is_ok())
.ok_or("素材提交记录无效")?.to_owned();
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
self.check_dispatch()?;
let response = self.http.get(format!("{}/api/desktop/deliveries/{cloud_id}/detail", self.origin))
.bearer_auth(token).timeout(Duration::from_secs(30)).send()
.map_err(|_| "素材库提交记录暂时无法核对,请重新点击完结")?;
self.check_cloud_authority(response.status().as_u16())?;
let (status, existing) = body(response, 2 * 1024 * 1024)?;
if status != 200 {
return Err(existing["error"].as_str().unwrap_or("素材库提交记录读取失败").into());
}
if existing["state"] == "removed" {
let id = existing["materialId"].as_str().unwrap_or("未知");
return Err(format!("原交付素材已被删除,素材 ID:{id},请在素材库中处理"));
}
if existing["requestId"] == request_id && existing["state"] == "completed" {
let material_id = existing["materialId"].as_str().filter(|id| !id.is_empty()).ok_or("素材库提交回执缺少素材 ID")?;
state["materialId"] = json!(material_id);
write_json(&state_file, &state)?;
return Ok(json!({"materialId":material_id,"requestId":request_id,"kind":"detail"}));
}
if let Some(id) = existing["materialId"].as_str().filter(|id| !id.is_empty()) {
return Err(format!("此项目已有完结交付,素材 ID:{id};已有素材已保留"));
}
let purpose = format!("xiaoyi:{cloud_id}:{request_id}");
let mut groups = json!({"main":[],"sku":[],"detail":[],"files":[]});
for (index, artifact) in artifacts.iter().enumerate() {
self.check_dispatch()?;
let key = index.to_string();
let mut upload = state["uploads"][&key].clone();
if upload["uploadId"].is_null() {
let chunks = artifact.size.div_ceil(CHUNK_SIZE);
upload = self.material_request("materials/upload/init", &json!({"fileName":artifact.name,
"fileSize":artifact.size,"totalChunks":chunks,"chunkSize":CHUNK_SIZE,"uploadPurpose":purpose}))?;
if upload["uploadId"].as_str().is_none() { return Err("素材库未返回上传编号".into()); }
upload["nextChunk"] = json!(0);
state["uploads"][&key] = upload.clone();
write_json(&state_file, &state)?;
}
let upload_id = upload["uploadId"].as_str().ok_or("素材上传编号缺失")?.to_owned();
if upload["complete"] != true {
let mut file = File::open(&artifact.path).map_err(|_| "成品文件无法读取")?;
let chunks = artifact.size.div_ceil(CHUNK_SIZE);
let start = upload["nextChunk"].as_u64().unwrap_or(0);
for index in start..chunks {
self.check_dispatch()?;
let offset = index * CHUNK_SIZE;
let size = (artifact.size - offset).min(CHUNK_SIZE);
file.seek(SeekFrom::Start(offset)).map_err(|_| "成品文件读取中断")?;
let mut bytes = vec![0; size as usize];
file.read_exact(&mut bytes).map_err(|_| "成品文件读取中断")?;
let response = self.http.post(format!("{}/api/materials/upload/chunk", self.origin))
.bearer_auth(token).header("Content-Type", "application/octet-stream")
.header("X-Upload-Id", &upload_id).header("X-Chunk-Index", index.to_string())
.header("X-File-Name", &artifact.name).header("X-Chunk-Size", size.to_string())
.timeout(Duration::from_secs(300)).body(bytes).send()
.map_err(|_| "成品上传中断,请重新点击完结继续提交")?;
self.check_cloud_authority(response.status().as_u16())?;
let (status, value) = body(response, 2 * 1024 * 1024)?;
if status == 404 {
state["uploads"][&key] = Value::Null;
write_json(&state_file, &state)?;
return Err("素材上传会话已失效,请重新点击完结继续提交".into());
}
if status != 200 {
return Err(value["error"].as_str().unwrap_or("成品上传失败,请重新点击完结继续提交").into());
}
state["uploads"][&key]["nextChunk"] = json!(index + 1);
write_json(&state_file, &state)?;
}
let completed = match self.material_request("materials/upload/complete", &json!({"uploadId":upload_id})) {
Err(error) if error == "素材上传会话已失效" => {
state["uploads"][&key] = Value::Null;
write_json(&state_file, &state)?;
return Err("素材上传会话已失效,请重新点击完结继续提交".into());
}
result => result?,
};
if completed["uploadId"] != upload_id || completed["fileSize"] != artifact.size {
return Err("素材库文件合并回执不一致".into());
}
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}));
}
if read_json(&project.join("context.json"))?["revision"].as_u64() != Some(revision)
|| detail_artifacts(project)? != artifacts
|| creation::load(project)?["brief"] != brief
{
return Err("项目或成品在上传期间发生变化,请重新核对后完结".into());
}
let result = match self.material_request("desktop/deliveries", &json!({"projectId":cloud_id,"kind":"detail",
"requestId":request_id,"productModel":model,"productName":brief["name"],
"identifierType":brief["identifierType"],"brandName":brief["brandName"],
"productCategoryName":brief["categoryName"],"assets":groups})) {
Err(error) if error == "素材上传记录已失效" => {
state["uploads"] = json!({});
write_json(&state_file, &state)?;
return Err("素材上传记录已过期,请重新点击完结继续提交".into());
}
result => result?,
};
if result["state"] == "removed" {
return Err("原交付素材已被删除,素材 ID 已保留,请在素材库中处理".into());
}
if result["state"] != "completed" { return Err("素材库未确认成品已提交".into()); }
let material_id = result["materialId"].as_str().filter(|id| !id.is_empty()).ok_or("素材库未返回素材 ID")?;
state["materialId"] = json!(material_id);
write_json(&state_file, &state)?;
Ok(json!({"materialId":material_id,"requestId":request_id,"kind":"detail"}))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registered_artifact_must_match_the_file_submitted() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("actual.jpg");
fs::write(&path, b"original output").unwrap();
let digest = canvas_workspace::file_digest(&path).unwrap();
let record = json!({"path":path,"sizeBytes":15,"sha256":digest});
let file = artifact(dir.path(), &record, "main", "main.jpg".into()).unwrap();
assert_eq!(file.path, path);
fs::write(&path, b"changed output!").unwrap();
assert!(artifact(dir.path(), &record, "main", "main.jpg".into()).is_err());
}
}

View File

@ -629,7 +629,7 @@ impl Backend {
}
Ok(())
}
fn check_cloud_authority(&self, status: u16) -> R<()> {
pub(super) fn check_cloud_authority(&self, status: u16) -> R<()> {
if status != 401 { return Ok(()); }
self.revoke_access("auth_revoked");
let _ = self.clone().renew_portal_session();
@ -637,6 +637,47 @@ impl Backend {
}
pub(super) fn sync_project(&mut self, input: &Value) -> R<Value> {
if input["status"] != "completed" {
return self.sync_project_core(input);
}
let id = input["doc"].as_u64().ok_or("请先打开项目")?;
let revision = input["revision"].as_u64().ok_or("缺少本机版本")?;
self.ensure_owner(id)?;
let dir = self.project_dir(id)?;
let artifacts = super::material_delivery::detail_artifacts(&dir)?;
let context = { let _guard = context_guard(); read_json(&dir.join("context.json"))? };
let synced = if context["revision"].as_u64() == Some(revision)
&& context["syncedRevision"].as_u64() == Some(revision)
&& context["syncDirty"] == false && context["project"]["source"] == "desktop"
&& context["project"]["id"].is_string()
{
json!({"cloudLink":context["project"],"syncDirty":false})
} else {
let mut draft = input.clone();
draft["status"] = json!("draft");
self.sync_project_core(&draft)?
};
if synced["syncDirty"] == true {
return Err("本机项目在同步期间发生变化,请重新保存后完结".into());
}
let cloud_id = synced["cloudLink"]["id"].as_str().ok_or("云项目身份缺失")?;
let receipt = self.upload_material_delivery(&dir, cloud_id, revision, &artifacts)?;
{
let _guard = context_guard();
let mut context = read_json(&dir.join("context.json"))?;
context["materialDelivery"] = receipt.clone();
context["syncDirty"] = json!(true);
write_json(&dir.join("context.json"), &context)?;
}
let mut result = self.sync_project_core(input).map_err(|error| format!(
"素材已入库(素材 ID:{}),重新完结会继续同步:{error}",
receipt["materialId"].as_str().unwrap_or("未知")
))?;
result["materialDelivery"] = receipt;
Ok(result)
}
fn sync_project_core(&mut self, input: &Value) -> R<Value> {
let id = input["doc"].as_u64();
let local_id = if let Some(local) = input["localId"].as_str() {
if input["accountId"] != self.auth["account"]["id"] || input["origin"] != self.origin { return Err("同步账户已变化,未上传其他账户项目".into()); }

View File

@ -2821,7 +2821,7 @@ impl Workspace {
Some("paused") => json!({"mode":"pause","state":"paused","reason":self.product_checkpoint["reason"],"error":null}),
_ => json!({"mode":null,"state":"idle","reason":null,"error":null}),
};
for key in ["cloudLink", "syncedRevision", "status"] {
for key in ["cloudLink", "syncedRevision", "status", "materialDelivery"] {
if !v[key].is_null() {
self.project_context[key] = v[key].clone();
}

View File

@ -659,6 +659,10 @@ pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Valu
if let Some(items) = value["projects"].as_array() {
w.merge_project_receipt(app, items);
}
if let Some(id) = value["materialDelivery"]["materialId"].as_str() {
w.project_context["materialDelivery"] = value["materialDelivery"].clone();
w.note(format!("成品已提交素材库,素材 ID:{id}"));
}
w.project_refresh_requested = true;
w.creation_progress = if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into();
}
@ -869,12 +873,15 @@ impl Workspace {
self.sync_confirm = true;
}
let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), "完结项目", self.sync_confirm, self.reduce_motion, 360.0, |ui| {
ui.label("将当前版本标记为完结并同步到云端?");
ui.label("将已完成的详情、主图和 SKU 成品提交到素材库,并同步项目?");
if let Some(id) = self.project_context["materialDelivery"]["materialId"].as_str() {
ui.label(format!("上次提交的素材 ID:{id}"));
}
ui.horizontal(|ui| {
if stitch_ui::action_button(ui, "取消", stitch_ui::ButtonRole::Secondary, true).clicked() {
self.sync_confirm = false;
}
if stitch_ui::action_button(ui, "完结并同步", stitch_ui::ButtonRole::Primary, idle).clicked() {
if stitch_ui::action_button(ui, "完结并提交", stitch_ui::ButtonRole::Primary, idle).clicked() {
self.sync_confirm = false;
self.sync_action(app, "project-sync", json!({"status":"completed","syncChatHistory":chat}));
}