接通小壹自动上架状态回传并准备发布 1.2612.102
This commit is contained in:
parent
d5b23f4667
commit
ed2bfbc81c
@ -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 },
|
||||
|
||||
@ -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(
|
||||
{
|
||||
|
||||
61
app/api/external/product-assets/route.ts
vendored
61
app/api/external/product-assets/route.ts
vendored
@ -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<Array<{brandName:string;productName:string;identifierType:string}>>(
|
||||
'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<Array<{
|
||||
brandName: string; productName: string; identifierType: string; eventId: string | null; listingStatus: ListingStatus | null
|
||||
}>>`
|
||||
SELECT d.brand_name AS "brandName", d.product_name AS "productName", d.identifier_type AS "identifierType",
|
||||
e.id AS "eventId", d.listing_status AS "listingStatus"
|
||||
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<string, any[]> = {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 - 删除素材
|
||||
*/
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -692,6 +692,32 @@ impl Backend {
|
||||
"projects":self.native_projects()?}))
|
||||
}
|
||||
|
||||
pub(super) fn delivery_status(&self, input: &Value) -> R<Value> {
|
||||
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<String> {
|
||||
let context = { let _guard = context_guard(); read_json(&dir.join("context.json"))? };
|
||||
if context["revision"].as_u64() != Some(revision) { return Err("本机版本已变化,请保存后重新完结".into()); }
|
||||
|
||||
@ -1 +1 @@
|
||||
1.2612.101
|
||||
1.2612.102
|
||||
|
||||
@ -1156,6 +1156,8 @@ pub struct Workspace {
|
||||
template_ui: template_slots::UiState,
|
||||
pending_slot_apply: Option<Value>,
|
||||
sync_confirm: bool,
|
||||
listing_read_at: Option<(u64, Instant)>,
|
||||
listing_read_error: Option<String>,
|
||||
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::<Vec<_>>());
|
||||
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);
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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(<SuperAdminsTab showToast={jest.fn()} />)
|
||||
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) => {
|
||||
|
||||
@ -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<string | null>(null)
|
||||
const [revealedApiKeys, setRevealedApiKeys] = useState<Record<string, string>>({})
|
||||
const [revealingApiKeyId, setRevealingApiKeyId] = useState<string | null>(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
|
||||
<tr key={key.id} className="hover:bg-gray-50 dark:hover:bg-gray-800">
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
|
||||
{key.name}
|
||||
{key.scope === 'xiaoyi_auto_listing' && <span className="block text-xs text-gray-600">小壹自动上架专用</span>}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">
|
||||
<div className="flex min-w-56 items-center gap-2">
|
||||
@ -1486,9 +1490,20 @@ export default function SuperAdminsTab({ showToast, onStateChange }: SuperAdmins
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<label className="mb-4 flex items-center gap-2 text-sm text-gray-900">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={listingKey}
|
||||
onChange={(event) => setListingKey(event.target.checked)}
|
||||
/>
|
||||
仅允许拉取小壹素材和回传上架状态
|
||||
</label>
|
||||
<div className="flex space-x-3">
|
||||
<button
|
||||
onClick={() => setShowCreateModal(false)}
|
||||
onClick={() => {
|
||||
setListingKey(false)
|
||||
setShowCreateModal(false)
|
||||
}}
|
||||
className="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 transition-colors"
|
||||
>
|
||||
取消
|
||||
|
||||
@ -52,6 +52,7 @@
|
||||
- `20261112154000_task_detail_zip_cleanup`
|
||||
- `20261126120000_salary_performance_versions`
|
||||
- `20261130120000_desktop_material_deliveries`
|
||||
- `20261201140000_xiaoyi_listing_status`:自动上架专用 Key 的权限范围、小壹交付单的上架状态及按素材 ID 查询索引。
|
||||
|
||||
`20261012_detail_generator` 仅新增个人详情页项目、私有文件、持久任务和品牌风格草案四张表及其约束/索引,不回填素材库或修改用户权限。正式验收前,启用配置仍只开放给当前有效超级管理员;私有文件目录独立持久挂载。
|
||||
|
||||
@ -422,7 +423,7 @@ docker run --rm \
|
||||
"$MIGRATOR_IMAGE" --apply
|
||||
```
|
||||
|
||||
工具会在修改数据库前先验证审计目录可执行“新建→原子改名→删除”,再依次完成:核对镜像 SHA、配置端口与数据库实际端口、核对机器生成的 receipt 和完整备份产物、拒绝未知待执行/失败 migration、执行 `prisma migrate deploy`,最后核对四十六条目标 migration 的数据库 checksum、完成状态、关键人员组织表、素材空壳标记、钉钉流程快照表及需求类型和表单字段、员工花名册历史快照表、业绩转化经营数据快照及同步状态表、字段类型与可空性、检测报告原五个可空字段和独立检测日期字段、`api_keys` 三个可空加密列、`api_key_reveal_audits` 关键列、租约/需求类型/API Key reveal 审计索引的精确列顺序、`materials_uploadId_key` 的唯一性/btree/单列/有效就绪状态/active-only 谓词、Logo 默认值,以及 `materials.task_detail_demand_type` 无默认值、`materials.task_detail_private` / `material_permission_pack_items.can_access_private` 默认值为 `false`,并用稳定语义核对 `materials_private_optimization_check`,确认私密任务详情仍被精确限制在“任务-详情 + 优化”条件下,同时确认品牌知识预览切片列为非空文本数组且默认空数组;AI 模型五表、能力证据及用途验证约束/索引也须通过前述结构检查,最后原子写审计 JSON。
|
||||
工具会在修改数据库前先验证审计目录可执行“新建→原子改名→删除”,再依次完成:核对镜像 SHA、配置端口与数据库实际端口、核对机器生成的 receipt 和完整备份产物、拒绝未知待执行/失败 migration、执行 `prisma migrate deploy`,最后核对全部目标 migration 的数据库 checksum、完成状态、关键人员组织表、素材空壳标记、钉钉流程快照表及需求类型和表单字段、员工花名册历史快照表、业绩转化经营数据快照及同步状态表、字段类型与可空性、检测报告原五个可空字段和独立检测日期字段、`api_keys` 三个可空加密列、`api_key_reveal_audits` 关键列、租约/需求类型/API Key reveal 审计索引的精确列顺序、`materials_uploadId_key` 的唯一性/btree/单列/有效就绪状态/active-only 谓词、Logo 默认值,以及 `materials.task_detail_demand_type` 无默认值、`materials.task_detail_private` / `material_permission_pack_items.can_access_private` 默认值为 `false`,并用稳定语义核对 `materials_private_optimization_check`,确认私密任务详情仍被精确限制在“任务-详情 + 优化”条件下,同时确认品牌知识预览切片列为非空文本数组且默认空数组;AI 模型五表、能力证据及用途验证约束/索引也须通过前述结构检查,最后原子写审计 JSON。
|
||||
|
||||
apply 成功后立即固定审计文件本身;后续“迁移批次部署”读取这一个文件,不能手工重写:
|
||||
|
||||
@ -438,7 +439,7 @@ test -n "$MIGRATION_AUDIT_SHA256"
|
||||
只有以下全部成立,才进入应用首次安全上线步骤:
|
||||
|
||||
- `applied.json` 的 `verified=true`;
|
||||
- 四十条 target migration 均 `completed=true`,source/database checksum 一致;
|
||||
- 全部目标 migration 均 `completed=true`,source/database checksum 一致;
|
||||
- `_prisma_migrations.finished_at` 非空、`rolled_back_at` 为空;
|
||||
- 视频租约列/索引、任务详情作业租约列/索引、active-only `uploadId` 唯一索引、品牌默认值精确匹配;
|
||||
- AI 模型配置及验证五表、用途/上下文/状态约束、幂等与未决测试唯一索引和任务检查点字段精确匹配;旧人工兼容启用约束已由新用途约束替换;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# 自动上架平台成套入库通知接口
|
||||
|
||||
更新时间:2026-04-22
|
||||
更新时间:2026-12-01
|
||||
|
||||
## 目标
|
||||
|
||||
@ -173,7 +173,8 @@ X-API-Key: your-api-key
|
||||
"outcomeKind": "detail",
|
||||
"projectId": "932bd913-9f2c-4462-a50c-c36d5e47d480",
|
||||
"occurredAt": "2026-11-30T08:00:00.000Z",
|
||||
"pullUrl": "https://sc.jiansun.vip/api/external/product-assets?materialId=35d8644b-1e09-4ce8-9bb0-c529b39ba52e"
|
||||
"pullUrl": "https://sc.jiansun.vip/api/external/product-assets?materialId=35d8644b-1e09-4ce8-9bb0-c529b39ba52e",
|
||||
"statusUrl": "https://sc.jiansun.vip/api/external/product-assets?materialId=35d8644b-1e09-4ce8-9bb0-c529b39ba52e"
|
||||
}
|
||||
```
|
||||
|
||||
@ -203,3 +204,39 @@ X-API-Key: your-api-key
|
||||
接收方持具有产品素材读取权限的 `X-API-Key` 请求 `pullUrl`,根据返回的 `assets` 分组和 `sortOrder` 取成品。单文件使用各条目的 `downloadUrl`,整套使用 `downloadUrls.all`。下载链接已签名,过期后重新查询素材。商品型号、品类、品牌和商品名称从查询结果读取。`categoryName` 表示店铺,项目未提供时为空。
|
||||
|
||||
回调由素材库服务器发起。接收方按 `eventId` 去重,并用 `materialId` 定位素材。返回 `2xx` 表示接收成功,超时或失败会重试,后台可手动补发。素材可能在收到通知后被撤回,拉取时以查询接口的当前结果为准。
|
||||
|
||||
### 接入方式
|
||||
|
||||
1. 自动上架系统提供可由素材库访问的 HTTPS POST 地址和回调鉴权配置。素材库管理员在「外部通知」新增目标,选中「小壹自动上架素材入库」。回调鉴权支持 Bearer 或固定自定义 Header。接收方先按 `eventId` 持久化任务并返回 `2xx`,后续异步拉取素材和处理上架。新增接收目标会收到已入库的历史通知。
|
||||
2. 管理员在「权限与凭证」创建 API Key,勾选「仅允许拉取小壹素材和回传上架状态」,通过安全渠道交给接收端。该 Key 以 `X-API-Key` 请求头发送,仅可按 `materialId` 拉取小壹交付素材和回传结果。它与接收 POST 通知使用的凭据独立。
|
||||
3. 使用 `GET pullUrl` 取 `data.spu`、`data.assets.sku[].skuCode`、`barcodes[]` 以及各图的 `downloadUrl`。条码和编号均为字符串。没有通知时,仍可按素材库提供的 `materialId` 调用同一个 GET。返回的 `data.eventId` 可用于回传。
|
||||
4. 上架处理中、成功或失败时,用同一把专用 API Key `PATCH statusUrl`。如果通知是旧版且缺少 `statusUrl`,用该通知的 `pullUrl`。回传成功后,小壹该工程的「上架状态」会显示最新结果,打开期间会自动刷新。
|
||||
|
||||
### 回传上架状态
|
||||
|
||||
```http
|
||||
PATCH /api/external/product-assets?materialId=35d8644b-1e09-4ce8-9bb0-c529b39ba52e
|
||||
X-API-Key: <小壹自动上架专用 Key>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"eventId": "b6797913-4d91-44b4-a614-30a5b9c13091",
|
||||
"sequence": 2,
|
||||
"state": "listed",
|
||||
"listingId": "listing-108626"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 规则 |
|
||||
| --- | --- |
|
||||
| `eventId` | 必填。小壹完结通知中的事件 ID,也可从素材 GET 响应取得 |
|
||||
| `sequence` | 必填。对同一素材从 1 起递增,每次状态变化使用新序号。重试使用相同序号及相同内容 |
|
||||
| `state` | 必填。 `listing` 上架中、`listed` 已上架、`failed` 上架失败。尚无回传显示 `pending` |
|
||||
| `listingId` | 可选。平台上架编号,最多 160 个字符 |
|
||||
| `message` | 可选。最多 500 个字符。失败时可填写给小壹用户查看的原因 |
|
||||
|
||||
成功响应为 `200`,`data` 含 `materialId`、`applied` 及最新的 `listingStatus`。重复或迟到的旧序号返回 `applied: false`。同一序号内容不同、事件 ID 不匹配或试图覆盖已成功状态返回 `409`。素材已撤回返回 `410`,不存在或不可对外提供返回 `404`。Key 缺失或无效返回 `401`,使用通用 Key 回传返回 `403`。失败后可以用更高序号回报重试或成功。
|
||||
|
||||
联调时用约定的测试工程,接收端只下载和核对结果,不真实发布商品。
|
||||
|
||||
@ -14,6 +14,7 @@ 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'
|
||||
import { pendingListingStatus, type ListingStatus } from '@/lib/xiaoyi-listing-status'
|
||||
|
||||
type DeliveryKind = 'detail' | 'video' | 'buyer_show'
|
||||
type FileInput = { uploadId: string; fileName: string; fileSize: number; sha256: string; skuCode?: string; barcode?: string }
|
||||
@ -110,18 +111,20 @@ async function authorizeProject(ownerId: string, projectId: string) {
|
||||
desktopAssert(rows.length, '项目不存在或无权访问', 404, 'not_found')
|
||||
}
|
||||
|
||||
export async function getDesktopDelivery(ownerId: string, projectId: string, kind: string): Promise<Receipt | null> {
|
||||
export async function getDesktopDelivery(ownerId: string, projectId: string, kind: string) {
|
||||
desktopId(projectId)
|
||||
desktopAssert(Object.hasOwn(TYPES, kind), '交付类型无效')
|
||||
await authorizeProject(ownerId, projectId)
|
||||
const rows = await prisma.$queryRawUnsafe<Array<Receipt>>(
|
||||
const rows = await prisma.$queryRawUnsafe<Array<Receipt & { listingStatus: ListingStatus | null }>>(
|
||||
`SELECT d.request_id AS "requestId", d.material_id AS "materialId", d.material_type AS "materialType",
|
||||
d.listing_status AS "listingStatus",
|
||||
CASE WHEN m.id IS NULL OR m."deletedAt" IS NOT NULL THEN 'removed' ELSE 'completed' END AS state
|
||||
FROM desktop_material_deliveries d LEFT JOIN materials m ON m.id=d.material_id
|
||||
WHERE d.owner_id=$1 AND d.project_id=$2 AND d.kind=$3`,
|
||||
ownerId, projectId, kind,
|
||||
)
|
||||
return rows[0] || null
|
||||
const [receipt] = rows
|
||||
return receipt ? { ...receipt, listingStatus: receipt.state === 'completed' ? receipt.listingStatus ?? pendingListingStatus : null } : null
|
||||
}
|
||||
|
||||
export async function createDesktopDelivery(ownerId: string, input: Input, reauthorize: () => Promise<unknown>): Promise<Receipt> {
|
||||
|
||||
@ -6,6 +6,9 @@ import { prisma } from './prisma';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import crypto from 'crypto';
|
||||
|
||||
export const XIAOYI_LISTING_KEY_SCOPE = 'xiaoyi_auto_listing'
|
||||
type ApiKeyScope = 'general' | typeof XIAOYI_LISTING_KEY_SCOPE
|
||||
|
||||
const API_KEY_HASH_PREFIX = 'v1';
|
||||
const API_KEY_ENCRYPTION_ENV = 'API_KEY_ENCRYPTION_KEY';
|
||||
const API_KEY_ENCRYPTION_ALGORITHM = 'aes-256-gcm';
|
||||
@ -155,7 +158,7 @@ export type ApiErrorCode = keyof typeof API_ERROR;
|
||||
* 验证 API Key
|
||||
* @returns API Key 记录,验证失败返回 null
|
||||
*/
|
||||
export async function validateApiKey(apiKey: string | null) {
|
||||
export async function validateApiKey(apiKey: string | null, allowXiaoyiListingKey = false) {
|
||||
if (!apiKey) {
|
||||
return null;
|
||||
}
|
||||
@ -168,6 +171,7 @@ export async function validateApiKey(apiKey: string | null) {
|
||||
name: true,
|
||||
isActive: true,
|
||||
createdBy: true,
|
||||
scope: true,
|
||||
},
|
||||
});
|
||||
let matchedLegacyPlaintext = false;
|
||||
@ -181,12 +185,13 @@ export async function validateApiKey(apiKey: string | null) {
|
||||
name: true,
|
||||
isActive: true,
|
||||
createdBy: true,
|
||||
scope: true,
|
||||
},
|
||||
});
|
||||
matchedLegacyPlaintext = Boolean(keyRecord);
|
||||
}
|
||||
|
||||
if (!keyRecord || !keyRecord.isActive) {
|
||||
if (!keyRecord || !keyRecord.isActive || (keyRecord.scope === XIAOYI_LISTING_KEY_SCOPE && !allowXiaoyiListingKey)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -274,7 +279,7 @@ export async function logApiCall(data: {
|
||||
/**
|
||||
* 生成错误响应
|
||||
*/
|
||||
export function errorResponse(error: typeof API_ERROR[ApiErrorCode]) {
|
||||
export function errorResponse(error: { code: string; message: string; status: number }) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
@ -308,7 +313,7 @@ export function generateApiKey(): string {
|
||||
/**
|
||||
* 创建 API Key
|
||||
*/
|
||||
export async function createApiKey(name: string, createdBy: string) {
|
||||
export async function createApiKey(name: string, createdBy: string, scope: ApiKeyScope = 'general') {
|
||||
const key = generateApiKey();
|
||||
const encryptedSecret = encryptApiKeySecret(key);
|
||||
|
||||
@ -318,12 +323,14 @@ export async function createApiKey(name: string, createdBy: string) {
|
||||
key: hashApiKey(key),
|
||||
...encryptedSecret,
|
||||
createdBy,
|
||||
scope,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
id: apiKey.id,
|
||||
name: apiKey.name,
|
||||
scope: apiKey.scope,
|
||||
key,
|
||||
createdAt: apiKey.createdAt,
|
||||
};
|
||||
@ -357,6 +364,7 @@ export async function getApiKeys() {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
scope: true,
|
||||
// 不返回完整 key,只返回前8位
|
||||
key: true,
|
||||
secretCiphertext: true,
|
||||
|
||||
@ -661,6 +661,7 @@ export async function queueXiaoyiDeliveries(limit = 20) {
|
||||
LIMIT $2
|
||||
`, XIAOYI_AUTO_LISTING_EVENT_TYPE, limit)
|
||||
for (const event of pending) {
|
||||
const materialUrl = `${getPublicAppOrigin()}/api/external/product-assets?materialId=${encodeURIComponent(event.materialId)}`
|
||||
const payload = {
|
||||
eventId: event.eventId,
|
||||
eventType: XIAOYI_AUTO_LISTING_EVENT_TYPE,
|
||||
@ -669,7 +670,8 @@ export async function queueXiaoyiDeliveries(limit = 20) {
|
||||
outcomeKind: event.outcomeKind,
|
||||
projectId: event.projectId,
|
||||
occurredAt: new Date(event.createdAt).toISOString(),
|
||||
pullUrl: `${getPublicAppOrigin()}/api/external/product-assets?materialId=${encodeURIComponent(event.materialId)}`,
|
||||
pullUrl: materialUrl,
|
||||
statusUrl: materialUrl,
|
||||
}
|
||||
const deliveryId = randomUUID()
|
||||
const inserted = await queryRaw<{ id: string }>(`
|
||||
|
||||
59
lib/xiaoyi-listing-status.ts
Normal file
59
lib/xiaoyi-listing-status.ts
Normal file
@ -0,0 +1,59 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
type ListingUpdate = {
|
||||
eventId: string
|
||||
sequence: number
|
||||
state: 'listing' | 'listed' | 'failed'
|
||||
listingId: string | null
|
||||
message: string | null
|
||||
}
|
||||
|
||||
export type ListingStatus = ListingUpdate & { updatedAt: string }
|
||||
|
||||
export const pendingListingStatus = { state: 'pending', sequence: 0 } as const
|
||||
|
||||
export function parseListingUpdate(body: unknown): ListingUpdate | null {
|
||||
if (!body || typeof body !== 'object') return null
|
||||
const { eventId, sequence, state, listingId, message } = body as Record<string, unknown>
|
||||
if (typeof eventId !== 'string' || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(eventId)
|
||||
|| typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 1
|
||||
|| (state !== 'listing' && state !== 'listed' && state !== 'failed')) return null
|
||||
if (listingId != null && (typeof listingId !== 'string' || !listingId.trim() || listingId.length > 160)) return null
|
||||
if (message != null && (typeof message !== 'string' || !message.trim() || message.length > 500)) return null
|
||||
return { eventId, sequence, state, listingId: listingId?.trim() ?? null, message: message?.trim() ?? null }
|
||||
}
|
||||
|
||||
export async function recordListingStatus(materialId: string, update: ListingUpdate) {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const [row] = await tx.$queryRaw<Array<{ eventId: string; deletedAt: Date | null; listingStatus: ListingStatus | null }>>`
|
||||
SELECT e.id AS "eventId", m."deletedAt", d.listing_status AS "listingStatus"
|
||||
FROM desktop_material_deliveries d
|
||||
JOIN xiaoyi_auto_listing_events e ON e.material_id = d.material_id
|
||||
JOIN materials m ON m.id = d.material_id
|
||||
WHERE d.material_id = ${materialId} AND m.access_scope = 'general' AND m.task_detail_private = false
|
||||
FOR UPDATE OF d, m
|
||||
`
|
||||
if (!row) return { status: 404, code: 'MATERIAL_NOT_FOUND', message: '小壹交付素材不存在' } as const
|
||||
if (row.deletedAt) return { status: 410, code: 'MATERIAL_DELETED', message: '素材已撤回' } as const
|
||||
if (row.eventId !== update.eventId) return { status: 409, code: 'EVENT_MISMATCH', message: '事件 ID 与素材不匹配' } as const
|
||||
|
||||
const current = row.listingStatus
|
||||
if (current && update.sequence <= current.sequence) {
|
||||
if (update.sequence === current.sequence && (update.state !== current.state
|
||||
|| update.listingId !== current.listingId || update.message !== current.message)) {
|
||||
return { status: 409, code: 'SEQUENCE_CONFLICT', message: '同一状态序号的内容必须一致' } as const
|
||||
}
|
||||
return { status: 200, applied: false, listingStatus: current } as const
|
||||
}
|
||||
if (current?.state === 'listed') {
|
||||
return { status: 409, code: 'ALREADY_LISTED', message: '上架成功后不能再更新此交付的状态' } as const
|
||||
}
|
||||
const listingStatus = { ...update, updatedAt: new Date().toISOString() }
|
||||
await tx.$executeRaw`
|
||||
UPDATE desktop_material_deliveries
|
||||
SET listing_status = ${JSON.stringify(listingStatus)}::jsonb
|
||||
WHERE material_id = ${materialId}
|
||||
`
|
||||
return { status: 200, applied: true, listingStatus } as const
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,5 @@
|
||||
ALTER TABLE api_keys ADD COLUMN scope TEXT NOT NULL DEFAULT 'general'
|
||||
CHECK (scope IN ('general', 'xiaoyi_auto_listing'));
|
||||
|
||||
ALTER TABLE desktop_material_deliveries ADD COLUMN listing_status JSONB;
|
||||
CREATE INDEX desktop_material_deliveries_material_id_idx ON desktop_material_deliveries (material_id);
|
||||
@ -866,6 +866,7 @@ model MaterialSkuBarcode {
|
||||
model ApiKey {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
scope String @default("general")
|
||||
key String @unique
|
||||
secretCiphertext String? @map("secret_ciphertext")
|
||||
secretNonce String? @map("secret_nonce")
|
||||
|
||||
@ -1705,6 +1705,7 @@ const expectedMigrationNames = new Set([
|
||||
'20261112154000_task_detail_zip_cleanup',
|
||||
'20261126120000_salary_performance_versions',
|
||||
'20261130120000_desktop_material_deliveries',
|
||||
'20261201140000_xiaoyi_listing_status',
|
||||
]);
|
||||
if (migrations.length !== expectedMigrationNames.size
|
||||
|| migrations.some((item) => !expectedMigrationNames.has(item && item.name)
|
||||
|
||||
@ -55,6 +55,7 @@ const TARGET_MIGRATIONS = Object.freeze([
|
||||
'20261112154000_task_detail_zip_cleanup',
|
||||
'20261126120000_salary_performance_versions',
|
||||
'20261130120000_desktop_material_deliveries',
|
||||
'20261201140000_xiaoyi_listing_status',
|
||||
])
|
||||
const VERIFIED_BACKUP_GENERATOR = 'scripts/create-verified-production-backup.mjs'
|
||||
const VERIFIED_BACKUP_MAINTENANCE_CONFIRMATION = 'NO_WRITES_DURING_SNAPSHOT'
|
||||
@ -373,7 +374,7 @@ export async function queryEvidence(prisma, localMigrations) {
|
||||
OR table_name = 'desktop_material_deliveries'
|
||||
OR table_name IN ('ai_model_providers', 'ai_model_catalog', 'ai_model_configuration', 'ai_model_audit', 'ai_model_verifications')
|
||||
OR table_name IN ('personnel_salary_bases', 'personnel_salary_base_audits', 'salary_position_configs', 'salary_position_config_audits', 'salary_performance_versions')
|
||||
OR (table_name = 'api_keys' AND column_name IN ('secret_ciphertext', 'secret_nonce', 'secret_auth_tag'))
|
||||
OR (table_name = 'api_keys' AND column_name IN ('secret_ciphertext', 'secret_nonce', 'secret_auth_tag', 'scope'))
|
||||
OR (table_name = 'api_key_reveal_audits' AND column_name IN ('id', 'api_key_id', 'viewer_user_id', 'created_at'))
|
||||
OR (table_name = 'system_settings' AND column_name IN ('headerLogoUrl', 'loginLogoUrl', 'logoUrl'))
|
||||
OR (table_name = 'organization_units' AND column_name IN ('id', 'source_dept_id', 'parent_id', 'path', 'level', 'is_active'))
|
||||
@ -454,7 +455,8 @@ export async function queryEvidence(prisma, localMigrations) {
|
||||
'personnel_salary_base_audits_initialization_key_key', 'personnel_salary_base_audits_record_id_created_at_idx',
|
||||
'salary_position_configs_personnel_position_id_idx', 'salary_grade_scheme_live_unique',
|
||||
'salary_performance_versions_position_id_effective_month_key',
|
||||
'desktop_material_deliveries_project_id_kind_key', 'desktop_material_deliveries_owner_id_request_id_kind_key'
|
||||
'desktop_material_deliveries_project_id_kind_key', 'desktop_material_deliveries_owner_id_request_id_kind_key',
|
||||
'desktop_material_deliveries_material_id_idx'
|
||||
)
|
||||
ORDER BY idx.relname`,
|
||||
)
|
||||
@ -500,7 +502,7 @@ export async function queryEvidence(prisma, localMigrations) {
|
||||
'team_function_config_audits_config_id_fkey', 'team_function_configs_revision_check',
|
||||
'material_purge_audits_job_id_fkey'
|
||||
) OR cls.relname IN ('desktop_client_grants', 'desktop_client_sessions', 'desktop_workspace_projects', 'desktop_workspace_assets', 'desktop_creation_tasks')
|
||||
OR cls.relname = 'desktop_material_deliveries'
|
||||
OR cls.relname IN ('desktop_material_deliveries', 'api_keys')
|
||||
OR cls.relname IN ('ai_model_providers', 'ai_model_catalog', 'ai_model_configuration', 'ai_model_verifications')
|
||||
OR cls.relname IN ('personnel_salary_bases', 'personnel_salary_base_audits', 'salary_position_configs', 'salary_position_config_audits', 'salary_performance_versions')
|
||||
OR (cls.relname IN ('material_logs', 'material_download_logs') AND ref.relname = 'materials'))
|
||||
@ -1279,6 +1281,25 @@ export function assertDesktopMaterialDeliveryEvidence(evidence) {
|
||||
table, 'desktop_material_deliveries_kind_check', ['kind'], "kind = ANY (ARRAY['detail'::text, 'video'::text, 'buyer_show'::text])")
|
||||
}
|
||||
|
||||
export function assertXiaoyiListingStatusEvidence(evidence) {
|
||||
const scope = evidence.columns.find(row => row.table_name === 'api_keys' && row.column_name === 'scope')
|
||||
if (scope?.data_type !== 'text' || scope.is_nullable !== 'NO' || normalizeColumnDefault(scope.column_default) !== 'general') {
|
||||
fail('Database column mismatch: api_keys.scope')
|
||||
}
|
||||
assertExactCheckConstraint(evidence.constraints.find(row => row.constraint_name === 'api_keys_scope_check'),
|
||||
'api_keys', 'api_keys_scope_check', ['scope'], "scope = ANY (ARRAY['general'::text, 'xiaoyi_auto_listing'::text])")
|
||||
const table = 'desktop_material_deliveries'
|
||||
const status = evidence.columns.find(row => row.table_name === table && row.column_name === 'listing_status')
|
||||
if (status?.data_type !== 'jsonb' || status.is_nullable !== 'YES' || status.column_default != null) {
|
||||
fail('Database column mismatch: desktop_material_deliveries.listing_status')
|
||||
}
|
||||
const index = evidence.indexes.find(row => row.indexname === 'desktop_material_deliveries_material_id_idx')
|
||||
if (!index || index.tablename !== table || index.indisunique || !index.indisvalid || !index.indisready || index.predicate) {
|
||||
fail('Database index mismatch: desktop_material_deliveries_material_id_idx')
|
||||
}
|
||||
assertExactBtreeIndex(index.indexdef, table, ['material_id'])
|
||||
}
|
||||
|
||||
function assertNoUnexpectedPendingMigrations(localMigrations, evidence) {
|
||||
const completed = completedMigrationMap(evidence.migrationRows)
|
||||
const targetSet = new Set(TARGET_MIGRATIONS)
|
||||
@ -1598,6 +1619,7 @@ async function main() {
|
||||
assertSalaryGradeEvidence(after)
|
||||
assertSalaryPerformanceVersionEvidence(after)
|
||||
assertDesktopMaterialDeliveryEvidence(after)
|
||||
assertXiaoyiListingStatusEvidence(after)
|
||||
}
|
||||
} finally {
|
||||
await verifyClient.$disconnect()
|
||||
|
||||
@ -460,6 +460,7 @@ test('target evidence rejects nullable logo columns and structurally wrong index
|
||||
['20261106160000_salary_personnel_grade', { checksum: 'salary-grade' }],
|
||||
['20261126120000_salary_performance_versions', { checksum: 'salary-versions' }],
|
||||
['20261130120000_desktop_material_deliveries', { checksum: 'desktop-deliveries' }],
|
||||
['20261201140000_xiaoyi_listing_status', { checksum: 'xiaoyi-listing-status' }],
|
||||
])
|
||||
const evidence = {
|
||||
migrationRows: [
|
||||
@ -739,6 +740,7 @@ test('target evidence rejects nullable logo columns and structurally wrong index
|
||||
evidence.migrationRows.push({ migration_name: '20261020120000_desktop_creation_tasks', checksum: 'native-tasks', finished_at: 'now', rolled_back_at: null }, { migration_name: '20261020150000_desktop_project_deletion', checksum: 'native-deletion', finished_at: 'now', rolled_back_at: null })
|
||||
evidence.migrationRows.push({ migration_name: '20261126120000_salary_performance_versions', checksum: 'salary-versions', finished_at: 'now', rolled_back_at: null })
|
||||
evidence.migrationRows.push({ migration_name: '20261130120000_desktop_material_deliveries', checksum: 'desktop-deliveries', finished_at: 'now', rolled_back_at: null })
|
||||
evidence.migrationRows.push({ migration_name: '20261201140000_xiaoyi_listing_status', checksum: 'xiaoyi-listing-status', finished_at: 'now', rolled_back_at: null })
|
||||
const native = desktopNativeEvidence()
|
||||
evidence.migrationRows.push({ migration_name: '20261023130000_personnel_salary_base', checksum: 'salary-base', finished_at: 'now', rolled_back_at: null },
|
||||
{ migration_name: '20261028090000_salary_position_configuration', checksum: 'salary-position', finished_at: 'now', rolled_back_at: null },
|
||||
@ -1138,7 +1140,7 @@ test('container supply chain and migrator image are immutable while SOP keeps co
|
||||
const targetBlock = migratorSource.match(/const TARGET_MIGRATIONS = Object\.freeze\(\[([\s\S]*?)\]\)/)?.[1]
|
||||
assert.ok(targetBlock, 'Migrator target list must be inspectable')
|
||||
const targets = [...targetBlock.matchAll(/'([^']+)'/g)].map(match => match[1])
|
||||
assert.equal(targets.length, 46)
|
||||
assert.equal(targets.length, 47)
|
||||
const deploymentTargets = deploymentSource.match(/const expectedMigrationNames = new Set\(\[([\s\S]*?)\]\)/)?.[1]
|
||||
assert.ok(deploymentTargets, 'Production migration audit targets must be inspectable')
|
||||
const auditedTargets = [...deploymentTargets.matchAll(/'([^']+)'/g)].map(match => match[1])
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
*
|
||||
* Required environment: XIAOYI_QA_BASE, XIAOYI_QA_DESKTOP_TOKEN,
|
||||
* XIAOYI_QA_OTHER_TOKEN, XIAOYI_QA_EXTERNAL_KEY, XIAOYI_QA_VIDEO_PATH.
|
||||
* Optional XIAOYI_QA_LISTING_KEY exercises status callbacks with a scoped Key.
|
||||
* The service must use isolated test data and storage. The script creates three
|
||||
* projects, uploaded files and materials in that isolated environment.
|
||||
*/
|
||||
@ -23,6 +24,7 @@ assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname), 'Accept
|
||||
const owner = required('XIAOYI_QA_DESKTOP_TOKEN')
|
||||
const other = required('XIAOYI_QA_OTHER_TOKEN')
|
||||
const externalKey = required('XIAOYI_QA_EXTERNAL_KEY')
|
||||
const listingKey = process.env.XIAOYI_QA_LISTING_KEY
|
||||
assert.notEqual(owner, other, 'Owner and second user require distinct sessions')
|
||||
const video = await readFile(required('XIAOYI_QA_VIDEO_PATH'))
|
||||
assert.ok(video.length > 32, 'Use a valid synthetic MP4 fixture')
|
||||
@ -51,7 +53,7 @@ async function request(method, pathname, { token = owner, data, bytes, headers =
|
||||
}
|
||||
|
||||
function expectStatus(result, allowed, name) {
|
||||
assert.ok(allowed.includes(result.status), name + ' returned HTTP ' + result.status + ' ' + JSON.stringify(result.body))
|
||||
assert.ok(allowed.includes(result.status), name + ' returned HTTP ' + result.status + ' ' + ' ' + (result.body?.error?.code ?? result.body?.code ?? ''))
|
||||
}
|
||||
|
||||
async function project(name) {
|
||||
@ -139,6 +141,41 @@ async function verifyDownload(material, expectedBytes) {
|
||||
throw Error('material download redirected too many times')
|
||||
}
|
||||
|
||||
async function checkListingReport(found, projectId, kind) {
|
||||
const materialId = found.materialId
|
||||
const endpoint = '/api/external/product-assets?materialId=' + encodeURIComponent(materialId)
|
||||
const keyHeaders = { token: null, headers: { 'X-API-Key': listingKey } }
|
||||
const report = (data, credentials = keyHeaders) => request('PATCH', endpoint, { ...credentials, data })
|
||||
const read = () => request('GET', '/api/desktop/deliveries/' + projectId + '/' + kind)
|
||||
const initial = await request('GET', endpoint, keyHeaders)
|
||||
expectStatus(initial, [200], 'scoped material read')
|
||||
const event = initial.body.data.eventId
|
||||
assert.ok(event)
|
||||
assert.equal(initial.body.data.listingStatus.state, 'pending')
|
||||
const first = { eventId: event, sequence: 1, state: 'listing' }
|
||||
expectStatus(await report(first, { token: null }), [401], 'missing callback key')
|
||||
expectStatus(await report(first, { token: null, headers: { 'X-API-Key': externalKey } }), [403], 'general key cannot report status')
|
||||
expectStatus(await request('DELETE', endpoint, keyHeaders), [401], 'scoped key cannot delete')
|
||||
expectStatus(await report({ ...first, eventId: randomUUID() }), [409], 'wrong event')
|
||||
expectStatus(await report({ ...first, sequence: 0 }), [400], 'invalid sequence')
|
||||
expectStatus(await report(first), [200], 'listing in progress')
|
||||
assert.equal((await read()).body.listingStatus.state, 'listing')
|
||||
const failed = { ...first, sequence: 2, state: 'failed', message: '测试失败原因' }
|
||||
expectStatus(await report(failed), [200], 'listing failure')
|
||||
assert.equal((await read()).body.listingStatus.message, failed.message)
|
||||
const listed = { ...first, sequence: 3, state: 'listed', listingId: 'QA-listing' }
|
||||
const [reportA, reportB] = await Promise.all([report(listed), report(listed)])
|
||||
expectStatus(reportA, [200], 'listing result')
|
||||
expectStatus(reportB, [200], 'concurrent duplicate listing result')
|
||||
assert.deepEqual([reportA.body.data.applied, reportB.body.data.applied].sort(), [false, true])
|
||||
assert.equal((await report(failed)).body.data.applied, false)
|
||||
expectStatus(await report({ ...listed, listingId: 'different' }), [409], 'sequence content collision')
|
||||
expectStatus(await report({ ...failed, sequence: 4 }), [409], 'reported success cannot regress')
|
||||
const last = await read()
|
||||
assert.equal(last.body.listingStatus.state, 'listed')
|
||||
assert.equal(last.body.listingStatus.listingId, listed.listingId)
|
||||
}
|
||||
|
||||
async function runCase(kind, materialType) {
|
||||
const projectId = await project('验收用 ' + kind)
|
||||
const requestId = randomUUID()
|
||||
@ -212,7 +249,9 @@ async function runCase(kind, materialType) {
|
||||
assert.ok(file.downloadUrl, 'Single-file download URL is missing')
|
||||
await verifyDownload({ downloadUrl: file.downloadUrl }, [bytes])
|
||||
}
|
||||
console.log(JSON.stringify({ kind, materialType, materialId, repeatedId: true, crossAccountDenied: true, externalReadable: true }))
|
||||
if (listingKey) await checkListingReport(found, projectId, kind)
|
||||
console.log(JSON.stringify({ kind, materialType, materialId, repeatedId: true, crossAccountDenied: true,
|
||||
externalReadable: true, listingReported: Boolean(listingKey) }))
|
||||
}
|
||||
|
||||
await runCase('detail', '自动上架-详情')
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user