fix(installation): replace existing drawing tasks by complete drawing ID

This commit is contained in:
WuYongJie 2026-11-07 18:03:57 +08:00
parent d54494dcc7
commit bfaab0ce4e
8 changed files with 187 additions and 35 deletions

View File

@ -0,0 +1,26 @@
/** @jest-environment node */
import { DrawingSystemClient } from "../drawing-system.client";
const originalFetch = global.fetch;
afterEach(() => { global.fetch = originalFetch; });
it("queries the complete drawing ID directly and ignores partial matches from the remote list", async () => {
const calls: string[] = [];
global.fetch = jest.fn(async (input) => {
const url = String(input); calls.push(url);
return new Response(JSON.stringify({ success: true, data: url.includes("Login")
? { token: "test-token" }
: [
{ taskId: "existing", spu: "GBGJ-CBZ0003", pictureId: "CBZ0003K01AV01" },
{ taskId: "partial", pictureId: "CBZ0003K01AV010" },
],
}), { headers: { "content-type": "application/json" } });
});
const client = new DrawingSystemClient({ apiBase: "https://api.test", authBase: "https://auth.test", desKey: "12345678", account: "test", password: "test" });
expect(await client.listTasksByDrawingId(" cbz0003k01av01 ")).toEqual([
{ taskId: "existing", spu: "GBGJ-CBZ0003", pictureId: "CBZ0003K01AV01" },
]);
const url = new URL(calls.find((url) => url.includes("GetMissionListData"))!);
expect(url.searchParams.get("PictureId")).toBe("CBZ0003K01AV01");
expect(url.searchParams.has("SkuModel")).toBe(false);
});

View File

@ -37,7 +37,7 @@ function harness(assetType: "drawing" | "video" = "drawing") {
const events: InstallationDrawingReplaceEvent[] = [];
const category = assetType === "video" ? "video" : "instructions";
const client = {
listTasksBySkuModel: jest.fn(async () => [{ taskId: "task1", pictureId: "DRAW001", makeContent: "3,4" }]),
listTasksByDrawingId: jest.fn(async () => [{ taskId: "task1", pictureId: "DRAW001", makeContent: "3,4" }]),
getTaskDetail: jest.fn(async () => ({ pictureId: "DRAW001", skucodes: ["BAR001"], files: { [category]: ["/new/1.jpg", "/new/2.jpg"] } })),
uploadTaskFile: jest.fn(async (_task: string, _category: string, file: File) => `/new/${file.name}`),
submitTaskFiles: jest.fn(async () => undefined),

View File

@ -148,7 +148,7 @@ function createHarness(options: { assetType?: "drawing" | "video" } = {}) {
const client = {
listTasksBySpu: jest.fn().mockResolvedValue([]),
listTasksBySkuModel: jest.fn().mockResolvedValue([]),
listTasksByDrawingId: jest.fn().mockResolvedValue([]),
uploadProductPictureFromUrl: jest
.fn()
.mockResolvedValue("/remote/product.jpg"),
@ -294,7 +294,7 @@ describe("IntakeInstallationDrawingUploadService", () => {
it("reuses an existing drawing-ID task when the remote task has no barcode list", async () => {
const harness = createHarness({ assetType: "video" });
harness.client.listTasksBySkuModel.mockResolvedValue([
harness.client.listTasksByDrawingId.mockResolvedValue([
{
taskId: "1790154570617",
spu: null,
@ -336,9 +336,9 @@ describe("IntakeInstallationDrawingUploadService", () => {
expect(result.file.installDrawingSyncStatus).toBe("succeeded");
});
it("still rejects an existing drawing-ID task with different remote barcodes", async () => {
it("reuses the same drawing ID across brand barcodes and replaces its existing instructions", async () => {
const harness = createHarness();
harness.client.listTasksBySkuModel.mockResolvedValue([
harness.client.listTasksByDrawingId.mockResolvedValue([
{
taskId: "remote-task",
spu: null,
@ -356,14 +356,24 @@ describe("IntakeInstallationDrawingUploadService", () => {
files: {},
});
await expect(
harness.service.upload({
productId: "product-1",
fileId: "file-1",
drawingId: "BJ0226K01AV01",
actor,
}),
).rejects.toThrow("图纸系统已有任务单绑定的条码与产品基础信息不一致");
harness.client.getTaskDetail.mockResolvedValueOnce({
pictureId: "BJ0226K01AV01", skucodes: ["OTHER-BARCODE"],
files: { instructions: ["/old/previous.pdf"] },
}).mockResolvedValueOnce({
pictureId: "BJ0226K01AV01", skucodes: ["OTHER-BARCODE"], files: {},
}).mockResolvedValueOnce({
pictureId: "BJ0226K01AV01", skucodes: ["OTHER-BARCODE"],
files: { instructions: ["/remote/install.pdf"] },
});
const result = await harness.service.upload({
productId: "product-1", fileId: "file-1", drawingId: "BJ0226K01AV01", actor,
});
expect(result.file.installDrawingSyncStatus).toBe("succeeded");
expect(harness.client.listTasksByDrawingId).toHaveBeenCalledWith("BJ0226K01AV01");
expect(harness.client.submitTaskFiles).toHaveBeenCalledWith(
"remote-task", { instructions: ["/remote/install.pdf"] },
{ deduplicateUrls: true, replaceCategories: ["instructions"] },
);
expect(harness.client.createTask).not.toHaveBeenCalled();
expect(harness.client.updateTaskMakeContent).not.toHaveBeenCalled();
});
@ -389,6 +399,57 @@ describe("IntakeInstallationDrawingUploadService", () => {
);
});
it.each([false, true])("replaces an old PDF with the complete JPEG version; second upload failure=%s", async (failSecond) => {
const h = createHarness();
Object.assign(h.file, { name: "page1.webp", mimeType: "image/webp", installVersionLabel: "V01", installOrder: 1 });
const second = { ...h.file, id: "file-2", name: "page2.webp", installOrder: 2 };
h.payload().uploadFiles = [second, h.file];
h.client.listTasksByDrawingId.mockResolvedValue([
{ taskId: "brand-task", pictureId: "BJ0226K01AV01", spu: "OTHER-BRAND", makeContent: "3" },
]);
h.client.getTaskDetail.mockResolvedValue({
pictureId: "BJ0226K01AV01", skucodes: ["OTHER-BRAND-BARCODE"],
files: { instructions: ["/old/original.pdf"] },
});
const webp = await sharp({ create: { width: 48, height: 64, channels: 3, background: "white" } }).webp().toBuffer();
global.fetch = jest.fn(async () => ({ ok: true, arrayBuffer: async () => new Uint8Array(webp).buffer })) as jest.Mock;
const uploaded: File[] = [];
h.client.uploadTaskFile.mockImplementation(async (_task, _category, file) => {
uploaded.push(file);
if (failSecond && uploaded.length === 2) throw new Error("second upload failed");
return `/new/${file.name}`;
});
h.client.submitTaskFiles.mockImplementation(async () => {
h.client.getTaskDetail.mockResolvedValue({
pictureId: "BJ0226K01AV01", skucodes: ["OTHER-BRAND-BARCODE"],
files: { instructions: ["/new/page1.jpg", "/new/page2.jpg"] },
});
});
const push = () => h.service.upload({ productId: "product-1", fileId: "file-1", drawingId: "BJ0226K01AV01", actor });
if (failSecond) {
await expect(push()).rejects.toThrow("second upload failed");
expect(h.client.submitTaskFiles).not.toHaveBeenCalled();
expect(h.repository.saveActiveWithLock).not.toHaveBeenCalled();
} else {
await expect(push()).resolves.toMatchObject({ file: { installDrawingSyncStatus: "succeeded" } });
expect(h.client.submitTaskFiles).toHaveBeenCalledTimes(1);
expect(h.client.submitTaskFiles).toHaveBeenCalledWith("brand-task", {
instructions: ["/new/page1.jpg", "/new/page2.jpg"],
}, { deduplicateUrls: true, replaceCategories: ["instructions"] });
expect(h.product.uploadFiles.every((file) => file.installDrawingSyncStatus === "succeeded")).toBe(true);
await h.service.upload({ productId: "product-1", fileId: "file-2", drawingId: "BJ0226K01AV01", actor });
expect(h.client.uploadTaskFile).toHaveBeenCalledTimes(2);
}
expect(uploaded.map((file) => file.name)).toEqual(["page1.jpg", "page2.jpg"]);
for (const file of uploaded) {
expect(file.type).toBe("image/jpeg");
expect(await sharp(Buffer.from(await file.arrayBuffer())).metadata()).toMatchObject({ format: "jpeg", width: 48, height: 64 });
}
expect(h.client.createTask).not.toHaveBeenCalled();
expect(h.client.updateTaskMakeContent).not.toHaveBeenCalled();
expect(h.file.name).toBe("page1.webp");
});
it("finds an attached installation file from the persisted payload if hydration omits it", async () => {
const harness = createHarness();
harness.productService.getById.mockResolvedValueOnce({
@ -465,7 +526,7 @@ describe("IntakeInstallationDrawingUploadService", () => {
}),
).rejects.toThrow("denied");
expect(harness.client.listTasksBySkuModel).not.toHaveBeenCalled();
expect(harness.client.listTasksByDrawingId).not.toHaveBeenCalled();
expect(harness.repository.saveActiveWithLock).not.toHaveBeenCalled();
});
});

View File

@ -237,6 +237,25 @@ export class DrawingSystemClient {
});
}
/** Drawing IDs are shared across brands; query the unique ID directly. */
async listTasksByDrawingId(drawingId: string): Promise<DrawingSystemTaskSummary[]> {
const normalizedId = drawingId.trim().toUpperCase();
return this.withAuthRetry(async () => {
const query = new URLSearchParams({
PictureId: normalizedId,
PageSize: "50",
PageIndex: "1",
});
const data = await this.requestJson<DrawingSystemTaskSummary[]>(
`${this.config.apiBase}/api/MissionList/GetMissionListData?${query.toString()}`,
{ headers: this.signHeaders(true) },
);
return (Array.isArray(data) ? data : []).filter((task) =>
Boolean(task?.taskId) && task.pictureId?.trim().toUpperCase() === normalizedId,
);
});
}
async createTask(input: {
taskId: string;
spu: string;

View File

@ -0,0 +1,48 @@
import { INSTALLATION_WORKSPACE_CATEGORY } from "@/app/intake/non-integrated/workspaces/documents/documentWorkspaceConfig";
import type { NonIntegratedProductRecord } from "@/app/intake/non-integrated/nonIntegratedStorage";
import { resolveInstallationFileDrawingId, resolveInstallationVersionLabel } from "@/app/intake/non-integrated/workspaces/style-assets/styleFileHelpers";
import { AppError, ErrorCode } from "@/server/core/errors";
import type { AuthUser } from "@/server/core/types";
import { IntakeInstallationDrawingReplaceService } from "./intake-installation-drawing-replace.service";
import { isRecord, normalizeCode, type InstallationDrawingPushDependencies, type StoredUploadFile } from "./intake-installation-drawing-push-support";
/** The caller holds the drawing-ID lease. Replace the whole version before
* removing files from an earlier product/version; retries of this version append. */
export async function replaceExistingInstallationVersion(
dependencies: InstallationDrawingPushDependencies,
input: { product: NonIntegratedProductRecord; file: StoredUploadFile; drawingId: string; actor: AuthUser },
): Promise<StoredUploadFile | null> {
if (input.file.installAssetType !== "drawing") return null;
const tasks = await dependencies.client.listTasksByDrawingId(input.drawingId);
const matches = tasks.filter((task) => normalizeCode(task.pictureId) === input.drawingId);
if (matches.length > 1) throw new AppError(ErrorCode.VALIDATION_FAILED, "图纸系统中存在多个同图纸 ID 任务单,请先核对");
if (!matches.length) return null;
const detail = await dependencies.client.getTaskDetail(matches[0].taskId);
if (detail.pictureId && normalizeCode(detail.pictureId) !== input.drawingId) {
throw new AppError(ErrorCode.VALIDATION_FAILED, "图纸系统已有任务单的图纸 ID 与当前资料不一致");
}
const category = "instructions";
const existingUrls = detail.files[category] ?? [];
if (!existingUrls.length) return null;
const record = await dependencies.repository.findActiveById(input.product.id);
const rawFiles = isRecord(record?.payload) && Array.isArray(record.payload.uploadFiles)
? record.payload.uploadFiles : [];
const versionLabel = resolveInstallationVersionLabel(input.file);
const knownIds = input.product.skuItems.map((sku) => normalizeCode(sku.drawingId)).filter(Boolean);
const files = rawFiles.filter((file): file is StoredUploadFile =>
isRecord(file) && file.category === INSTALLATION_WORKSPACE_CATEGORY &&
file.installAssetType === input.file.installAssetType && file.installDrawingSyncStatus !== "not_applicable" &&
resolveInstallationFileDrawingId(file as StoredUploadFile, knownIds) === input.drawingId &&
resolveInstallationVersionLabel(file as StoredUploadFile) === versionLabel,
);
const currentUrls = new Set(files.map((file) => file.installDrawingSyncFileUrl).filter(Boolean));
if (existingUrls.every((url) => currentUrls.has(url))) return null;
const updated = await new IntakeInstallationDrawingReplaceService(dependencies).replaceWithinLease({
productId: input.product.id, drawingId: input.drawingId,
assetType: "drawing",
versionLabel, fileIds: files.map((file) => file.id), actor: input.actor,
}, () => undefined);
return updated.find((file) => file.id === input.file.id) ?? null;
}

View File

@ -92,13 +92,12 @@ export class InstallationDrawingPushSupport {
imageUrl: string;
makeContent: string;
}) {
const tasks = await this.dependencies.client.listTasksBySkuModel(
input.product.spu,
const tasks = await this.dependencies.client.listTasksByDrawingId(
input.drawingId,
);
const existing = await this.validateExistingTask(
tasks,
input.drawingId,
input.barcodes,
);
if (existing) {
const nextMakeContent = mergeMakeContent(
@ -140,9 +139,8 @@ export class InstallationDrawingPushSupport {
// the stable drawing ID before allowing a retry to create a duplicate.
if (error instanceof DrawingSystemClientError) {
const recovered = await this.validateExistingTask(
await this.dependencies.client.listTasksBySkuModel(input.product.spu),
await this.dependencies.client.listTasksByDrawingId(input.drawingId),
input.drawingId,
input.barcodes,
);
if (recovered) return recovered.taskId;
}
@ -153,7 +151,6 @@ export class InstallationDrawingPushSupport {
protected async validateExistingTask(
tasks: DrawingSystemTaskSummary[],
drawingId: string,
expectedBarcodes: string[],
) {
const matches = tasks.filter(
(task) => normalizeCode(task.pictureId) === drawingId,
@ -174,19 +171,11 @@ export class InstallationDrawingPushSupport {
"图纸系统已有任务单的图纸 ID 与当前资料不一致",
);
}
const actualBarcodes = Array.from(
new Set(detail.skucodes.map(normalizeCode).filter(Boolean)),
).sort();
// 部分历史任务单的详情接口没有返回条码,但完整图纸 ID 已唯一命中;
// 这种情况仍应复用任务单,把新资料追加到同一图纸 ID 下。
if (actualBarcodes.length === 0) return task;
if (actualBarcodes.join(",") !== [...expectedBarcodes].sort().join(",")) {
throw new AppError(
ErrorCode.VALIDATION_FAILED,
"图纸系统已有任务单绑定的条码与产品基础信息不一致",
);
}
return task;
// A shared drawing ID can have different brand barcodes. Keep the existing
// task's bindings when updating its required content.
return detail.skucodes.length > 0
? { ...task, skucodes: detail.skucodes.join(",") }
: task;
}
protected async readStoredFile(file: StoredUploadFile, productId: string) {

View File

@ -25,13 +25,14 @@ export class IntakeInstallationDrawingReplaceService extends InstallationDrawing
const lease = await this.pushLock.acquire(drawingId);
if (!lease) throw new AppError(ErrorCode.VALIDATION_FAILED, "此图纸 ID 正在推送,请稍后再试");
try {
return await this.replaceFiles({ ...input, drawingId }, onEvent);
return await this.replaceWithinLease({ ...input, drawingId }, onEvent);
} finally {
await lease.release();
}
}
private async replaceFiles(
/** Internal entry for ordinary pushes that already hold the drawing-ID lock. */
async replaceWithinLease(
input: InstallationDrawingReplaceInput & { actor: AuthUser },
onEvent: (event: InstallationDrawingReplaceEvent) => void,
) {

View File

@ -5,6 +5,7 @@ import type { AuthUser } from "@/server/core/types";
import { installationDrawingPushLock, type InstallationDrawingPushLock } from "@/server/repositories/installation-drawing-push-lock.repository";
import { DrawingSystemClientError } from "./drawing-system.client";
import { isInstallationDrawingImage, verifyInstallationDrawingImage } from "./installation-drawing-images";
import { replaceExistingInstallationVersion } from "./installation-drawing-existing-version.service";
import { InstallationDrawingPushSupport, isRecord, normalizeCode, toSafeErrorMessage, type StoredUploadFile, type InstallationDrawingPushDependencies } from "./intake-installation-drawing-push-support";
export class IntakeInstallationDrawingUploadService extends InstallationDrawingPushSupport {
@ -101,6 +102,13 @@ export class IntakeInstallationDrawingUploadService extends InstallationDrawingP
return { file, drawingId, barcodes, alreadySynced: true };
}
const replacedFile = await replaceExistingInstallationVersion(
this.dependencies, { product, file, drawingId, actor: input.actor },
);
if (replacedFile) {
return { file: replacedFile, drawingId, barcodes, alreadySynced: false };
}
const selectedSku = matchingSkus[0];
const skuModel =
matchingSkus.map((sku) => sku.model.trim()).find(Boolean) || product.spu;