From 16cfc166142352e000e1e735ad921e7e289991dd Mon Sep 17 00:00:00 2001 From: apple Date: Tue, 24 Nov 2026 11:36:49 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(production-stop-demands):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E8=AF=A6=E6=83=85=E6=9F=A5=E8=AF=A2=E4=B8=8E=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E4=BA=8B=E5=8A=A1=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/lib/product-stop-demand-state.ts | 4 +- ...oduct-stop-demand-state.repository.test.ts | 7 +++ ...-demands-rejection-time.repository.test.ts | 8 +++ ...mands-workflow-defaults.repository.test.ts | 54 ++++++++++++++++ .../production-stop-demands.repository.ts | 61 +++++++++++-------- 5 files changed, 109 insertions(+), 25 deletions(-) create mode 100644 furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-workflow-defaults.repository.test.ts diff --git a/furniture-3d-system/src/lib/product-stop-demand-state.ts b/furniture-3d-system/src/lib/product-stop-demand-state.ts index 54ec6ad4..3511200b 100644 --- a/furniture-3d-system/src/lib/product-stop-demand-state.ts +++ b/furniture-3d-system/src/lib/product-stop-demand-state.ts @@ -67,7 +67,9 @@ export function productStopRejectionLookupKey( const before = input.before instanceof Date && !Number.isNaN(input.before.getTime()) ? input.before.toISOString() : '' - return `${barcode}\u0000${before}` + // 该键会作为 jsonb 字段传给 PostgreSQL。jsonb 不接受 \u0000, + // 因此使用可逆且 JSON 安全的二元组序列化,避免详情查询直接报 22P05。 + return JSON.stringify([barcode, before]) } export const PRODUCT_STOP_REJECTED_DEMAND_STATUS_LABEL = diff --git a/furniture-3d-system/src/server/repositories/__tests__/product-stop-demand-state.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/product-stop-demand-state.repository.test.ts index d35e78f3..2ce1c8cd 100644 --- a/furniture-3d-system/src/server/repositories/__tests__/product-stop-demand-state.repository.test.ts +++ b/furniture-3d-system/src/server/repositories/__tests__/product-stop-demand-state.repository.test.ts @@ -19,6 +19,13 @@ const before = new Date('2026-11-21T01:00:00.000Z') beforeEach(() => jest.resetAllMocks()) +it('驳回查询键不含 PostgreSQL jsonb 不支持的 NUL 字符', () => { + const key = productStopRejectionLookupKey({ barcode: 'a1', before }) + + expect(key).not.toContain('\u0000') + expect(JSON.parse(key)).toEqual(['A1', before.toISOString()]) +}) + it('允许人工期初覆盖最近驳回分类和原因,同时保留历史需求单号', async () => { jest.mocked(prisma.productStopDemandStateOverride.findMany).mockResolvedValue([{ barcode: 'A1', diff --git a/furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-rejection-time.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-rejection-time.repository.test.ts index 09c34041..355dee25 100644 --- a/furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-rejection-time.repository.test.ts +++ b/furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-rejection-time.repository.test.ts @@ -55,6 +55,7 @@ describe('停产需求驳回时间', () => { rejectionAt: rejectedAt, }), }) + expect(prismaMock.$transaction).not.toHaveBeenCalled() }) it('进入已确认待走流程时清空需求和历史不同意票的驳回字段', async () => { @@ -78,6 +79,13 @@ describe('停产需求驳回时间', () => { reason: '', }, }) + expect(prismaMock.$transaction).toHaveBeenCalledWith( + expect.any(Function), + expect.objectContaining({ + maxWait: 10_000, + timeout: 30_000, + }), + ) }) it('读取已确认待走流程记录时隐藏历史驳回内容', () => { diff --git a/furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-workflow-defaults.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-workflow-defaults.repository.test.ts new file mode 100644 index 00000000..0d9cf55c --- /dev/null +++ b/furniture-3d-system/src/server/repositories/__tests__/production-stop-demands-workflow-defaults.repository.test.ts @@ -0,0 +1,54 @@ +/** @jest-environment node */ + +jest.mock('@/lib/prisma', () => ({ + prisma: { + productionStopConfirmationWorkflowNode: { + findMany: jest.fn(), + createMany: jest.fn(), + }, + }, +})) + +import { PRODUCTION_STOP_CONFIRMATION_WORKFLOW_DEFAULTS } from '@/lib/production-stop-confirmation-workflow' +import { prisma } from '@/lib/prisma' +import { productionStopDemandRepository } from '../production-stop-demands.repository' + +const prismaMock = prisma as unknown as { + productionStopConfirmationWorkflowNode: { + findMany: jest.Mock + createMany: jest.Mock + } +} + +describe('停产需求确认流程默认节点', () => { + beforeEach(() => { + jest.clearAllMocks() + prismaMock.productionStopConfirmationWorkflowNode.createMany.mockResolvedValue({ count: 0 }) + }) + + it('节点已存在时只读取,不重复写入', async () => { + prismaMock.productionStopConfirmationWorkflowNode.findMany.mockResolvedValue( + PRODUCTION_STOP_CONFIRMATION_WORKFLOW_DEFAULTS.map((node) => ({ + sortOrder: node.sortOrder, + })), + ) + + await productionStopDemandRepository.ensureConfirmationWorkflowDefaults() + + expect(prismaMock.productionStopConfirmationWorkflowNode.findMany).toHaveBeenCalledTimes(1) + expect(prismaMock.productionStopConfirmationWorkflowNode.createMany).not.toHaveBeenCalled() + }) + + it('缺少节点时用单条 createMany 幂等补齐', async () => { + prismaMock.productionStopConfirmationWorkflowNode.findMany.mockResolvedValue([ + { sortOrder: 1 }, + ]) + + await productionStopDemandRepository.ensureConfirmationWorkflowDefaults() + + expect(prismaMock.productionStopConfirmationWorkflowNode.createMany).toHaveBeenCalledWith({ + data: PRODUCTION_STOP_CONFIRMATION_WORKFLOW_DEFAULTS.slice(1).map((node) => ({ ...node })), + skipDuplicates: true, + }) + }) +}) diff --git a/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts b/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts index bb0d706f..c50c3087 100644 --- a/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts +++ b/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts @@ -2875,22 +2875,29 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit }) { const changedAt = patch.at ?? new Date() const clearHistoricalRejection = patch.status === 'CONFIRMED_WAIT_FLOW' - await prisma.$transaction(async (tx) => { - await tx.productionStopDemand.update({ + const data = { + demandStatus: patch.status, + demandStatusAt: changedAt, + ...(patch.status === 'REJECTED' + ? { rejectionAt: changedAt } + : clearHistoricalRejection + ? { rejectionAt: null } + : {}), + ...(clearHistoricalRejection ? { confirmationReasons: '' } : {}), + ...(patch.note !== undefined ? { demandStatusNote: patch.note } : {}), + } + if (!clearHistoricalRejection) { + // 普通状态变化只有一张表需要写入,不额外占用交互式事务连接。 + await prisma.productionStopDemand.update({ where: { id: demandId }, - data: { - demandStatus: patch.status, - demandStatusAt: changedAt, - ...(patch.status === 'REJECTED' - ? { rejectionAt: changedAt } - : clearHistoricalRejection - ? { rejectionAt: null } - : {}), - ...(clearHistoricalRejection ? { confirmationReasons: '' } : {}), - ...(patch.note !== undefined ? { demandStatusNote: patch.note } : {}), - }, + data, }) - if (clearHistoricalRejection) { + } else { + await prisma.$transaction(async (tx) => { + await tx.productionStopDemand.update({ + where: { id: demandId }, + data, + }) await tx.productionStopDemandConfirmationVote.updateMany({ where: { demandId, @@ -2901,8 +2908,11 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit reason: '', }, }) - } - }) + }, { + maxWait: 10_000, + timeout: 30_000, + }) + } await this.syncDemandStateToProductStopSnapshot(demandId) } @@ -2991,15 +3001,18 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit } async ensureConfirmationWorkflowDefaults() { - await prisma.$transaction( - PRODUCTION_STOP_CONFIRMATION_WORKFLOW_DEFAULTS.map((node) => ( - prisma.productionStopConfirmationWorkflowNode.upsert({ - where: { sortOrder: node.sortOrder }, - create: node, - update: {}, - }) - )), + const existing = await prisma.productionStopConfirmationWorkflowNode.findMany({ + select: { sortOrder: true }, + }) + const existingSortOrders = new Set(existing.map((node) => node.sortOrder)) + const missing = PRODUCTION_STOP_CONFIRMATION_WORKFLOW_DEFAULTS.filter( + (node) => !existingSortOrders.has(node.sortOrder), ) + if (!missing.length) return + await prisma.productionStopConfirmationWorkflowNode.createMany({ + data: missing.map((node) => ({ ...node })), + skipDuplicates: true, + }) } async listConfirmationWorkflowNodes() { From 8d3b94f46e413c082e6e0ec2cb16256170262014 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Tue, 24 Nov 2026 10:36:22 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix(clearance):=20=E6=8C=89=E6=89=B9?= =?UTF-8?q?=E6=AC=A1=E5=92=8C=E4=BC=98=E5=85=88=E7=BA=A7=E9=9A=90=E8=97=8F?= =?UTF-8?q?=E8=BF=90=E8=90=A5=E6=95=8F=E6=84=9F=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../supply-chain/clearance/options/route.ts | 6 + .../tasks/applications/route.test.ts | 83 ++++ .../clearance/tasks/applications/route.ts | 16 +- .../ClearanceReviewWorkbench.test.tsx | 29 ++ .../clearance/ClearanceReviewWorkbench.tsx | 387 +++++++++++------- .../management/clearance/ClearanceView.tsx | 193 ++++----- .../management/clearance/clearance.module.css | 158 ++++++- .../src/lib/supply-chain-permission-paths.ts | 5 +- .../supply-chain-permission-settings.test.ts | 6 + .../supply-chain-clearance.repository.ts | 93 ++++- ...hain-clearance-task-import.service.test.ts | 113 ++++- .../supply-chain-clearance.service.test.ts | 71 ++++ ...ply-chain-clearance-task-import.service.ts | 191 +++++---- .../supply-chain-clearance.service.ts | 89 +++- 14 files changed, 1097 insertions(+), 343 deletions(-) create mode 100644 furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.test.ts diff --git a/furniture-3d-system/src/app/api/supply-chain/clearance/options/route.ts b/furniture-3d-system/src/app/api/supply-chain/clearance/options/route.ts index 6d53bf92..a1090872 100644 --- a/furniture-3d-system/src/app/api/supply-chain/clearance/options/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/clearance/options/route.ts @@ -3,6 +3,7 @@ import { z } from 'zod' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { supplyChainClearanceService } from '@/server/services/supply-chain-clearance.service' +import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service' const querySchema = z.object({ field: z.string().trim().min(1).max(80), @@ -18,11 +19,16 @@ export async function GET(request: NextRequest) { if (!parsed.success) { return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '筛选项查询参数不正确', 400, ctx.requestId) } + const reviewAccess = await supplyChainPermissionSettingsService.getUserAccess( + ctx.user, + 'clearanceReview', + ) return jsonSuccess( await supplyChainClearanceService.getPoolFilterOptions({ field: parsed.data.field, query: parsed.data.q, limit: parsed.data.limit, + canReview: reviewAccess.edit, }), 200, ctx.requestId, diff --git a/furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.test.ts b/furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.test.ts new file mode 100644 index 00000000..9e9fe03f --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.test.ts @@ -0,0 +1,83 @@ +import type { NextRequest } from 'next/server' + +const mockHandleRequest = jest.fn() +const mockJsonSuccess = jest.fn() +const mockJsonError = jest.fn() +const mockGetUserAccess = jest.fn() +const mockGetTaskApplications = jest.fn() + +jest.mock('@/server/core/response', () => ({ + handleRequest: (...args: unknown[]) => mockHandleRequest(...args), + jsonSuccess: (...args: unknown[]) => mockJsonSuccess(...args), + jsonError: (...args: unknown[]) => mockJsonError(...args), +})) + +jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({ + supplyChainPermissionSettingsService: { + getUserAccess: (...args: unknown[]) => mockGetUserAccess(...args), + }, +})) + +jest.mock('@/server/services/supply-chain-clearance.service', () => ({ + supplyChainClearanceService: { + getTaskApplications: (...args: unknown[]) => mockGetTaskApplications(...args), + }, +})) + +const { GET } = require('./route') + +function request() { + return { + nextUrl: new URL( + 'http://localhost/api/supply-chain/clearance/tasks/applications?period=2026-11&barcode=SKU001&round=1&mine=1', + ), + } as NextRequest +} + +describe('GET clearance task applications', () => { + beforeEach(() => { + jest.clearAllMocks() + mockHandleRequest.mockImplementation(async ( + _request: NextRequest, + handler: (ctx: unknown) => unknown, + ) => handler({ + requestId: 'req-applications', + user: { id: 'operator-1', name: '运营A', role: 'USER' }, + })) + mockJsonSuccess.mockImplementation((data) => ({ data })) + mockJsonError.mockImplementation((code, message, status) => ({ code, message, status })) + mockGetTaskApplications.mockResolvedValue({ + periodKey: '2026-11', + barcode: 'SKU001', + round: 1, + applications: [], + }) + }) + + it('allows an operations user to load their own confirmation records', async () => { + mockGetUserAccess.mockImplementation(async (_user, target) => ({ + edit: target === 'clearanceOperation', + })) + + const response = await GET(request()) + + expect(response).toEqual({ data: expect.objectContaining({ applications: [] }) }) + expect(mockGetTaskApplications).toHaveBeenCalledWith(expect.objectContaining({ + user: expect.objectContaining({ id: 'operator-1' }), + canReview: false, + onlyMine: true, + })) + }) + + it('rejects users without either operations or review edit permission', async () => { + mockGetUserAccess.mockResolvedValue({ edit: false }) + + const response = await GET(request()) + + expect(response).toMatchObject({ + message: '当前账号没有清货任务确认或审核权限', + status: 403, + }) + expect(mockGetTaskApplications).not.toHaveBeenCalled() + }) +}) diff --git a/furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.ts b/furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.ts index fd42b652..ab1e3c7e 100644 --- a/furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/clearance/tasks/applications/route.ts @@ -14,10 +14,18 @@ export async function GET(request: NextRequest) { if (!barcode || (round !== 1 && round !== 2)) { return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '任务申请查询参数不正确', 400, ctx.requestId) } - const reviewAccess = await supplyChainPermissionSettingsService.getUserAccess( - ctx.user, - 'clearanceReview', - ) + const [operationAccess, reviewAccess] = await Promise.all([ + supplyChainPermissionSettingsService.getUserAccess(ctx.user, 'clearanceOperation'), + supplyChainPermissionSettingsService.getUserAccess(ctx.user, 'clearanceReview'), + ]) + if (!operationAccess.edit && !reviewAccess.edit) { + return jsonError( + ErrorCode.AUTH_PERMISSION_DENIED, + '当前账号没有清货任务确认或审核权限', + 403, + ctx.requestId, + ) + } return jsonSuccess( await supplyChainClearanceService.getTaskApplications({ periodKey, diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.test.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.test.tsx index 57e1a518..0553cf90 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.test.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.test.tsx @@ -102,6 +102,14 @@ describe('ClearanceReviewWorkbench', () => { expect(screen.queryByText('退回后重新提交')).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: '删除历史退回' })).not.toBeInTheDocument() expect(screen.getAllByText('重复申请 ×2')).toHaveLength(2) + expect(screen.getByLabelText('自定义冻结字段')).toHaveValue('submittedAt') + const barcodeHeader = screen.getByRole('columnheader', { name: '商品编码' }) + fireEvent.change(screen.getByLabelText('自定义冻结字段'), { + target: { value: 'barcode' }, + }) + expect(barcodeHeader).toHaveStyle({ position: 'sticky' }) + expect(barcodeHeader).toHaveStyle({ top: '0px' }) + expect(barcodeHeader.style.left).not.toBe('') }) it('submits reviewer-adjusted quantities and discounts for operator confirmation', async () => { @@ -140,6 +148,27 @@ describe('ClearanceReviewWorkbench', () => { ))).toBe(true) }) expect(onReviewed).toHaveBeenCalled() + expect(await screen.findByRole('status')).toHaveTextContent( + '已全部初审通过:2 条任务已推送运营确认', + ) + }) + + it('shows an explicit success notice after returning selected applications', async () => { + render() + + expect(await screen.findByText('申请人A')).toBeInTheDocument() + fireEvent.click(screen.getByLabelText('选择 SKU-A 申请人A')) + fireEvent.change(screen.getByPlaceholderText(/审核反馈或退回原因/), { + target: { value: '任务量需要重新评估' }, + }) + fireEvent.click(screen.getByRole('button', { name: '批量退回' })) + + expect(await screen.findByRole('status')).toHaveTextContent('已退回成功:2 条任务等待运营修改') }) it('locks values for final review after the operator confirms', async () => { diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.tsx index 00ee4375..a478cbb6 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceReviewWorkbench.tsx @@ -1,6 +1,6 @@ 'use client' -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useState, type CSSProperties } from 'react' import { Check, X } from 'lucide-react' import limitStyles from '../custom-table/limit-management.module.css' import ui from './clearance.module.css' @@ -86,6 +86,32 @@ const REVIEW_STATUS_OPTIONS = [ { key: 'RESUBMITTED', label: '已重新提交', countKey: 'resubmitted' }, { key: 'PASSED', label: '已通过', countKey: 'passed' }, ] as const +const REVIEW_COLUMNS = [ + { key: 'select', label: '', width: 42 }, + { key: 'ownerName', label: '清货负责人', width: 100 }, + { key: 'submittedByName', label: '提交人', width: 100 }, + { key: 'submittedAt', label: '申请时间', width: 150 }, + { key: 'barcode', label: '商品编码', width: 110 }, + { key: 'clearanceCode', label: '清货商品编码', width: 150 }, + { key: 'productName', label: '商品名称', width: 190 }, + { key: 'salesStatus', label: '销售状态', width: 82 }, + { key: 'priority', label: '优先级', width: 110 }, + { key: 'profitCenter', label: '利润中心', width: 110 }, + { key: 'stockJianshang', label: '简尚库存', width: 90 }, + { key: 'stockFactory', label: '工厂库存', width: 90 }, + { key: 'clearanceTotal', label: '清货总量', width: 90 }, + { key: 'dailySales', label: '日销', width: 80 }, + { key: 'availableDays', label: '可用天数', width: 90 }, + { key: 'taskQty', label: '申请任务量', width: 112 }, + { key: 'discount', label: '申请折扣', width: 100 }, + { key: 'reason', label: '申请原因', width: 220 }, + { key: 'status', label: '审核状态', width: 140 }, + { key: 'feedback', label: '审核反馈', width: 180 }, + { key: 'totalScore', label: '总分数', width: 90 }, + { key: 'suggestedDiscount', label: '建议折扣', width: 100 }, + { key: 'previousMonthDiscount', label: '上月折扣', width: 100 }, +] as const +type ReviewColumnKey = (typeof REVIEW_COLUMNS)[number]['key'] const EMPTY_REVIEW_ROWS: ReviewRow[] = [] async function requestJson(url: string, init?: RequestInit): Promise { @@ -135,6 +161,8 @@ export function ClearanceReviewWorkbench({ const [query, setQuery] = useState('') const [profitCenter, setProfitCenter] = useState('') const [statusFilter, setStatusFilter] = useState('ALL') + const [frozenThrough, setFrozenThrough] = useState('submittedAt') + const [toast, setToast] = useState('') const [reviewValues, setReviewValues] = useState controller.abort() }, [page, periodKey, profitCenter, query, refreshKey, roundValue, statusFilter]) + useEffect(() => { + if (!toast) return + const timer = window.setTimeout(() => setToast(''), 3600) + return () => window.clearTimeout(timer) + }, [toast]) + const rows = data?.rows ?? EMPTY_REVIEW_ROWS const isSelectableRow = (row: ReviewRow) => ( statusFilter === 'ALL' || statusFilter === 'REVIEW' @@ -192,6 +226,145 @@ export function ClearanceReviewWorkbench({ const selectedRows = rows.filter((row) => selected.includes(row.taskId)) const selectedStatuses = new Set(selectedRows.map((row) => row.status)) const selectedStage = selectedStatuses.size === 1 ? Array.from(selectedStatuses)[0] : '' + const frozenColumnIndex = REVIEW_COLUMNS.findIndex((column) => column.key === frozenThrough) + const columnOffsets = new Map() + let columnOffset = 0 + for (const column of REVIEW_COLUMNS) { + columnOffsets.set(column.key, columnOffset) + columnOffset += column.width + } + const reviewTableWidth = columnOffset + + function reviewCellStyle(key: ReviewColumnKey, header = false): CSSProperties { + const index = REVIEW_COLUMNS.findIndex((column) => column.key === key) + const frozen = index >= 0 && index <= frozenColumnIndex + return { + ...(header ? { top: 0, position: 'sticky' } : {}), + ...(frozen ? { left: columnOffsets.get(key) ?? 0, position: 'sticky' } : {}), + zIndex: header ? frozen ? 42 : 30 : frozen ? 12 : undefined, + } + } + + function reviewCellClass(key: ReviewColumnKey, header = false) { + return [ + header ? ui.reviewStickyHeader : '', + REVIEW_COLUMNS.findIndex((column) => column.key === key) <= frozenColumnIndex + ? ui.reviewFrozenColumn + : '', + ].filter(Boolean).join(' ') || undefined + } + + function renderReviewCell(row: ReviewRow, key: ReviewColumnKey) { + if (key === 'select') { + return ( + setSelected((current) => ( + current.includes(row.taskId) + ? current.filter((id) => id !== row.taskId) + : [...current, row.taskId] + ))} + aria-label={`选择 ${row.barcode} ${row.submittedByName}`} + /> + ) + } + if (key === 'submittedAt') return new Date(row.submittedAt).toLocaleString('zh-CN', { hour12: false }) + if (key === 'productName') { + return {row.productName || '—'} + } + if (key === 'taskQty') { + return ( + setReviewValues((current) => ({ + ...current, + [row.taskId]: { + taskQty: event.target.value, + discount: current[row.taskId]?.discount + ?? String(Number((row.discount * 10).toFixed(1))), + }, + }))} + /> + ) + } + if (key === 'discount') { + return ( + <> + setReviewValues((current) => ({ + ...current, + [row.taskId]: { + taskQty: current[row.taskId]?.taskQty ?? String(row.taskQty), + discount: event.target.value, + }, + }))} + /> + 折 + + ) + } + if (key === 'status') { + return ( + <> + {row.statusLabel || row.reviewDecisionLabel || row.status} + {row.duplicateGroupSize > 1 && ( + + 重复申请 ×{row.duplicateGroupSize} + + )} + {row.reviewDecisionLabel && row.reviewDecisionLabel !== row.statusLabel && ( + + {row.reviewDecisionLabel} + + )} + {row.reviewAdjustment?.summary && ( + + 经管修改:{row.reviewAdjustment.summary} + + )} + + ) + } + if (key === 'feedback') { + return {row.rejectReason || '—'} + } + if (key === 'reason') { + return {row.reason || '—'} + } + if (key === 'totalScore') return numberText(row.totalScore) + if (key === 'suggestedDiscount') { + return row.suggestedDiscount == null + ? '—' + : `${Number((row.suggestedDiscount * 10).toFixed(1))}折` + } + if (key === 'previousMonthDiscount') { + return row.previousMonthDiscount == null + ? '—' + : `${Number((row.previousMonthDiscount * 10).toFixed(1))}折` + } + const numericKeys: ReviewColumnKey[] = [ + 'stockJianshang', + 'stockFactory', + 'clearanceTotal', + 'dailySales', + ] + const value = row[key] + if (value == null || value === '') return '—' + return numericKeys.includes(key) ? String(value) : String(value) + } const review = useCallback(async (action: 'approve' | 'reject') => { if (!selected.length || busy) return @@ -229,6 +402,7 @@ export function ClearanceReviewWorkbench({ setBusy(true) setError('') setMessage('') + setToast('') try { const result = await requestJson<{ count: number @@ -245,14 +419,16 @@ export function ClearanceReviewWorkbench({ }), }, ) - setMessage( - action === 'approve' - ? selectedRows.every((row) => row.status === 'CONFIRMED') - ? `已终审通过 ${result.count} 条任务并推送清货任务` - : `已初审通过 ${result.count} 条任务并推送运营确认` - : `已批量退回 ${result.count} 条任务申请,等待运营修改` - + (result.notification?.message ? `;${result.notification.message}` : ''), - ) + const notificationMessage = result.notification?.message + ? `;${result.notification.message}` + : '' + const successMessage = action === 'approve' + ? selectedRows.every((row) => row.status === 'CONFIRMED') + ? `已全部终审通过:${result.count} 条任务已推送清货任务${notificationMessage}` + : `已全部初审通过:${result.count} 条任务已推送运营确认${notificationMessage}` + : `已退回成功:${result.count} 条任务等待运营修改${notificationMessage}` + setMessage(successMessage) + setToast(successMessage) setReviewFeedback('') setRefreshKey((value) => value + 1) onReviewed() @@ -292,6 +468,12 @@ export function ClearanceReviewWorkbench({ + {toast && ( +
+
+ )}
审核状态 @@ -368,6 +550,18 @@ export function ClearanceReviewWorkbench({ ))} + 已选 {selected.length} / 本页 {rows.length} 条 · 共 {data?.total ?? 0} 条 @@ -411,41 +605,37 @@ export function ClearanceReviewWorkbench({ {message &&
{message}
}
- +
+ + {REVIEW_COLUMNS.map((column) => ( + + ))} + - - - - - - - - - - - - - - - - - - - - - - - + {REVIEW_COLUMNS.map((column) => ( + + ))} @@ -457,102 +647,23 @@ export function ClearanceReviewWorkbench({ row.duplicateGroupSize > 1 ? ui.reviewWorkbenchRowDuplicate : '', ].filter(Boolean).join(' ') || undefined} > - - - - - - - - - - - - - - - - - - - - - - - + {REVIEW_COLUMNS.map((column) => ( + + ))} ))} diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx index b405861f..01ac33de 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/ClearanceView.tsx @@ -2459,57 +2459,94 @@ export function ClearanceView({ 月末复盘 -
-
- 审核状态 - 点击筛选 +
+
+
+ 审核状态 + 点击筛选 +
+
+ {POOL_REVIEW_STATUS_OPTIONS.map((option) => { + const count = pool?.reviewStatusCounts?.[option.countKey] ?? 0 + const active = poolReviewStatus === option.key + return ( + + ) + })} +
+ {canReview && pool?.taskAssignmentSummary && ( + + 已定 {fmtInt(pool.taskAssignmentSummary.detailCount)} 条 + {' · '} + {fmtInt(pool.taskAssignmentSummary.taskQty)} 件 + + )}
-
- {POOL_REVIEW_STATUS_OPTIONS.map((option) => { - const count = pool?.reviewStatusCounts?.[option.countKey] ?? 0 - const active = poolReviewStatus === option.key - return ( - - ) - })} -
- {canReview && pool?.taskAssignmentSummary && ( - - 已定 {fmtInt(pool.taskAssignmentSummary.detailCount)} 条 - {' · '} - {fmtInt(pool.taskAssignmentSummary.taskQty)} 件 - + {canReview && ( +
+
+ 优先级人工调整 + 已选 {selectedPoolBarcodes.length} 个编码 +
+ { + setPriorityBatchValue(event.target.value) + setPriorityError('') + }} + /> + + + {priorityError && {priorityError}} +
)}
-
)} +
+ +
)} /> - {canReview && ( -
-
- 优先级人工调整 - 已选 {selectedPoolBarcodes.length} 个编码,仅经管可操作 -
- { - setPriorityBatchValue(event.target.value) - setPriorityError('') - }} - /> - - - {priorityError && {priorityError}} -
- )} - {poolError &&
{poolError}
}
diff --git a/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css b/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css index 7293bb17..baa52946 100644 --- a/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css +++ b/furniture-3d-system/src/app/supply-chain/management/clearance/clearance.module.css @@ -121,7 +121,10 @@ .reviewStatusInline { display: flex; + width: auto; min-width: 0; + max-width: 100%; + flex: 0 1 auto; align-items: center; gap: 7px; overflow: hidden; @@ -132,12 +135,22 @@ box-shadow: 0 1px 2px rgba(24, 24, 27, 0.03); } +.reviewStatusPriorityGroup { + display: grid; + min-width: 0; + grid-row: 2; + grid-column: 1 / -1; + grid-template-columns: minmax(0, max-content) minmax(280px, 1fr); + align-items: center; + gap: 8px; +} + .reviewStatusInlineTitle { display: flex; flex: 0 0 auto; flex-direction: column; gap: 1px; - min-width: 58px; + min-width: 52px; } .reviewStatusInlineTitle b { @@ -154,7 +167,7 @@ display: flex; min-width: 0; flex: 1; - gap: 4px; + gap: 3px; overflow-x: auto; padding: 1px 0 2px; scrollbar-width: thin; @@ -163,8 +176,8 @@ .reviewStatusChip { height: 26px; flex: 0 0 auto; - gap: 4px; - padding: 0 7px; + gap: 3px; + padding: 0 5px; font-size: 10px; } @@ -184,20 +197,22 @@ .priorityBatchBar { display: flex; + min-width: 0; + flex: none; flex-wrap: wrap; align-items: center; - gap: 6px; - margin: 0 24px 10px; + gap: 4px; + margin: 0; border: 1px solid #dbe5f3; border-radius: 7px; background: #f8fbff; - padding: 6px 10px; + padding: 6px; } .priorityBatchBar > div:first-child { display: flex; - min-width: 150px; - flex: 1; + min-width: 76px; + flex: 0 1 88px; flex-direction: column; gap: 2px; } @@ -213,7 +228,13 @@ } .priorityBatchBar .cellInput { - width: 170px; + width: min(92px, 100%); +} + +.priorityBatchBar button { + height: 30px !important; + padding: 0 6px !important; + font-size: 11px !important; } .poolSelectCheckbox { @@ -1517,15 +1538,19 @@ .poolToolbar { display: grid; - grid-template-columns: 276px minmax(0, 1fr) auto; + grid-template-columns: 276px minmax(0, 1fr); align-items: stretch; gap: 12px; background: linear-gradient(180deg, #fff 0%, #fbfcfb 100%); padding: 10px 24px; } -.poolToolbar > .toolbarSettings { - align-self: center; +.filterToolbarSettings { + display: flex; + align-items: center; +} + +.filterToolbarSettings > .toolbarSettings { margin-left: 0; } @@ -2885,6 +2910,10 @@ font: inherit; } +.reviewFreezeControl select { + min-width: 164px; +} + .reviewWorkbenchSearch { display: flex; min-width: min(320px, 100%); @@ -2950,14 +2979,61 @@ } .reviewWorkbenchTableWrap { + position: relative; min-height: 0; flex: 1; overflow: auto; padding: 0 16px 16px; + isolation: isolate; } .reviewWorkbenchTableWrap table { min-width: 2050px; + table-layout: fixed; +} + +.reviewStickyHeader { + position: sticky; + top: 0; + background: #eef0ef; + box-shadow: inset 0 -1px 0 #d4d4d8; +} + +.reviewFrozenColumn { + position: sticky; + background: #fff; + box-shadow: inset -1px 0 0 #e4e4e7; +} + +.reviewStickyHeader.reviewFrozenColumn { + background: #eef0ef; +} + +.reviewWorkbenchTableWrap tbody tr:hover .reviewFrozenColumn { + background: #fafafa; +} + +.reviewWorkbenchToast { + position: fixed; + z-index: 90; + right: 50%; + bottom: 28px; + display: inline-flex; + max-width: min(680px, calc(100vw - 32px)); + min-height: 42px; + align-items: center; + gap: 8px; + transform: translateX(50%); + border: 1px solid #86efac; + border-radius: 7px; + background: #f0fdf4; + padding: 9px 14px; + color: #166534; + font-size: 12px; + font-weight: 650; + line-height: 1.45; + box-shadow: 0 12px 36px rgba(22, 101, 52, 0.18); + pointer-events: none; } .reviewWorkbenchPager { @@ -3470,6 +3546,38 @@ flex: 1; } +@media (min-width: 1450px) { + .poolToolbar { + grid-template-columns: max-content minmax(0, 1fr); + grid-template-rows: auto auto; + align-items: center; + gap: 8px 12px; + } + + .poolPeriodBlock { + display: contents; + } + + .poolPeriodBlock select { + width: max-content; + max-width: 100%; + justify-self: start; + grid-row: 1; + grid-column: 1; + } + + .poolToolbar .flow { + justify-self: start; + grid-row: 2; + grid-column: 1 / -1; + } + + .reviewStatusPriorityGroup { + grid-row: 1; + grid-column: 2; + } +} + @media (max-width: 1100px) { .statGrid { grid-template-columns: repeat(3, minmax(0, 1fr)); @@ -3494,7 +3602,7 @@ } .poolToolbar { - grid-template-columns: minmax(0, 1fr) auto; + grid-template-columns: minmax(0, 1fr); align-items: start; } @@ -3503,21 +3611,29 @@ grid-column: 1; } - .poolToolbar > .toolbarSettings { - grid-row: 1; - grid-column: 2; - align-self: start; - } - .poolOverview { grid-template-columns: repeat(2, minmax(0, 1fr)); grid-row: 2; grid-column: 1 / -1; } - .reviewStatusInline { + .reviewStatusPriorityGroup { + display: flex; grid-row: 2; grid-column: 1 / -1; + align-items: stretch; + flex-direction: column; + } + + .reviewStatusInline { + width: auto; + flex: 0 1 auto; + } + + .priorityBatchBar { + flex-direction: row; + min-width: 0; + flex-basis: auto; } } diff --git a/furniture-3d-system/src/lib/supply-chain-permission-paths.ts b/furniture-3d-system/src/lib/supply-chain-permission-paths.ts index e2b78ec5..c5ebd841 100644 --- a/furniture-3d-system/src/lib/supply-chain-permission-paths.ts +++ b/furniture-3d-system/src/lib/supply-chain-permission-paths.ts @@ -422,11 +422,14 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method: return { targetKey: 'clearanceOperation' as const, action: 'edit' as const } } if (pathname.startsWith('/api/supply-chain/clearance/tasks/')) { + if (pathname.endsWith('/applications')) { + // 申请人和审核人共用此接口,路由内按运营或审核权限及本人范围校验。 + return null + } if ( pathname.endsWith('/review') || pathname.endsWith('/adjust') || pathname.endsWith('/push-reviewed') - || pathname.endsWith('/applications') ) { return { targetKey: 'clearanceReview' as const, action: 'edit' as const } } diff --git a/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts b/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts index 6b9c3e8a..a5e4f2f7 100644 --- a/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts +++ b/furniture-3d-system/src/lib/supply-chain-permission-settings.test.ts @@ -63,6 +63,12 @@ describe('supply chain permission settings', () => { 'POST', ), ).toEqual({ targetKey: 'clearanceOperation', action: 'edit' }) + expect( + getSupplyChainApiPermissionRequirement( + '/api/supply-chain/clearance/tasks/applications', + 'GET', + ), + ).toBeNull() }) it('allows viewing price push archives but requires review edit permission to generate one', () => { diff --git a/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts b/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts index 8e63a798..0ef6706b 100644 --- a/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts +++ b/furniture-3d-system/src/server/repositories/supply-chain-clearance.repository.ts @@ -842,12 +842,22 @@ class SupplyChainClearanceRepository { return latest } - async listPoolBarcodesByPriorityKeywords(statDate: Date, keywords: readonly string[]) { + async listPoolBarcodesByPriorityKeywords( + statDate: Date, + keywords: readonly string[], + batchKeywords: readonly string[] = [], + ) { const normalized = keywords.map((keyword) => keyword.trim()).filter(Boolean) - if (!normalized.length) return [] - const conditions = normalized.map((keyword) => ( - Prisma.sql`COALESCE("extra"->>'priority', '') ILIKE ${`%${escapeLike(keyword)}%`}` - )) + const normalizedBatch = batchKeywords.map((keyword) => keyword.trim()).filter(Boolean) + if (!normalized.length && !normalizedBatch.length) return [] + const conditions = [ + ...normalized.map((keyword) => ( + Prisma.sql`COALESCE("extra"->>'priority', '') ILIKE ${`%${escapeLike(keyword)}%`}` + )), + ...normalizedBatch.map((keyword) => ( + Prisma.sql`COALESCE("extra"->>'clearanceBatch', '') ILIKE ${`%${escapeLike(keyword)}%`}` + )), + ] const rows = await prisma.$queryRaw>(Prisma.sql` SELECT DISTINCT "barcode" FROM "SupplyChainClearancePoolSnapshot" @@ -1193,6 +1203,63 @@ class SupplyChainClearanceRepository { })) } + async listPoolItemsForTaskPeriodByCodes(periodKey: string, codes: string[]) { + const normalized = normalizedBarcodes(codes) + if (!normalized.length) return [] + const generation = await this.findPoolGeneration(periodKey) + const snapshot = generation ?? await prisma.supplyChainClearancePoolSnapshot.findFirst({ + where: { periodKey }, + orderBy: [{ statDate: 'desc' }, { statTime: 'desc' }], + select: { statDate: true }, + }) + if (!snapshot) return [] + const matchedIds = await prisma.$queryRaw>(Prisma.sql` + SELECT "id" + FROM "SupplyChainClearancePoolSnapshot" + WHERE "periodKey" = ${periodKey} + AND "statDate" = ${snapshot.statDate} + AND COALESCE("extra"->>'clearanceBatch', '') <> '正常销售' + AND ( + UPPER("barcode") IN (${Prisma.join(normalized)}) + OR UPPER(COALESCE("extra"->>'clearanceCode', '')) IN (${Prisma.join(normalized)}) + ) + `) + if (!matchedIds.length) return [] + const items = await prisma.supplyChainClearancePoolSnapshot.findMany({ + where: { id: { in: matchedIds.map((row) => row.id) } }, + select: { + barcode: true, + spu: true, + sku: true, + productName: true, + brand: true, + productStatus: true, + salesStatus: true, + ownerName: true, + department: true, + directorName: true, + costPrice: true, + stockJianshang: true, + stockFactory: true, + totalStock: true, + dailySales: true, + availableDays: true, + extra: true, + }, + }) + if (!items.length) return [] + const familySalesKeys = clearanceSkuFamilySalesKeySet( + await this.listPoolSkuFamilyStatuses( + periodKey, + items.map((item) => item.sku), + ), + ) + return items.map((item) => ({ + ...item, + skuFamilyHasSalesStatus: familySalesKeys.has(clearanceSkuFamilyKey(item.sku)), + })) + } + async listPoolRowsForAutoPricePush(periodKey: string) { const generation = await this.findPoolGeneration(periodKey) const snapshot = generation ?? await prisma.supplyChainClearancePoolSnapshot.findFirst({ @@ -1356,6 +1423,22 @@ class SupplyChainClearanceRepository { return updates.length } + async updateTaskAuditSnapshots(updates: Array<{ + id: string + data: Prisma.SupplyChainClearanceTaskUncheckedUpdateInput + }>) { + if (!updates.length) return 0 + await prisma.$transaction(async (tx) => { + for (const update of updates) { + await tx.supplyChainClearanceTask.update({ + where: { id: update.id }, + data: update.data, + }) + } + }, { maxWait: 10_000, timeout: 120_000 }) + return updates.length + } + async updateTaskOwnerSnapshots(updates: Array<{ id: string ownerName: string diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts index 505b2496..63089c4f 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance-task-import.service.test.ts @@ -40,7 +40,7 @@ function poolItem(overrides: Record = {}) { function repository() { return { - listPoolItemsForTaskPeriod: jest.fn().mockResolvedValue([ + listPoolItemsForTaskPeriodByCodes: jest.fn().mockResolvedValue([ poolItem(), poolItem({ barcode: 'SKU-B', @@ -131,9 +131,76 @@ describe('SupplyChainClearanceTaskImportService', () => { }) }) + it('resolves a combined clearance code and creates its component tasks', async () => { + const comboCode = 'ZH-BG006401AN1242V01-1-BG006401BN1242V01-1' + const repo = repository() + repo.listTasksForManualImport.mockResolvedValue([]) + repo.listPoolItemsForTaskPeriodByCodes.mockResolvedValue([ + poolItem({ + barcode: 'BG006401AN1242V01', + sku: 'BG006401AN1242', + stockJianshang: 20, + costPrice: '100.000', + extra: { + profitCenter: '运营中心A', + clearanceCode: comboCode, + clearanceTotal: 10, + }, + }), + poolItem({ + barcode: 'BG006401BN1242V01', + sku: 'BG006401BN1242', + stockJianshang: 10, + costPrice: '80.000', + extra: { + profitCenter: '运营中心A', + clearanceCode: comboCode, + clearanceTotal: 10, + }, + }), + ]) + const service = new SupplyChainClearanceTaskImportService(repo as never) + + await expect(service.importTasks({ + periodKey: '2026-11', + user, + buffer: await workbookBuffer([ + [comboCode, '铁心兰', 15, '5折', '组合清货'], + ]), + })).resolves.toMatchObject({ + importedCount: 2, + createdCount: 2, + updatedCount: 0, + adjustedToStockCount: 2, + }) + + expect(repo.listTasksForManualImport).toHaveBeenCalledWith('2026-11', [ + 'BG006401AN1242V01', + 'BG006401BN1242V01', + ]) + expect(repo.writeTasksWithEvents).toHaveBeenCalledWith([ + expect.objectContaining({ + create: expect.objectContaining({ + barcode: 'BG006401AN1242V01', + taskQty: 10, + clearancePrice: '50.000', + ownerName: '铁心兰', + }), + }), + expect.objectContaining({ + create: expect.objectContaining({ + barcode: 'BG006401BN1242V01', + taskQty: 10, + clearancePrice: '40.000', + ownerName: '铁心兰', + }), + }), + ]) + }) + it('reports sales-status barcodes that try to apply a discount', async () => { const repo = repository() - repo.listPoolItemsForTaskPeriod.mockResolvedValue([ + repo.listPoolItemsForTaskPeriodByCodes.mockResolvedValue([ poolItem({ barcode: 'SALE-1', productStatus: '销售', @@ -148,7 +215,45 @@ describe('SupplyChainClearanceTaskImportService', () => { buffer: await workbookBuffer([ ['SALE-1', '铁心兰', 10, '8折', '清仓'], ]), - })).rejects.toThrow('清货商品编码 SALE-1 不允许申请折扣:清货商品编码状态为销售') + })).rejects.toThrow('SALE-1(清货商品编码状态为销售)') + }) + + it('reports every sales-status code when a discount import has multiple invalid rows', async () => { + const codes = [ + 'GBSFY-SJ034101N1280V01', + 'GBSFY-CBG013101AN1280V01', + 'GBSFY-CBG013101BN1280V01', + 'GBSFY-AD035401N1280V01', + 'GBSFY-BG007201N1280V01', + 'GBSFY-SJ022304N1280V01', + 'GBSFY-BG007101N1280V01', + 'GBSFY-SN020301N1280V01', + 'GBSFY-XG026302N1280V01', + 'GBSFY-XG026301N1280V01', + ] + const repo = repository() + repo.listPoolItemsForTaskPeriodByCodes.mockResolvedValue(codes.map((barcode) => poolItem({ + barcode, + productStatus: '销售', + salesStatus: '销售', + extra: { profitCenter: '运营中心A', clearanceCode: barcode }, + }))) + const service = new SupplyChainClearanceTaskImportService(repo as never) + + await expect(service.importTasks({ + periodKey: '2026-11', + user, + buffer: await workbookBuffer(codes.map((barcode) => [ + barcode, + '铁心兰', + 10, + '8折', + '清仓', + ])), + })).rejects.toThrow(codes.map((barcode) => ( + `${barcode}(清货商品编码状态为销售)` + )).join('、')) + expect(repo.writeTasksWithEvents).not.toHaveBeenCalled() }) it('creates separate tasks for the same barcode imported by different operators', async () => { @@ -181,7 +286,7 @@ describe('SupplyChainClearanceTaskImportService', () => { it('reports barcodes missing from the selected clearance pool', async () => { const repo = repository() - repo.listPoolItemsForTaskPeriod.mockResolvedValue([]) + repo.listPoolItemsForTaskPeriodByCodes.mockResolvedValue([]) const service = new SupplyChainClearanceTaskImportService(repo as never) await expect(service.importTasks({ diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts index b7b761d9..d63fd177 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-clearance.service.test.ts @@ -102,6 +102,7 @@ jest.mock('@/server/repositories/supply-chain-clearance.repository', () => ({ findPoolImagesByBarcodes: jest.fn(), findPoolItemsByBarcodes: jest.fn(), listPoolItemsForTaskPeriod: jest.fn(), + listPoolItemsForTaskPeriodByCodes: jest.fn(), listPoolRowsForAutoPricePush: jest.fn(), listPoolSkuFamilyStatuses: jest.fn(), listProductArchiveTaskValuesByBarcodes: jest.fn(), @@ -109,6 +110,7 @@ jest.mock('@/server/repositories/supply-chain-clearance.repository', () => ({ listTasks: jest.fn(), findTask: jest.fn(), updateTaskCostPrices: jest.fn(), + updateTaskAuditSnapshots: jest.fn(), updateTaskOwnerSnapshots: jest.fn(), findDraftTask: jest.fn(), findActiveTask: jest.fn(), @@ -511,6 +513,7 @@ describe('supply-chain-clearance workflow', () => { repository.listTaskRowsForPoolRefresh.mockResolvedValue([]) repository.supplementPoolRowsForRefresh.mockResolvedValue([]) repository.updatePoolDailyMetrics.mockResolvedValue(0) + repository.updateTaskAuditSnapshots.mockResolvedValue(0) repository.listPoolFilterOptions.mockResolvedValue([]) repository.listPoolRowsForAutoPricePush.mockResolvedValue([]) repository.poolOverview.mockResolvedValue({ @@ -1052,6 +1055,7 @@ describe('supply-chain-clearance workflow', () => { expect(repository.listPoolBarcodesByPriorityKeywords).toHaveBeenCalledWith( new Date('2026-11-20T00:00:00.000Z'), ['库存积压', '代发仓'], + ['库存积压'], ) expect(repository.listPool).toHaveBeenCalledWith(expect.objectContaining({ excludeBarcodes: ['HIDDEN-1'], @@ -3015,6 +3019,17 @@ describe('supply-chain-clearance workflow', () => { expect(result.values).toEqual(expect.arrayContaining(['广东佛山', '普通清货', '库存积压'])) }) + it('hides operator-only priority options for ordinary operations users', async () => { + repository.listPoolFilterOptions.mockResolvedValue(['A 固定任务', '代发仓']) + + const result = await supplyChainClearanceService.getPoolFilterOptions({ + field: 'priority', + canReview: false, + }) + + expect(result.values).toEqual(['A 固定任务']) + }) + it('builds automatic price candidates from enabled priority rules', async () => { repository.findClearanceConfig.mockResolvedValue({ priorityRules: [{ @@ -3320,6 +3335,62 @@ describe('supply-chain-clearance workflow', () => { }) }) + it('backfills missing reviewer score snapshots before rendering the workbench', async () => { + repository.findClearanceConfig.mockResolvedValue({ + reviewScoreConfig: decimalReviewScoreConfig, + } as never) + repository.listLatestApprovedTaskDiscountsBefore.mockResolvedValue([{ + barcode: 'SKU001', + profitCenter: '运营中心A', + discount: '0.80', + }] as never) + repository.listTasks.mockResolvedValue([{ + ...pendingTask, + auditAvailableDays: null, + auditDailySales: null, + auditInboundDays: null, + auditStockUsableDaysScore: null, + auditDailySalesScore: null, + auditInboundDaysScore: null, + auditTotalScore: null, + auditSuggestedDiscount: null, + auditPreviousMonthDiscount: null, + auditScoreVersion: '', + auditScoredAt: null, + }] as never) + repository.listPoolItemsForTaskPeriod.mockResolvedValue([{ + ...poolItem, + availableDays: '40', + dailySales: '2.5', + extra: { + profitCenter: '运营中心A', + inboundDays: 20, + }, + }] as never) + + const review = await supplyChainClearanceService.getReviewWorkbench({ + periodKey: '2026-10', + round: 1, + }) + + expect(review.rows[0]).toMatchObject({ + totalScore: 8.75, + suggestedDiscount: 0.55, + previousMonthDiscount: 0.8, + }) + expect(repository.updateTaskAuditSnapshots).toHaveBeenCalledWith([ + expect.objectContaining({ + id: pendingTask.id, + data: expect.objectContaining({ + auditTotalScore: 8.75, + auditSuggestedDiscount: 0.55, + auditPreviousMonthDiscount: 0.8, + auditScoredAt: expect.any(Date), + }), + }), + ]) + }) + it('treats legacy rejected tasks as pending operator confirmation in the review workbench', async () => { repository.listTasks.mockResolvedValue([ { ...pendingTask, id: 'pending', status: 'PENDING', events: [] }, diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts b/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts index 8569860e..24ea12e0 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance-task-import.service.ts @@ -13,7 +13,7 @@ const PERIOD_PATTERN = /^\d{4}-(0[1-9]|1[0-2])$/ type TaskImportRepository = Pick< typeof supplyChainClearanceRepository, - | 'listPoolItemsForTaskPeriod' + | 'listPoolItemsForTaskPeriodByCodes' | 'listProductArchiveTaskValuesByBarcodes' | 'listTasksForManualImport' | 'listOwnerProfitCenters' @@ -59,6 +59,18 @@ function isSalesStatus(value: unknown) { return String(value ?? '').trim() === '销售' } +function salesDiscountError(item: { + salesStatus: string + productStatus: string + skuFamilyHasSalesStatus: boolean +}) { + if (item.skuFamilyHasSalesStatus) return '同货号存在销售状态商品' + if (isSalesStatus(item.salesStatus) || isSalesStatus(item.productStatus)) { + return '清货商品编码状态为销售' + } + return '' +} + function barcodeList(values: readonly string[]) { return Array.from(new Set(values)).slice(0, 30).join('、') } @@ -102,7 +114,8 @@ export class SupplyChainClearanceTaskImportService { const lines = [ '清货任务人工导入:清货商品编码不能重复;已有同编码任务会更新并重新进入待审核。', `统计月为当前选择的 ${periodKey},模板不单独填写统计月。`, - '清货商品编码必须在当前清货池唯一存在;清货负责人不能为空。', + '清货商品编码必须存在于当前清货池;清货负责人不能为空。', + '可填写清货池展示的清货商品编码;组合编码会自动展开为对应组件任务。', '任务量支持小数,系统统一向上取整;超过简尚库存时按简尚库存保留。', '折扣填写 1–10 折或留空;支持“五折”自动转换为“5折”,申请折扣时必须填写原因。', '清货负责人即任务运营负责人,与执行导入的账号无关。', @@ -137,37 +150,55 @@ export class SupplyChainClearanceTaskImportService { ) } - const barcodes = Array.from(new Set(rows.map((row) => row.barcode))) - const [poolItems, archiveItems, existingTasks, latestRound, ownerCenters] = await Promise.all([ - this.repository.listPoolItemsForTaskPeriod(periodKey, barcodes), - this.repository.listProductArchiveTaskValuesByBarcodes(barcodes), - this.repository.listTasksForManualImport(periodKey, barcodes), + const importCodes = Array.from(new Set(rows.map((row) => row.barcode))) + const [poolItems, latestRound, ownerCenters] = await Promise.all([ + this.repository.listPoolItemsForTaskPeriodByCodes(periodKey, importCodes), this.repository.latestTaskRound(periodKey), this.repository.listOwnerProfitCenters(), ]) - const poolItemsByBarcode = new Map() + const importCodeSet = new Set(importCodes) + const poolItemsByImportCode = new Map() for (const item of poolItems) { const barcode = item.barcode.trim().toUpperCase() - const items = poolItemsByBarcode.get(barcode) ?? [] - items.push(item) - poolItemsByBarcode.set(barcode, items) + const clearanceCode = String(poolExtra(item.extra).clearanceCode ?? '') + .trim() + .toUpperCase() + for (const code of new Set([barcode, clearanceCode])) { + if (!code || !importCodeSet.has(code)) continue + const items = poolItemsByImportCode.get(code) ?? [] + items.push(item) + poolItemsByImportCode.set(code, items) + } } - const ambiguousBarcodes = Array.from(poolItemsByBarcode) - .filter(([, items]) => items.length !== 1) - .map(([barcode]) => barcode) + const ambiguousBarcodes = importCodes.filter((code) => { + const directMatches = (poolItemsByImportCode.get(code) ?? []).filter((item) => ( + item.barcode.trim().toUpperCase() === code + )) + return directMatches.length > 1 + }) if (ambiguousBarcodes.length) { throw new AppError( ErrorCode.VALIDATION_INVALID_FORMAT, `以下清货商品编码在清货池存在多条记录,无法唯一导入:${barcodeList(ambiguousBarcodes)}`, ) } - const missingBarcodes = barcodes.filter((barcode) => !poolItemsByBarcode.has(barcode)) + const missingBarcodes = importCodes.filter((code) => !(poolItemsByImportCode.get(code)?.length)) if (missingBarcodes.length) { throw new AppError( ErrorCode.RESOURCE_NOT_FOUND, `以下清货商品编码未匹配到当前清货池:${barcodeList(missingBarcodes)}`, ) } + const matchedBarcodes = Array.from(new Set( + Array.from(poolItemsByImportCode.values()) + .flat() + .map((item) => item.barcode.trim().toUpperCase()) + .filter(Boolean), + )) + const [archiveItems, existingTasks] = await Promise.all([ + this.repository.listProductArchiveTaskValuesByBarcodes(matchedBarcodes), + this.repository.listTasksForManualImport(periodKey, matchedBarcodes), + ]) const archiveByBarcode = new Map(archiveItems.map((item) => [ item.barcode.trim().toUpperCase(), item, @@ -187,61 +218,82 @@ export class SupplyChainClearanceTaskImportService { )))}`, ) } + const salesDiscountErrors = rows.flatMap((row) => { + if (row.discount >= 1) return [] + const matchedItems = new Map( + (poolItemsByImportCode.get(row.barcode) ?? []).map((item) => [ + item.barcode.trim().toUpperCase(), + item, + ]), + ).values() + const reason = Array.from(matchedItems) + .map((item) => salesDiscountError(item)) + .find(Boolean) + return reason ? [`${row.barcode}(${reason})`] : [] + }) + if (salesDiscountErrors.length) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + `以下清货商品编码不允许申请折扣:${barcodeList(salesDiscountErrors)}`, + ) + } - const preparedRows = rows.map((row) => { - const poolItem = poolItemsByBarcode.get(row.barcode)?.[0] - if (!poolItem) throw new Error(`Missing pool item for ${row.barcode}`) - const extra = poolExtra(poolItem.extra) - const profitCenter = String(extra.profitCenter ?? '').trim() - || profitCenterByOwner.get(row.clearanceOwner.trim()) - || '' - if (!profitCenter) { - throw new AppError( - ErrorCode.VALIDATION_REQUIRED_FIELD, - `清货商品编码 ${row.barcode} 无法确定利润中心`, - ) - } - const hasSalesStatus = isSalesStatus(poolItem.salesStatus) - || isSalesStatus(poolItem.productStatus) - || poolItem.skuFamilyHasSalesStatus - if (row.discount < 1 && hasSalesStatus) { - const reason = poolItem.skuFamilyHasSalesStatus - ? '同货号存在销售状态商品' - : '清货商品编码状态为销售' - throw new AppError( - ErrorCode.VALIDATION_INVALID_FORMAT, - `清货商品编码 ${row.barcode} 不允许申请折扣:${reason}`, - ) - } - const stockJianshang = Math.max(0, poolItem.stockJianshang) - const taskQty = Math.min(row.taskQty, stockJianshang) - const archiveItem = archiveByBarcode.get(row.barcode) - const costPrice = number(poolItem.costPrice) ?? number(archiveItem?.costPrice) - const clearancePrice = row.discount < 1 - ? (() => { - if (costPrice == null || costPrice <= 0) { - throw new AppError( - ErrorCode.VALIDATION_INVALID_FORMAT, - `清货商品编码 ${row.barcode} 缺少成本价,无法计算清货价`, - ) - } - return Number((costPrice * row.discount).toFixed(3)) - })() - : null - return { - ...row, - requestedTaskQty: row.taskQty, - profitCenter, - taskQty, - stockJianshang, - costPrice, - clearancePrice, - department: poolItem.department || '', - sku: poolItem.sku || '', - productName: poolItem.productName || '', - brand: poolItem.brand || '', - productStatus: poolItem.productStatus || '', - } + const preparedRows = rows.flatMap((row) => { + const matchedItems = Array.from(new Map( + (poolItemsByImportCode.get(row.barcode) ?? []).map((item) => [ + item.barcode.trim().toUpperCase(), + item, + ]), + ).values()) + if (!matchedItems.length) throw new Error(`Missing pool item for ${row.barcode}`) + const groupStockLimit = Math.min(...matchedItems.map((poolItem) => { + const clearanceTotal = number(poolExtra(poolItem.extra).clearanceTotal) + return Math.max(0, clearanceTotal ?? poolItem.stockJianshang) + })) + return matchedItems.map((poolItem) => { + const componentBarcode = poolItem.barcode.trim().toUpperCase() + const extra = poolExtra(poolItem.extra) + const profitCenter = String(extra.profitCenter ?? '').trim() + || profitCenterByOwner.get(row.clearanceOwner.trim()) + || '' + if (!profitCenter) { + throw new AppError( + ErrorCode.VALIDATION_REQUIRED_FIELD, + `清货商品编码 ${row.barcode} 无法确定利润中心`, + ) + } + const stockJianshang = Math.max(0, poolItem.stockJianshang) + const taskQty = Math.min(row.taskQty, groupStockLimit) + const archiveItem = archiveByBarcode.get(componentBarcode) + const costPrice = number(poolItem.costPrice) ?? number(archiveItem?.costPrice) + const clearancePrice = row.discount < 1 + ? (() => { + if (costPrice == null || costPrice <= 0) { + throw new AppError( + ErrorCode.VALIDATION_INVALID_FORMAT, + `清货商品编码 ${row.barcode} 缺少成本价,无法计算清货价`, + ) + } + return Number((costPrice * row.discount).toFixed(3)) + })() + : null + return { + ...row, + barcode: componentBarcode, + importCode: row.barcode, + requestedTaskQty: row.taskQty, + profitCenter, + taskQty, + stockJianshang, + costPrice, + clearancePrice, + department: poolItem.department || '', + sku: poolItem.sku || '', + productName: poolItem.productName || '', + brand: poolItem.brand || '', + productStatus: poolItem.productStatus || '', + } + }) }) const candidatesByKey = new Map() @@ -314,6 +366,7 @@ export class SupplyChainClearanceTaskImportService { after: { periodKey, barcode: row.barcode, + importCode: row.importCode, profitCenter: row.profitCenter, clearanceOwner: row.clearanceOwner, importedTaskQty: row.requestedTaskQty, diff --git a/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts b/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts index ceb68e35..ff7d96b5 100644 --- a/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts +++ b/furniture-3d-system/src/server/services/supply-chain-clearance.service.ts @@ -169,6 +169,7 @@ const EXCLUDED_CLEARANCE_BARCODES = new Set([ 'GBGJ-MPWL01N126V01', ]) const OPERATOR_HIDDEN_CLEARANCE_PRIORITY_KEYWORDS = ['库存积压', '代发仓'] as const +const OPERATOR_HIDDEN_CLEARANCE_BATCH_KEYWORDS = ['库存积压'] as const const MANUAL_PRIORITY_BACKUP_CUTOFF_PERIOD = '2026-11' function number(value: unknown) { @@ -2293,10 +2294,20 @@ class SupplyChainClearanceService { : await supplyChainClearanceRepository.listPoolBarcodesByPriorityKeywords( hiddenPriorityStatDate, OPERATOR_HIDDEN_CLEARANCE_PRIORITY_KEYWORDS, + OPERATOR_HIDDEN_CLEARANCE_BATCH_KEYWORDS, ) const hiddenPriorityBarcodeSet = new Set( hiddenPriorityBarcodes.map((barcode) => barcode.trim().toUpperCase()), ) + if (!canViewAllApplications) { + for (const task of rawPeriodTasks) { + if (OPERATOR_HIDDEN_CLEARANCE_PRIORITY_KEYWORDS.some((keyword) => ( + String(task.priorityOverride ?? '').includes(keyword) + ))) { + hiddenPriorityBarcodeSet.add(task.barcode.trim().toUpperCase()) + } + } + } const periodTasks = rawPeriodTasks.filter((task) => ( !hiddenPriorityBarcodeSet.has(task.barcode.trim().toUpperCase()) )) @@ -2917,6 +2928,7 @@ class SupplyChainClearanceService { field: string query?: string limit?: number + canReview?: boolean }) { const field = input.field.trim().slice(0, 80) if (!field) { @@ -2960,14 +2972,24 @@ class SupplyChainClearanceService { query: input.query?.trim().slice(0, 300) ?? '', limit: input.limit ?? 200, }) - if (field !== 'priority') return { values: repositoryValues } + const hideOperatorValues = input.canReview === false + && (field === 'priority' || field === 'clearanceBatch') + const hiddenKeywords = field === 'clearanceBatch' + ? OPERATOR_HIDDEN_CLEARANCE_BATCH_KEYWORDS + : OPERATOR_HIDDEN_CLEARANCE_PRIORITY_KEYWORDS + const visibleValues = (values: string[]) => ( + hideOperatorValues + ? values.filter((value) => !hiddenKeywords.some((keyword) => value.includes(keyword))) + : values + ) + if (field !== 'priority') return { values: visibleValues(repositoryValues) } const query = input.query?.trim().toLowerCase() ?? '' const limit = Math.min(500, Math.max(1, Math.floor(input.limit ?? 200))) const values = Array.from(new Set([...priorityValues, ...repositoryValues])) .filter((value) => !query || value.toLowerCase().includes(query)) .sort((left, right) => left.localeCompare(right, 'zh-Hans-CN', { numeric: true })) .slice(0, limit) - return { values } + return { values: visibleValues(values) } } async listAutoPricePushCandidates(periodKeyInput: string, currentAt = new Date()) { @@ -3587,6 +3609,9 @@ class SupplyChainClearanceService { && !OPERATOR_HIDDEN_CLEARANCE_PRIORITY_KEYWORDS.some((keyword) => ( task.priority.includes(keyword) )) + && !OPERATOR_HIDDEN_CLEARANCE_BATCH_KEYWORDS.some((keyword) => ( + String(task.clearanceBatch ?? '').includes(keyword) + )) ) ) const visible = roundScoped.filter((task) => task.status === 'APPROVED') @@ -3942,10 +3967,54 @@ class SupplyChainClearanceService { const poolByBarcode = new Map( poolItems.map((item) => [item.barcode.trim().toUpperCase(), item]), ) + const missingAuditTasks = applications.filter((task) => !task.auditScoredAt) + const auditSnapshotByTaskId = new Map>() + if (missingAuditTasks.length) { + const [clearanceConfig, priorDiscountRows] = await Promise.all([ + supplyChainClearanceRepository.findClearanceConfig(), + supplyChainClearanceRepository.listLatestApprovedTaskDiscountsBefore({ + periodKey, + barcodes: Array.from(new Set(missingAuditTasks.map((task) => task.barcode))), + }), + ]) + const reviewScoreConfig = normalizeClearanceReviewScoreConfig( + clearanceConfig?.reviewScoreConfig, + ) + const priorDiscounts = priorDiscountByBarcodeAndCenter(priorDiscountRows) + for (const task of missingAuditTasks) { + const poolItem = poolByBarcode.get(task.barcode.trim().toUpperCase()) + if (!poolItem) continue + const profitCenter = task.profitCenter.trim() + || String(poolExtra(poolItem).profitCenter ?? '').trim() + if (!profitCenter) continue + auditSnapshotByTaskId.set( + task.id, + taskAuditSnapshot( + poolItem, + priorDiscounts.get( + `${task.barcode.trim().toUpperCase()}\u0000${profitCenter}`, + ) ?? null, + reviewScoreConfig, + ), + ) + } + if (auditSnapshotByTaskId.size) { + void supplyChainClearanceRepository.updateTaskAuditSnapshots( + Array.from(auditSnapshotByTaskId, ([id, data]) => ({ id, data })), + ).catch((error) => { + console.warn('[clearance-review-workbench] failed to backfill audit snapshots', { + periodKey, + count: auditSnapshotByTaskId.size, + error: error instanceof Error ? error.message : String(error), + }) + }) + } + } const rows = applications.map((task) => { const poolItem = poolByBarcode.get(task.barcode.trim().toUpperCase()) const extra = poolItem ? poolExtra(poolItem) : {} const discount = number(task.discount) ?? 0 + const auditSnapshot = auditSnapshotByTaskId.get(task.id) return { taskId: task.id, barcode: task.barcode, @@ -3987,11 +4056,17 @@ class SupplyChainClearanceService { returnedBeforeResubmit: returnedBeforeResubmit(task), rejectReason: task.rejectReason, reviewedAt: task.reviewedAt?.toISOString() ?? null, - totalScore: number(task.auditTotalScore), - suggestedDiscount: number(task.auditSuggestedDiscount), - previousMonthDiscount: number(task.auditPreviousMonthDiscount), - auditScoreVersion: task.auditScoreVersion, - auditScoredAt: task.auditScoredAt?.toISOString() ?? null, + totalScore: number(auditSnapshot?.auditTotalScore ?? task.auditTotalScore), + suggestedDiscount: number( + auditSnapshot?.auditSuggestedDiscount ?? task.auditSuggestedDiscount, + ), + previousMonthDiscount: number( + auditSnapshot?.auditPreviousMonthDiscount ?? task.auditPreviousMonthDiscount, + ), + auditScoreVersion: auditSnapshot?.auditScoreVersion ?? task.auditScoreVersion, + auditScoredAt: ( + auditSnapshot?.auditScoredAt ?? task.auditScoredAt + )?.toISOString() ?? null, } }) return { From 04a625825d6031ca1fe1249c33584238140d2424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B1=85=E5=B1=85?= Date: Tue, 24 Nov 2026 12:02:46 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=81=9C=E4=BA=A7?= =?UTF-8?q?=E4=B8=8B=E6=9E=B6=EF=BC=9A=E5=94=AF=E5=93=81=E4=BB=93=E4=BB=85?= =?UTF-8?q?=E5=AF=B9=E8=BF=90=E8=90=A5=E4=B8=AD=E5=BF=83C=E5=85=8D?= =?UTF-8?q?=E4=B8=8B=E6=9E=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 唯品仓库存从普通简尚库存拆出;仅唯品仓有库存时生成下架通知,排除运营中心C链接,其他部门按全渠道下架处理。 --- .../架构设计/停产下架管理数据源-20261019.md | 1 + ...-discontinuation-source.repository.test.ts | 37 +++++++++++++++++++ ...chain-discontinuation-source.repository.ts | 21 ++++++++++- ...-chain-discontinuation-link-import.test.ts | 8 ++++ ...pply-chain-discontinuation.service.test.ts | 32 ++++++++++++++++ .../supply-chain-discontinuation.builder.ts | 10 +++-- 6 files changed, 105 insertions(+), 4 deletions(-) diff --git a/furniture-3d-system/docs/架构设计/停产下架管理数据源-20261019.md b/furniture-3d-system/docs/架构设计/停产下架管理数据源-20261019.md index 2aee34d2..f7353886 100644 --- a/furniture-3d-system/docs/架构设计/停产下架管理数据源-20261019.md +++ b/furniture-3d-system/docs/架构设计/停产下架管理数据源-20261019.md @@ -58,6 +58,7 @@ - 仓库名称通过 `JianSun.dbo.jst_warehouseInfo` 映射。 - `三方-南昌樵舍仓` 作为京喜渠道仓单独汇总,不计入普通简尚库存。 - 渠道专用仓库存不计入简尚主库存,单独返回到“渠道专用仓库存”和“专用仓备注”。 +- `唯品仓` 库存不计入普通简尚库存;其他仓均为 0、仅唯品仓有库存时,生成下架通知并排除运营中心C链接,其他部门显示下架。 - 库存预警的“库存所在仓库”只统计实际计入公有可用数且有正库存的普通仓。 - 同一商品在多个仓库有库存时拆成多条明细,不合并仓库名称。 - 虚拟云仓库存按各仓库存占比分摊到仓库明细,分摊后各行公有可用数合计与原商品汇总值一致。 diff --git a/furniture-3d-system/src/server/repositories/__tests__/supply-chain-discontinuation-source.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-discontinuation-source.repository.test.ts index f8c0dbd9..8da5af38 100644 --- a/furniture-3d-system/src/server/repositories/__tests__/supply-chain-discontinuation-source.repository.test.ts +++ b/furniture-3d-system/src/server/repositories/__tests__/supply-chain-discontinuation-source.repository.test.ts @@ -238,4 +238,41 @@ describe('supply-chain-discontinuation-source repository', () => { expect(inventorySql).not.toContain("NOT LIKE N'%不可释放%'") expect(warehouseSql).not.toContain("NOT LIKE N'%不可释放%'") }) + + it('separates VIP warehouse stock and maps it to Operations C', async () => { + const request = { + input: jest.fn().mockReturnThis(), + query: jest.fn().mockResolvedValue({ + recordset: [{ + barcode: 'SKU-VIP', + warehouseStock: 0, + jingxiStock: 0, + channelStock: 0, + vipStock: 5, + specialWarehouseNote: '', + warehouseName: '', + }], + }), + } + const pool = { + request: jest.fn(() => request), + } + ;(repository as unknown as { + getPool: () => Promise + }).getPool = jest.fn().mockResolvedValue(pool) + + await expect(repository.listInventoryByBarcodes(['SKU-VIP'])).resolves.toEqual([{ + barcode: 'SKU-VIP', + stockJianshang: 0, + jingxiStock: 0, + channelStock: 0, + vipStock: 5, + specialWarehouseNote: '唯品仓-运营中心C', + warehouseName: '', + }]) + + const sqlText = String(request.query.mock.calls[0]?.[0] ?? '') + expect(sqlText).toContain("warehouse_name LIKE N'%唯品仓%'") + expect(sqlText).toContain("warehouse_name NOT LIKE N'%唯品仓%'") + }) }) diff --git a/furniture-3d-system/src/server/repositories/supply-chain-discontinuation-source.repository.ts b/furniture-3d-system/src/server/repositories/supply-chain-discontinuation-source.repository.ts index c0d7c06d..dedb207a 100644 --- a/furniture-3d-system/src/server/repositories/supply-chain-discontinuation-source.repository.ts +++ b/furniture-3d-system/src/server/repositories/supply-chain-discontinuation-source.repository.ts @@ -11,6 +11,7 @@ export type DiscontinuationInventoryProfile = { stockJianshang: number jingxiStock: number channelStock: number + vipStock?: number specialWarehouseNote: string warehouseName?: string } @@ -228,6 +229,7 @@ class SupplyChainDiscontinuationSourceRepository { warehouseStock: number jingxiStock: number channelStock: number + vipStock: number specialWarehouseNote: string warehouseName: string }>(` @@ -259,6 +261,7 @@ class SupplyChainDiscontinuationSourceRepository { warehouse_name, CASE WHEN warehouse_name NOT LIKE N'%专用仓%' + AND warehouse_name NOT LIKE N'%唯品仓%' AND warehouse_name <> N'三方-南昌樵舍仓' AND warehouse_remark NOT IN (${excludedRemarks}) AND ( @@ -271,6 +274,7 @@ class SupplyChainDiscontinuationSourceRepository { END AS included_available, CASE WHEN warehouse_name NOT LIKE N'%专用仓%' + AND warehouse_name NOT LIKE N'%唯品仓%' AND warehouse_name <> N'三方-南昌樵舍仓' AND warehouse_remark NOT IN (${excludedRemarks}) AND ( @@ -310,15 +314,25 @@ class SupplyChainDiscontinuationSourceRepository { SUM( CASE WHEN inventory.warehouse_name LIKE N'%专用仓%' + AND inventory.warehouse_name NOT LIKE N'%唯品仓%' AND inventory.public_available > 0 THEN inventory.public_available ELSE 0 END ) AS channelStock, + SUM( + CASE + WHEN inventory.warehouse_name LIKE N'%唯品仓%' + AND inventory.public_available > 0 + THEN inventory.public_available + ELSE 0 + END + ) AS vipStock, ISNULL( STRING_AGG( CASE WHEN inventory.warehouse_name LIKE N'%专用仓%' + AND inventory.warehouse_name NOT LIKE N'%唯品仓%' AND inventory.public_available > 0 THEN inventory.warehouse_name END, @@ -337,7 +351,11 @@ class SupplyChainDiscontinuationSourceRepository { stockJianshang: Math.max(0, Number(row.warehouseStock ?? 0)), jingxiStock: Math.max(0, Number(row.jingxiStock ?? 0)), channelStock: Number(row.channelStock ?? 0), - specialWarehouseNote: String(row.specialWarehouseNote ?? ''), + vipStock: Math.max(0, Number(row.vipStock ?? 0)), + specialWarehouseNote: [ + String(row.specialWarehouseNote ?? '').trim(), + Number(row.vipStock ?? 0) > 0 ? '唯品仓-运营中心C' : '', + ].filter(Boolean).join('、'), warehouseName: String(row.warehouseName ?? ''), })) } @@ -383,6 +401,7 @@ class SupplyChainDiscontinuationSourceRepository { SUM(public_available) AS stockJianshang FROM inventory WHERE warehouse_name NOT LIKE N'%专用仓%' + AND warehouse_name NOT LIKE N'%唯品仓%' AND warehouse_name <> N'三方-南昌樵舍仓' AND warehouse_remark NOT IN (${excludedRemarks}) AND ( diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation-link-import.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation-link-import.test.ts index 8a67e37e..fea946c0 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation-link-import.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation-link-import.test.ts @@ -19,6 +19,14 @@ describe('discontinuation link import commit guard', () => { '简尚-分销部睢宁专用仓', '运营中心G', )).toBe(false) + expect(shouldExcludeDedicatedWarehouseLink( + '唯品仓-运营中心C', + '运营中心C', + )).toBe(true) + expect(shouldExcludeDedicatedWarehouseLink( + '唯品仓-运营中心C', + '运营中心A', + )).toBe(false) }) it('suppresses links owned by the same department as positive cloud stock', () => { diff --git a/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation.service.test.ts b/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation.service.test.ts index d502eb00..5d5e8ba9 100644 --- a/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/supply-chain-discontinuation.service.test.ts @@ -1266,6 +1266,38 @@ describe('buildDiscontinuationNoticeRows', () => { }) }) + it('creates a notice when only the VIP warehouse has stock and scopes it away from Operations C links', () => { + const rows = buildDiscontinuationNoticeRows({ + products: [{ + barcode: 'VIP-ONLY', + sku: 'VIP-SKU', + productStatus: '停产', + costPrice: '50', + }], + inventory: [{ + barcode: 'VIP-ONLY', + stockJianshang: 0, + jingxiStock: 0, + channelStock: 0, + vipStock: 5, + specialWarehouseNote: '唯品仓-运营中心C', + }], + factoryStock: [], + replacementRules: [], + activeVariants: [], + replacementStatusByBarcode: new Map(), + combos: [], + comboItems: [], + }) + + expect(rows[0]).toMatchObject({ + barcode: 'VIP-ONLY', + handlingNote: '全渠道下架', + replacementBarcode: '', + specialWarehouseNote: '唯品仓-运营中心C', + }) + }) + it('marks a Jingxi-only product as replacement when the replacement also has Jingxi stock', () => { const rows = buildDiscontinuationNoticeRows({ products: [ diff --git a/furniture-3d-system/src/server/services/supply-chain-discontinuation.builder.ts b/furniture-3d-system/src/server/services/supply-chain-discontinuation.builder.ts index 9b3b8121..a9c34ca3 100644 --- a/furniture-3d-system/src/server/services/supply-chain-discontinuation.builder.ts +++ b/furniture-3d-system/src/server/services/supply-chain-discontinuation.builder.ts @@ -242,12 +242,14 @@ export function buildDiscontinuationNoticeRows(input: { const stockJianshang = Math.max(0, Math.trunc(inventory?.stockJianshang ?? 0)) const jingxiStock = Math.max(0, Math.trunc(inventory?.jingxiStock ?? 0)) const channelStock = Math.max(0, Math.trunc(inventory?.channelStock ?? 0)) + const vipStock = Math.max(0, Math.trunc(inventory?.vipStock ?? 0)) const factory = factoryMap.get(barcode) const stockFactory = Math.max(0, Math.trunc(factory?.stockFactory ?? 0)) totalStockByBarcode.set(barcode, stockJianshang + stockFactory) if (stockJianshang + stockFactory !== 0) continue const onlyJingxi = - jingxiStock > 0 && stockJianshang + stockFactory + channelStock === 0 + jingxiStock > 0 + && stockJianshang + stockFactory + channelStock + vipStock === 0 const productSku = code(product.sku) const matchedRule = latestBySourceCode.get(barcode) @@ -281,7 +283,7 @@ export function buildDiscontinuationNoticeRows(input: { input.replacementStatusByBarcode.get(code(variant.barcode)) ?? variant.productStatus const productHasNoStock = - stockJianshang + stockFactory + channelStock + jingxiStock === 0 + stockJianshang + stockFactory + channelStock + jingxiStock + vipStock === 0 const productIsUnavailable = ['停产', '退市'].includes(product.productStatus.trim()) const isFxReplacementCode = (value: string) => code(value).includes('FX-') @@ -533,8 +535,10 @@ export function buildDiscontinuationNoticeRows(input: { const stockFactory = Math.max(0, Math.trunc(factory?.stockFactory ?? 0)) const channelStock = Math.max(0, Math.trunc(inventory?.channelStock ?? 0)) const jingxiStock = Math.max(0, Math.trunc(inventory?.jingxiStock ?? 0)) + const vipStock = Math.max(0, Math.trunc(inventory?.vipStock ?? 0)) const onlyJingxi = - jingxiStock > 0 && stockJianshang + stockFactory + channelStock === 0 + jingxiStock > 0 + && stockJianshang + stockFactory + channelStock + vipStock === 0 const hasReplacement = hasBlockingReplacementComponent(comboCode) rows.push({ barcode: combo.comboCode, From 7bf2a17ad0f7ca2b3a19c810af180deee8bf90f1 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Tue, 24 Nov 2026 13:13:36 +0800 Subject: [PATCH 4/4] feat(supplier): collapse high-cost category details --- .../SupplierManagementClient.test.tsx | 51 +++++++++++++++++++ .../SupplierManagementClient.tsx | 29 +++++++++-- .../legacy-purchase-modules.module.css | 18 +++++++ 3 files changed, 95 insertions(+), 3 deletions(-) diff --git a/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.test.tsx b/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.test.tsx index 19e7a920..f2f962c9 100644 --- a/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.test.tsx +++ b/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.test.tsx @@ -106,4 +106,55 @@ describe('SupplierManagementClient supply assurance', () => { expect(await screen.findByRole('button', { name: '能力画像' })).toBeInTheDocument() expect(screen.queryByRole('button', { name: '风险清单' })).not.toBeInTheDocument() }) + + it('collapses and expands the high-cost category details', async () => { + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + success: true, + data: [{ + supplierName: '高成本供应商', + supplierCode: 'SUP-HIGH', + grade: 'D', + gradeLabel: '成本显著偏高', + deviationRate: 0.2, + coverageRate: 1, + productCount: 5, + validPriceCount: 5, + categories: [{ + category: '板式 / 书桌', + productCount: 5, + validPriceCount: 5, + supplierMedianPrice: 120, + categoryBenchmarkPrice: 100, + deviationRate: 0.2, + grade: 'D', + }], + }], + }), + }) as Response + + const store = createLegacySupplierStore() + store.capabilities = [capability('SUP-HIGH', '高成本供应商', '开料')] + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: '采购成本评估' })) + await waitFor(() => expect(screen.getByRole('button', { name: '收合明细' })).toBeInTheDocument()) + expect(document.getElementById('high-cost-category-details')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: '收合明细' })) + expect(screen.getByRole('button', { name: '展开明细' })).toHaveAttribute('aria-expanded', 'false') + expect(document.getElementById('high-cost-category-details')).not.toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: '展开明细' })) + expect(screen.getByRole('button', { name: '收合明细' })).toHaveAttribute('aria-expanded', 'true') + expect(document.getElementById('high-cost-category-details')).toBeInTheDocument() + }) }) diff --git a/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.tsx b/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.tsx index ae92e2e9..c5dad4b2 100644 --- a/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.tsx +++ b/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/SupplierManagementClient.tsx @@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react' import Link from 'next/link' -import { Download, FileUp, Search } from 'lucide-react' +import { ChevronDown, ChevronUp, Download, FileUp, Search } from 'lucide-react' import type { LegacySupplierCapabilityRecord, LegacySupplierEquipmentRecord, @@ -209,6 +209,7 @@ export function SupplierManagementClient({ const [costAssessments, setCostAssessments] = useState([]) const [costLoading, setCostLoading] = useState(true) const [costError, setCostError] = useState('') + const [highCostExpanded, setHighCostExpanded] = useState(true) const [analysisTab, setAnalysisTab] = useState('capability') const [query, setQuery] = useState('') const [category, setCategory] = useState('all') @@ -509,8 +510,30 @@ export function SupplierManagementClient({
-

高成本材质 / 类目

优先复核采购价高于同材质、同二级类目基准的产品

{highCostCategories.length} 项
-
- setSelected( - allSelected ? [] : selectableRows.map((row) => row.taskId), - )} - aria-label="全选待审核申请" - /> - 清货负责人提交人申请时间商品编码清货商品编码商品名称销售状态优先级利润中心简尚库存工厂库存清货总量日销可用天数申请任务量申请折扣申请原因审核状态审核反馈总分数建议折扣上月折扣 + {column.key === 'select' ? ( + setSelected( + allSelected ? [] : selectableRows.map((row) => row.taskId), + )} + aria-label="全选待审核申请" + /> + ) : column.label} +
- setSelected((current) => ( - current.includes(row.taskId) - ? current.filter((id) => id !== row.taskId) - : [...current, row.taskId] - ))} - aria-label={`选择 ${row.barcode} ${row.submittedByName}`} - /> - {row.ownerName || '—'}{row.submittedByName || '—'}{new Date(row.submittedAt).toLocaleString('zh-CN', { hour12: false })}{row.barcode}{row.clearanceCode}{row.productName || '—'}{row.salesStatus || '—'}{row.priority || '—'}{row.profitCenter || '—'}{row.stockJianshang}{row.stockFactory}{row.clearanceTotal == null ? '—' : row.clearanceTotal}{row.dailySales == null ? '—' : row.dailySales}{row.availableDays || '—'} - setReviewValues((current) => ({ - ...current, - [row.taskId]: { - taskQty: event.target.value, - discount: current[row.taskId]?.discount - ?? String(Number((row.discount * 10).toFixed(1))), - }, - }))} - /> - - setReviewValues((current) => ({ - ...current, - [row.taskId]: { - taskQty: current[row.taskId]?.taskQty ?? String(row.taskQty), - discount: event.target.value, - }, - }))} - /> - 折 - {row.reason || '—'} - {row.statusLabel || row.reviewDecisionLabel || row.status} - {row.duplicateGroupSize > 1 && ( - - 重复申请 ×{row.duplicateGroupSize} - - )} - {row.reviewDecisionLabel && row.reviewDecisionLabel !== row.statusLabel && ( - - {row.reviewDecisionLabel} - - )} - {row.reviewAdjustment?.summary && ( - - 经管修改:{row.reviewAdjustment.summary} - - )} - - {row.rejectReason || '—'} - {numberText(row.totalScore)} - {row.suggestedDiscount == null - ? '—' - : `${Number((row.suggestedDiscount * 10).toFixed(1))}折`} - - {row.previousMonthDiscount == null - ? '—' - : `${Number((row.previousMonthDiscount * 10).toFixed(1))}折`} - + {renderReviewCell(row, column.key)} +
{highCostCategories.slice(0, 50).map(({ profile, category }) => )}
供应商材质 / 二级类目采购价中位同业基准偏差等级
{profile.supplier}{category.category}{category.supplierMedianPrice?.toFixed(2) || '—'}{category.categoryBenchmarkPrice?.toFixed(2) || '—'}{costDeviation(category.deviationRate)}{category.grade}
+
+

高成本材质 / 类目

优先复核采购价高于同材质、同二级类目基准的产品

+
+ {highCostCategories.length} 项 + +
+
+ {highCostExpanded ? ( +
+ + + {highCostCategories.slice(0, 50).map(({ profile, category }) => )} +
供应商材质 / 二级类目采购价中位同业基准偏差等级
{profile.supplier}{category.category}{category.supplierMedianPrice?.toFixed(2) || '—'}{category.categoryBenchmarkPrice?.toFixed(2) || '—'}{costDeviation(category.deviationRate)}{category.grade}
+
+ ) : null}
diff --git a/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/legacy-purchase-modules.module.css b/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/legacy-purchase-modules.module.css index 3b29db75..9f89f9bb 100644 --- a/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/legacy-purchase-modules.module.css +++ b/furniture-3d-system/src/app/supply-chain/purchase/legacy-modules/legacy-purchase-modules.module.css @@ -137,6 +137,24 @@ .panelHeader h2 { margin: 0; color: #27272a; font-size: 13px; } .panelHeader p { margin: 4px 0 0; color: #8b8b92; font-size: 10px; } +.panelHeaderActions { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px; } +.compactButton { + display: inline-flex; + height: 28px; + align-items: center; + justify-content: center; + gap: 5px; + border: 1px solid #d4d4d8; + border-radius: 6px; + background: #fff; + padding: 0 9px; + color: #3f3f46; + font: inherit; + font-size: 11px; + font-weight: 600; + cursor: pointer; +} +.compactButton:hover { border-color: #a1a1aa; background: #fafafa; } .toolbar { border-bottom: 1px solid #e4e4e7;