diff --git a/furniture-3d-system/prisma/migrations/20260827161500_add_finished_product_progress/migration.sql b/furniture-3d-system/prisma/migrations/20260827161500_add_finished_product_progress/migration.sql new file mode 100644 index 00000000..cbbd7c36 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260827161500_add_finished_product_progress/migration.sql @@ -0,0 +1,49 @@ +CREATE TABLE "FinishedProductProgressItem" ( + "id" TEXT NOT NULL, + "contractNumber" TEXT NOT NULL, + "imageUrl" TEXT, + "itemNumber" TEXT NOT NULL DEFAULT '', + "barcode" TEXT NOT NULL, + "productName" TEXT NOT NULL DEFAULT '', + "supplier" TEXT NOT NULL DEFAULT '', + "brand" TEXT NOT NULL DEFAULT '', + "orderedQuantity" INTEGER NOT NULL DEFAULT 0, + "inTransitQuantity" INTEGER NOT NULL DEFAULT 0, + "orderDueDate" DATE, + "currentNode" TEXT NOT NULL DEFAULT '', + "realtimeProgress" TEXT NOT NULL DEFAULT '', + "createdById" TEXT, + "createdByName" TEXT NOT NULL DEFAULT '', + "updatedById" TEXT, + "updatedByName" TEXT NOT NULL DEFAULT '', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "FinishedProductProgressItem_pkey" PRIMARY KEY ("id") +); + +CREATE TABLE "FinishedProductProgressChangeLog" ( + "id" TEXT NOT NULL, + "itemId" TEXT NOT NULL, + "operation" TEXT NOT NULL, + "actorId" TEXT, + "actorName" TEXT NOT NULL, + "changes" JSONB NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "FinishedProductProgressChangeLog_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "FinishedProductProgressItem_contractNumber_barcode_key" ON "FinishedProductProgressItem"("contractNumber", "barcode"); +CREATE INDEX "FinishedProductProgressItem_itemNumber_idx" ON "FinishedProductProgressItem"("itemNumber"); +CREATE INDEX "FinishedProductProgressItem_supplier_idx" ON "FinishedProductProgressItem"("supplier"); +CREATE INDEX "FinishedProductProgressItem_brand_idx" ON "FinishedProductProgressItem"("brand"); +CREATE INDEX "FinishedProductProgressItem_currentNode_idx" ON "FinishedProductProgressItem"("currentNode"); +CREATE INDEX "FinishedProductProgressItem_orderDueDate_idx" ON "FinishedProductProgressItem"("orderDueDate"); +CREATE INDEX "FinishedProductProgressItem_updatedAt_idx" ON "FinishedProductProgressItem"("updatedAt"); +CREATE INDEX "FinishedProductProgressChangeLog_itemId_createdAt_idx" ON "FinishedProductProgressChangeLog"("itemId", "createdAt"); +CREATE INDEX "FinishedProductProgressChangeLog_createdAt_idx" ON "FinishedProductProgressChangeLog"("createdAt"); + +ALTER TABLE "FinishedProductProgressChangeLog" +ADD CONSTRAINT "FinishedProductProgressChangeLog_itemId_fkey" +FOREIGN KEY ("itemId") REFERENCES "FinishedProductProgressItem"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/furniture-3d-system/prisma/migrations/20260827172500_add_installation_tool_articulation_config/migration.sql b/furniture-3d-system/prisma/migrations/20260827172500_add_installation_tool_articulation_config/migration.sql new file mode 100644 index 00000000..9495049b --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20260827172500_add_installation_tool_articulation_config/migration.sql @@ -0,0 +1,2 @@ +ALTER TABLE "InstallationDemoTool" +ADD COLUMN "articulationConfig" JSONB; diff --git a/furniture-3d-system/prisma/schema.prisma b/furniture-3d-system/prisma/schema.prisma index 8e0029fb..f22eb25b 100644 --- a/furniture-3d-system/prisma/schema.prisma +++ b/furniture-3d-system/prisma/schema.prisma @@ -94,6 +94,51 @@ model SampleProgressChangeLog { @@index([itemId, createdAt]) } +model FinishedProductProgressItem { + id String @id @default(cuid()) + contractNumber String + imageUrl String? @db.Text + itemNumber String @default("") + barcode String + productName String @default("") + supplier String @default("") + brand String @default("") + orderedQuantity Int @default(0) + inTransitQuantity Int @default(0) + orderDueDate DateTime? @db.Date + currentNode String @default("") + realtimeProgress String @default("") @db.Text + createdById String? + createdByName String @default("") + updatedById String? + updatedByName String @default("") + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + changeLogs FinishedProductProgressChangeLog[] + + @@unique([contractNumber, barcode]) + @@index([itemNumber]) + @@index([supplier]) + @@index([brand]) + @@index([currentNode]) + @@index([orderDueDate]) + @@index([updatedAt]) +} + +model FinishedProductProgressChangeLog { + id String @id @default(cuid()) + itemId String + item FinishedProductProgressItem @relation(fields: [itemId], references: [id], onDelete: Cascade) + operation String + actorId String? + actorName String + changes Json + createdAt DateTime @default(now()) + + @@index([itemId, createdAt]) + @@index([createdAt]) +} + // ============================================ // 产品分类 // ============================================ @@ -3881,6 +3926,7 @@ model InstallationDemoTool { motionAxis Json? spinTurns Float @default(3) strikeDistanceRatio Float @default(0.2) + articulationConfig Json? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } @@ -3996,3 +4042,4 @@ model ScriptMonitorRun { @@index([scriptId, startedAt(sort: Desc)]) @@index([agentId, startedAt(sort: Desc)]) } + diff --git a/furniture-3d-system/src/app/api/intake/barcode-print/route.ts b/furniture-3d-system/src/app/api/intake/barcode-print/route.ts index bbf2af20..5a255228 100644 --- a/furniture-3d-system/src/app/api/intake/barcode-print/route.ts +++ b/furniture-3d-system/src/app/api/intake/barcode-print/route.ts @@ -123,3 +123,27 @@ export async function DELETE(request: NextRequest) { { requireAuth: true }, ) } + +export async function PATCH(request: NextRequest) { + return handleRequest( + request, + async (ctx) => { + const body = readObjectBody(await request.json().catch(() => null)) + + try { + const result = await barcodePrintService.updateImportRecords( + ctx.user, + body.ids, + body.fields, + ) + return jsonSuccess(result, 200, ctx.requestId) + } catch (error) { + if (error instanceof AppError) { + return jsonError(error.code, error.message, error.statusCode, ctx.requestId) + } + throw error + } + }, + { requireAuth: true }, + ) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/[id]/history/route.ts b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/[id]/history/route.ts new file mode 100644 index 00000000..6a059644 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/[id]/history/route.ts @@ -0,0 +1,12 @@ +import { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { finishedProductProgressService } from '@/server/services/finished-product-progress.service' + +type Context = { params: Promise<{ id: string }> } + +export async function GET(request: NextRequest, context: Context) { + return handleRequest(request, async (ctx) => { + const { id } = await context.params + return jsonSuccess(await finishedProductProgressService.listChangeLogs(id, ctx.user), 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/[id]/route.ts b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/[id]/route.ts new file mode 100644 index 00000000..93262a70 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/[id]/route.ts @@ -0,0 +1,13 @@ +import { NextRequest } from 'next/server' +import { handleRequest, jsonSuccess } from '@/server/core/response' +import { finishedProductProgressService } from '@/server/services/finished-product-progress.service' + +type Context = { params: Promise<{ id: string }> } + +export async function PATCH(request: NextRequest, context: Context) { + return handleRequest(request, async (ctx) => { + const { id } = await context.params + const body = await request.json().catch(() => null) + return jsonSuccess(await finishedProductProgressService.update(id, body, ctx.user), 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/import/route.ts b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/import/route.ts new file mode 100644 index 00000000..75b02491 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/import/route.ts @@ -0,0 +1,70 @@ +import { NextRequest, NextResponse } from 'next/server' +import * as XLSX from 'xlsx' +import { + FINISHED_PRODUCT_PROGRESS_IMPORT_HEADERS, + type FinishedProductProgressImportProgress, + type FinishedProductProgressImportStreamEvent, +} from '@/lib/finished-product-progress' +import { ErrorCode, isAppError } from '@/server/core/errors' +import { handleRequest, jsonError } from '@/server/core/response' +import { finishedProductProgressService } from '@/server/services/finished-product-progress.service' + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const form = await request.formData() + const file = form.get('file') + if (!(file instanceof File)) return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请选择 Excel 文件', 400, ctx.requestId) + if (file.size > 10 * 1024 * 1024) return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, 'Excel 文件不能超过10MB', 400, ctx.requestId) + + const workbook = XLSX.read(Buffer.from(await file.arrayBuffer()), { type: 'buffer', cellDates: true }) + const sheet = workbook.Sheets[workbook.SheetNames[0]] + if (!sheet) return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, 'Excel 文件没有工作表', 400, ctx.requestId) + const rawRows = XLSX.utils.sheet_to_json>(sheet, { defval: '' }) + const rows = rawRows.map((raw) => Object.fromEntries(Object.entries(raw).flatMap(([header, value]) => { + const key = FINISHED_PRODUCT_PROGRESS_IMPORT_HEADERS[header.trim()] + return key ? [[key, value]] : [] + }))) + if (rows.length === 0) return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '导入文件没有可用数据', 400, ctx.requestId) + if (rows.length > 5_000) return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, '单次最多导入5000行', 400, ctx.requestId) + + const encoder = new TextEncoder() + const stream = new ReadableStream({ + start(controller) { + let closed = false + let progress: FinishedProductProgressImportProgress = { processed: 0, total: rows.length, created: 0, updated: 0 } + const send = (event: FinishedProductProgressImportStreamEvent) => { + if (closed) return + try { controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`)) } catch { closed = true } + } + const close = () => { + if (closed) return + closed = true + controller.close() + } + + send({ type: 'progress', progress }) + void finishedProductProgressService.importRows(rows, ctx.user, (next) => { + progress = next + send({ type: 'progress', progress }) + }).then((result) => { + progress = { processed: rows.length, total: rows.length, ...result } + send({ type: 'complete', progress }) + close() + }).catch((error: unknown) => { + console.error(`[${ctx.requestId}] Finished product progress import failed:`, error) + send({ type: 'error', progress, message: isAppError(error) ? error.message : '导入过程中发生错误' }) + close() + }) + }, + }) + + return new NextResponse(stream, { + status: 200, + headers: { + 'Content-Type': 'application/x-ndjson; charset=utf-8', + 'Cache-Control': 'no-cache, no-transform', + 'X-Accel-Buffering': 'no', + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/route.ts b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/route.ts new file mode 100644 index 00000000..d56b593e --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/route.ts @@ -0,0 +1,36 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { EMPTY_FINISHED_PRODUCT_PROGRESS_FILTERS } from '@/lib/finished-product-progress' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { finishedProductProgressService } from '@/server/services/finished-product-progress.service' + +const listSchema = z.object({ + page: z.coerce.number().int().min(1).default(1), + pageSize: z.coerce.number().int().min(1).max(200).default(50), + search: z.string().trim().max(200).default(''), + supplier: z.string().trim().max(200).default(''), + brand: z.string().trim().max(200).default(''), + currentNode: z.string().trim().max(200).default(''), + dueDateFrom: z.string().trim().max(20).default(''), + dueDateTo: z.string().trim().max(20).default(''), +}) + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const parsed = listSchema.safeParse({ + ...EMPTY_FINISHED_PRODUCT_PROGRESS_FILTERS, + ...Object.fromEntries(request.nextUrl.searchParams.entries()), + }) + if (!parsed.success) return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '成品进度筛选条件不正确', 400, ctx.requestId) + const { page, pageSize, ...filters } = parsed.data + return jsonSuccess(await finishedProductProgressService.listPage({ page, pageSize, filters, user: ctx.user }), 200, ctx.requestId) + }, { requireAuth: true }) +} + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const body = await request.json().catch(() => null) + return jsonSuccess(await finishedProductProgressService.create(body, ctx.user), 201, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/template/route.ts b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/template/route.ts new file mode 100644 index 00000000..785c7af3 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/finished-product-progress/template/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from 'next/server' +import * as XLSX from 'xlsx' +import { FINISHED_PRODUCT_PROGRESS_FIELDS } from '@/lib/finished-product-progress' +import { handleRequest } from '@/server/core/response' +import { finishedProductProgressService } from '@/server/services/finished-product-progress.service' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + await finishedProductProgressService.requireTemplateAccess(ctx.user) + const headers = FINISHED_PRODUCT_PROGRESS_FIELDS.map((field) => field.label) + const sheet = XLSX.utils.aoa_to_sheet([headers]) + sheet['!cols'] = headers.map((header) => ({ wch: Math.max(14, header.length * 2 + 4) })) + const workbook = XLSX.utils.book_new() + XLSX.utils.book_append_sheet(workbook, sheet, '成品进度导入') + const content = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }) as Buffer + return new NextResponse(new Uint8Array(content), { + status: 200, + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': "attachment; filename*=UTF-8''%E6%88%90%E5%93%81%E8%BF%9B%E5%BA%A6%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx", + 'Cache-Control': 'no-store', + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/supplier-information/[barcode]/history/route.ts b/furniture-3d-system/src/app/api/supply-chain/supplier-information/[barcode]/history/route.ts new file mode 100644 index 00000000..edcccd1b --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/supplier-information/[barcode]/history/route.ts @@ -0,0 +1,23 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { supplyChainSupplierInformationService } from '@/server/services/supply-chain-supplier-information.service' + +const barcodeSchema = z.string().trim().min(1).max(160) + +export async function GET( + request: NextRequest, + context: { params: Promise<{ barcode: string }> }, +) { + return handleRequest(request, async (ctx) => { + await supplyChainSupplierInformationService.requireViewAccess(ctx.user) + const params = await context.params + const parsed = barcodeSchema.safeParse(decodeURIComponent(params.barcode)) + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '条码格式不正确', 400, ctx.requestId) + } + const history = await supplyChainSupplierInformationService.listHistory(parsed.data) + return jsonSuccess(history, 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/supplier-information/history/route.ts b/furniture-3d-system/src/app/api/supply-chain/supplier-information/history/route.ts new file mode 100644 index 00000000..acc9337d --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/supplier-information/history/route.ts @@ -0,0 +1,19 @@ +import { NextRequest } from 'next/server' +import { z } from 'zod' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { supplyChainSupplierInformationService } from '@/server/services/supply-chain-supplier-information.service' + +const barcodeSchema = z.string().trim().min(1).max(160) + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + await supplyChainSupplierInformationService.requireViewAccess(ctx.user) + const parsed = barcodeSchema.safeParse(request.nextUrl.searchParams.get('barcode') ?? '') + if (!parsed.success) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '条码格式不正确', 400, ctx.requestId) + } + const history = await supplyChainSupplierInformationService.listHistory(parsed.data) + return jsonSuccess(history, 200, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/supplier-information/import/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/supplier-information/import/route.test.ts new file mode 100644 index 00000000..9285f757 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/supplier-information/import/route.test.ts @@ -0,0 +1,106 @@ +import { ReadableStream as NodeReadableStream } from 'node:stream/web' + +export {} + +const mockHandleRequest = jest.fn() +const mockJsonError = jest.fn() +const mockRequireEditAccess = jest.fn() +const mockImportRows = jest.fn() +const mockSheetToJson = jest.fn() + +jest.mock('@/server/core/response', () => ({ + handleRequest: (...args: unknown[]) => mockHandleRequest(...args), + jsonError: (...args: unknown[]) => mockJsonError(...args), +})) + +jest.mock('@/server/services/supply-chain-supplier-information.service', () => ({ + supplyChainSupplierInformationService: { + requireEditAccess: (...args: unknown[]) => mockRequireEditAccess(...args), + importRows: (...args: unknown[]) => mockImportRows(...args), + }, +})) + +jest.mock('xlsx', () => ({ + read: () => ({ SheetNames: ['供应商信息导入'], Sheets: { 供应商信息导入: {} } }), + utils: { sheet_to_json: (...args: unknown[]) => mockSheetToJson(...args) }, +})) + +class MockFile { + size = 32 + async arrayBuffer() { return new ArrayBuffer(32) } +} + +const { POST } = require('./route') + +describe('POST /api/supply-chain/supplier-information/import', () => { + const originalFile = global.File + const originalReadableStream = global.ReadableStream + + beforeAll(() => { + Object.defineProperty(global, 'File', { configurable: true, value: MockFile }) + Object.defineProperty(global, 'ReadableStream', { configurable: true, value: NodeReadableStream }) + }) + + afterAll(() => { + Object.defineProperty(global, 'File', { configurable: true, value: originalFile }) + Object.defineProperty(global, 'ReadableStream', { configurable: true, value: originalReadableStream }) + }) + + beforeEach(() => { + jest.clearAllMocks() + mockHandleRequest.mockImplementation(async (_request: unknown, handler: (ctx: unknown) => unknown) => handler({ + requestId: 'req-supplier-import', + user: { id: 'buyer-1', name: '采购员', role: 'USER' }, + })) + mockSheetToJson.mockReturnValue([ + ['条码', '采购', '供应商', '稳定生产周期'], + ['BC-001', '采购A', '供应商A', '30天'], + ['UNKNOWN', '', '供应商B', ''], + ]) + mockImportRows.mockImplementation(async (_rows, _user, onProgress) => { + const first = { processed: 1, total: 2, updated: 1, failed: 0, errors: [] } + const complete = { + processed: 2, + total: 2, + updated: 1, + failed: 1, + errors: [{ rowNumber: 3, barcode: 'UNKNOWN', message: '条码不存在于产品档案' }], + } + onProgress(first) + onProgress(complete) + return complete + }) + }) + + it('maps template columns and streams success, failure and row errors', async () => { + const response = await POST({ + formData: async () => ({ get: () => new MockFile() }), + }) + const reader = response.body.getReader() + const decoder = new TextDecoder() + let body = '' + while (true) { + const { done, value } = await reader.read() + if (done) break + body += decoder.decode(value, { stream: true }) + } + body += decoder.decode() + const events = body.trim().split('\n').map((line: string) => JSON.parse(line)) + + expect(mockRequireEditAccess).toHaveBeenCalledWith(expect.objectContaining({ id: 'buyer-1' })) + expect(mockImportRows).toHaveBeenCalledWith([ + { + rowNumber: 2, + barcode: 'BC-001', + updates: { purchaseOwner: '采购A', supplierName: '供应商A', stableLeadTime: '30天' }, + }, + { rowNumber: 3, barcode: 'UNKNOWN', updates: { supplierName: '供应商B' } }, + ], expect.objectContaining({ id: 'buyer-1' }), expect.any(Function)) + expect(events.at(-1)).toEqual({ + type: 'complete', + progress: expect.objectContaining({ updated: 1, failed: 1 }), + }) + expect(events.at(-1).progress.errors[0]).toEqual(expect.objectContaining({ rowNumber: 3 })) + expect(response.headers.get('Content-Type')).toContain('application/x-ndjson') + }) +}) diff --git a/furniture-3d-system/src/app/api/supply-chain/supplier-information/import/route.ts b/furniture-3d-system/src/app/api/supply-chain/supplier-information/import/route.ts new file mode 100644 index 00000000..0deed07b --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/supplier-information/import/route.ts @@ -0,0 +1,135 @@ +import { NextRequest, NextResponse } from 'next/server' +import * as XLSX from 'xlsx' +import { + SUPPLY_CHAIN_SUPPLIER_INFORMATION_IMPORT_FIELDS, + type SupplyChainSupplierInformationEditableField, + type SupplyChainSupplierInformationImportProgress, + type SupplyChainSupplierInformationImportRow, + type SupplyChainSupplierInformationImportStreamEvent, +} from '@/lib/supply-chain-supplier-information' +import { ErrorCode, isAppError } from '@/server/core/errors' +import { handleRequest, jsonError } from '@/server/core/response' +import { supplyChainSupplierInformationService } from '@/server/services/supply-chain-supplier-information.service' + +const MAX_FILE_SIZE = 10 * 1024 * 1024 +const MAX_ROWS = 5_000 + +function cellText(value: unknown) { + return String(value ?? '').trim() +} + +function parseRows(sheet: XLSX.WorkSheet) { + const matrix = XLSX.utils.sheet_to_json(sheet, { + header: 1, + defval: '', + raw: false, + }) + const headerRow = matrix[0]?.map(cellText) ?? [] + const headerIndex = new Map(headerRow.map((header, index) => [header, index])) + const barcodeIndex = headerIndex.get('条码') ?? headerIndex.get('barcode') + if (barcodeIndex === undefined) return { error: '导入文件缺少“条码”列', rows: [] } + + const rows = matrix.slice(1).flatMap((values, index) => { + if (!values.some((value) => cellText(value))) return [] + const updates = Object.fromEntries( + SUPPLY_CHAIN_SUPPLIER_INFORMATION_IMPORT_FIELDS.flatMap((field) => { + if (field.key === 'barcode') return [] + const columnIndex = headerIndex.get(field.label) ?? headerIndex.get(field.key) + if (columnIndex === undefined) return [] + const value = cellText(values[columnIndex]) + return value ? [[field.key, value]] : [] + }), + ) as Partial> + return [{ + rowNumber: index + 2, + barcode: cellText(values[barcodeIndex]), + updates, + } satisfies SupplyChainSupplierInformationImportRow] + }) + return { rows } +} + +export async function POST(request: NextRequest) { + return handleRequest(request, async (ctx) => { + await supplyChainSupplierInformationService.requireEditAccess(ctx.user) + const form = await request.formData() + const file = form.get('file') + if (!(file instanceof File)) { + return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请选择 Excel 文件', 400, ctx.requestId) + } + if (file.size > MAX_FILE_SIZE) { + return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, 'Excel 文件不能超过10MB', 400, ctx.requestId) + } + + const workbook = XLSX.read(Buffer.from(await file.arrayBuffer()), { type: 'buffer' }) + const sheet = workbook.Sheets[workbook.SheetNames[0]] + if (!sheet) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, 'Excel 文件没有工作表', 400, ctx.requestId) + } + const parsed = parseRows(sheet) + if (parsed.error) { + return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, parsed.error, 400, ctx.requestId) + } + if (parsed.rows.length === 0) { + return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '导入文件没有可用数据', 400, ctx.requestId) + } + if (parsed.rows.length > MAX_ROWS) { + return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, '单次最多导入5000行', 400, ctx.requestId) + } + + const encoder = new TextEncoder() + const initial: SupplyChainSupplierInformationImportProgress = { + processed: 0, + total: parsed.rows.length, + updated: 0, + failed: 0, + errors: [], + } + const stream = new ReadableStream({ + start(controller) { + let closed = false + let progress = initial + const send = (event: SupplyChainSupplierInformationImportStreamEvent) => { + if (closed) return + try { + controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`)) + } catch { + closed = true + } + } + const close = () => { + if (closed) return + closed = true + controller.close() + } + + send({ type: 'progress', progress }) + void supplyChainSupplierInformationService.importRows(parsed.rows, ctx.user, (next) => { + progress = next + send({ type: 'progress', progress }) + }).then((result) => { + progress = result + send({ type: 'complete', progress }) + close() + }).catch((error: unknown) => { + console.error(`[${ctx.requestId}] Supplier information import failed:`, error) + send({ + type: 'error', + progress, + message: isAppError(error) ? error.message : '导入过程中发生错误', + }) + close() + }) + }, + }) + + return new NextResponse(stream, { + status: 200, + headers: { + 'Content-Type': 'application/x-ndjson; charset=utf-8', + 'Cache-Control': 'no-cache, no-transform', + 'X-Accel-Buffering': 'no', + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.test.ts index c830ed4b..0487eabb 100644 --- a/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.test.ts +++ b/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.test.ts @@ -3,7 +3,8 @@ export {} const mockHandleRequest = jest.fn() const mockJsonSuccess = jest.fn() const mockJsonError = jest.fn() -const mockUpdateSupplier = jest.fn() +const mockRequireEditAccess = jest.fn() +const mockUpdateBarcode = jest.fn() jest.mock('@/server/core/response', () => ({ handleRequest: (...args: unknown[]) => mockHandleRequest(...args), @@ -13,7 +14,8 @@ jest.mock('@/server/core/response', () => ({ jest.mock('@/server/services/supply-chain-supplier-information.service', () => ({ supplyChainSupplierInformationService: { - updateSupplier: (...args: unknown[]) => mockUpdateSupplier(...args), + requireEditAccess: (...args: unknown[]) => mockRequireEditAccess(...args), + updateBarcode: (...args: unknown[]) => mockUpdateBarcode(...args), }, })) @@ -30,10 +32,10 @@ describe('PUT /api/supply-chain/supplier-information', () => { }) it('passes validated supplier updates and the authenticated actor to the service', async () => { - mockUpdateSupplier.mockResolvedValue({ affectedBarcodes: 2, changedValues: 2 }) + mockUpdateBarcode.mockResolvedValue({ barcode: 'BC-001', changedValues: 2 }) const request = { json: jest.fn().mockResolvedValue({ - supplierKey: '浩远', + barcode: 'BC-001', updates: { purchaseOwner: '采购B', stableLeadTime: '30天', @@ -45,8 +47,9 @@ describe('PUT /api/supply-chain/supplier-information', () => { const response = await PUT(request) expect(mockHandleRequest.mock.calls[0][2]).toEqual({ requireAuth: true }) - expect(mockUpdateSupplier).toHaveBeenCalledWith({ - supplierKey: '浩远', + expect(mockRequireEditAccess).toHaveBeenCalledWith(expect.objectContaining({ id: 'buyer-1' })) + expect(mockUpdateBarcode).toHaveBeenCalledWith({ + barcode: 'BC-001', updates: { purchaseOwner: '采购B', stableLeadTime: '30天', @@ -59,12 +62,12 @@ describe('PUT /api/supply-chain/supplier-information', () => { it('rejects an edit that has no concrete field value', async () => { const request = { - json: jest.fn().mockResolvedValue({ supplierKey: '浩远', updates: {} }), + json: jest.fn().mockResolvedValue({ barcode: 'BC-001', updates: {} }), } const response = await PUT(request) - expect(mockUpdateSupplier).not.toHaveBeenCalled() + expect(mockUpdateBarcode).not.toHaveBeenCalled() expect(response).toEqual(expect.objectContaining({ message: '供应商信息修改内容不正确', status: 400, diff --git a/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.ts b/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.ts index 1eeffbed..e7181358 100644 --- a/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/supplier-information/route.ts @@ -5,16 +5,16 @@ import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { supplyChainSupplierInformationService } from '@/server/services/supply-chain-supplier-information.service' const updateSchema = z.object({ - supplierKey: z.string().trim().min(1).max(180), + barcode: z.string().trim().min(1).max(160), updates: z.object({ - purchaseOwner: z.string().trim().min(1).max(160).optional(), - supplierName: z.string().trim().min(1).max(180).optional(), - minimumOrderQuantity: z.string().trim().min(1).max(120).optional(), - firstLeadTime: z.string().trim().min(1).max(120).optional(), - stableLeadTime: z.string().trim().min(1).max(120).optional(), - palletSpec: z.string().trim().min(1).max(240).optional(), - backupSupplier: z.string().trim().min(1).max(180).optional(), - supplierType: z.string().trim().min(1).max(160).optional(), + purchaseOwner: z.string().trim().max(160).optional(), + supplierName: z.string().trim().max(180).optional(), + minimumOrderQuantity: z.string().trim().max(120).optional(), + firstLeadTime: z.string().trim().max(120).optional(), + stableLeadTime: z.string().trim().max(120).optional(), + palletSpec: z.string().trim().max(240).optional(), + backupSupplier: z.string().trim().max(180).optional(), + supplierType: z.string().trim().max(160).optional(), }).strict(), }).strict().refine((input) => Object.keys(input.updates).length > 0, { message: '请至少填写一项要修改的内容', @@ -34,7 +34,8 @@ export async function PUT(request: NextRequest) { ) } - const result = await supplyChainSupplierInformationService.updateSupplier({ + await supplyChainSupplierInformationService.requireEditAccess(ctx.user) + const result = await supplyChainSupplierInformationService.updateBarcode({ ...parsed.data, user: ctx.user, }) diff --git a/furniture-3d-system/src/app/api/supply-chain/supplier-information/template/route.ts b/furniture-3d-system/src/app/api/supply-chain/supplier-information/template/route.ts new file mode 100644 index 00000000..2d803337 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/supplier-information/template/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from 'next/server' +import * as XLSX from 'xlsx' +import { SUPPLY_CHAIN_SUPPLIER_INFORMATION_IMPORT_FIELDS } from '@/lib/supply-chain-supplier-information' +import { handleRequest } from '@/server/core/response' +import { supplyChainSupplierInformationService } from '@/server/services/supply-chain-supplier-information.service' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + await supplyChainSupplierInformationService.requireViewAccess(ctx.user) + const headers = SUPPLY_CHAIN_SUPPLIER_INFORMATION_IMPORT_FIELDS.map((field) => field.label) + const sheet = XLSX.utils.aoa_to_sheet([headers]) + sheet['!cols'] = headers.map((header) => ({ wch: Math.max(14, header.length * 2 + 4) })) + const workbook = XLSX.utils.book_new() + XLSX.utils.book_append_sheet(workbook, sheet, '供应商信息导入') + const content = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }) as Buffer + return new NextResponse(new Uint8Array(content), { + status: 200, + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent('供应商信息导入模板.xlsx')}`, + 'Cache-Control': 'no-store', + }, + }) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/installation-demo-workbench/lib/installationToolboxApi.ts b/furniture-3d-system/src/app/installation-demo-workbench/lib/installationToolboxApi.ts index 25ec02d9..980b37fc 100644 --- a/furniture-3d-system/src/app/installation-demo-workbench/lib/installationToolboxApi.ts +++ b/furniture-3d-system/src/app/installation-demo-workbench/lib/installationToolboxApi.ts @@ -4,6 +4,7 @@ import type { InstallationToolItem } from '../types' import type { InstallationToolMotionType, InstallationToolMotionVector3, + InstallationHingeMotionConfig, } from '@/lib/installation-demo-tool-motion' interface ToolMutationInput { @@ -18,6 +19,7 @@ interface ToolMutationInput { motionAxis?: InstallationToolMotionVector3 | null spinTurns?: number strikeDistanceRatio?: number + articulationConfig?: InstallationHingeMotionConfig | null } async function readResponse(response: Response): Promise { diff --git a/furniture-3d-system/src/app/installation-demo-workbench/tools/InstallationToolboxClient.tsx b/furniture-3d-system/src/app/installation-demo-workbench/tools/InstallationToolboxClient.tsx index 115f1c58..2069f891 100644 --- a/furniture-3d-system/src/app/installation-demo-workbench/tools/InstallationToolboxClient.tsx +++ b/furniture-3d-system/src/app/installation-demo-workbench/tools/InstallationToolboxClient.tsx @@ -4,7 +4,9 @@ import Link from 'next/link' import { ArrowLeft, Plus, Wrench } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' import { + createDefaultInstallationHingeMotionConfig, normalizeInstallationToolMotionConfig, + type InstallationHingeJointKey, type InstallationToolMotionConfig, } from '@/lib/installation-demo-tool-motion' import { useInstallationToolbox } from '../hooks/useInstallationToolbox' @@ -28,6 +30,7 @@ function buildToolMotionConfig(tool: ReturnType[' motionAxis: tool.motionAxis, spinTurns: tool.spinTurns, strikeDistanceRatio: tool.strikeDistanceRatio, + articulationConfig: tool.articulationConfig, }) } @@ -41,6 +44,9 @@ export default function InstallationToolboxClient({ canEdit }: InstallationToolb const [submitting, setSubmitting] = useState(false) const [saving, setSaving] = useState(false) const [previewing, setPreviewing] = useState(false) + const [modelNodeNames, setModelNodeNames] = useState([]) + const [activeHingeJoint, setActiveHingeJoint] = useState('primary') + const [hingeProgress, setHingeProgress] = useState(0) const [gizmoMode, setGizmoMode] = useState<'translate' | 'rotate'>('translate') const [message, setMessage] = useState(null) const [motionConfig, setMotionConfig] = useState(() => @@ -62,8 +68,36 @@ export default function InstallationToolboxClient({ canEdit }: InstallationToolb if (!selectedTool) return setMotionConfig(buildToolMotionConfig(selectedTool)) setPreviewing(false) + setModelNodeNames([]) + setActiveHingeJoint('primary') + setHingeProgress(0) setMessage(null) - }, [selectedTool?.id]) + }, [selectedTool]) + + useEffect(() => { + if ( + motionConfig.motionType !== 'hinge' || + motionConfig.articulationConfig || + modelNodeNames.length < 3 + ) return + setMotionConfig((current) => ({ + ...current, + articulationConfig: createDefaultInstallationHingeMotionConfig(modelNodeNames), + })) + }, [modelNodeNames, motionConfig.articulationConfig, motionConfig.motionType]) + + useEffect(() => { + if (!previewing || motionConfig.motionType !== 'hinge') return + const startedAt = performance.now() + let animationFrame = 0 + const animate = () => { + const phase = ((performance.now() - startedAt) % 2400) / 2400 + setHingeProgress(0.5 - 0.5 * Math.cos(Math.PI * 2 * phase)) + animationFrame = window.requestAnimationFrame(animate) + } + animate() + return () => window.cancelAnimationFrame(animationFrame) + }, [motionConfig.motionType, previewing]) const submit = async () => { if (!canEdit || !file || !toolCode.trim() || !name.trim()) return @@ -193,8 +227,11 @@ export default function InstallationToolboxClient({ canEdit }: InstallationToolb canEdit={canEdit} previewing={previewing} gizmoMode={gizmoMode} + activeHingeJoint={activeHingeJoint} + hingeProgress={hingeProgress} onGizmoModeChange={setGizmoMode} onConfigChange={setMotionConfig} + onNodeNamesChange={setModelNodeNames} /> @@ -221,14 +258,24 @@ export default function InstallationToolboxClient({ canEdit }: InstallationToolb saving={saving} previewing={previewing} message={effectiveMessage} + nodeNames={modelNodeNames} + activeHingeJoint={activeHingeJoint} + hingeProgress={hingeProgress} onConfigChange={(nextConfig) => { setPreviewing(false) setMotionConfig(nextConfig) setMessage(null) }} onSave={() => void saveMotion()} - onTogglePreview={() => setPreviewing((current) => !current)} + onTogglePreview={() => { + setPreviewing((current) => { + if (current) setHingeProgress(0) + return !current + }) + }} onDelete={() => void remove()} + onActiveHingeJointChange={setActiveHingeJoint} + onHingeProgressChange={setHingeProgress} /> ) : (