fix(xiaoyi): 修复三件套切页与问题反馈通知

This commit is contained in:
WuYongJie 2026-12-02 18:56:03 +08:00
parent b989cd0038
commit bf80fe7a7e
6 changed files with 407 additions and 52 deletions

View File

@ -13,7 +13,7 @@ jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() }))
jest.mock('@/lib/youyidian-notification-center', () => ({ submitYouyidianNotification: jest.fn() }))
jest.mock('@/lib/prisma', () => ({ prisma: {
user: { findUnique: jest.fn() },
user: { findUnique: jest.fn(), findMany: jest.fn() },
desktopClientFeedback: { createMany: jest.fn(), findFirst: jest.fn(), findUnique: jest.fn() },
} }))
@ -42,7 +42,9 @@ function get(idParam = id) {
beforeEach(() => {
jest.resetAllMocks()
jest.replaceProperty(process, 'env', { ...process.env, YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID: 'recipient-test' })
jest.replaceProperty(process, 'env', {
...process.env, YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID: 'recipient-test', YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS: '',
})
jest.mocked(requireDesktop).mockResolvedValue({ id: 'session-01', account: { id: ownerId, name: '提交人甲' }, isSuperAdmin: false, expiresAt: createdAt })
jest.mocked(submitYouyidianNotification).mockResolvedValue({ id: 'notice-01', projectCode: 'test', status: 'pending', recipientUserId: 'recipient-test', title: '小壹问题反馈' })
})
@ -71,6 +73,67 @@ describe('POST /api/desktop/feedback', () => {
expect(jest.mocked(submitYouyidianNotification)).toHaveBeenCalledWith(expect.objectContaining({
recipientUserId: 'recipient-test', idempotencyKey: `desktop-feedback:${id}`, actionUrl: expect.stringMatching(`/feedback/${id}$`),
}))
expect(userStore.findMany).not.toHaveBeenCalled()
})
it('deduplicates configured DingTalk IDs and delivers to each recipient independently', async () => {
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS = ' ding-second, , recipient-test, ding-second, ding-third '
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
jest.mocked(submitYouyidianNotification)
.mockRejectedValueOnce(new Error('opaque details'))
.mockResolvedValueOnce({ id: 'notice-02', projectCode: 'test', status: 'failed', recipientUserId: 'ding-second', title: '小壹问题反馈' })
expect((await post()).status).toBe(200)
expect(jest.mocked(submitYouyidianNotification).mock.calls.map(([input]) => [input.recipientUserId, input.idempotencyKey])).toEqual(
['recipient-test', 'ding-second', 'ding-third'].map(recipient => [recipient, `desktop-feedback:${id}:${recipient}`]),
)
expect(userStore.findMany).not.toHaveBeenCalled()
expect(warning.mock.calls).toEqual([
['[desktop-feedback] 通知投递失败', { feedbackId: id, recipientUserId: 'recipient-test', errorCode: 'notification_request_failed' }],
['[desktop-feedback] 通知投递失败', { feedbackId: id, recipientUserId: 'ding-second', errorCode: 'delivery_failed' }],
])
})
it('uses active super-admin DingTalk IDs and sends a bounded, sanitized summary with the feedback link', async () => {
delete process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS = ' , '
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
userStore.findMany.mockResolvedValue([
{ id: 'app-admin-id', dingtalkUserId: 'ding-admin', username: 'admin', realName: '管理员' },
] as Awaited<ReturnType<typeof prisma.user.findMany>>)
const summary = '🛋'.repeat(125)
const response = await post({ feedbackId: id, summary, context: {
project: { name: '森屿布艺沙发', cookie: 'private' }, clientVersion: '1.2612.107', errors: ['Bearer fake-secret'],
} })
expect(response.status).toBe(200)
expect(userStore.findMany).toHaveBeenCalledWith({
where: {
isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true,
dingtalkUserId: { not: null }, NOT: { dingtalkUserId: '' },
},
select: { id: true, dingtalkUserId: true, realName: true, username: true },
})
expect(submitYouyidianNotification).toHaveBeenCalledWith({
recipientUserId: 'ding-admin', idempotencyKey: `desktop-feedback:${id}`, title: '小壹问题反馈',
content: `反馈人:提交人甲\n项目:森屿布艺沙发\n客户端版本:1.2612.107\n摘要:${'🛋'.repeat(120)}\n反馈编号:${id}`,
actionTitle: '查看反馈', actionUrl: expect.stringMatching(`^https?://[^/]+/feedback/${id}$`),
})
})
it('warns without attempting delivery when no eligible recipient exists', async () => {
const warning = jest.spyOn(console, 'warn').mockImplementation(() => {})
delete process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID
userStore.findMany.mockResolvedValue([])
feedbackStore.createMany.mockResolvedValue({ count: 1 })
feedbackStore.findFirst.mockResolvedValue(record)
expect((await post()).status).toBe(200)
expect(submitYouyidianNotification).not.toHaveBeenCalled()
expect(warning).toHaveBeenCalledWith('[desktop-feedback] 没有可用的钉钉收件人', { feedbackId: id })
})
it('validates before writing and enforces the body size limit', async () => {
@ -90,7 +153,9 @@ describe('POST /api/desktop/feedback', () => {
expect(feedbackStore.createMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({
snapshot: { errors: ['[敏感信息已移除]', '[图片已移除]'] },
}) }))
expect(warning).toHaveBeenCalledWith('[desktop-feedback] 通知投递失败', { feedbackId: id })
expect(warning).toHaveBeenCalledWith('[desktop-feedback] 通知投递失败', {
feedbackId: id, recipientUserId: 'recipient-test', errorCode: 'notification_request_failed',
})
})
it('does not expose another account’s receipt for a reused UUID', async () => {

View File

@ -2625,7 +2625,7 @@ pub(super) fn save_edited_output(dir: &Path, doc: &Document, bytes: &[u8]) -> R<
}
pub(super) fn activate_edited_output(dir: &Path, doc: &Document) -> R<Value> {
activate_edited_output_with_knowledge(dir, doc, &Value::Null)
activate_edited_output_with_knowledge(dir, doc, &Value::Null, true)
}
fn apply_locked_production_profiles(state: &mut Value, knowledge: &Value) -> R<()> {
@ -2645,16 +2645,29 @@ fn apply_locked_production_profiles(state: &mut Value, knowledge: &Value) -> R<(
Ok(())
}
fn activate_edited_output_with_knowledge(dir: &Path, doc: &Document, knowledge: &Value) -> R<Value> {
fn product_view_variant<'a>(state: &'a Value, component: &str, requested: Option<&'a str>) -> R<&'a str> {
// Empty lists in older projects can still be viewed and saved. Production
// eligibility remains governed by the selected colors and detail barcode.
if state["brief"]["outputVariantIds"][component].as_array().is_some_and(Vec::is_empty)
&& !(component == "detail" && creation::detail_barcode(&state["brief"]).is_some())
{
let id = requested.or_else(|| state["activeVariantId"].as_str()).ok_or("当前花色缺失")?;
variant(state, id)?;
return Ok(id);
}
output_variant(state, component, requested)
}
fn activate_edited_output_with_knowledge(dir: &Path, doc: &Document, knowledge: &Value, viewing: bool) -> R<Value> {
let mut state = load(dir)?;
apply_locked_production_profiles(&mut state, knowledge)?;
let meta = mapping(doc).ok_or("当前画布没有产品模板映射")?;
let component = meta["component"].as_str().filter(|id| SUPPORTED_PRODUCTION_OUTPUTS.contains(id)).ok_or("当前画布类型缺失")?;
let pack = state["productTemplates"].get(component).ok_or("当前产品模板已变化")?.clone();
let variant_id = uuid(&meta["variantId"], "编辑稿花色")?;
let selected = if viewing { product_view_variant } else { output_variant };
if meta["workspaceId"] != state["id"] || meta["templateHash"] != pack["contentHash"]
|| !output_uses_variant(&state["brief"], component, &variant_id) || variant(&state, &variant_id).is_err()
{
|| selected(&state, component, Some(&variant_id)).is_err() {
return Err("当前产品画布不属于所选输出".into());
}
let key = mapping_key(&variant_id, component, meta["outputId"].as_str());
@ -2663,6 +2676,9 @@ fn activate_edited_output_with_knowledge(dir: &Path, doc: &Document, knowledge:
state["structureHash"] = json!(hash(&json!([pack["contentHash"],state["width"]]).to_string()));
state["template"] = pack;
state["activeMapping"] = json!(key);
if let Some(issues) = state["productTemplateIssues"].as_object_mut() {
issues.remove(component);
}
state["mappings"][&key] = meta;
let expected = revision(&state);
persist_locked(dir, &mut state, expected)
@ -4530,6 +4546,8 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
"knowledgeVersion":pack["xiaoyi"]["knowledgeVersion"]});
let mut workflow = json!({"canvasFirst":true,"revision":state["revision"],"workspaceId":state["id"],"structureHash":state["structureHash"],"templateId":state["template"]["id"],"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],"templateName":state["template"]["name"],"template":template,"confirmed":true,"confirmationKind":"template-selection","pending":pending,"recoveryCandidateId":recovery_candidates.first(),"recoveryCandidateIds":recovery_candidates,"activeVariantId":active,"variantId":active,"variants":state["variants"],"outputVariantIds":state["brief"]["outputVariantIds"],"outputId":state["activeOutput"],"outputs":outputs,"slots":slots,"capabilities":{"imageDispatchAllowed":ready&&!pending&&active_color_enabled,"copyDispatchAllowed":ready&&!pending&&active_color_enabled,"localApplyAllowed":ready}});
if state["productTemplates"].is_object() {
workflow["productTemplateOutputs"] = json!(SUPPORTED_PRODUCTION_OUTPUTS.iter()
.filter(|output| state["productTemplates"][**output].is_object()).collect::<Vec<_>>());
workflow["productionStages"] = json!(resumable_stages(dir, &state, &current["revision"], false));
workflow["productionBlocks"] = json!(blocked_production_stages(&state));
workflow["scopedProductionPending"] = json!(scoped_production_pending);
@ -5114,10 +5132,15 @@ impl Backend {
}
let component = skeleton_component(&state, input)?.to_owned();
let component = component.as_str();
if let Some(reason) = state["productTemplateIssues"][component].as_str() {
return Err(reason.to_owned());
let stale_issue = state["productTemplateIssues"][component].as_str().map(str::to_owned);
if !state["productTemplates"][component].is_object() {
if let Some(reason) = &stale_issue { return Err(reason.clone()); }
if state["productTemplates"].is_object() {
return Err("当前项目没有所选输出的固定模板".into());
}
}
let variant_id = output_variant(&state, component, input["variantId"].as_str())?.to_owned();
let select_variant = if browsing { product_view_variant } else { output_variant };
let variant_id = select_variant(&state, component, input["variantId"].as_str())?.to_owned();
if handoff { apply_locked_production_profiles(&mut state, &input["knowledge"])?; }
if let Some(pack) = state["productTemplates"].get(component) {
if handoff && !input["knowledge"].is_null() && pack["xiaoyi"] != input["knowledge"] {
@ -5227,7 +5250,27 @@ impl Backend {
state["activeOutput"] = json!(component);
state["activeMapping"] = json!(key);
state["mappings"][&key] = meta;
if stale_issue.is_some() && let Some(issues) = state["productTemplateIssues"].as_object_mut() {
issues.remove(component);
}
let mut result = if browsing {
if let Some(reason) = stale_issue.as_deref() {
let _guard = sync::context_guard();
let mut current = load(&dir)?;
if current["id"] != state["id"]
|| current["productTemplates"][component]["contentHash"] != state["template"]["contentHash"]
{
return Err("产品模板已变化,未切换查看".into());
}
if current["productTemplateIssues"][component] == reason
&& let Some(issues) = current["productTemplateIssues"].as_object_mut()
{
issues.remove(component);
let expected = revision(&current);
persist_locked(&dir, &mut current, expected)?;
}
state["productTemplateIssues"] = current["productTemplateIssues"].clone();
}
let workflow = snapshot_for_view(&dir, Some(state), false)?;
json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,
"pending":workflow["pending"],"workflow":workflow,"canvasFirst":true})
@ -5235,7 +5278,7 @@ impl Backend {
if input["continueProduct"] == true {
let _guard = sync::context_guard();
// 载入草稿期间可能新增候选预留,交接时读取最新工作区。
activate_edited_output_with_knowledge(&dir, &native, &input["knowledge"])?;
activate_edited_output_with_knowledge(&dir, &native, &input["knowledge"], false)?;
} else {
let previous = revision(&state);
persist(&dir, state, previous)?;
@ -6542,6 +6585,65 @@ mod tests {
}
}
#[test]
fn product_view_clears_only_the_recovered_template_issue() {
let fixture = fixture();
let mut backend = Backend::new(fixture.dir.join("profile")).unwrap();
let doc = 1;
backend.bind_new(doc);
let dir = backend.project_dir(doc).unwrap();
write_json(&dir.join("context.json"), &json!({"doc":doc})).unwrap();
let creation = creation::load(&dir).unwrap();
write_json(&dir.join("creation.json"), &creation).unwrap();
let mut state = load(&fixture.dir).unwrap();
let mut main = pack();
main["outputs"][0]["component"] = json!("main_images");
main["contentHash"] = json!(template_slots::pack_hash(&main).unwrap());
state["brief"]["outputVariantIds"] = json!({"main_images":[]});
state["productTemplates"] = json!({"detail":state["template"],"main_images":main});
state["productTemplateIssues"] = json!({"main_images":"早期原稿导入失败","sku_images":"SKU 原稿缺失"});
let state = persist(&dir, state, 0).unwrap();
let (events, receiver) = mpsc::channel();
let ctx = egui::Context::default();
let mut input = json!({"doc":doc,"baseRevision":1,"workspaceId":state["id"],"outputId":"sku_images",
"variantId":state["activeVariantId"],"productViewId":1});
assert_eq!(backend.canvas_workspace_action("slot-product-view", &input, &events, &ctx).unwrap_err(), "SKU 原稿缺失");
input["outputId"] = json!("main_images");
input["documentId"] = json!("missing-page");
assert!(backend.canvas_workspace_action("slot-product-view", &input, &events, &ctx).is_err());
assert_eq!(load(&dir).unwrap()["productTemplateIssues"], state["productTemplateIssues"]);
input["documentId"] = Value::Null;
let receipt = backend.canvas_workspace_action("slot-product-view", &input, &events, &ctx).unwrap();
assert_eq!(receipt["outputId"], "main_images");
assert_eq!(receipt["workflow"]["productTemplateOutputs"], json!(["detail","main_images"]));
assert_eq!(receipt["workflow"]["productionBlocks"][0]["outputId"], "sku_images");
let canvas = receiver.try_iter().find_map(|event| match event {
Event::SlotCanvas(native, _) => Some(native),
_ => None,
}).unwrap();
let saved = load(&dir).unwrap();
assert_eq!(saved["productTemplateIssues"], json!({"sku_images":"SKU 原稿缺失"}));
assert_eq!(saved["activeOutput"], "detail");
assert_eq!(saved["revision"], receipt["workflow"]["revision"]);
let mut saved = {
let _guard = sync::context_guard();
activate_edited_output(&dir, &canvas).unwrap()
};
assert_eq!(saved["activeOutput"], "main_images");
saved["productTemplateIssues"]["main_images"] = json!("历史错误");
saved["brief"]["outputVariantIds"] = Value::Null;
let expected = revision(&saved);
persist(&dir, saved, expected).unwrap();
input["continueProduct"] = json!(true);
input["variantId"] = Value::Null;
backend.canvas_workspace_action("slot-skeleton", &input, &events, &ctx).unwrap();
let saved = load(&dir).unwrap();
assert_eq!(saved["productTemplateIssues"], json!({"sku_images":"SKU 原稿缺失"}));
assert_eq!(saved["activeOutput"], "main_images");
}
#[test]
fn product_start_reports_runnable_outputs_without_opening_a_canvas() {
let fixture = fixture();

View File

@ -5,6 +5,7 @@
//! to the durable workflow journal, not to canvas construction.
use photocraft_color::SampleType;
use photocraft_doc::{Affine, Document, Layer, LayerContent, LayerId, SmartObject, SmartSource, Subpath, VectorMask};
use photocraft_engine::color_cmds::{convert_document, document_profile, profile_from_bytes};
use photocraft_engine::Session;
use photocraft_geom::Rect;
use serde_json::{Value, json};
@ -357,6 +358,12 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt
super::template_slots::validate_pack(pack)?;
uuid::Uuid::parse_str(variant).map_err(|_| "花色编号无效")?;
if component == "detail" && document.is_some() { return Err("此发布请打开完整详情画布,原稿页面将全部保留".into()); }
let output_label = match component {
"detail" => "详情",
"main_images" => "主图",
"sku_images" => "SKU",
_ => component,
};
let mut outputs: Vec<_> = pack["outputs"].as_array().ok_or("模板页面缺失")?.iter()
.filter(|output| output["component"] == component && document.is_none_or(|id| output["id"] == id)).cloned().collect();
if outputs.is_empty() { return Err("当前固定模板没有所选组件,请检查模板更新".into()); }
@ -367,14 +374,26 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt
let mut engine = shared.lock().map_err(|_| "字体引擎不可用")?;
if engine.fonts.register_font_data(bytes).is_empty() { return Err("模板字体无法加载".into()); }
}
let sources = prepared["originals"].as_array().cloned().unwrap_or_else(|| vec![json!({"originalPath":prepared["originalPath"],"canvas":pack["enterprise"]["canvas"]})]);
let sources = prepared["originals"].as_array().cloned().unwrap_or_else(|| vec![json!({
"assetId":pack["enterprise"]["originalAssetId"],"originalPath":prepared["originalPath"],"canvas":pack["enterprise"]["canvas"]
})]);
let stack_originals = sources.len() > 1;
let mut parts = Vec::new();
let mut mappings = Vec::new();
let mut warnings = Vec::new();
let mut mapped_pages = HashSet::new();
for source in &sources {
let selected: Vec<_> = outputs.iter().filter(|output| output["originalAssetId"].is_null() || output["originalAssetId"] == source["assetId"]).collect();
let selected: Vec<_> = outputs.iter().filter(|output| {
match output["originalAssetId"].as_str() {
Some(id) => !id.is_empty() && source["assetId"] == id,
None => output["originalAssetId"].is_null() && !stack_originals,
}
}).collect();
if selected.is_empty() { return Err("模板准备结果包含其他组件原稿".into()); }
for output in &selected {
let id = output["id"].as_str().ok_or("原稿页面编号缺失")?;
if !mapped_pages.insert(id) { return Err(format!("页面「{id}」绑定了重复的组件原稿")); }
}
let (doc, fields, notices) = enterprise_source(pack, source, &selected, variant)?;
let mut top = 0;
if stack_originals {
@ -387,15 +406,29 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt
mappings.extend(fields);
warnings.extend(notices);
}
if let Some(output) = outputs.iter().find(|output| output["id"].as_str().is_none_or(|id| !mapped_pages.contains(id))) {
return Err(format!("{output_label}页面 {} 缺少绑定原稿", output["id"]));
}
// Original attachments can arrive in a different order from the pages.
parts.sort_by_key(|(top, _, _)| *top);
let (_, first, _) = parts.first().ok_or("模板原稿未下载")?;
if parts.iter().any(|(_, part, _)| part.size.width != first.size.width || part.mode != first.mode || part.icc_profile != first.icc_profile) {
return Err("组件原稿的宽度、色彩模式或色彩配置不一致".into());
let ((_, first, _), rest) = parts.split_first_mut().ok_or("模板原稿未下载")?;
for (_, part, pages) in rest {
let page = mappings.get(pages.start).and_then(|page| page["documentId"].as_str()).ok_or("组件原稿缺少页面编号")?;
if part.size.width != first.size.width {
return Err(format!("{output_label}页面「{page}」原稿宽度为 {} 像素,首份原稿为 {} 像素", part.size.width, first.size.width));
}
if part.mode != first.mode {
return Err(format!("{output_label}页面「{page}」原稿色彩模式与首份原稿不一致"));
}
if part.icc_profile != first.icc_profile {
harmonize_original_profile(part, first).map_err(|error| format!("{output_label}页面「{page}」无法统一色彩配置:{error}"))?;
warnings.push(format!("页面「{page}」已统一到首份原稿的色彩配置"));
}
}
// The combined canvas uses the highest source precision. Widen only imported
// copies using the engine's existing depth conversion (including 32-bit linear light).
let depth = parts.iter().map(|(_, part, _)| part.depth).max_by_key(|depth| depth.bits()).unwrap_or(first.depth);
let first_depth = first.depth;
let depth = parts.iter().map(|(_, part, _)| part.depth).max_by_key(|depth| depth.bits()).unwrap_or(first_depth);
let mut parts = parts.into_iter().map(|(top, part, pages)| {
if part.depth == depth { return Ok((top, part, pages)); }
let command = match depth {
@ -416,10 +449,18 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt
let mut resources = Vec::new();
let mut patterns = Vec::new();
for (top, mut part, pages) in std::iter::once((first_top, doc.clone(), first_pages)).chain(parts) {
let top = u32::try_from(top).map_err(|_| "组件页面纵坐标无效")?;
// Keep the stacked canvas within the PSB dimension limit.
let end = top.checked_add(part.size.height).filter(|end| *end <= 300_000).ok_or("组件总高超出 PSB 限制")?;
if top < height { return Err("组件原稿的页面范围重叠".into()); }
let pages = mappings.get_mut(pages).ok_or("组件原稿缺少页面")?;
let page = pages.iter().find(|output| output["top"] == height)
.filter(|_| top == u64::from(height)).ok_or("组件原稿与页面位置不一致")?;
let page = pages.iter().find(|output| output["top"] == top).ok_or("组件原稿与页面位置不一致")?;
let label = page["documentId"].as_str().ok_or("组件原稿缺少页面编号")?;
for page in pages.iter() {
let bottom = page["top"].as_u64().zip(page["height"].as_u64())
.and_then(|(y, h)| y.checked_add(h)).ok_or("组件页面高度无效")?;
if bottom > u64::from(end) { return Err(format!("页面 {} 超出其绑定原稿范围", page["documentId"])); }
}
// Embed each source's own linked payload before combining documents.
// Identical PSD layer ids and linked-file names belong to that source only.
let linked: Vec<_> = part.walk().into_iter().filter(|(_, _, layer)| matches!(&layer.content, LayerContent::Smart(s) if matches!(s.source, SmartSource::Linked { .. }))).map(|(_, _, layer)| layer.id).collect();
@ -442,12 +483,12 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt
page["originalGroupId"] = json!(group_id.0);
}
part.layers.push(group);
let part_height = part.size.height;
resources.extend(part.metadata.psd_global_blocks.clone());
patterns.extend(part.patterns.clone());
let mut session = Session::new();
session.add_document(part, None);
if height > 0 { session.execute("edit.transform", json!({"layer":group_id.0,"matrix":[1,0,0,1,0,height]})).map_err(|error| format!("原稿无法定位:{error}"))?; }
// Move by whole pixels so the converted Smart Object cache is kept.
if top > 0 { session.execute("layer.translate", json!({"layer":group_id.0,"dy":top})).map_err(|error| format!("原稿无法定位:{error}"))?; }
let mut placed = session.active().ok_or("组件原稿不可用")?.doc.as_ref().clone();
for (id, lock) in locks {
if let Some(layer) = placed.layer_mut(id) { layer.locks = lock; }
@ -457,7 +498,7 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt
scale_text_points(&mut placed.layers, dpi_scale);
}
groups.extend(placed.layers);
height = height.checked_add(part_height).ok_or("组件总高无效")?;
height = end;
}
doc.layers = groups;
doc.size.height = height;
@ -471,10 +512,31 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt
let mut used = HashSet::new();
for layer in &mut doc.layers { layer_ids(layer, &mut used)?; }
}
// Page ordinals in review and export refer to the fixed pack's page order.
mappings.sort_by_key(|page| outputs.iter().position(|out| out["id"] == page["documentId"]));
metadata(&mut doc, json!({"version":1,"canvasFirst":true,"templateId":pack["id"],"templateVersion":pack["version"],"templateHash":pack["contentHash"],"variantId":variant,"component":component,"outputId":document,"enterprise":pack["enterprise"],"importWarnings":warnings,"outputs":mappings,"originalPsdLayerIds":original_layer_ids}));
Ok(doc)
}
fn harmonize_original_profile(part: &mut Document, first: &Document) -> R<()> {
// Untagged documents use the engine's working profile for their color mode.
let profile = |doc: &Document| match &doc.icc_profile {
Some(bytes) => profile_from_bytes(bytes).map_err(|error| error.to_string()),
None => Ok(document_profile(doc)),
};
let source = profile(part)?;
let target = profile(first)?;
if source.color_space != document_profile(part).color_space || target.color_space != document_profile(first).color_space {
return Err("嵌入的 ICC 与原稿色彩模式不匹配".into());
}
if !source.same_colors(&target) {
convert_document(part, &target, Default::default(), true).map_err(|error| error.to_string())?;
if part.mode != first.mode { return Err("此色彩模式无法原样转换 ICC".into()); }
}
part.icc_profile = first.icc_profile.clone();
Ok(())
}
// PSD text sizes are imported as points at the source DPI. After stacking
// PSBs, keep their rendered pixel sizes at the combined canvas DPI.
fn scale_text_points(layers: &mut [Layer], scale: f32) {
@ -901,19 +963,32 @@ mod tests {
8, 4, photocraft_codecs::ChannelLayout::Rgba, [140, 90, 40, 255].repeat(32),
).unwrap();
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let pages = [("M01", 1440, 0, 72.0), ("M02", 1440, 1440, 96.0), ("M08", 1920, 2880, 120.0)];
use photocraft_engine::color_cmds::resolve_profile;
let srgb = resolve_profile("srgb", None, None).unwrap().to_bytes();
let display_p3 = resolve_profile("display-p3", None, None).unwrap().to_bytes();
let pages = [("M01", 1440, 0, 72.0), ("M02", 1440, 1460, 96.0), ("M08", 1920, 2900, 120.0)];
let mut outputs = Vec::new();
let mut originals = Vec::new();
let wrong_width = dir.path().join("wrong-width.psd");
for (name, height, top, dpi) in pages {
let mut source = photocraft_io::import("source.png", &png).unwrap().document;
source.size = photocraft_doc::Size::new(1440, height);
source.resolution_dpi = dpi;
source.icc_profile = match name {
"M01" => Some(srgb.clone()),
"M08" => Some(display_p3.clone()),
_ => None,
};
let field = format!("{name}-I01");
source.layers[0].name = field.clone();
source.layers[0].psd_id = Some(18);
let path = dir.path().join(format!("{name}.psd"));
let bytes = photocraft_io::export(&source, "psd", &Default::default()).unwrap().bytes;
fs::write(&path, bytes).unwrap();
if name == "M08" {
source.size.width = 1432;
fs::write(&wrong_width, photocraft_io::export(&source, "psd", &Default::default()).unwrap().bytes).unwrap();
}
originals.push(json!({"assetId":name,"originalPath":path,"canvas":[1440,height]}));
outputs.push(json!({"id":name,"name":name,"component":"main_images","width":1440,"height":height,"top":top,"originalAssetId":name,
"slots":[{"fieldId":field,"name":name,"kind":"image","crop":"cover","frame":{"x":0,"y":1,"width":8,"height":3},
@ -927,10 +1002,17 @@ mod tests {
let variant = uuid::Uuid::new_v4().to_string();
let prepared = json!({"fonts":[],"originals":[originals[0],originals[2],originals[1]]});
let doc = enterprise(&pack, &prepared, "main_images", None, &variant).unwrap();
assert_eq!(doc.size, photocraft_doc::Size::new(1440, 4800));
assert_eq!(doc.size, photocraft_doc::Size::new(1440, 4820));
assert_eq!(doc.icc_profile, Some(srgb));
assert_eq!(doc.layers.len(), pages.len());
let meta: Value = serde_json::from_str(&doc.metadata.text.iter()
.find(|(key, _)| key == "jiansun.slot-mapping.v1").unwrap().1).unwrap();
assert_eq!(meta["outputs"].as_array().unwrap().iter().map(|page| page["documentId"].as_str().unwrap()).collect::<Vec<_>>(),
["M01", "M02", "M08"]);
let warnings = meta["importWarnings"].as_array().unwrap();
for page in ["M02", "M08"] {
assert!(warnings.iter().any(|warning| warning.as_str().unwrap().contains(&format!("「{page}」已统一"))));
}
for ((name, height, top, _), group) in pages.into_iter().zip(&doc.layers) {
let page = meta["outputs"].as_array().unwrap().iter().find(|page| page["documentId"] == name).unwrap();
assert_eq!(group.name, name);
@ -946,12 +1028,30 @@ mod tests {
assert_eq!(meta["originalPsdLayerIds"][layer.id.0.to_string()], 18);
assert_eq!(field["frame"]["y"], f64::from(top + 1));
assert_eq!(layer_frame(&doc, layer).y0, top + 1);
let surface = layer.surface().unwrap();
let bounds = surface.content_bounds();
let pixel = surface.pixel(bounds.x0, bounds.y0);
assert_eq!(pixel[3], 1.0);
if name == "M08" {
assert!((pixel[0] - 140.0 / 255.0).abs() > 1.0 / 255.0);
} else {
assert!((pixel[0] - 140.0 / 255.0).abs() <= 1.0 / 255.0);
}
}
let layers = doc.walk();
assert_eq!(layers.iter().map(|(_, _, layer)| layer.id).collect::<HashSet<_>>().len(), layers.len());
assert_eq!(layers.iter().map(|(_, _, layer)| layer.psd_id.unwrap()).collect::<HashSet<_>>().len(), layers.len());
let mut prepared = prepared;
let missing = json!({"fonts":[],"originals":[originals[0],originals[2]]});
assert!(enterprise(&pack, &missing, "main_images", None, &variant).unwrap_err().contains("M02"));
let duplicate = json!({"fonts":[],"originals":[originals[0],originals[0],originals[1],originals[2]]});
assert!(enterprise(&pack, &duplicate, "main_images", None, &variant).unwrap_err().contains("重复"));
let mut mismatched = prepared.clone();
mismatched["originals"][1]["originalPath"] = json!(wrong_width);
mismatched["originals"][1]["canvas"][0] = json!(1432);
assert_eq!(enterprise(&pack, &mismatched, "main_images", None, &variant).unwrap_err(),
"主图页面「M08」原稿宽度为 1432 像素,首份原稿为 1440 像素");
prepared["originals"].as_array_mut().unwrap().swap(0, 1);
let reordered = enterprise(&pack, &prepared, "main_images", None, &variant).unwrap();
assert_eq!(reordered.layers[0].name, "M01");
@ -960,7 +1060,7 @@ mod tests {
let mut overlapping = pack.clone();
overlapping["outputs"][2]["top"] = json!(1440);
overlapping["contentHash"] = json!(super::super::template_slots::pack_hash(&overlapping).unwrap());
assert_eq!(enterprise(&overlapping, &prepared, "main_images", None, &variant).unwrap_err(), "组件原稿与页面位置不一致");
assert_eq!(enterprise(&overlapping, &prepared, "main_images", None, &variant).unwrap_err(), "组件原稿的页面范围重叠");
pack["outputs"][2]["top"] = Value::Null;
pack["outputs"][2]["slots"] = json!([]);

View File

@ -2033,6 +2033,7 @@ impl Workspace {
let installed_colors = self.template_workflow["variants"].as_array().or_else(|| self.creation_brief["variants"].as_array());
let variants: Vec<_> = installed_colors.into_iter().flatten()
.filter(|row| self.template_workflow["outputVariantIds"][&self.canvas_workspace.output].as_array()
.filter(|ids| !ids.is_empty())
.is_none_or(|ids| ids.contains(&row["id"]))).cloned().collect();
let current_color_visible = variants.iter().any(|row| row["id"] == self.canvas_workspace.variant);
// Wrap the output group and colour group as meaningful
@ -2041,7 +2042,8 @@ impl Workspace {
let selected = outputs.iter().position(|(id, _)| *id == self.canvas_workspace.output).unwrap_or(0);
let map_template = self.template_workflow["templateVersion"].as_str().is_some_and(|version| version.starts_with("map-"));
let [detail, main, sku] = outputs.map(|(id, label)| (label, !map_template
|| self.template_workflow["outputs"].as_array().into_iter().flatten().any(|output| output["outputId"] == id)));
|| self.template_workflow["outputs"].as_array().into_iter().flatten().any(|output| output["outputId"] == id)
|| self.template_workflow["productTemplateOutputs"].as_array().into_iter().flatten().any(|output| output == id)));
let choices = [detail, main, sku, ("主图视频", false), ("买家秀", false)];
let output_width = choices.iter().map(|(label, _)| super::stitch_ui::segment_width(ui, label)).sum::<f32>()
+ super::stitch_ui::SEGMENT_GAP * (choices.len() - 1) as f32 + 6.0 + ui.spacing().item_spacing.x + 1.0;
@ -2054,7 +2056,10 @@ impl Workspace {
if self.canvas_workspace.output != id || self.canvas_workspace.scope_blocked
|| !current_color_visible || self.product_view_pending() {
let request = json!({"outputId":id});
if let Err(e) = self.slot_action(app, "slot-skeleton", request) { self.error = e; }
if let Err(error) = self.slot_action(app, "slot-skeleton", request) {
self.product_views.view_error = Some(error.clone());
self.error = error;
}
}
}
});

View File

@ -329,15 +329,19 @@ impl Workspace {
fn product_stage_for_view(&self, input: &Value) -> Result<Stage, String> {
let output = input["outputId"].as_str().ok_or("输出类型缺失")?;
let available = self.template_workflow["outputVariantIds"][output].as_array();
let variant = input["variantId"].as_str().or_else(|| {
let shown = self.template_workflow["variantId"].as_str()?;
if available.is_none_or(|list| list.iter().any(|value| value == shown)) {
Some(shown)
} else {
available?.first()?.as_str()
}
}).ok_or("当前输出没有已选款式")?;
let available = self.template_workflow["outputVariantIds"][output].as_array().filter(|ids| !ids.is_empty());
let variant = input["variantId"].as_str().filter(|id| !id.is_empty())
.or_else(|| self.template_workflow["variantId"].as_str().filter(|shown| {
!shown.is_empty() && available.is_none_or(|ids| ids.iter().any(|id| id == *shown))
}))
.or_else(|| {
if let Some(ids) = available {
ids.first()?.as_str()
} else {
self.template_workflow["variants"][0]["id"].as_str()
.or_else(|| self.creation_brief["variants"][0]["id"].as_str())
}
}).ok_or("当前输出没有已选款式")?;
Stage::read(&json!({"outputId":output,"variantId":variant})).ok_or_else(|| "产品画布类型无效".into())
}
@ -349,6 +353,13 @@ impl Workspace {
}
pub(super) fn request_product_view(&mut self, app: &PhotocraftApp, input: &Value) -> Result<Value, String> {
self.begin_product_view(app, input).inspect_err(|error| {
self.product_views.view_error = Some(error.clone());
self.error = error.clone();
})
}
fn begin_product_view(&mut self, app: &PhotocraftApp, input: &Value) -> Result<Value, String> {
let active = app.session.active().ok_or("请先打开产品画布")?;
if self.open_projects.get(&active.doc.id.0).is_none_or(|project| !project.starts_with(&self.local_identity(""))) {
return Err("当前产品画布归属已变化".into());
@ -668,7 +679,7 @@ impl Workspace {
ViewTarget::WorkingCanvas => {
if self.product_views.worker.as_ref().and_then(|worker| Stage::read(&worker.workflow)) != Some(request.stage.clone()) {
let input = json!({"outputId":request.stage.output,"variantId":request.stage.variant});
if let Err(error) = self.request_product_view(app, &input) { self.error = error; }
let _ = self.request_product_view(app, &input);
return;
}
let Some(mut worker) = self.product_views.worker.take() else { return; };
@ -679,7 +690,7 @@ impl Workspace {
ViewTarget::CachedCanvas => {
let Some(mut view) = self.product_views.cached.remove(&request.stage) else {
let input = json!({"outputId":request.stage.output,"variantId":request.stage.variant});
if let Err(error) = self.request_product_view(app, &input) { self.error = error; }
let _ = self.request_product_view(app, &input);
return;
};
view.swap_view(self, app);
@ -4229,6 +4240,37 @@ mod tests {
});
}
#[test]
fn product_view_uses_legacy_variants_and_surfaces_synchronous_errors() {
let (tx, requests) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
let _ = requests.try_recv().unwrap();
w.account = json!({"id":"local"});
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
let app = PhotocraftApp::new(session, crate::Services::default());
let doc = app.session.active().unwrap().doc.id.0;
w.open_projects.insert(doc, w.local_identity("project"));
let input = json!({"outputId":"main_images"});
let error = w.request_product_view(&app, &input).unwrap_err();
assert_eq!(error, "当前输出没有已选款式");
assert_eq!(w.product_views.view_error.as_deref(), Some(error.as_str()));
assert_eq!(w.error, error);
w.template_workflow = json!({"workspaceId":"workspace","outputId":"detail",
"variants":[{"id":"old-project-color"}]});
assert_eq!(w.product_stage_for_view(&input).unwrap().variant, "old-project-color");
w.template_workflow["variants"] = json!([]);
w.template_workflow["outputVariantIds"] = json!({"main_images":[]});
w.creation_brief = json!({"variants":[{"id":"brief-color"}]});
w.request_product_view(&app, &input).unwrap();
let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected view load"); };
assert_eq!(method, "slot-product-view");
assert_eq!(input["variantId"], "brief-color");
assert!(w.product_views.view_error.is_none());
}
#[test]
fn product_view_failed_records_canvas_view_error_until_next_switch() {
let (tx, requests) = mpsc::channel();

View File

@ -5,6 +5,29 @@ import { submitYouyidianNotification } from '@/lib/youyidian-notification-center
import { DesktopClientError } from './contract.mjs'
import { feedbackIdSchema, parseDesktopFeedback } from './feedback-contract'
async function feedbackNotificationRecipients() {
const configured = [
process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID ?? '',
...(process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS ?? '').split(','),
].map(id => id.trim()).filter(Boolean)
if (configured.length) return Array.from(new Set(configured))
const admins = await prisma.user.findMany({
where: {
isActive: true, status: 'active', archivedAt: null, isSuperAdmin: true,
dingtalkUserId: { not: null }, NOT: { dingtalkUserId: '' },
},
select: { id: true, dingtalkUserId: true, realName: true, username: true },
})
return Array.from(new Set(admins.map(admin => admin.dingtalkUserId?.trim()).filter((id): id is string => Boolean(id))))
}
function notificationText(value: unknown, limit: number) {
if (typeof value !== 'string') return ''
return Array.from(value.replace(/\s+/g, ' ').trim()).slice(0, limit).join('')
.replace(/[\\`*_\[\]~#<>]/g, '\\$&')
}
export async function submitDesktopFeedback(ownerId: string, raw: string) {
const data = parseDesktopFeedback(raw)
const { feedbackId } = data
@ -14,27 +37,45 @@ export async function submitDesktopFeedback(ownerId: string, raw: string) {
})
const record = await prisma.desktopClientFeedback.findFirst({
where: { feedbackId, ownerId },
select: { feedbackId: true, status: true, createdAt: true },
select: { feedbackId: true, status: true, createdAt: true, owner: { select: { realName: true, username: true } } },
})
if (!record) throw new DesktopClientError('反馈编号不可用', 409, 'feedback_id_conflict')
const detailPath = `/feedback/${feedbackId}`
if (count === 1) {
try {
const recipientUserId = process.env.YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID?.trim()
if (!recipientUserId) throw new Error('Missing feedback recipient')
const result = await submitYouyidianNotification({
idempotencyKey: `desktop-feedback:${feedbackId}`,
recipientUserId,
title: '小壹问题反馈',
content: `收到一条小壹客户端问题反馈。反馈编号 ${feedbackId}`,
actionTitle: '查看反馈',
actionUrl: `${getPublicAppOrigin()}${detailPath}`,
})
if (result.status === 'failed') throw new Error('Feedback notification failed')
const recipients = await feedbackNotificationRecipients()
if (!recipients.length) {
console.warn('[desktop-feedback] 没有可用的钉钉收件人', { feedbackId })
} else {
const project = data.snapshot.project
const projectName = project && typeof project === 'object' && !Array.isArray(project) ? project.name : undefined
const content = [
`反馈人:${notificationText(record.owner.realName || record.owner.username, 80)}`,
`项目:${notificationText(projectName, 120) || '未提供'}`,
`客户端版本:${notificationText(data.snapshot.clientVersion, 48) || '未提供'}`,
`摘要:${notificationText(data.summary, 120)}`,
`反馈编号:${feedbackId}`,
].join('\n')
const actionUrl = `${getPublicAppOrigin()}${detailPath}`
await Promise.all(recipients.map(async recipientUserId => {
const idempotencyKey = recipients.length === 1
? `desktop-feedback:${feedbackId}`
: `desktop-feedback:${feedbackId}:${recipientUserId}`
let errorCode = 'delivery_failed'
try {
const result = await submitYouyidianNotification({
idempotencyKey, recipientUserId, title: '小壹问题反馈', content, actionTitle: '查看反馈', actionUrl,
})
if (result.status !== 'failed') return
} catch {
errorCode = 'notification_request_failed'
}
console.warn('[desktop-feedback] 通知投递失败', { feedbackId, recipientUserId, errorCode })
}))
}
} catch {
// Errors from the external service can include request details. Only log the feedback ID.
console.warn('[desktop-feedback] 通知投递失败', { feedbackId })
console.warn('[desktop-feedback] 通知准备失败', { feedbackId, errorCode: 'notification_preparation_failed' })
}
}
return { feedback: { feedbackId, status: record.status, createdAt: record.createdAt, detailPath } }