From ed2bfbc81cec5d3cdf1ec8f87695775a9ee77503 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Tue, 1 Dec 2026 12:31:08 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E9=80=9A=E5=B0=8F=E5=A3=B9=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E4=B8=8A=E6=9E=B6=E7=8A=B6=E6=80=81=E5=9B=9E=E4=BC=A0?= =?UTF-8?q?=E5=B9=B6=E5=87=86=E5=A4=87=E5=8F=91=E5=B8=83=201.2612.102?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/admin/api-keys/route.test.ts | 12 ++ app/api/admin/api-keys/route.ts | 11 +- app/api/external/product-assets/route.ts | 61 +++++++-- .../apps/photocraft/src/jiansun_backend.rs | 7 +- .../apps/photocraft/src/jiansun_sync.rs | 26 ++++ apps/detail-photocraft/client-version.txt | 2 +- .../crates/ui-egui/src/jiansun.rs | 15 ++ .../crates/ui-egui/src/jiansun/creation.rs | 129 +++++++++++++++--- components/SuperAdminsTab.test.tsx | 22 +++ components/SuperAdminsTab.tsx | 19 ++- docs/生产数据库安全增量迁移SOP-2026-08-12.md | 5 +- docs/自动上架平台成套入库通知接口.md | 41 +++++- lib/desktop-client/deliveries.ts | 9 +- lib/external-api.ts | 16 ++- lib/external-auto-listing.ts | 4 +- lib/xiaoyi-listing-status.ts | 59 ++++++++ .../migration.sql | 5 + prisma/schema.prisma | 1 + scripts/git-incremental-deploy.ps1 | 1 + scripts/safe-production-migrate.mjs | 28 +++- scripts/safe-production-migrate.test.mjs | 4 +- scripts/xiaoyi-delivery-acceptance.mjs | 43 +++++- 22 files changed, 468 insertions(+), 52 deletions(-) create mode 100644 lib/xiaoyi-listing-status.ts create mode 100644 prisma/migrations/20261201140000_xiaoyi_listing_status/migration.sql diff --git a/app/api/admin/api-keys/route.test.ts b/app/api/admin/api-keys/route.test.ts index 61af77a2..46099991 100644 --- a/app/api/admin/api-keys/route.test.ts +++ b/app/api/admin/api-keys/route.test.ts @@ -31,6 +31,7 @@ jest.mock('@/lib/department-permission', () => ({ jest.mock('@/lib/external-api', () => ({ ApiKeyEncryptionConfigError: class ApiKeyEncryptionConfigError extends Error {}, ApiKeyNotRecoverableError: class ApiKeyNotRecoverableError extends Error {}, + XIAOYI_LISTING_KEY_SCOPE: 'xiaoyi_auto_listing', getApiKeys: jest.fn(), createApiKey: jest.fn(), getApiKeyPreview: jest.fn((key: string) => `${String(key).slice(0, 8)}...`), @@ -61,6 +62,17 @@ describe('admin api-keys routes', () => { ;(isSuperAdmin as jest.Mock).mockResolvedValue(true) }) + test('仅接受已知的密钥用途并将小壹上架用途传给创建函数', async () => { + ;(createApiKey as jest.Mock).mockResolvedValue({ id: 'listing-key', key: 'isolated-test-key' }) + const request = (scope: string) => new Request('http://localhost/api/admin/api-keys', { + method: 'POST', body: JSON.stringify({ name: '自动上架', scope }), + }) + expect((await createApiKeyRoute(request('wrong') as any)).status).toBe(400) + expect(createApiKey).not.toHaveBeenCalled() + expect((await createApiKeyRoute(request('xiaoyi_auto_listing') as any)).status).toBe(200) + expect(createApiKey).toHaveBeenCalledWith('自动上架', 'admin-1', 'xiaoyi_auto_listing') + }) + test('GET 会继续返回 masked key 预览', async () => { ;(getApiKeys as jest.Mock).mockResolvedValue([ { id: 'key-1', key: 'abcdefgh12345678', name: '任务系统', isActive: true, canReveal: true }, diff --git a/app/api/admin/api-keys/route.ts b/app/api/admin/api-keys/route.ts index bfa3a80a..40a77ab1 100644 --- a/app/api/admin/api-keys/route.ts +++ b/app/api/admin/api-keys/route.ts @@ -13,6 +13,7 @@ import { createApiKey, getApiKeyPreview, getApiKeys, + XIAOYI_LISTING_KEY_SCOPE, } from '@/lib/external-api'; /** @@ -81,7 +82,7 @@ export async function POST(request: NextRequest) { } const body = await request.json(); - const { name } = body; + const { name, scope } = body; if (!name || typeof name !== 'string' || name.trim().length === 0) { return NextResponse.json( @@ -90,7 +91,13 @@ export async function POST(request: NextRequest) { ); } - const apiKey = await createApiKey(name.trim(), userId); + if (scope !== undefined && scope !== 'general' && scope !== XIAOYI_LISTING_KEY_SCOPE) { + return NextResponse.json({ success: false, error: '密钥用途无效' }, { status: 400 }); + } + + const apiKey = scope === XIAOYI_LISTING_KEY_SCOPE + ? await createApiKey(name.trim(), userId, scope) + : await createApiKey(name.trim(), userId); return NextResponse.json( { diff --git a/app/api/external/product-assets/route.ts b/app/api/external/product-assets/route.ts index 31c8ab6b..0d721d24 100644 --- a/app/api/external/product-assets/route.ts +++ b/app/api/external/product-assets/route.ts @@ -1,5 +1,8 @@ import { isRestrictedMaterial } from '@/lib/material-access-scope' import { prisma } from '@/lib/prisma' +import { isXiaoyiDeliveryMaterial } from '@/lib/xiaoyi-delivery-material' +import { parseListingUpdate, pendingListingStatus, recordListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status' +import { XIAOYI_LISTING_KEY_SCOPE } from '@/lib/external-api' /** * 外部接口:产品全案素材查询和删除 @@ -56,11 +59,14 @@ export async function GET(request: NextRequest) { const materialId = request.nextUrl.searchParams.get('materialId') // 验证 API Key - const keyRecord = await validateApiKey(apiKey); + const keyRecord = await validateApiKey(apiKey, true); if (!keyRecord) { return errorResponse(API_ERROR.INVALID_API_KEY); } + const listingOnly = keyRecord.scope === XIAOYI_LISTING_KEY_SCOPE + if (listingOnly && !isValidMaterialId(materialId)) return errorResponse(API_ERROR.INVALID_MATERIAL_ID) + if (!taskNo && !materialId) { await logApiCall({ apiKeyId: keyRecord.id, @@ -105,7 +111,8 @@ export async function GET(request: NextRequest) { // 查询素材 console.log('[external/product-assets] Querying material:', { taskNo, materialId }); const found: any = materialId ? await getMaterialById(materialId) : await getMaterialByTaskNo(taskNo as string); - let material = found && !isRestrictedMaterial(found) ? found : null; + let material = found && !isRestrictedMaterial(found) + && (!listingOnly || isXiaoyiDeliveryMaterial(found.materialType)) ? found : null; if (material && !material.deletedAt && material.taskStatus !== TASK_STATUS.FETCHED) { const updated = await updateTaskStatus(material.id, TASK_STATUS.FETCHED, { taskFetchedAt: new Date(), @@ -158,11 +165,16 @@ export async function GET(request: NextRequest) { console.log('[external/product-assets] Base URL:', baseUrl); console.log('[external/product-assets] Material type:', material.materialType); - if (['自动上架-详情', '自动上架-视频', '自动上架-买家秀'].includes(material.materialType)) { - const delivery = await prisma.$queryRawUnsafe>( - 'SELECT brand_name AS "brandName",product_name AS "productName",identifier_type AS "identifierType" FROM desktop_material_deliveries WHERE material_id=$1', - material.id, - ) + if (isXiaoyiDeliveryMaterial(material.materialType)) { + const [delivery] = await prisma.$queryRaw>` + SELECT d.brand_name AS "brandName", d.product_name AS "productName", d.identifier_type AS "identifierType", + e.id AS "eventId", d.listing_status AS "listingStatus" + FROM desktop_material_deliveries d LEFT JOIN xiaoyi_auto_listing_events e ON e.material_id = d.material_id + WHERE d.material_id = ${material.id} + ` + if (listingOnly && !delivery?.eventId) return errorResponse(API_ERROR.MATERIAL_NOT_FOUND) const groups: Record = {main: [], sku: [], detail: [], video: [], buyer_show: []} for (const asset of material.assets || []) { if (!groups[asset.assetType]) continue @@ -185,10 +197,11 @@ 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, + spu: groups.sku.some(asset => asset.barcodes.length) || delivery?.identifierType === 'spu' ? material.productModel : null, categoryName: material.categoryName, productCategoryName: material.productCategoryName, - brandName: delivery[0]?.brandName || '', productName: delivery[0]?.productName || '', identifierType: delivery[0]?.identifierType || '', + brandName: delivery?.brandName || '', productName: delivery?.productName || '', identifierType: delivery?.identifierType || '', isFullSet: material.materialType === '自动上架-详情' && ['main', 'sku', 'detail'].every(group => groups[group].length), + ...(delivery?.eventId && { eventId: delivery.eventId, listingStatus: delivery.listingStatus ?? pendingListingStatus }), assets: groups, files: material.materialType === '自动上架-视频' ? groups.video : material.materialType === '自动上架-买家秀' ? groups.buyer_show : [], downloadUrl: generateDownloadUrl(baseUrl, {materialId: material.id, downloadType: 'all'}), @@ -410,6 +423,36 @@ export async function GET(request: NextRequest) { } } +/** PATCH - Report a listing outcome for a Xiaoyi delivery. */ +export async function PATCH(request: NextRequest) { + const startTime = Date.now() + const key = await validateApiKey(getApiKeyFromRequest(request), true) + if (!key) return errorResponse(API_ERROR.INVALID_API_KEY) + if (key.scope !== XIAOYI_LISTING_KEY_SCOPE) { + return errorResponse({ code: 'INVALID_KEY_SCOPE', message: '需要小壹自动上架专用 API Key', status: 403 }) + } + const materialId = request.nextUrl.searchParams.get('materialId') + if (!isValidMaterialId(materialId)) return errorResponse(API_ERROR.INVALID_MATERIAL_ID) + const input = await request.json().catch(() => null) + const update = parseListingUpdate(input) + if (!update) return errorResponse({ code: 'INVALID_LISTING_STATUS', message: '上架状态回传字段无效', status: 400 }) + try { + const result = await recordListingStatus(materialId, update) + await logApiCall({ + apiKeyId: key.id, endpoint: '/api/external/product-assets', method: 'PATCH', + queryType: 'materialId', queryValue: materialId, statusCode: result.status, duration: Date.now() - startTime, ipAddress: getClientIp(request), + userAgent: request.headers.get('user-agent') || undefined, + }) + if (result.status !== 200) return errorResponse(result) + const response = successResponse({ materialId, applied: result.applied, listingStatus: result.listingStatus }) + response.headers.set('Cache-Control', 'private, no-store') + return response + } catch (error) { + console.error('[external/product-assets] Failed to persist listing status:', error) + return errorResponse(API_ERROR.SERVER_ERROR) + } +} + /** * DELETE - 删除素材 */ diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index d74affe4..83a40bf7 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -1589,6 +1589,7 @@ impl Backend { } "project-delete" => self.delete_project(input), "project-sync" => self.sync_project(input), + "delivery-status" => self.delivery_status(input), "project-state" => self.project_state(input), "configure-knowledge" => knowledge_http::configure(input), "configure-xiaoyi-knowledge" => Ok(knowledge_http::configure_xiaoyi(input)), @@ -2159,7 +2160,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } return true; } - if matches!(method.as_str(), "materials" | "creation-catalog" | "creation-thumbnail" | "preview") { + if matches!(method.as_str(), "materials" | "creation-catalog" | "creation-thumbnail" | "preview" | "delivery-status") { if method.starts_with("creation-") && let Some(doc) = input["doc"].as_u64() { @@ -2181,7 +2182,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { reader.action(&task_method, &input, &task_events, &task_ctx) }; if task_method != "preview" || result.is_err() { - let result = if matches!(task_method.as_str(), "materials" | "preview") { + let result = if matches!(task_method.as_str(), "materials" | "preview" | "delivery-status") { Ok(bound_material_read(result, &task_reference)) } else { Ok(bound_creation_read(result, &task_reference)) @@ -2190,7 +2191,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace { } task_ctx.request_repaint_of(egui::ViewportId::ROOT); }) { - let result = if matches!(method.as_str(), "materials" | "preview") { + let result = if matches!(method.as_str(), "materials" | "preview" | "delivery-status") { Ok(bound_material_read(Err(error.into()), &reference)) } else { let mut value = bound_creation_read(Err(error.into()), &reference); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs index e2e436f9..c0f110c3 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs @@ -692,6 +692,32 @@ impl Backend { "projects":self.native_projects()?})) } + pub(super) fn delivery_status(&self, input: &Value) -> R { + let doc = input["doc"].as_u64().ok_or("项目身份无效")?; + self.ensure_owner(doc)?; + self.check_dispatch()?; + let dir = self.project_dir(doc)?; + let context = { + let _guard = context_guard(); + read_json(&dir.join("context.json"))? + }; + if context["project"]["source"] != "desktop" { + return Ok(json!({"delivery":null})); + } + let project = context["project"]["id"].as_str().and_then(|id| Uuid::parse_str(id).ok()) + .ok_or("云项目身份无效")?; + let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?; + let response = self.http.get(format!("{}/api/desktop/deliveries/{project}/detail", self.origin)) + .bearer_auth(token).timeout(Duration::from_secs(10)).send() + .map_err(|_| "素材库连接失败,请稍后重试")?; + self.check_cloud_authority(response.status().as_u16())?; + let (status, value) = body(response, 16 * 1024)?; + if status != 200 { + return Err(value["error"].as_str().unwrap_or("上架状态读取失败").into()); + } + Ok(if value["materialId"].is_string() { json!({"delivery":value}) } else { value }) + } + fn delivery_project_id(&self, dir: &Path, revision: u64, artifacts: &[super::material_delivery::Artifact]) -> R { let context = { let _guard = context_guard(); read_json(&dir.join("context.json"))? }; if context["revision"].as_u64() != Some(revision) { return Err("本机版本已变化,请保存后重新完结".into()); } diff --git a/apps/detail-photocraft/client-version.txt b/apps/detail-photocraft/client-version.txt index a0877ab1..84d970c9 100644 --- a/apps/detail-photocraft/client-version.txt +++ b/apps/detail-photocraft/client-version.txt @@ -1 +1 @@ -1.2612.101 +1.2612.102 diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 7e6749db..cb428104 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1156,6 +1156,8 @@ pub struct Workspace { template_ui: template_slots::UiState, pending_slot_apply: Option, sync_confirm: bool, + listing_read_at: Option<(u64, Instant)>, + listing_read_error: Option, sync_dirty: bool, sync_request_meta: String, } @@ -1702,6 +1704,8 @@ impl Workspace { template_ui: template_slots::UiState::default(), pending_slot_apply: None, sync_confirm: false, + listing_read_at: None, + listing_read_error: None, sync_dirty: true, sync_request_meta: String::new(), }; @@ -1903,6 +1907,11 @@ impl Workspace { state["creationView"]["thumbnailReady"] = json!(self.creation_thumbs.keys().collect::>()); state["navigation"] = json!({"view":if self.material {"materials"}else if self.library {"projects"}else{"creation"},"step":self.creation_step,"geometry":self.navigation_geometry}); state["projectState"] = json!({"syncDirty":self.sync_dirty,"cloudLink":self.project_context["cloudLink"],"syncedRevision":self.project_context["syncedRevision"],"status":self.project_context["status"]}); + state["projectState"]["delivery"] = json!({ + "open":self.sync_confirm, + "receipt":self.project_context["materialDelivery"], + "readError":self.listing_read_error, + }); state["recovery"] = json!({"startupResumeChecked":self.startup_resume_checked,"userInteracted":self.startup_interacted,"lastStatus":self.recovery_status}); state @@ -3103,6 +3112,12 @@ impl Workspace { } return; } + if method == "delivery-status" { + if let Ok(value) = result { + creation::listing_status_received(self, app, &value); + } + return; + } if method == "project-list" { if let Ok(value) = result { self.receive_project_list(app, &value); 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 ac0a7cbc..0d3b2a93 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -668,6 +668,43 @@ pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Valu "成品已提交素材库;项目可另行云同步" } else if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into(); } +pub(super) fn listing_status_received(w: &mut Workspace, app: &PhotocraftApp, value: &Value) { + if !bound(w, app, value) { + return; + } + w.listing_read_error = value["error"].as_str().map(str::to_owned); + if let Some(receipt) = value["delivery"].as_object() { + if receipt.get("materialId").and_then(Value::as_str).is_none() { + return; + } + let current = &mut w.project_context["materialDelivery"]; + if current["materialId"] != value["delivery"]["materialId"] { + *current = Value::Object(receipt.clone()); + } else if current["state"] != "removed" + && (value["delivery"]["state"] == "removed" + || value["delivery"]["listingStatus"]["sequence"].as_u64() >= current["listingStatus"]["sequence"].as_u64()) + { + current["state"] = value["delivery"]["state"].clone(); + current["listingStatus"] = value["delivery"]["listingStatus"].clone(); + } + } +} + +fn listing_status_text(receipt: &Value) -> (&'static str, stitch_ui::StatusTone) { + use stitch_ui::StatusTone::{Error, Neutral}; + if receipt["state"] == "removed" { + return ("素材已撤回", Neutral); + } + match receipt["listingStatus"]["state"].as_str() { + Some("pending") => ("等待上架", Neutral), + Some("listing") => ("上架中", Neutral), + Some("listed") => ("已上架", Neutral), + Some("failed") => ("上架失败", Error), + _ if receipt["state"] == "completed" => ("暂无上架状态", Neutral), + _ => ("正在查询上架状态", Neutral), + } +} + // The import worker reports a final receipt rather than intermediate bytes; // expose activity only and never manufacture an upload percentage. fn reference_import_activity(busy: Option<&str>) -> Option<&'static str> { @@ -846,13 +883,21 @@ impl Workspace { ui.ctx().data_mut(|data| data.insert_temp(chat_option, *chat)); } }; + let delivered = self.project_context["materialDelivery"]["materialId"].is_string() + && self.project_context["status"] == "completed"; let actions = |ui: &mut Ui, height| { let sync = stitch_ui::action_button_height(ui, label, stitch_ui::ButtonRole::Secondary, idle && changed && !self.creation_dirty, height) .on_hover_text(hint).on_disabled_hover_text(hint).clicked(); - let finish = stitch_ui::action_button_height(ui, "完结", stitch_ui::ButtonRole::Primary, idle && !self.unknown && !self.creation_dirty, height).clicked(); - (sync, finish) + let (finish_label, finish_role) = if delivered { + ("上架状态", stitch_ui::ButtonRole::Secondary) + } else { + ("完结", stitch_ui::ButtonRole::Primary) + }; + let finish = stitch_ui::action_button_height(ui, finish_label, finish_role, + delivered || (idle && !self.unknown && !self.creation_dirty), height); + (sync, finish.clicked(), finish.rect) }; - let (sync, finish) = if compact { + let (sync, finish, finish_rect) = if compact { ui.allocate_ui_with_layout(egui::vec2(visible_width, 38.0), egui::Layout::top_down(egui::Align::Max), |ui| { ui.spacing_mut().item_spacing = egui::vec2(4.0, 0.0); ui.spacing_mut().button_padding = egui::vec2(4.0, 1.0); @@ -868,26 +913,65 @@ impl Workspace { chat_control(ui, &mut chat); actions(ui, crate::theme::agent_scale::control::DEFAULT) }; + self.navigation_geometry["delivery"] = rect_value(finish_rect); if sync { self.sync_action(app, "project-sync", json!({"status":"draft","syncChatHistory":chat})); } if finish { self.sync_confirm = true; + self.listing_read_at = None; + self.listing_read_error = None; } - let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), "完结项目", self.sync_confirm, self.reduce_motion, 360.0, |ui| { - 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() { - self.sync_confirm = false; - self.sync_action(app, "project-sync", json!({"status":"completed","syncChatHistory":chat})); - } - }); + if self.sync_confirm && self.project_context["cloudLink"]["source"] == "desktop" + && let Some(doc) = app.session.active().map(|state| state.doc.id.0) + { + let now = Instant::now(); + if self.listing_read_at.is_none_or(|(last_doc, next)| last_doc != doc || now >= next) { + self.listing_read_at = Some((doc, now + Duration::from_secs(15))); + if self.tx.send(Request::Action("delivery-status".into(), json!({"doc":doc}))).is_err() { + self.listing_read_error = Some("本机服务已停止,请重启后查看".into()); + } + } + ui.ctx().request_repaint_after(Duration::from_secs(15)); + } + let title = if delivered { "上架状态" } else { "完结项目" }; + let closed = stitch_ui::dialog(ui, egui::Id::unique("xiaoyi-finish-project"), title, + self.sync_confirm, self.reduce_motion, 360.0, |ui| { + if !delivered { + ui.label("将已完成的详情、主图和 SKU 成品提交到素材库?项目备份可另行云同步。"); + } + let receipt = &self.project_context["materialDelivery"]; + if let Some(id) = receipt["materialId"].as_str() { + let (text, tone) = listing_status_text(receipt); + if receipt["state"].is_string() || self.listing_read_error.is_none() { + stitch_ui::status_label(ui, text, tone); + } + if let Some(message) = receipt["listingStatus"]["message"].as_str() + && receipt["listingStatus"]["state"] == "failed" && receipt["state"] != "removed" + { + ui.label(message); + } + ui.label(format!("素材 ID {id}")); + if let Some(listing_id) = receipt["listingStatus"]["listingId"].as_str() + && receipt["listingStatus"]["state"] == "listed" && receipt["state"] != "removed" + { + ui.label(format!("上架编号 {listing_id}")); + } + } + if let Some(error) = &self.listing_read_error { + stitch_ui::status_label(ui, "上架状态刷新失败", stitch_ui::StatusTone::Warning) + .on_hover_text(error); + } + ui.horizontal_wrapped(|ui| { + let dismiss = if delivered { "关闭" } else { "取消" }; + if stitch_ui::action_button(ui, dismiss, stitch_ui::ButtonRole::Secondary, true).clicked() { + self.sync_confirm = false; + } + if !delivered && 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})); + } + }); }); if closed { self.sync_confirm = false; } } @@ -2608,6 +2692,17 @@ pub(super) fn output_tag(ui: &mut Ui, id: &str, text: &str, upcoming: bool) -> e } } +#[cfg(test)] +#[test] +fn listing_receipt_distinguishes_reported_failure_and_recalled_assets() { + let success = json!({"state":"completed","listingStatus":{"state":"listed"}}); + assert_eq!(listing_status_text(&success).0, "已上架"); + let failed = json!({"state":"completed","listingStatus":{"state":"failed"}}); + assert_eq!(listing_status_text(&failed), ("上架失败", stitch_ui::StatusTone::Error)); + let removed = json!({"state":"removed","listingStatus":{"state":"listed"}}); + assert_eq!(listing_status_text(&removed).0, "素材已撤回"); +} + #[cfg(test)] mod tests { use crate::jiansun::test_support::SettleUi; diff --git a/components/SuperAdminsTab.test.tsx b/components/SuperAdminsTab.test.tsx index 6928549f..c92e5f86 100644 --- a/components/SuperAdminsTab.test.tsx +++ b/components/SuperAdminsTab.test.tsx @@ -53,6 +53,28 @@ describe('SuperAdminsTab workbench navigation', () => { expect(choice).toBeChecked() }) + test('可以创建只能拉取小壹素材并回传状态的专用 Key', async () => { + const user = userEvent.setup() + const fetchMock = global.fetch as jest.Mock + const fallback = fetchMock.getMockImplementation()! + fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => + init?.method === 'POST' + ? Promise.resolve({ ok: true, json: async () => ({ data: { key: 'isolated-test-key' } }) } as Response) + : fallback(input, init), + ) + render() + await user.click(await screen.findByRole('button', { name: /权限与凭证/ })) + await user.click(screen.getByRole('button', { name: '创建素材平台 API Key' })) + await user.type(screen.getByPlaceholderText('例如:任务系统'), '自动上架') + await user.click(screen.getByRole('checkbox', { name: '仅允许拉取小壹素材和回传上架状态' })) + await user.click(screen.getByRole('button', { name: '创建' })) + await screen.findByText('isolated-test-key') + expect(fetchMock).toHaveBeenCalledWith('/api/admin/api-keys', expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ name: '自动上架', scope: 'xiaoyi_auto_listing' }), + })) + }) + test('超级管理员可按需查看并再次隐藏完整 API Key', async () => { const user = userEvent.setup() ;(global.fetch as jest.Mock).mockImplementation((input: RequestInfo | URL) => { diff --git a/components/SuperAdminsTab.tsx b/components/SuperAdminsTab.tsx index 44d60b01..9032792a 100644 --- a/components/SuperAdminsTab.tsx +++ b/components/SuperAdminsTab.tsx @@ -21,6 +21,7 @@ interface SuperAdmin { interface ApiKey { id: string + scope?: 'general' | 'xiaoyi_auto_listing' name: string key: string canReveal: boolean @@ -211,6 +212,7 @@ export default function SuperAdminsTab({ showToast, onStateChange }: SuperAdmins const [apiKeysLoading, setApiKeysLoading] = useState(true) const [showCreateModal, setShowCreateModal] = useState(false) const [newKeyName, setNewKeyName] = useState('') + const [listingKey, setListingKey] = useState(false) const [createdKey, setCreatedKey] = useState(null) const [revealedApiKeys, setRevealedApiKeys] = useState>({}) const [revealingApiKeyId, setRevealingApiKeyId] = useState(null) @@ -553,13 +555,14 @@ export default function SuperAdminsTab({ showToast, onStateChange }: SuperAdmins const response = await fetch('/api/admin/api-keys', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name: newKeyName }), + body: JSON.stringify({ name: newKeyName, scope: listingKey ? 'xiaoyi_auto_listing' : 'general' }), }) if (response.ok) { const data = await response.json() setCreatedKey(data.data.key) setNewKeyName('') + setListingKey(false) showToast('API Key 创建成功', 'success') fetchApiKeys() } else { @@ -897,6 +900,7 @@ export default function SuperAdminsTab({ showToast, onStateChange }: SuperAdmins {key.name} + {key.scope === 'xiaoyi_auto_listing' && 小壹自动上架专用}
@@ -1486,9 +1490,20 @@ export default function SuperAdminsTab({ showToast, onStateChange }: SuperAdmins } }} /> +