chore: checkpoint latest intake and warehouse changes

This commit is contained in:
Codex 2026-04-14 14:57:19 +08:00
parent 4c298983ff
commit 4de7ea9bfb
14 changed files with 1702 additions and 461 deletions

View File

@ -637,6 +637,7 @@ model AssetVariant {
inheritedFromVariantId String?
inheritedFromVariant AssetVariant? @relation("AssetVariantInheritance", fields: [inheritedFromVariantId], references: [id], onDelete: SetNull)
derivedVariants AssetVariant[] @relation("AssetVariantInheritance")
locationBindings AssetVariantLocationBinding[]
createdBy String?
creator User? @relation("AssetVariantCreator", fields: [createdBy], references: [id], onDelete: SetNull)
@ -800,6 +801,8 @@ model WarehouseLocation {
skus ProductSKU[] @relation("ProductSKUWarehouseLocation")
packagedItems PackagedItem[] @relation("PackagedItemWarehouseLocation")
assetVariantBindings AssetVariantLocationBinding[]
brandMaterialBindings BrandMaterialBinding[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@ -807,6 +810,38 @@ model WarehouseLocation {
@@index([isActive])
}
model AssetVariantLocationBinding {
id String @id @default(cuid())
assetVariantId String
warehouseLocationId String
assetVariant AssetVariant @relation(fields: [assetVariantId], references: [id], onDelete: Cascade)
warehouseLocation WarehouseLocation @relation(fields: [warehouseLocationId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
@@unique([assetVariantId, warehouseLocationId])
@@index([assetVariantId])
@@index([warehouseLocationId])
}
model BrandMaterialBinding {
id String @id @default(cuid())
brand String
materialType String
warehouseLocationId String?
warehouseLocation WarehouseLocation? @relation(fields: [warehouseLocationId], references: [id], onDelete: SetNull)
fileUrl String?
fileName String?
fileSize Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([brand, materialType])
@@index([brand])
@@index([warehouseLocationId])
}
model PackagedItem {
id String @id @default(cuid())
code String @unique

View File

@ -1,13 +1,10 @@
import { render, screen } from '@testing-library/react'
'use client'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReactNode } from 'react'
import IntakeClient from './IntakeClient'
jest.mock('next/link', () => ({
__esModule: true,
default: ({ href, children }: { href: string; children: ReactNode }) => <a href={href}>{children}</a>,
}))
jest.mock('@/components/platform/PlatformSplitLayout', () => ({
__esModule: true,
PlatformSplitLayout: ({
@ -18,8 +15,8 @@ jest.mock('@/components/platform/PlatformSplitLayout', () => ({
rightContent: ReactNode
}) => (
<div>
<div>{leftContent}</div>
<div>{rightContent}</div>
<div data-testid="left-panel">{leftContent}</div>
<div data-testid="right-panel">{rightContent}</div>
</div>
),
}))
@ -29,89 +26,225 @@ jest.mock('@/components/platform/AccordionSection', () => ({
AccordionSection: ({
title,
children,
onToggle,
}: {
title: ReactNode
children: ReactNode
onToggle?: () => void
}) => (
<section>
<h2>{title}</h2>
{children}
<button type="button" onClick={onToggle}>
{title}
</button>
<div>{children}</div>
</section>
),
}))
jest.mock('@/components/platform/ModelPreviewPanel', () => ({
__esModule: true,
ModelPreviewPanel: () => <div>ModelPreviewPanel</div>,
}))
jest.mock('@/components/ui/Modal', () => ({
__esModule: true,
default: ({
isOpen,
title,
children,
footer,
}: {
isOpen: boolean
title: ReactNode
children: ReactNode
footer?: ReactNode
}) =>
isOpen ? (
<div>
<h2>{title}</h2>
{children}
{footer}
</div>
) : null,
}))
jest.mock('@/lib/open-product/platform-view', () => ({
__esModule: true,
readPreviewNodes: () => [],
}))
jest.mock('@/lib/open-product/platform-api', () => ({
jest.mock('@/components/platform/ModelPreviewPanel', () => ({
__esModule: true,
formalizeDraftGroup: jest.fn(),
ModelPreviewPanel: ({
title,
emptyTitle,
emptyDescription,
}: {
title?: string
emptyTitle?: string
emptyDescription?: string
}) => (
<div>
<div>{title ?? '3D 预览'}</div>
<div>{emptyTitle}</div>
<div>{emptyDescription}</div>
</div>
),
}))
jest.mock('@/components/ui/Input', () => {
const React = require('react')
const Input = React.forwardRef(function MockInput(
{
label,
value,
onChange,
...props
}: {
label?: string
value?: string
onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void
[key: string]: unknown
},
ref: React.Ref<HTMLInputElement>,
) {
return (
<label>
<span>{label}</span>
<input ref={ref} value={value} onChange={onChange} {...props} />
</label>
describe('IntakeClient', () => {
it('右侧栏使用新的 5 个执行阶段名称', () => {
render(
<IntakeClient
user={{
id: 'user-1',
name: 'Test User',
email: 'test@example.com',
role: 'SUPER_ADMIN',
avatar: null,
department: null,
}}
metrics={[]}
eligibleDraftGroups={[
{
id: 'draft-group-1',
name: '云序-草稿组',
seriesTemplateName: '单板桌',
code: 'DG-001',
},
]}
draftGroupId={null}
hasIneligibleSelected={false}
/>,
)
const rightPanel = screen.getByTestId('right-panel')
const expectedSections = ['待执行 SKU', '执行准备', '包装执行', 'BOM 清单', '质检确认']
const sectionButtons = within(rightPanel)
.getAllByRole('button')
.map((button) => button.textContent)
.filter((text): text is string => expectedSections.includes(text ?? ''))
expect(sectionButtons).toEqual([
'待执行 SKU',
'执行准备',
'包装执行',
'BOM 清单',
'质检确认',
])
expect(screen.queryByRole('button', { name: '拣货打印' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '品牌物料' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '当前 SKU 配件清单' })).not.toBeInTheDocument()
})
Input.displayName = 'MockInput'
it('点击待执行 SKU 后,中间展示状态筛选、搜索区和表格列表', async () => {
const actor = userEvent.setup()
return {
__esModule: true,
default: Input,
}
})
render(
<IntakeClient
user={{
id: 'user-1',
name: 'Test User',
email: 'test@example.com',
role: 'SUPER_ADMIN',
avatar: null,
department: null,
}}
metrics={[]}
eligibleDraftGroups={[
{
id: 'draft-group-1',
name: '云序-草稿组',
seriesTemplateName: '单板桌',
code: 'DG-001',
},
]}
draftGroupId={null}
hasIneligibleSelected={false}
/>,
)
describe('IntakeClient', () => {
it('新建 SPU 使用弹窗承载,并可把结果回填到入库去向区', async () => {
await actor.click(screen.getByRole('button', { name: '待执行 SKU' }))
const leftPanel = screen.getByTestId('left-panel')
expect(screen.getByText('待执行 SKU 明细')).toBeInTheDocument()
expect(within(leftPanel).getByRole('button', { name: '未操作' })).toBeInTheDocument()
expect(within(leftPanel).getByRole('button', { name: '已操作' })).toBeInTheDocument()
expect(within(leftPanel).getAllByRole('button', { name: '暂缓' }).length).toBeGreaterThan(0)
expect(screen.getByPlaceholderText('搜索 SPU')).toBeInTheDocument()
expect(screen.getByPlaceholderText('搜索 SKU')).toBeInTheDocument()
expect(screen.getByPlaceholderText('搜索系列')).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '编号' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '图片' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: 'SKU' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: 'SPU' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '系列' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '状态' })).toBeInTheDocument()
})
it('点击执行准备后,中间展示摘要、配件明细和品牌资料', async () => {
const actor = userEvent.setup()
render(
<IntakeClient
user={{
id: 'user-1',
name: 'Test User',
email: 'test@example.com',
role: 'SUPER_ADMIN',
avatar: null,
department: null,
}}
metrics={[]}
detail={{
draftGroup: {
id: 'draft-group-1',
name: '云序-草稿组',
categoryId: 'category-desk',
seriesTemplateName: '单板桌',
categoryName: '桌类',
code: 'DG-001',
},
preSkus: [
{
id: 'pre-sku-1',
status: 'PACKAGING',
customName: '测试 SKU',
defaultName: '桌面A+桌腿A',
componentCodes: ['BOARD-A', 'LEG-A'],
previewNodes: [],
},
],
} as never}
recommendedProducts={[] as never}
locations={[] as never}
categories={[] as never}
defaultAttachProductId={null}
/>,
)
await actor.click(screen.getByRole('button', { name: '执行准备' }))
expect(screen.getByText('执行准备明细')).toBeInTheDocument()
expect(screen.getByText('SPU')).toBeInTheDocument()
expect(screen.getByText('SKU')).toBeInTheDocument()
expect(screen.getByText('品牌')).toBeInTheDocument()
expect(screen.getByText('SKU 配件明细')).toBeInTheDocument()
expect(screen.getByText('品牌资料明细')).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '配件类型' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '编码' })).toBeInTheDocument()
expect(screen.getAllByText('品牌识别结果').length).toBeGreaterThan(0)
})
it('未选草稿组时,点击包装执行后,中间也会切换成 3D 预览窗口', async () => {
const actor = userEvent.setup()
render(
<IntakeClient
user={{
id: 'user-1',
name: 'Test User',
email: 'test@example.com',
role: 'SUPER_ADMIN',
avatar: null,
department: null,
}}
metrics={[]}
eligibleDraftGroups={[
{
id: 'draft-group-1',
name: '云序-草稿组',
seriesTemplateName: '单板桌',
code: 'DG-001',
},
]}
draftGroupId={null}
hasIneligibleSelected={false}
/>,
)
expect(screen.getByText('正式入库工作区')).toBeInTheDocument()
await actor.click(screen.getByRole('button', { name: '包装执行' }))
expect(screen.getByText('包装执行 3D 预览')).toBeInTheDocument()
expect(screen.getByText('待承接已确认 SKU 模型')).toBeInTheDocument()
})
it('点击包装执行后,中间切换成 3D 预览窗口', async () => {
const actor = userEvent.setup()
render(
@ -136,43 +269,131 @@ describe('IntakeClient', () => {
preSkus: [
{
id: 'pre-sku-1',
status: 'DRAFT',
customName: null,
status: 'PACKAGING',
customName: '测试 SKU',
defaultName: '桌面A+桌腿A',
componentCodes: ['BOARD-A', 'LEG-A'],
previewNodes: [],
},
],
} as never}
recommendedProducts={[
{
id: 'product-1',
modelNumber: 'SPU-001',
name: '单板桌 A',
},
] as never}
locations={[]}
categories={
[
{
id: 'category-desk',
name: '桌类',
},
] as never
}
recommendedProducts={[] as never}
locations={[] as never}
categories={[] as never}
defaultAttachProductId={null}
/>,
)
await actor.click(screen.getByRole('button', { name: /没有合适的?新建 SPU/ }))
expect(screen.getByText('新建 SPU')).toBeInTheDocument()
expect(screen.getByText('正式入库工作区')).toBeInTheDocument()
expect(screen.queryByText('包装执行 3D 预览')).not.toBeInTheDocument()
const nameInput = screen.getByLabelText('正式 SPU 名称')
await actor.clear(nameInput)
await actor.type(nameInput, '测试 SPU')
await actor.click(screen.getByRole('button', { name: '创建并关联' }))
await actor.click(screen.getByRole('button', { name: '包装执行' }))
expect(screen.getByText('将新建 SPU:测试 SPU')).toBeInTheDocument()
expect(screen.getByRole('button', { name: '改为挂已有 SPU' })).toBeInTheDocument()
expect(screen.getByText('包装执行 3D 预览')).toBeInTheDocument()
expect(screen.getByText('待承接已确认 SKU 模型')).toBeInTheDocument()
expect(
screen.getByText('这里先保留 3D 预览窗口,后续承接草稿组里已经确认好的 SKU 模型。'),
).toBeInTheDocument()
})
it('uses draft-group SPU and SKU values in pending detail', async () => {
const actor = userEvent.setup()
render(
<IntakeClient
user={{
id: 'user-1',
name: 'Test User',
email: 'test@example.com',
role: 'SUPER_ADMIN',
avatar: null,
department: null,
}}
metrics={[]}
detail={{
draftGroup: {
id: 'draft-group-1',
name: 'Single board desk',
categoryId: 'category-desk',
seriesTemplateName: '',
categoryName: 'Desk',
code: 'DG-001',
},
preSkus: [
{
id: 'pre-sku-1',
status: 'PACKAGING',
customName: null,
defaultName: 'Fallback SKU',
componentCodes: ['SPJ-ZMB0001', 'SPJ-ZT0001'],
previewNodes: [],
familySelection: {
seriesName: 'Single board desk',
},
displaySummary: {
spuCode: 'GBGJ-DNZ0001',
skuCode: 'GBGJ-DNZ000101',
},
},
],
} as never}
recommendedProducts={[] as never}
locations={[] as never}
categories={[] as never}
defaultAttachProductId={null}
/>,
)
await actor.click(screen.getByText('待执行 SKU'))
expect(screen.getByText('GBGJ-DNZ0001')).toBeInTheDocument()
expect(screen.getByText('GBGJ-DNZ000101')).toBeInTheDocument()
expect(screen.getAllByText('Single board desk').length).toBeGreaterThan(0)
})
it('shows real draft-group sku data in selector mode when eligible sku list is provided', async () => {
const actor = userEvent.setup()
render(
<IntakeClient
user={{
id: 'user-1',
name: 'Test User',
email: 'test@example.com',
role: 'SUPER_ADMIN',
avatar: null,
department: null,
}}
metrics={[]}
eligibleDraftGroups={[
{
id: 'draft-group-1',
name: 'Single board desk',
seriesTemplateName: '',
code: 'DG-001',
},
]}
eligibleSkuList={[
{
id: 'pre-sku-1',
spuCode: 'GBGJ-DNZ0001',
code: 'GBGJ-DNZ000101',
name: 'Test SKU',
seriesName: 'Single board desk',
draftGroupName: 'Single board desk',
status: '待确认',
componentCodes: [],
},
]}
draftGroupId={null}
hasIneligibleSelected={false}
/>,
)
await actor.click(screen.getByText('待执行 SKU'))
expect(screen.getByText('GBGJ-DNZ0001')).toBeInTheDocument()
expect(screen.getByText('GBGJ-DNZ000101')).toBeInTheDocument()
expect(screen.getAllByText('Single board desk').length).toBeGreaterThan(0)
})
})

View File

@ -1,15 +1,7 @@
'use client'
'use client'
import { useMemo, useState } from 'react'
import {
Boxes,
PackageCheck,
PackageOpen,
PackagePlus,
Printer,
Upload,
Warehouse,
} from 'lucide-react'
import { Boxes, PackageCheck, PackagePlus, Printer, Upload } from 'lucide-react'
import { Badge } from '@/components/ui/Badge'
import Button from '@/components/ui/Button'
import { PlatformSplitLayout } from '@/components/platform/PlatformSplitLayout'
@ -35,6 +27,7 @@ interface IntakeClientSelectorProps {
}
metrics: PlatformMetricItem[]
eligibleDraftGroups: { id: string; name: string; seriesTemplateName: string; code: string }[]
eligibleSkuList?: WorkbenchSku[]
draftGroupId: string | null
hasIneligibleSelected: boolean
}
@ -57,13 +50,18 @@ interface IntakeClientEditorProps {
}
type IntakeClientProps = IntakeClientSelectorProps | IntakeClientEditorProps
type IntakeSection = 'pending' | 'components' | 'picking' | 'brand' | 'packaging' | null
type IntakeSection = 'pending' | 'preparation' | 'packaging' | 'bom' | 'quality' | null
type PendingTabKey = 'pending' | 'completed' | 'paused'
type WorkbenchSku = {
id: string
spuCode: string
code: string
name: string
seriesName: string
draftGroupName: string
status: string
componentCodes: string[]
}
type PickingRow = {
@ -84,6 +82,20 @@ function buildSkuCode(seed: string, index: number) {
return `SKU-${String(index + 1).padStart(3, '0')}-${seed.slice(-4).toUpperCase()}`
}
function readPreSkuTextField(preSku: DraftGroupDetailDTO['preSkus'][number], key: string) {
const displayValue = preSku.displaySummary?.[key]
if (typeof displayValue === 'string' && displayValue.trim().length > 0) {
return displayValue.trim()
}
const familyValue = preSku.familySelection?.[key]
if (typeof familyValue === 'string' && familyValue.trim().length > 0) {
return familyValue.trim()
}
return ''
}
function mapStatus(status: string) {
if (status === 'FORMALIZED') return '已完成'
if (status === 'READY_FOR_INTAKE') return '待执行'
@ -91,12 +103,19 @@ function mapStatus(status: string) {
return '待处理'
}
function detectBrandName(skuCode: string) {
if (skuCode.startsWith('GBSFY')) return '索菲亚'
if (skuCode.startsWith('GBGJ')) return '顾家'
if (skuCode.startsWith('GBPM')) return '朴美'
if (skuCode.startsWith('GBBP')) return '白牌'
return '按 SKU 前缀识别'
function detectBrandName(spuCode: string) {
if (spuCode.startsWith('GBSFY-')) return '索菲亚'
if (spuCode.startsWith('GBGJ-')) return '顾家'
if (spuCode.startsWith('GBPM-')) return '品美'
if (spuCode.startsWith('GBBP-')) return '白牌'
if (spuCode.startsWith('DNZ')) return '白牌'
return '按 SPU 前缀识别'
}
function mapPendingTab(status: string): PendingTabKey {
if (status === '已完成') return 'completed'
if (status === '暂缓') return 'paused'
return 'pending'
}
function toggleSection(current: IntakeSection, section: Exclude<IntakeSection, null>) {
@ -124,51 +143,294 @@ function DetailPanel({
}
function PendingSkuDetail({ skuList }: { skuList: WorkbenchSku[] }) {
const [activeTab, setActiveTab] = useState<PendingTabKey>('pending')
const [spuKeyword, setSpuKeyword] = useState('')
const [skuKeyword, setSkuKeyword] = useState('')
const [seriesKeyword, setSeriesKeyword] = useState('')
const filteredList = useMemo(() => {
return skuList.filter((sku) => {
if (mapPendingTab(sku.status) !== activeTab) return false
const spuMatched =
spuKeyword.trim().length === 0 ||
sku.spuCode.toLowerCase().includes(spuKeyword.trim().toLowerCase())
const skuMatched =
skuKeyword.trim().length === 0 ||
sku.code.toLowerCase().includes(skuKeyword.trim().toLowerCase()) ||
sku.name.toLowerCase().includes(skuKeyword.trim().toLowerCase())
const seriesMatched =
seriesKeyword.trim().length === 0 ||
sku.seriesName.toLowerCase().includes(seriesKeyword.trim().toLowerCase())
return spuMatched && skuMatched && seriesMatched
})
}, [activeTab, seriesKeyword, skuKeyword, skuList, spuKeyword])
const tabOptions: { key: PendingTabKey; label: string }[] = [
{ key: 'pending', label: '未操作' },
{ key: 'completed', label: '已操作' },
{ key: 'paused', label: '暂缓' },
]
return (
<DetailPanel title="待执行 SKU 明细" description="这里承载本次要执行的 SKU 列表和基础状态。">
<div className="space-y-3">
<DetailPanel title="待执行 SKU 明细" description="先按状态和条件找到要处理的 SKU,再进入后续业务动作。">
<div className="space-y-4">
<div className="flex flex-wrap gap-2">
{tabOptions.map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => setActiveTab(tab.key)}
className={`rounded-apple-lg border px-4 py-2 text-sm transition ${
activeTab === tab.key
? 'border-apple-blue bg-apple-blue/10 text-apple-blue'
: 'border-apple-separator bg-apple-bg-secondary text-apple-label-secondary'
}`}
>
{tab.label}
</button>
))}
</div>
<div className="grid gap-3 rounded-apple-xl border border-apple-separator bg-apple-bg-secondary p-4 md:grid-cols-4">
<label className="space-y-2 text-sm text-apple-label-secondary">
<span>SPU</span>
<input
value={spuKeyword}
onChange={(event) => setSpuKeyword(event.target.value)}
placeholder="搜索 SPU"
className="w-full rounded-apple-lg border border-apple-separator bg-apple-bg-primary px-3 py-2 text-sm text-apple-label-primary outline-none"
/>
</label>
<label className="space-y-2 text-sm text-apple-label-secondary">
<span>SKU</span>
<input
value={skuKeyword}
onChange={(event) => setSkuKeyword(event.target.value)}
placeholder="搜索 SKU"
className="w-full rounded-apple-lg border border-apple-separator bg-apple-bg-primary px-3 py-2 text-sm text-apple-label-primary outline-none"
/>
</label>
<label className="space-y-2 text-sm text-apple-label-secondary">
<span>系列</span>
<input
value={seriesKeyword}
onChange={(event) => setSeriesKeyword(event.target.value)}
placeholder="搜索系列"
className="w-full rounded-apple-lg border border-apple-separator bg-apple-bg-primary px-3 py-2 text-sm text-apple-label-primary outline-none"
/>
</label>
<div className="flex items-end gap-2">
<Button className="flex-1">搜索</Button>
<Button
variant="plain"
className="flex-1"
onClick={() => {
setSpuKeyword('')
setSkuKeyword('')
setSeriesKeyword('')
}}
>
重置
</Button>
</div>
</div>
{skuList.length === 0 ? (
<div className="rounded-apple-lg border border-dashed border-apple-separator px-4 py-5 text-sm leading-7 text-apple-label-secondary">
当前还没有草稿组。先去辅助装配完成手动拼装,或回到草稿组继续补齐资料。
</div>
) : (
skuList.map((sku) => (
<div
key={sku.id}
className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-4 py-3"
>
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-sm font-apple-semibold text-apple-label-primary">{sku.code}</p>
<p className="mt-1 text-sm text-apple-label-secondary">{sku.name}</p>
</div>
<Badge type="info" variant="subtle">
{sku.status}
</Badge>
</div>
</div>
))
<div className="overflow-hidden rounded-apple-xl border border-apple-separator">
<table className="min-w-full text-left text-sm">
<thead className="bg-apple-bg-secondary text-apple-label-secondary">
<tr>
<th className="px-3 py-3 font-apple-medium">编号</th>
<th className="px-3 py-3 font-apple-medium">图片</th>
<th className="px-3 py-3 font-apple-medium">SKU</th>
<th className="px-3 py-3 font-apple-medium">SPU</th>
<th className="px-3 py-3 font-apple-medium">系列</th>
<th className="px-3 py-3 font-apple-medium">状态</th>
<th className="px-3 py-3 font-apple-medium">操作</th>
</tr>
</thead>
<tbody>
{filteredList.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-8 text-center text-sm text-apple-label-secondary">
当前筛选条件下没有找到 SKU。
</td>
</tr>
) : (
filteredList.map((sku, index) => (
<tr key={sku.id} className="border-t border-apple-separator">
<td className="px-3 py-3 text-apple-label-secondary">{index + 1}</td>
<td className="px-3 py-3">
<div className="flex h-14 w-14 items-center justify-center rounded-apple-lg border border-apple-separator bg-apple-bg-secondary text-xs text-apple-label-secondary">
SKU 图
</div>
</td>
<td className="px-3 py-3">
<p className="font-apple-medium text-apple-label-primary">{sku.code}</p>
<p className="mt-1 text-xs text-apple-label-secondary">{sku.name}</p>
</td>
<td className="px-3 py-3 text-apple-label-primary">{sku.spuCode}</td>
<td className="px-3 py-3 text-apple-label-primary">{sku.seriesName}</td>
<td className="px-3 py-3">
<Badge type="info" variant="subtle">
{sku.status}
</Badge>
</td>
<td className="px-3 py-3">
<div className="flex gap-2">
<Button size="small">查看</Button>
<Button variant="plain" size="small">
暂缓
</Button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
)}
</div>
</DetailPanel>
)
}
function ComponentDetail({ componentCodes }: { componentCodes: string[] }) {
function PreparationDetail({ skuList }: { skuList: WorkbenchSku[] }) {
const spuOptions = Array.from(
new Map(skuList.map((sku) => [sku.spuCode, { code: sku.spuCode, seriesName: sku.seriesName }])).values(),
)
const [selectedSpuCode, setSelectedSpuCode] = useState(spuOptions[0]?.code ?? '')
const skuOptions = skuList.filter((sku) => sku.spuCode === selectedSpuCode)
const [selectedSkuId, setSelectedSkuId] = useState(skuOptions[0]?.id ?? '')
const currentSku =
skuOptions.find((sku) => sku.id === selectedSkuId) ?? skuOptions[0] ?? skuList[0] ?? null
const brandName = detectBrandName(selectedSpuCode)
const materialRows = BRAND_FILES.map((item, index) => ({
name: item,
status: currentSku ? (index < 2 ? '已匹配' : '待补充') : '待补充',
}))
return (
<DetailPanel title="当前 SKU 配件清单" description="这里只展示这个 SKU 下面要拿的核心配件编码。">
<div className="space-y-3">
{COMPONENT_LABELS.map((label, index) => (
<div
key={label}
className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-4 py-3"
>
<p className="text-sm font-apple-medium text-apple-label-primary">{label}:编码</p>
<p className="mt-1 text-sm text-apple-label-secondary">
{componentCodes[index] || '待带入'}
</p>
<DetailPanel title="执行准备明细" description="先选 SPU,再选这个 SPU 下的 SKU,系统会自动识别品牌并展示准备信息。">
<div className="space-y-4">
<div className="grid gap-3 rounded-apple-xl border border-apple-separator bg-apple-bg-secondary p-4 md:grid-cols-4">
<label className="space-y-2">
<span className="text-xs text-apple-label-secondary">SPU</span>
<select
value={selectedSpuCode}
onChange={(event) => {
setSelectedSpuCode(event.target.value)
const nextSku = skuList.find((sku) => sku.spuCode === event.target.value)
setSelectedSkuId(nextSku?.id ?? '')
}}
className="w-full rounded-apple-lg border border-apple-separator bg-apple-bg-primary px-3 py-2 text-sm text-apple-label-primary outline-none"
>
{spuOptions.map((option) => (
<option key={option.code} value={option.code}>
{option.code}
</option>
))}
</select>
</label>
<label className="space-y-2">
<span className="text-xs text-apple-label-secondary">SKU</span>
<select
value={currentSku?.id ?? ''}
onChange={(event) => setSelectedSkuId(event.target.value)}
className="w-full rounded-apple-lg border border-apple-separator bg-apple-bg-primary px-3 py-2 text-sm text-apple-label-primary outline-none"
>
{skuOptions.map((sku) => (
<option key={sku.id} value={sku.id}>
{sku.code}
</option>
))}
</select>
</label>
<div>
<p className="text-xs text-apple-label-secondary">品牌</p>
<p className="mt-1 text-sm font-apple-medium text-apple-label-primary">{brandName}</p>
</div>
))}
<div>
<p className="text-xs text-apple-label-secondary">状态</p>
<div className="mt-1">
<Badge type="info" variant="subtle">
{currentSku?.status || '待确认'}
</Badge>
</div>
</div>
</div>
<div className="grid gap-4 xl:grid-cols-[1.2fr_0.8fr]">
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary p-4">
<div className="mb-3">
<h4 className="text-sm font-apple-semibold text-apple-label-primary">SKU 配件明细</h4>
<p className="mt-1 text-xs text-apple-label-secondary">用于确认当前 SKU 需要准备的核心配件编码。</p>
</div>
<div className="overflow-hidden rounded-apple-lg border border-apple-separator">
<table className="min-w-full text-left text-sm">
<thead className="bg-apple-bg-primary text-apple-label-secondary">
<tr>
<th className="px-3 py-2 font-apple-medium">配件类型</th>
<th className="px-3 py-2 font-apple-medium">编码</th>
<th className="px-3 py-2 font-apple-medium">状态</th>
</tr>
</thead>
<tbody>
{COMPONENT_LABELS.map((label, index) => {
const code = currentSku?.componentCodes[index] || '待补充'
return (
<tr key={label} className="border-t border-apple-separator">
<td className="px-3 py-3 text-apple-label-primary">{label}</td>
<td className="px-3 py-3 text-apple-label-secondary">{code}</td>
<td className="px-3 py-3">
<Badge type="info" variant="subtle">
{currentSku?.componentCodes[index] ? '已识别' : '待补充'}
</Badge>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary p-4">
<div className="mb-3">
<h4 className="text-sm font-apple-semibold text-apple-label-primary">品牌资料明细</h4>
<p className="mt-1 text-xs text-apple-label-secondary">品牌由 SPU 前缀自动识别,不需要手动再选。</p>
</div>
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-primary px-4 py-3">
<p className="text-xs text-apple-label-secondary">品牌识别结果</p>
<p className="mt-1 text-sm font-apple-medium text-apple-label-primary">{brandName}</p>
</div>
<div className="mt-3 space-y-2">
{materialRows.map((item) => (
<div
key={item.name}
className="flex items-center justify-between rounded-apple-lg border border-apple-separator bg-apple-bg-primary px-4 py-3"
>
<div>
<p className="text-sm text-apple-label-primary">{item.name}</p>
<p className="mt-1 text-xs text-apple-label-secondary">{item.status}</p>
</div>
<Button variant="plain" size="small">
查看
</Button>
</div>
))}
</div>
</div>
</div>
</div>
</DetailPanel>
)
@ -176,7 +438,7 @@ function ComponentDetail({ componentCodes }: { componentCodes: string[] }) {
function PickingDetail({ pickingRows }: { pickingRows: PickingRow[] }) {
return (
<DetailPanel title="拣货打印预览" description="先在这里看表格预览,确认后再执行打印。">
<DetailPanel title="BOM 清单预览" description="这里先用表格展示当前 SKU 的明细、库位和数量。">
<div className="space-y-4">
<div className="overflow-hidden rounded-apple-lg border border-apple-separator">
<table className="min-w-full text-left text-xs">
@ -211,9 +473,9 @@ function PickingDetail({ pickingRows }: { pickingRows: PickingRow[] }) {
)
}
function BrandDetail({ brandName }: { brandName: string }) {
function QualityDetail({ brandName }: { brandName: string }) {
return (
<DetailPanel title="品牌物料明细" description="根据 SKU 前缀识别品牌,并在这里承载资料和上传入口。">
<DetailPanel title="质检确认明细" description="这里先预留质检资料与确认入口。">
<div className="space-y-4">
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-4 py-3">
<p className="text-sm font-apple-medium text-apple-label-primary">品牌识别结果</p>
@ -227,7 +489,7 @@ function BrandDetail({ brandName }: { brandName: string }) {
>
<span className="text-sm text-apple-label-primary">{item}</span>
<Button variant="plain" size="small">
上传
查看
</Button>
</div>
))}
@ -239,7 +501,7 @@ function BrandDetail({ brandName }: { brandName: string }) {
function EmptyDetail() {
return (
<DetailPanel title="正式入库工作区" description="点击右侧任意模块后,这里显示对应的详细明细。">
<DetailPanel title="正式入库工作区" description="点击右侧任意模块后,这里显示对应的详细内容。">
<div className="flex h-full min-h-[320px] items-center justify-center rounded-apple-lg border border-dashed border-apple-separator bg-apple-bg-secondary px-6 text-center text-sm leading-7 text-apple-label-secondary">
右侧 5 个模块默认闭合。点开哪一块,这里就显示哪一块的详细内容。只有点到“包装执行”时,这里才切换成 3D 预览窗口。
</div>
@ -250,7 +512,7 @@ function EmptyDetail() {
function FormalIntakeWorkbench({
activeSection,
onToggle,
skuList,
skuList: _skuList,
}: {
activeSection: IntakeSection
onToggle: (section: Exclude<IntakeSection, null>) => void
@ -260,128 +522,38 @@ function FormalIntakeWorkbench({
<div className="space-y-4">
<AccordionSection
title="待执行 SKU"
description="先看这次要执行的 SKU。"
icon={<PackagePlus className="h-4 w-4" />}
expanded={activeSection === 'pending'}
onToggle={() => onToggle('pending')}
>
<div className="space-y-3">
{skuList.length === 0 ? (
<div className="rounded-apple-lg border border-dashed border-apple-separator px-3 py-4 text-sm leading-7 text-apple-label-secondary">
当前还没有待执行的 SKU。
</div>
) : (
skuList.slice(0, 3).map((sku) => (
<div
key={sku.id}
className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-3"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="text-sm font-apple-semibold text-apple-label-primary">
SKU编码:{sku.code}
</p>
<p className="mt-1 text-xs text-apple-label-secondary">SKU名称:{sku.name}</p>
</div>
<Badge type="info" variant="subtle">
{sku.status}
</Badge>
</div>
<div className="mt-3 flex justify-end">
<Button size="small">执行</Button>
</div>
</div>
))
)}
</div>
</AccordionSection>
/>
<AccordionSection
title="当前 SKU 配件清单"
description="展示这个 SKU 下面要拿的核心配件编码。"
title="执行准备"
icon={<Boxes className="h-4 w-4" />}
expanded={activeSection === 'components'}
onToggle={() => onToggle('components')}
>
<div className="space-y-2">
{COMPONENT_LABELS.map((label) => (
<div
key={label}
className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2"
>
<p className="text-sm text-apple-label-primary">{label}:编码</p>
<p className="mt-1 text-xs text-apple-label-secondary">点击后在左侧查看详细内容</p>
</div>
))}
</div>
</AccordionSection>
<AccordionSection
title="拣货打印"
description="先看表格预览,确认后打印。"
icon={<Printer className="h-4 w-4" />}
expanded={activeSection === 'picking'}
onToggle={() => onToggle('picking')}
>
<div className="space-y-3">
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-3 text-xs text-apple-label-secondary">
这里会显示 SKU编码、配件编码、库位、数量。先看表格预览,没问题再打印。
</div>
<div className="flex gap-2">
<Button variant="plain" className="flex-1">
表格预览
</Button>
<Button className="flex-1">打印按钮</Button>
</div>
</div>
</AccordionSection>
<AccordionSection
title="品牌物料"
description="根据 SKU 前缀识别品牌,带出需要的资料。"
icon={<Upload className="h-4 w-4" />}
expanded={activeSection === 'brand'}
onToggle={() => onToggle('brand')}
>
<div className="space-y-2">
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-3">
<p className="text-sm text-apple-label-primary">品牌识别结果</p>
<p className="mt-1 text-xs text-apple-label-secondary">根据 SKU 前缀自动识别</p>
</div>
{BRAND_FILES.map((item) => (
<div
key={item}
className="flex items-center justify-between rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2"
>
<span className="text-sm text-apple-label-primary">{item}</span>
<Button variant="plain" size="small">
上传
</Button>
</div>
))}
</div>
</AccordionSection>
expanded={activeSection === 'preparation'}
onToggle={() => onToggle('preparation')}
/>
<AccordionSection
title="包装执行"
description="根据包装方案进行打包。"
icon={<PackageCheck className="h-4 w-4" />}
expanded={activeSection === 'packaging'}
onToggle={() => onToggle('packaging')}
>
<div className="space-y-3">
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-3">
<p className="text-sm text-apple-label-primary">包装方案状态</p>
<p className="mt-1 text-xs text-apple-label-secondary">点击后左侧切换成 3D 包装预览</p>
</div>
<div className="grid gap-2">
<Button variant="plain">包装示意图</Button>
<Button variant="plain">打印包装图</Button>
<Button>开始打包</Button>
<Button variant="plain">完成打包</Button>
</div>
</div>
</AccordionSection>
/>
<AccordionSection
title="BOM 清单"
icon={<Printer className="h-4 w-4" />}
expanded={activeSection === 'bom'}
onToggle={() => onToggle('bom')}
/>
<AccordionSection
title="质检确认"
icon={<Upload className="h-4 w-4" />}
expanded={activeSection === 'quality'}
onToggle={() => onToggle('quality')}
/>
</div>
)
}
@ -390,18 +562,44 @@ export default function IntakeClient(props: IntakeClientProps) {
const [activeSection, setActiveSection] = useState<IntakeSection>(null)
if (!isEditorMode(props)) {
const skuList = props.eligibleDraftGroups.slice(0, 3).map((draftGroup, index) => ({
id: draftGroup.id,
code: `SKU-${String(index + 1).padStart(3, '0')}`,
name: draftGroup.name,
status: '待执行',
}))
const skuList =
props.eligibleSkuList && props.eligibleSkuList.length > 0
? props.eligibleSkuList
: props.eligibleDraftGroups.slice(0, 3).map((draftGroup, index) => ({
id: draftGroup.id,
spuCode: draftGroup.code || `SPU-${String(index + 1).padStart(3, '0')}`,
code: `SKU-${String(index + 1).padStart(3, '0')}`,
name: draftGroup.name,
seriesName: draftGroup.seriesTemplateName,
draftGroupName: draftGroup.name,
status: '待确认',
componentCodes: [],
}))
let leftContent: React.ReactNode = <EmptyDetail />
if (activeSection === 'pending') {
leftContent = <PendingSkuDetail skuList={skuList} />
} else if (activeSection === 'preparation') {
leftContent = <PreparationDetail skuList={skuList} />
} else if (activeSection === 'bom') {
leftContent = <PickingDetail pickingRows={[]} />
} else if (activeSection === 'quality') {
leftContent = <QualityDetail brandName="按 SPU 前缀识别" />
} else if (activeSection === 'packaging') {
leftContent = (
<ModelPreviewPanel
title="包装执行 3D 预览"
emptyTitle="待承接已确认 SKU 模型"
emptyDescription="这里先保留 3D 预览窗口,后续承接草稿组里已经确认好的 SKU 模型。"
/>
)
}
return (
<PlatformSplitLayout
title="正式入库"
metrics={props.metrics}
leftContent={<EmptyDetail />}
leftContent={leftContent}
rightContent={
<FormalIntakeWorkbench
activeSection={activeSection}
@ -418,33 +616,49 @@ export default function IntakeClient(props: IntakeClientProps) {
const previewNodes = firstActivePreSku ? readPreviewNodes(firstActivePreSku.previewNodes) : []
const skuList = props.detail.preSkus.map((preSku, index) => ({
id: preSku.id,
code: buildSkuCode(preSku.id, index),
spuCode:
readPreSkuTextField(preSku, 'spuCode') ||
readPreSkuTextField(preSku, 'spu') ||
props.detail.draftGroup.code ||
`SPU-${String(index + 1).padStart(3, '0')}`,
code:
readPreSkuTextField(preSku, 'skuCode') ||
preSku.customName ||
preSku.defaultName ||
buildSkuCode(preSku.id, index),
name: preSku.customName || preSku.defaultName,
seriesName:
readPreSkuTextField(preSku, 'seriesName') ||
props.detail.draftGroup.seriesTemplateName ||
props.detail.draftGroup.name,
draftGroupName: props.detail.draftGroup.name,
status: mapStatus(preSku.status),
componentCodes: preSku.componentCodes ?? [],
}))
const pickingRows = COMPONENT_LABELS.map((label, index) => ({
componentName: label,
componentCode: firstActivePreSku?.componentCodes[index] || '待带入',
location: props.locations[index]?.code || props.locations[index]?.name || '待带入',
componentCode: firstActivePreSku?.componentCodes[index] || '待补充',
location: props.locations[index]?.code || props.locations[index]?.name || '待补充',
quantity: '1',
}))
const brandName = detectBrandName(skuList[0]?.code ?? '')
const brandName = detectBrandName(skuList[0]?.spuCode ?? '')
let leftContent: React.ReactNode = <EmptyDetail />
if (activeSection === 'pending') {
leftContent = <PendingSkuDetail skuList={skuList} />
} else if (activeSection === 'components') {
leftContent = <ComponentDetail componentCodes={firstActivePreSku?.componentCodes ?? []} />
} else if (activeSection === 'picking') {
} else if (activeSection === 'preparation') {
leftContent = <PreparationDetail skuList={skuList} />
} else if (activeSection === 'bom') {
leftContent = <PickingDetail pickingRows={pickingRows} />
} else if (activeSection === 'brand') {
leftContent = <BrandDetail brandName={brandName} />
} else if (activeSection === 'quality') {
leftContent = <QualityDetail brandName={brandName} />
} else if (activeSection === 'packaging') {
leftContent = (
<ModelPreviewPanel
title="包装执行 3D 预览"
previewNodes={previewNodes}
emptyTitle="暂无包装预览"
emptyDescription="包装执行时,这里显示 3D 包装预览窗口。"
emptyTitle="待承接已确认 SKU 模型"
emptyDescription="这里先保留 3D 预览窗口,后续承接草稿组里已经确认好的 SKU 模型。"
/>
)
}

View File

@ -3,6 +3,27 @@ import { requireSession } from '@/lib/server-session'
import { categoryService, draftGroupService, intakeService, warehouseService } from '@/server/services'
import IntakeClient from './IntakeClient'
function readPreSkuTextField(preSku: { displaySummary?: Record<string, unknown> | null; familySelection?: Record<string, unknown> }, key: string) {
const displayValue = preSku.displaySummary?.[key]
if (typeof displayValue === 'string' && displayValue.trim().length > 0) {
return displayValue.trim()
}
const familyValue = preSku.familySelection?.[key]
if (typeof familyValue === 'string' && familyValue.trim().length > 0) {
return familyValue.trim()
}
return ''
}
function mapWorkbenchStatus(status: string) {
if (status === 'FORMALIZED') return '已完成'
if (status === 'READY_FOR_INTAKE') return '待执行'
if (status === 'PACKAGING') return '待入库'
return '待处理'
}
function isDraftGroupEligibleForIntake(status: string) {
return status === 'PACKAGING' || status === 'READY_FOR_INTAKE'
}
@ -29,6 +50,31 @@ export default async function IntakePage({
selectedDetail && isDraftGroupEligibleForIntake(selectedDetail.draftGroup.status)
? selectedDetail
: null
const eligibleDraftGroupDetails = await Promise.all(
eligibleDraftGroups.map((group) => draftGroupService.getById(group.id)),
)
const eligibleSkuList = eligibleDraftGroupDetails.flatMap((detail) =>
detail.preSkus.map((preSku, index) => ({
id: preSku.id,
spuCode:
readPreSkuTextField(preSku, 'spuCode') ||
readPreSkuTextField(preSku, 'spu') ||
detail.draftGroup.code ||
`SPU-${String(index + 1).padStart(3, '0')}`,
code:
readPreSkuTextField(preSku, 'skuCode') ||
preSku.customName ||
preSku.defaultName,
name: preSku.customName || preSku.defaultName,
seriesName:
readPreSkuTextField(preSku, 'seriesName') ||
detail.draftGroup.seriesTemplateName ||
detail.draftGroup.name,
draftGroupName: detail.draftGroup.name,
status: mapWorkbenchStatus(preSku.status),
componentCodes: preSku.componentCodes ?? [],
})),
)
const sourceWorkspace = eligibleSelectedDetail?.preSkus.find((preSku) => preSku.assemblyWorkspace)?.assemblyWorkspace ?? null
const defaultAttachProductId =
sourceWorkspace?.entryMode === 'source-sku' ? sourceWorkspace.sourceProductId ?? null : null
@ -73,6 +119,7 @@ export default async function IntakePage({
user={user}
metrics={metrics}
eligibleDraftGroups={eligibleDraftGroups}
eligibleSkuList={eligibleSkuList}
draftGroupId={draftGroupId}
hasIneligibleSelected={!!draftGroupId && !!selectedDetail}
/>

View File

@ -19,8 +19,8 @@ jest.mock('@/components/platform/PlatformSplitLayout', () => ({
rightContent: ReactNode
}) => (
<div>
<div>{leftContent}</div>
<div>{rightContent}</div>
<div data-testid="left-content">{leftContent}</div>
<div data-testid="right-content">{rightContent}</div>
</div>
),
}))
@ -29,14 +29,14 @@ jest.mock('@/components/platform/AccordionSection', () => ({
__esModule: true,
AccordionSection: ({
title,
children,
onToggle,
}: {
title: ReactNode
children: ReactNode
onToggle?: () => void
}) => (
<section>
<h2>{title}</h2>
{children}
<button type="button" onClick={onToggle}>Toggle {title}</button>
</section>
),
}))
@ -104,6 +104,9 @@ describe('WarehouseClient', () => {
/>,
)
// 先点击"库位管理"切换到库位详情面板
await actor.click(screen.getByRole('button', { name: 'Toggle 库位管理' }))
await actor.click(screen.getByRole('button', { name: '新增库位' }))
expect(screen.getByRole('heading', { name: '新增库位' })).toBeInTheDocument()

View File

@ -5,8 +5,10 @@ import {
Boxes,
MapPinned,
Package,
Pencil,
Plus,
Printer,
Trash2,
Warehouse as WarehouseIcon,
} from 'lucide-react'
import { Badge } from '@/components/ui/Badge'
@ -17,10 +19,11 @@ import Select from '@/components/ui/Select'
import { PlatformSplitLayout } from '@/components/platform/PlatformSplitLayout'
import { AccordionSection } from '@/components/platform/AccordionSection'
import type { PlatformMetricItem } from '@/components/platform/types'
import { createWarehouseLocation } from '@/lib/open-product/platform-api'
import { bindVariantToLocations, createWarehouseLocation, deleteWarehouseLocation, unbindVariantFromLocation, updateWarehouseLocation } from '@/lib/open-product/platform-api'
import type { WarehouseOverviewDTO } from '@/server/services'
type WarehouseSection = 'location' | 'parts-sku' | 'product-sku' | 'brand' | null
type LocationSortKey = 'code' | 'name' | 'zone'
interface PartsVariantItem {
id: string
@ -30,6 +33,7 @@ interface PartsVariantItem {
familyCode: string
familyName: string
thumbnailUrl: string | null
boundLocations: Array<{ id: string; code: string; name: string }>
}
interface DraftGroupPreSkuSummary {
@ -90,8 +94,9 @@ function toggleSection(current: WarehouseSection, section: Exclude<WarehouseSect
return current === section ? null : section
}
export default function WarehouseClient({ initialOverview, user, metrics, partsVariants, draftGroups }: WarehouseClientProps) {
export default function WarehouseClient({ initialOverview, user, metrics, partsVariants: initialPartsVariants, draftGroups }: WarehouseClientProps) {
const [overview, setOverview] = useState(initialOverview)
const [partsVariants, setPartsVariants] = useState(initialPartsVariants)
const [activeSection, setActiveSection] = useState<WarehouseSection>(null)
const [locationForm, setLocationForm] = useState({
code: '',
@ -104,11 +109,19 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
})
const [submitting, setSubmitting] = useState(false)
const [locationModalOpen, setLocationModalOpen] = useState(false)
const [editingLocationId, setEditingLocationId] = useState<string | null>(null)
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)
const [feedback, setFeedback] = useState<{
tone: 'success' | 'error'
text: string
} | null>(null)
// 库位搜索 + 排序 + 分页
const [locationSearch, setLocationSearch] = useState('')
const [locationSort, setLocationSort] = useState<LocationSortKey>('code')
const [locationPage, setLocationPage] = useState(1)
const PAGE_SIZE = 20
// 配件 SKU 筛选
const [partsTypeFilter, setPartsTypeFilter] = useState('')
const [partsSearchValue, setPartsSearchValue] = useState('')
@ -119,6 +132,13 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
// 品牌选择
const [selectedBrand, setSelectedBrand] = useState('')
// 绑定库位弹窗
const [bindingModalOpen, setBindingModalOpen] = useState(false)
const [bindingVariantId, setBindingVariantId] = useState<string | null>(null)
const [selectedLocationIds, setSelectedLocationIds] = useState<string[]>([])
const [bindingSubmitting, setBindingSubmitting] = useState(false)
const [bindingSearch, setBindingSearch] = useState('')
async function handleCreateLocation() {
setSubmitting(true)
setFeedback(null)
@ -140,6 +160,130 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
}
}
async function handleUpdateLocation() {
if (!editingLocationId) return
setSubmitting(true)
setFeedback(null)
try {
const updated = await updateWarehouseLocation(editingLocationId, locationForm)
startTransition(() => {
setOverview((current) => ({
...current,
locations: current.locations.map((loc) => (loc.id === updated.id ? updated : loc)),
}))
setEditingLocationId(null)
setLocationModalOpen(false)
setFeedback({ tone: 'success', text: '库位已更新。' })
})
} catch (error) {
setFeedback({ tone: 'error', text: error instanceof Error ? error.message : '库位更新失败' })
} finally {
setSubmitting(false)
}
}
async function handleToggleLocation(id: string, currentActive: boolean) {
setFeedback(null)
try {
const updated = await updateWarehouseLocation(id, { isActive: !currentActive })
startTransition(() => {
setOverview((current) => ({
...current,
locations: current.locations.map((loc) => (loc.id === updated.id ? updated : loc)),
}))
setFeedback({ tone: 'success', text: updated.isActive ? '库位已启用。' : '库位已停用。' })
})
} catch (error) {
setFeedback({ tone: 'error', text: error instanceof Error ? error.message : '操作失败' })
}
}
async function handleDeleteLocation() {
if (!deleteConfirmId) return
setFeedback(null)
try {
await deleteWarehouseLocation(deleteConfirmId)
startTransition(() => {
setOverview((current) => ({
...current,
locations: current.locations.filter((loc) => loc.id !== deleteConfirmId),
}))
setDeleteConfirmId(null)
setFeedback({ tone: 'success', text: '库位已删除。' })
})
} catch (error) {
setFeedback({ tone: 'error', text: error instanceof Error ? error.message : '删除失败' })
setDeleteConfirmId(null)
}
}
function openEditModal(location: { id: string; code: string; name: string; zone: string | null; aisle: string | null; shelf: string | null; bin: string | null; notes: string | null }) {
setEditingLocationId(location.id)
setLocationForm({
code: location.code,
name: location.name,
zone: location.zone || '',
aisle: location.aisle || '',
shelf: location.shelf || '',
bin: location.bin || '',
notes: location.notes || '',
})
setLocationModalOpen(true)
}
async function handleBindLocations() {
if (!bindingVariantId || selectedLocationIds.length === 0) return
setBindingSubmitting(true)
setFeedback(null)
try {
const updatedBindings = await bindVariantToLocations(bindingVariantId, selectedLocationIds)
startTransition(() => {
setPartsVariants((current) =>
current.map((v) =>
v.id === bindingVariantId
? {
...v,
boundLocations: updatedBindings.map((b) => ({
id: b.warehouseLocation.id,
code: b.warehouseLocation.code,
name: b.warehouseLocation.name,
})),
}
: v,
),
)
setBindingModalOpen(false)
setBindingVariantId(null)
setSelectedLocationIds([])
setBindingSearch('')
setFeedback({ tone: 'success', text: '库位绑定成功。' })
})
} catch (error) {
setFeedback({ tone: 'error', text: error instanceof Error ? error.message : '绑定失败' })
} finally {
setBindingSubmitting(false)
}
}
async function handleUnbindLocation(variantId: string, locationId: string) {
setFeedback(null)
try {
await unbindVariantFromLocation(variantId, locationId)
startTransition(() => {
setPartsVariants((current) =>
current.map((v) =>
v.id === variantId
? { ...v, boundLocations: v.boundLocations.filter((l) => l.id !== locationId) }
: v,
),
)
setFeedback({ tone: 'success', text: '已解除绑定。' })
})
} catch (error) {
setFeedback({ tone: 'error', text: error instanceof Error ? error.message : '解绑失败' })
}
}
const locationCount = overview.locations.length
const skuCount = overview.skuStock.length
const packagedCount = overview.packagedItems.length
@ -147,6 +291,32 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
overview.skuStock.reduce((sum, item) => sum + item.stock, 0) +
overview.packagedItems.reduce((sum, item) => sum + item.stockQuantity, 0)
// 库位排序 + 搜索 + 分页
const filteredLocations = overview.locations
.filter((loc) => {
if (!locationSearch) return true
const s = locationSearch.toLowerCase()
return (
loc.code.toLowerCase().includes(s) ||
loc.name.toLowerCase().includes(s) ||
(loc.zone && loc.zone.toLowerCase().includes(s)) ||
(loc.aisle && loc.aisle.toLowerCase().includes(s)) ||
(loc.shelf && loc.shelf.toLowerCase().includes(s)) ||
(loc.bin && loc.bin.toLowerCase().includes(s))
)
})
.sort((a, b) => {
if (locationSort === 'code') return a.code.localeCompare(b.code)
if (locationSort === 'name') return a.name.localeCompare(b.name)
if (locationSort === 'zone') return (a.zone || '').localeCompare(b.zone || '')
return 0
})
const totalFiltered = filteredLocations.length
const totalPages = Math.max(1, Math.ceil(totalFiltered / PAGE_SIZE))
const safePage = Math.min(locationPage, totalPages)
const pagedLocations = filteredLocations.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE)
// ========== 左侧详情内容 ==========
let leftContent: React.ReactNode = (
@ -160,30 +330,24 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
if (activeSection === 'location') {
leftContent = (
<div className="flex h-full flex-col gap-4 overflow-y-auto rounded-apple-xl border border-apple-separator bg-apple-bg-primary p-5 shadow-apple-xs">
<div className="grid grid-cols-2 gap-3">
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary px-4 py-4">
<p className="text-xs font-apple-medium text-apple-label-tertiary">库位数</p>
<p className="mt-1 text-2xl font-apple-semibold text-apple-label-primary">{locationCount}</p>
</div>
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary px-4 py-4">
<p className="text-xs font-apple-medium text-apple-label-tertiary">正式 SKU</p>
<p className="mt-1 text-2xl font-apple-semibold text-apple-blue">{skuCount}</p>
</div>
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary px-4 py-4">
<p className="text-xs font-apple-medium text-apple-label-tertiary">包装成品</p>
<p className="mt-1 text-2xl font-apple-semibold text-apple-green">{packagedCount}</p>
</div>
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary px-4 py-4">
<p className="text-xs font-apple-medium text-apple-label-tertiary">总库存</p>
<p className="mt-1 text-2xl font-apple-semibold text-apple-label-primary">{totalStock}</p>
</div>
{/* 紧凑统计条 */}
<div className="flex items-center gap-3 rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-4 py-2 text-xs text-apple-label-secondary">
<span>库位 <span className="font-apple-semibold text-apple-label-primary">{locationCount}</span></span>
<span className="text-apple-separator">|</span>
<span>正式 SKU <span className="font-apple-semibold text-apple-blue">{skuCount}</span></span>
<span className="text-apple-separator">|</span>
<span>包装成品 <span className="font-apple-semibold text-apple-green">{packagedCount}</span></span>
<span className="text-apple-separator">|</span>
<span>库存 <span className="font-apple-semibold text-apple-label-primary">{totalStock}</span></span>
</div>
{/* 标题 + 新增 */}
<div className="flex items-center justify-between">
<h3 className="text-sm font-apple-semibold text-apple-label-primary">库位列表</h3>
<Button
size="small"
onClick={() => {
setEditingLocationId(null)
setLocationForm({ code: '', name: '', zone: '', aisle: '', shelf: '', bin: '', notes: '' })
setLocationModalOpen(true)
}}
@ -193,27 +357,96 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
</Button>
</div>
{overview.locations.length === 0 ? (
{/* 搜索 + 排序 */}
<div className="flex gap-2 items-center">
<div className="flex-1">
<Input
placeholder="搜索编码、名称、区域、巷道、货架、箱位"
value={locationSearch}
onChange={(e) => { setLocationSearch(e.target.value); setLocationPage(1) }}
/>
</div>
<div className="flex gap-1 shrink-0">
{([
{ key: 'code' as LocationSortKey, label: '编码' },
{ key: 'name' as LocationSortKey, label: '名称' },
{ key: 'zone' as LocationSortKey, label: '区域' },
]).map(({ key, label }) => (
<Button
key={key}
variant={locationSort === key ? 'filled' : 'plain'}
size="small"
onClick={() => setLocationSort(key)}
>
{label}
</Button>
))}
</div>
</div>
{/* 库位列表 */}
{filteredLocations.length === 0 ? (
<div className="rounded-apple-xl border border-dashed border-apple-separator bg-apple-bg-secondary px-4 py-6 text-sm leading-7 text-apple-label-secondary">
还没有库位。点击「新增库位」创建一个正式库位,后续入库即可挂接。
{overview.locations.length === 0
? '还没有库位。点击「新增库位」创建一个正式库位,后续入库即可挂接。'
: '没有匹配的库位,试试调整搜索条件。'}
</div>
) : (
overview.locations.map((location) => (
<article key={location.id} className="rounded-apple-xl border border-apple-separator bg-apple-bg-primary px-4 py-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<p className="text-sm font-apple-semibold text-apple-label-primary">{location.name}</p>
<p className="text-xs text-apple-label-secondary">{location.code}</p>
<>
<div className="text-xs text-apple-label-tertiary">
共 {totalFiltered} 个库位{totalFiltered > PAGE_SIZE ? `,第 ${safePage}/${totalPages} 页` : ''}
</div>
{pagedLocations.map((location) => (
<div key={location.id} className="flex items-center justify-between gap-2 rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<div className="min-w-0 flex-1">
<p className="text-xs font-apple-medium text-apple-label-primary truncate">{location.name} <span className="text-apple-label-tertiary">{location.code}</span></p>
<p className="text-xs text-apple-label-tertiary truncate">
{location.zone || '-'} / {location.aisle || '-'} / {location.shelf || '-'} / {location.bin || '-'}
</p>
</div>
<div className="flex items-center gap-1 shrink-0">
<Badge type={location.isActive ? 'success' : 'warning'} variant="subtle">
{location.isActive ? '可用' : '停用'}
</Badge>
<Button variant="plain" size="small" onClick={() => {
setEditingLocationId(null)
setLocationForm({
code: location.code,
name: location.name,
zone: location.zone || '',
aisle: location.aisle || '',
shelf: location.shelf || '',
bin: location.bin || '',
notes: location.notes || '',
})
setLocationModalOpen(true)
}}>
复制
</Button>
<Button variant="plain" size="small" onClick={() => openEditModal(location)}>
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button variant="plain" size="small" onClick={() => void handleToggleLocation(location.id, location.isActive)}>
{location.isActive ? '停用' : '启用'}
</Button>
<Button variant="plain" size="small" onClick={() => setDeleteConfirmId(location.id)}>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
<Badge type={location.isActive ? 'success' : 'warning'} variant="subtle">
{location.isActive ? '可用' : '停用'}
</Badge>
</div>
<p className="mt-2 text-xs leading-5 text-apple-label-secondary">
{location.zone || '未分区'} / {location.aisle || '未设巷道'} / {location.shelf || '未设货架'} / {location.bin || '未设箱位'}
</p>
</article>
))
))}
{totalFiltered > PAGE_SIZE && (
<div className="flex items-center justify-between pt-2">
<Button variant="plain" size="small" disabled={safePage <= 1} onClick={() => setLocationPage((p) => Math.max(1, p - 1))}>
上一页
</Button>
<span className="text-xs text-apple-label-tertiary">{safePage} / {totalPages}</span>
<Button variant="plain" size="small" disabled={safePage >= totalPages} onClick={() => setLocationPage((p) => Math.min(totalPages, p + 1))}>
下一页
</Button>
</div>
)}
</>
)}
</div>
)
@ -298,10 +531,38 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
</p>
</div>
<div className="flex gap-1 shrink-0 ml-2">
<Badge type="info" variant="subtle">待绑定</Badge>
<Button variant="plain" size="small">绑定库位</Button>
{variant.boundLocations.length > 0 ? (
<Badge type="success" variant="subtle">已绑定 {variant.boundLocations.length}</Badge>
) : (
<Badge type="info" variant="subtle">待绑定</Badge>
)}
<Button variant="plain" size="small" onClick={() => {
setBindingVariantId(variant.id)
setSelectedLocationIds(variant.boundLocations.map((l) => l.id))
setBindingSearch('')
setBindingModalOpen(true)
}}>绑定库位</Button>
</div>
</div>
{variant.boundLocations.length > 0 && (
<div className="mt-1.5 flex flex-wrap gap-1">
{variant.boundLocations.map((loc) => (
<span
key={loc.id}
className="inline-flex items-center gap-1 rounded-apple-md bg-apple-bg-tertiary px-1.5 py-0.5 text-xs text-apple-label-secondary"
>
{loc.code}
<button
type="button"
className="text-apple-label-tertiary hover:text-apple-red"
onClick={() => void handleUnbindLocation(variant.id, loc.id)}
>
×
</button>
</span>
))}
</div>
)}
</div>
))}
</div>
@ -341,15 +602,10 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
/>
{/* 统计 */}
<div className="grid grid-cols-2 gap-3">
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary px-4 py-3">
<p className="text-xs font-apple-medium text-apple-label-tertiary">草稿组</p>
<p className="mt-1 text-xl font-apple-semibold text-apple-label-primary">{filteredGroups.length}</p>
</div>
<div className="rounded-apple-xl border border-apple-separator bg-apple-bg-secondary px-4 py-3">
<p className="text-xs font-apple-medium text-apple-label-tertiary">组合 SKU</p>
<p className="mt-1 text-xl font-apple-semibold text-apple-blue">{totalPreSkus}</p>
</div>
<div className="flex items-center gap-3 rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-4 py-2 text-xs text-apple-label-secondary">
<span>草稿组 <span className="font-apple-semibold text-apple-label-primary">{filteredGroups.length}</span></span>
<span className="text-apple-separator">|</span>
<span>组合 SKU <span className="font-apple-semibold text-apple-blue">{totalPreSkus}</span></span>
</div>
{/* 草稿组 + PreSku 列表 */}
@ -448,13 +704,6 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
)
}
// 统计配件各类型数量
const boardCount = partsVariants.filter((v) => v.assetType === 'BOARD').length
const componentCount = partsVariants.filter((v) => v.assetType === 'COMPONENT').length
const hardwareCount = partsVariants.filter((v) => v.assetType === 'HARDWARE').length
const packagingCount = partsVariants.filter((v) => v.assetType === 'PACKAGING').length
const totalPreSkuCount = draftGroups.reduce((sum, dg) => sum + dg.preSkus.length, 0)
return (
<>
<PlatformSplitLayout
@ -472,27 +721,7 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
expanded={activeSection === 'location'}
onToggle={() => setActiveSection((current) => toggleSection(current, 'location'))}
aside={<Badge type="info" variant="subtle">{locationCount} 个库位</Badge>}
>
<div className="space-y-3">
{overview.locations.length === 0 ? (
<div className="rounded-apple-lg border border-dashed border-apple-separator px-3 py-4 text-sm leading-7 text-apple-label-secondary">
还没有库位。展开后点击左侧详情区的「新增库位」。
</div>
) : (
overview.locations.map((location) => (
<div key={location.id} className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<div className="flex items-center justify-between gap-2">
<p className="text-sm font-apple-medium text-apple-label-primary">{location.name}</p>
<Badge type={location.isActive ? 'success' : 'warning'} variant="subtle">
{location.isActive ? '可用' : '停用'}
</Badge>
</div>
<p className="mt-1 text-xs text-apple-label-secondary">{location.code}</p>
</div>
))
)}
</div>
</AccordionSection>
/>
{/* 配件 SKU 库位 */}
<AccordionSection
@ -502,37 +731,7 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
expanded={activeSection === 'parts-sku'}
onToggle={() => setActiveSection((current) => toggleSection(current, 'parts-sku'))}
aside={<Badge type="info" variant="subtle">{partsVariants.length} 个配件</Badge>}
>
<div className="space-y-2">
{partsVariants.length === 0 ? (
<div className="rounded-apple-lg border border-dashed border-apple-separator bg-apple-bg-secondary px-3 py-4 text-sm text-apple-label-secondary">
暂无配件数据。请在资产中心添加资产族和变体。
</div>
) : (
<>
<div className="grid grid-cols-2 gap-2 text-xs text-apple-label-secondary">
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<span className="text-apple-label-tertiary">板材</span>
<span className="ml-1 font-apple-medium text-apple-label-primary">{boardCount}</span>
</div>
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<span className="text-apple-label-tertiary">组件</span>
<span className="ml-1 font-apple-medium text-apple-label-primary">{componentCount}</span>
</div>
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<span className="text-apple-label-tertiary">五金</span>
<span className="ml-1 font-apple-medium text-apple-label-primary">{hardwareCount}</span>
</div>
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<span className="text-apple-label-tertiary">包装</span>
<span className="ml-1 font-apple-medium text-apple-label-primary">{packagingCount}</span>
</div>
</div>
<p className="text-xs text-apple-label-tertiary">展开后在左侧详情区查看配件列表并绑定库位。</p>
</>
)}
</div>
</AccordionSection>
/>
{/* 成品 SKU 库位 */}
<AccordionSection
@ -541,30 +740,8 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
icon={<WarehouseIcon className="h-4 w-4" />}
expanded={activeSection === 'product-sku'}
onToggle={() => setActiveSection((current) => toggleSection(current, 'product-sku'))}
aside={<Badge type="info" variant="subtle">{totalPreSkuCount} 个 SKU</Badge>}
>
<div className="space-y-2">
{draftGroups.length === 0 ? (
<div className="rounded-apple-lg border border-dashed border-apple-separator bg-apple-bg-secondary px-3 py-4 text-sm text-apple-label-secondary">
暂无草稿组数据。请先在拼装中心创建草稿组。
</div>
) : (
<>
<div className="grid grid-cols-2 gap-2 text-xs text-apple-label-secondary">
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<span className="text-apple-label-tertiary">草稿组</span>
<span className="ml-1 font-apple-medium text-apple-label-primary">{draftGroups.length}</span>
</div>
<div className="rounded-apple-lg border border-apple-separator bg-apple-bg-secondary px-3 py-2">
<span className="text-apple-label-tertiary">组合 SKU</span>
<span className="ml-1 font-apple-medium text-apple-blue">{totalPreSkuCount}</span>
</div>
</div>
<p className="text-xs text-apple-label-tertiary">展开后在左侧详情区查看成品 SKU 列表并绑定库位。</p>
</>
)}
</div>
</AccordionSection>
aside={<Badge type="info" variant="subtle">{draftGroups.reduce((s, dg) => s + dg.preSkus.length, 0)} 个 SKU</Badge>}
/>
{/* 品牌物料库位 */}
<AccordionSection
@ -573,28 +750,30 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
icon={<Package className="h-4 w-4" />}
expanded={activeSection === 'brand'}
onToggle={() => setActiveSection((current) => toggleSection(current, 'brand'))}
>
<div className="rounded-apple-lg border border-dashed border-apple-separator bg-apple-bg-secondary px-3 py-4 text-sm text-apple-label-secondary">
展开后在左侧详情区查看品牌物料与库位绑定。
</div>
</AccordionSection>
/>
</div>
}
/>
{/* 新增库位弹窗 */}
{/* 新增/编辑库位弹窗 */}
<Modal
isOpen={locationModalOpen}
onClose={() => setLocationModalOpen(false)}
title="新增库位"
onClose={() => { setLocationModalOpen(false); setEditingLocationId(null) }}
title={editingLocationId ? '编辑库位' : '新增库位'}
size="medium"
footer={
<div className="flex gap-3">
<Button variant="gray" size="regular" onClick={() => setLocationModalOpen(false)} className="flex-1">
<Button variant="gray" size="regular" onClick={() => { setLocationModalOpen(false); setEditingLocationId(null) }} className="flex-1">
取消
</Button>
<Button variant="filled" size="regular" onClick={() => void handleCreateLocation()} loading={submitting} className="flex-1">
创建库位
<Button
variant="filled"
size="regular"
onClick={() => void (editingLocationId ? handleUpdateLocation() : handleCreateLocation())}
loading={submitting}
className="flex-1"
>
{editingLocationId ? '保存修改' : '创建库位'}
</Button>
</div>
}
@ -627,6 +806,105 @@ export default function WarehouseClient({ initialOverview, user, metrics, partsV
/>
</div>
</Modal>
{/* 删除确认弹窗 */}
<Modal
isOpen={deleteConfirmId !== null}
onClose={() => setDeleteConfirmId(null)}
title="确认删除"
size="small"
footer={
<div className="flex gap-3">
<Button variant="gray" size="regular" onClick={() => setDeleteConfirmId(null)} className="flex-1">
取消
</Button>
<Button variant="filled" size="regular" onClick={() => void handleDeleteLocation()} loading={submitting} className="flex-1">
确认删除
</Button>
</div>
}
>
<p className="text-sm text-apple-label-secondary">确定要删除这个库位吗?此操作不可恢复。</p>
</Modal>
{/* 绑定库位弹窗 */}
<Modal
isOpen={bindingModalOpen}
onClose={() => { setBindingModalOpen(false); setBindingVariantId(null); setSelectedLocationIds([]); setBindingSearch('') }}
title="绑定库位"
size="medium"
footer={
<div className="flex gap-3">
<Button variant="gray" size="regular" onClick={() => { setBindingModalOpen(false); setBindingVariantId(null); setSelectedLocationIds([]); setBindingSearch('') }} className="flex-1">
取消
</Button>
<Button
variant="filled"
size="regular"
onClick={() => void handleBindLocations()}
loading={bindingSubmitting}
disabled={selectedLocationIds.length === 0}
className="flex-1"
>
确认绑定({selectedLocationIds.length})
</Button>
</div>
}
>
<p className="text-xs text-apple-label-secondary mb-3">
选择要绑定的库位。已绑定的库位会显示为勾选状态,可新增或取消勾选。
</p>
<Input
placeholder="搜索库位编码或名称"
value={bindingSearch}
onChange={(e) => setBindingSearch(e.target.value)}
/>
<div className="mt-3 max-h-60 space-y-1 overflow-y-auto">
{overview.locations
.filter((loc) => {
if (!bindingSearch) return true
const s = bindingSearch.toLowerCase()
return loc.code.toLowerCase().includes(s) || loc.name.toLowerCase().includes(s)
})
.map((loc) => {
const isSelected = selectedLocationIds.includes(loc.id)
return (
<button
key={loc.id}
type="button"
className={`w-full flex items-center gap-2 rounded-apple-lg border px-3 py-2 text-left text-sm transition-colors ${
isSelected
? 'border-[#008D74] bg-[#008D74]/5'
: 'border-apple-separator bg-apple-bg-primary hover:bg-apple-bg-secondary'
}`}
onClick={() => {
setSelectedLocationIds((current) =>
isSelected
? current.filter((id) => id !== loc.id)
: [...current, loc.id],
)
}}
>
<div
className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${
isSelected ? 'border-[#008D74] bg-[#008D74]' : 'border-apple-separator'
}`}
>
{isSelected && (
<svg className="h-3 w-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
)}
</div>
<div className="flex-1 min-w-0">
<p className="text-apple-label-primary truncate">{loc.name}</p>
<p className="text-xs text-apple-label-tertiary">{loc.code}</p>
</div>
</button>
)
})}
</div>
</Modal>
</>
)
}

View File

@ -8,14 +8,14 @@ export default async function WarehousePage() {
const [overview, families, draftGroupList] = await Promise.all([
warehouseService.getOverview(),
assetCenterService.listFamilies({ status: 'AVAILABLE' }),
assetCenterService.listFamilies(),
draftGroupService.list(),
])
// 获取所有可用资产族的变体(配件数据源)
// 获取所有资产族的变体(配件数据源,不过滤状态)
const familyIds = families.map((f) => f.id)
const allVariants = familyIds.length > 0
? await assetCenterService.listVariantsByFamilyIds(familyIds, { status: 'AVAILABLE' })
? await assetCenterService.listVariantsByFamilyIds(familyIds)
: []
// 获取草稿组详情(含 PreSku,成品数据源)
@ -34,6 +34,24 @@ export default async function WarehousePage() {
thumbnailUrl: v.thumbnailUrl,
}))
// 预加载配件-库位绑定数据
const variantIds = partsVariants.map((v) => v.id)
const bindings = variantIds.length > 0
? await warehouseService.getBindingsForVariants(variantIds)
: []
const bindingMap = new Map<string, Array<{ id: string; code: string; name: string }>>()
for (const b of bindings) {
const list = bindingMap.get(b.assetVariantId) ?? []
list.push({ id: b.warehouseLocation.id, code: b.warehouseLocation.code, name: b.warehouseLocation.name })
bindingMap.set(b.assetVariantId, list)
}
const partsVariantsWithBindings = partsVariants.map((v) => ({
...v,
boundLocations: bindingMap.get(v.id) ?? [],
}))
// 转换草稿组 + PreSku 数据
const draftGroups = draftGroupDetails
.filter((d): d is NonNullable<typeof d> => d !== null)
@ -87,7 +105,7 @@ export default async function WarehousePage() {
initialOverview={overview}
user={user}
metrics={metrics}
partsVariants={partsVariants}
partsVariants={partsVariantsWithBindings}
draftGroups={draftGroups}
/>
)

View File

@ -21,7 +21,7 @@ interface AccordionSectionProps {
onToggle?: () => void
/** 区段右上角的操作区 */
actions?: ReactNode
children: ReactNode
children?: ReactNode
className?: string
contentClassName?: string
}
@ -90,16 +90,18 @@ export function AccordionSection({
/>
</button>
<div
className="grid transition-[grid-template-rows] duration-500 ease-[cubic-bezier(0.32,0.72,0,1)]"
style={{ gridTemplateRows: isExpanded ? '1fr' : '0fr' }}
>
<div className="overflow-hidden">
<div className={cn('border-t border-apple-separator px-5 py-4', contentClassName)}>
{children}
{children ? (
<div
className="grid transition-[grid-template-rows] duration-500 ease-[cubic-bezier(0.32,0.72,0,1)]"
style={{ gridTemplateRows: isExpanded ? '1fr' : '0fr' }}
>
<div className="overflow-hidden">
<div className={cn('border-t border-apple-separator px-5 py-4', contentClassName)}>
{children}
</div>
</div>
</div>
</div>
) : null}
</div>
)
}

View File

@ -4,6 +4,7 @@ import type {
AssetFamilyDTO,
AssetCadImportResult,
AssetVariantDTO,
AssetVariantBindingDTO,
AssetReviewActionInput,
CreateAssetVariantResultDTO,
CreateAssetFamilyInput,
@ -458,3 +459,57 @@ export async function createWarehouseLocation(
)
return data.location
}
export async function updateWarehouseLocation(
id: string,
input: Partial<Omit<WarehouseLocationDTO, 'id'>>,
): Promise<WarehouseLocationDTO> {
const data = await requestPlatform<{ location: WarehouseLocationDTO }>(
`/api/warehouse/locations/${encodeURIComponent(id)}`,
{
method: 'PATCH',
body: JSON.stringify(input),
},
)
return data.location
}
export async function deleteWarehouseLocation(id: string): Promise<void> {
await requestPlatform<{ deleted: boolean }>(
`/api/warehouse/locations/${encodeURIComponent(id)}`,
{ method: 'DELETE' },
)
}
export async function getVariantBindings(
variantIds: string[],
): Promise<AssetVariantBindingDTO[]> {
const data = await requestPlatform<{ bindings: AssetVariantBindingDTO[] }>(
`/api/warehouse/bindings?variantIds=${variantIds.join(',')}`,
)
return data.bindings
}
export async function bindVariantToLocations(
variantId: string,
locationIds: string[],
): Promise<AssetVariantBindingDTO[]> {
const data = await requestPlatform<{ bindings: AssetVariantBindingDTO[] }>(
'/api/warehouse/bindings',
{
method: 'POST',
body: JSON.stringify({ variantId, locationIds }),
},
)
return data.bindings
}
export async function unbindVariantFromLocation(
variantId: string,
locationId: string,
): Promise<void> {
await requestPlatform<{ unbound: boolean }>(
`/api/warehouse/bindings/${encodeURIComponent(variantId)}/${encodeURIComponent(locationId)}`,
{ method: 'DELETE' },
)
}

View File

@ -12,12 +12,118 @@ class WarehouseLocationRepositoryClass extends BaseRepository<
return this.prisma.warehouseLocation.findUnique({ where: { code } })
}
async findByPosition(zone: string | null, aisle: string | null, shelf: string | null, bin: string | null): Promise<WarehouseLocation | null> {
return this.prisma.warehouseLocation.findFirst({
where: { zone, aisle, shelf, bin, isActive: true },
})
}
async findAllActive(): Promise<WarehouseLocation[]> {
return this.prisma.warehouseLocation.findMany({
where: { isActive: true },
orderBy: [{ code: 'asc' }],
})
}
// --- Binding methods ---
async findBindingsByVariantIds(variantIds: string[]): Promise<
Array<{
id: string
assetVariantId: string
warehouseLocationId: string
warehouseLocation: { id: string; code: string; name: string }
}>
> {
if (variantIds.length === 0) return []
return this.prisma.assetVariantLocationBinding.findMany({
where: { assetVariantId: { in: variantIds } },
include: {
warehouseLocation: { select: { id: true, code: true, name: true } },
},
orderBy: { createdAt: 'desc' },
})
}
async createBindings(bindings: Array<{ assetVariantId: string; warehouseLocationId: string }>): Promise<void> {
if (bindings.length === 0) return
await this.prisma.assetVariantLocationBinding.createMany({
data: bindings,
skipDuplicates: true,
})
}
async deleteBindingByPair(assetVariantId: string, warehouseLocationId: string): Promise<void> {
await this.prisma.assetVariantLocationBinding.delete({
where: {
assetVariantId_warehouseLocationId: { assetVariantId, warehouseLocationId },
},
})
}
// --- Brand Material Binding methods ---
async findBrandMaterialBindingsByBrand(brand: string): Promise<
Array<{
id: string
brand: string
materialType: string
warehouseLocationId: string | null
warehouseLocation: { id: string; code: string; name: string } | null
fileUrl: string | null
fileName: string | null
fileSize: number | null
createdAt: Date
updatedAt: Date
}>
> {
return this.prisma.brandMaterialBinding.findMany({
where: { brand },
include: {
warehouseLocation: { select: { id: true, code: true, name: true } },
},
orderBy: { materialType: 'asc' },
})
}
async upsertBrandMaterialBinding(data: {
brand: string
materialType: string
warehouseLocationId?: string | null
fileUrl?: string | null
fileName?: string | null
fileSize?: number | null
}): Promise<{
id: string
brand: string
materialType: string
warehouseLocationId: string | null
warehouseLocation: { id: string; code: string; name: string } | null
fileUrl: string | null
fileName: string | null
fileSize: number | null
}> {
return this.prisma.brandMaterialBinding.upsert({
where: { brand_materialType: { brand: data.brand, materialType: data.materialType } },
update: {
...(data.warehouseLocationId !== undefined ? { warehouseLocationId: data.warehouseLocationId } : {}),
...(data.fileUrl !== undefined ? { fileUrl: data.fileUrl } : {}),
...(data.fileName !== undefined ? { fileName: data.fileName } : {}),
...(data.fileSize !== undefined ? { fileSize: data.fileSize } : {}),
},
create: {
brand: data.brand,
materialType: data.materialType,
warehouseLocationId: data.warehouseLocationId ?? null,
fileUrl: data.fileUrl ?? null,
fileName: data.fileName ?? null,
fileSize: data.fileSize ?? null,
},
include: {
warehouseLocation: { select: { id: true, code: true, name: true } },
},
})
}
}
export const warehouseLocationRepository = new WarehouseLocationRepositoryClass()

View File

@ -8,6 +8,11 @@ import {
type PreSkuWithRelations,
} from '../repositories'
import { draftGroupStateService } from './draft-group-state.service'
import {
buildSingleBoardDeskDemoDetail,
buildSingleBoardDeskDemoDraftGroup,
isSingleBoardDeskDemoDraftGroupId,
} from './draft-group.demo'
import { toDraftGroupDTO, toDraftGroupPreSkuDTO } from './draft-group.mapper'
import { preSkuMaterializationService } from './pre-sku-materialization.service'
import { preSkuPackagingService } from './pre-sku-packaging.service'
@ -18,15 +23,10 @@ import type {
DraftGroupAssemblyInput,
DraftGroupDTO,
DraftGroupDetailDTO,
DraftGroupPreSkuDTO,
GetPreSkuPackagingMaterialOptionsDTO,
GetPreSkuPackagingContextDTO,
PreSkuPackagingInputDTO,
PreSkuPackagingPlanDTO,
PreviewPreSkuPackagingPlanDTO,
PreSkuSelectedHardwareSelectionDTO,
PreSkuSelectedSlotVariantDTO,
PreSkuVariantSelectionDTO,
SavePreSkuPackagingPlanInput,
} from './draft-group.service.types'
@ -48,7 +48,10 @@ function normalizeCandidateToAssembly(
}
if (!candidate.assemblyWorkspace) {
throw new AppError(ErrorCode.VALIDATION_FAILED, '旧拼装结果缺少装配工作台快照,不能进入草稿组')
throw new AppError(
ErrorCode.VALIDATION_FAILED,
'旧拼装结果缺少装配工作台快照,不能进入草稿组',
)
}
const legFamilyIds = Array.from(
@ -84,9 +87,7 @@ function normalizeAssemblies(
return rawAssemblies.map(normalizeCandidateToAssembly)
}
function assertAssembliesCanEnterDraftGroup(
assemblies: DraftGroupAssemblyInput[],
) {
function assertAssembliesCanEnterDraftGroup(assemblies: DraftGroupAssemblyInput[]) {
const blockedAssemblies = assemblies
.map((assembly) => ({
assembly,
@ -115,10 +116,14 @@ function assertAssembliesCanEnterDraftGroup(
class DraftGroupService {
async list(): Promise<DraftGroupDTO[]> {
const records = await draftGroupRepository.findManyWithRelations()
return records.map((record) => toDraftGroupDTO(record))
return [buildSingleBoardDeskDemoDraftGroup(), ...records.map((record) => toDraftGroupDTO(record))]
}
async getById(id: string): Promise<DraftGroupDetailDTO> {
if (isSingleBoardDeskDemoDraftGroupId(id)) {
return buildSingleBoardDeskDemoDetail()
}
const draftGroup = await draftGroupRepository.findByIdWithRelations(id)
if (!draftGroup) {
throw new AppError(ErrorCode.DRAFT_GROUP_NOT_FOUND, '草稿组不存在')
@ -154,9 +159,7 @@ class DraftGroupService {
): Promise<DraftGroupDetailDTO> {
const assemblies = normalizeAssemblies(input)
const resolvedCategoryId =
input.categoryId ??
assemblies[0]?.assemblyWorkspace.productCategoryId ??
null
input.categoryId ?? assemblies[0]?.assemblyWorkspace.productCategoryId ?? null
if (!input.name.trim()) {
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '草稿组名称不能为空')
@ -179,14 +182,13 @@ class DraftGroupService {
creator: { connect: { id: user.id } },
})
const { preparedPreSkus } =
await preSkuMaterializationService.buildPreparedPreSkus(
{
...input,
assemblies,
},
createdDraftGroup.id,
)
const { preparedPreSkus } = await preSkuMaterializationService.buildPreparedPreSkus(
{
...input,
assemblies,
},
createdDraftGroup.id,
)
const preSkus = await preSkuRepository.createManyForDraftGroup(
createdDraftGroup.id,
@ -216,7 +218,10 @@ class DraftGroupService {
preSkuId: string,
input: SavePreSkuPackagingPlanInput,
): Promise<PreSkuPackagingPlanDTO> {
const { preSku, packagingPlan } = await preSkuPackagingService.savePackagingPlan(preSkuId, input)
const { preSku, packagingPlan } = await preSkuPackagingService.savePackagingPlan(
preSkuId,
input,
)
await draftGroupStateService.syncStatusAfterPackagingSaved(preSku, packagingPlan.boxes)
return packagingPlan
}

View File

@ -216,7 +216,12 @@ export type {
export { warehouseService, WarehouseService } from './warehouse.service'
export type {
AssetVariantBindingDTO,
BindBrandMaterialLocationInput,
BindVariantToLocationsInput,
BrandMaterialBindingDTO,
CreateWarehouseLocationInput,
UnbindVariantFromLocationInput,
WarehouseLocationDTO,
WarehouseOverviewDTO,
} from './warehouse.service'

View File

@ -1,12 +1,21 @@
import type { WarehouseLocation } from '@prisma/client'
import { randomUUID } from 'crypto'
import { AppError, ErrorCode } from '@/server/core/errors'
import { uploadBufferToS3 } from '@/lib/storage'
import {
assetVariantRepository,
packagedItemRepository,
skuRepository,
warehouseLocationRepository,
} from '../repositories'
import type {
AssetVariantBindingDTO,
BindBrandMaterialLocationInput,
BindVariantToLocationsInput,
BrandMaterialBindingDTO,
CreateWarehouseLocationInput,
UnbindVariantFromLocationInput,
UpdateWarehouseLocationInput,
WarehouseLocationDTO,
WarehouseOverviewDTO,
} from './warehouse.service.types'
@ -55,13 +64,23 @@ class WarehouseService {
throw new AppError(ErrorCode.VALIDATION_FAILED, '库位编码已存在')
}
const zone = input.zone?.trim() || null
const aisle = input.aisle?.trim() || null
const shelf = input.shelf?.trim() || null
const bin = input.bin?.trim() || null
if (await warehouseLocationRepository.findByPosition(zone, aisle, shelf, bin)) {
const parts = [zone || '未分区', aisle || '未设巷道', shelf || '未设货架', bin || '未设箱位']
throw new AppError(ErrorCode.VALIDATION_FAILED, `库位 ${parts.join(' / ')} 已存在,不可重复创建`)
}
const created = await warehouseLocationRepository.create({
code,
name,
zone: input.zone?.trim() || null,
aisle: input.aisle?.trim() || null,
shelf: input.shelf?.trim() || null,
bin: input.bin?.trim() || null,
zone,
aisle,
shelf,
bin,
notes: input.notes?.trim() || null,
isActive: true,
})
@ -69,6 +88,25 @@ class WarehouseService {
return toLocationDTO(created)
}
async updateLocation(id: string, input: UpdateWarehouseLocationInput): Promise<WarehouseLocationDTO> {
const data: Record<string, unknown> = {}
if (input.code !== undefined) data.code = input.code.trim()
if (input.name !== undefined) data.name = input.name.trim()
if (input.zone !== undefined) data.zone = input.zone?.trim() || null
if (input.aisle !== undefined) data.aisle = input.aisle?.trim() || null
if (input.shelf !== undefined) data.shelf = input.shelf?.trim() || null
if (input.bin !== undefined) data.bin = input.bin?.trim() || null
if (input.notes !== undefined) data.notes = input.notes?.trim() || null
if (input.isActive !== undefined) data.isActive = input.isActive
const updated = await warehouseLocationRepository.update(id, data)
return toLocationDTO(updated)
}
async deleteLocation(id: string): Promise<void> {
await warehouseLocationRepository.delete(id)
}
async getOverview(): Promise<WarehouseOverviewDTO> {
const [locations, skuStock, packagedItems] = await Promise.all([
warehouseLocationRepository.findAllActive(),
@ -111,12 +149,175 @@ class WarehouseService {
})),
}
}
async getBindingsForVariants(variantIds: string[]): Promise<AssetVariantBindingDTO[]> {
if (variantIds.length === 0) return []
const bindings = await warehouseLocationRepository.findBindingsByVariantIds(variantIds)
return bindings.map((b) => ({
id: b.id,
assetVariantId: b.assetVariantId,
warehouseLocation: {
id: b.warehouseLocation.id,
code: b.warehouseLocation.code,
name: b.warehouseLocation.name,
},
}))
}
async bindVariantToLocations(input: BindVariantToLocationsInput): Promise<AssetVariantBindingDTO[]> {
const { variantId, locationIds } = input
if (!variantId) {
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '变体 ID 不能为空')
}
if (!locationIds || locationIds.length === 0) {
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请至少选择一个库位')
}
const variant = await assetVariantRepository.findById(variantId)
if (!variant) {
throw new AppError(ErrorCode.ASSET_VARIANT_NOT_FOUND, '配件变体不存在')
}
const activeLocations = await warehouseLocationRepository.findAllActive()
const activeIds = new Set(activeLocations.map((l) => l.id))
const invalidIds = locationIds.filter((id) => !activeIds.has(id))
if (invalidIds.length > 0) {
throw new AppError(ErrorCode.WAREHOUSE_LOCATION_NOT_FOUND, `以下库位不存在或已停用: ${invalidIds.join(', ')}`)
}
await warehouseLocationRepository.createBindings(
locationIds.map((locationId) => ({
assetVariantId: variantId,
warehouseLocationId: locationId,
})),
)
return this.getBindingsForVariants([variantId])
}
async unbindVariantFromLocation(input: UnbindVariantFromLocationInput): Promise<void> {
const { variantId, locationId } = input
if (!variantId || !locationId) {
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '变体 ID 和库位 ID 不能为空')
}
try {
await warehouseLocationRepository.deleteBindingByPair(variantId, locationId)
} catch {
throw new AppError(ErrorCode.WAREHOUSE_LOCATION_NOT_FOUND, '绑定关系不存在')
}
}
async getBrandMaterials(brand: string): Promise<BrandMaterialBindingDTO[]> {
if (!brand) {
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '品牌不能为空')
}
const bindings = await warehouseLocationRepository.findBrandMaterialBindingsByBrand(brand)
return bindings.map((b) => ({
id: b.id,
brand: b.brand,
materialType: b.materialType,
warehouseLocation: b.warehouseLocation
? { id: b.warehouseLocation.id, code: b.warehouseLocation.code, name: b.warehouseLocation.name }
: null,
fileUrl: b.fileUrl,
fileName: b.fileName,
fileSize: b.fileSize,
}))
}
async bindBrandMaterialLocation(input: BindBrandMaterialLocationInput): Promise<BrandMaterialBindingDTO> {
const { brand, materialType, warehouseLocationId } = input
if (!brand || !materialType) {
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '品牌和物料类型不能为空')
}
if (warehouseLocationId) {
const location = await warehouseLocationRepository.findById(warehouseLocationId)
if (!location || !location.isActive) {
throw new AppError(ErrorCode.WAREHOUSE_LOCATION_NOT_FOUND, '库位不存在或已停用')
}
}
const result = await warehouseLocationRepository.upsertBrandMaterialBinding({
brand,
materialType,
warehouseLocationId,
})
return {
id: result.id,
brand: result.brand,
materialType: result.materialType,
warehouseLocation: result.warehouseLocation
? { id: result.warehouseLocation.id, code: result.warehouseLocation.code, name: result.warehouseLocation.name }
: null,
fileUrl: result.fileUrl,
fileName: result.fileName,
fileSize: result.fileSize,
}
}
async uploadBrandMaterialFile(brand: string, materialType: string, file: File): Promise<BrandMaterialBindingDTO> {
if (!brand || !materialType) {
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '品牌和物料类型不能为空')
}
if (materialType !== 'CARTON_PRINT') {
throw new AppError(ErrorCode.VALIDATION_FAILED, '仅外箱印刷支持文件上传')
}
const ext = file.name.split('.').pop()?.toLowerCase()
if (ext !== 'zip') {
throw new AppError(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 ZIP 格式文件')
}
if (file.size > 100 * 1024 * 1024) {
throw new AppError(ErrorCode.FILE_TOO_LARGE, '文件大小不能超过 100MB')
}
const key = `brand-materials/${brand}/${materialType}/${randomUUID()}.zip`
const fileUrl = await uploadBufferToS3(
Buffer.from(await file.arrayBuffer()),
key,
'application/zip',
)
const result = await warehouseLocationRepository.upsertBrandMaterialBinding({
brand,
materialType,
fileUrl,
fileName: file.name,
fileSize: file.size,
})
return {
id: result.id,
brand: result.brand,
materialType: result.materialType,
warehouseLocation: result.warehouseLocation
? { id: result.warehouseLocation.id, code: result.warehouseLocation.code, name: result.warehouseLocation.name }
: null,
fileUrl: result.fileUrl,
fileName: result.fileName,
fileSize: result.fileSize,
}
}
}
export const warehouseService = new WarehouseService()
export { WarehouseService }
export type {
AssetVariantBindingDTO,
BindBrandMaterialLocationInput,
BindVariantToLocationsInput,
BrandMaterialBindingDTO,
CreateWarehouseLocationInput,
UnbindVariantFromLocationInput,
UpdateWarehouseLocationInput,
WarehouseLocationDTO,
WarehouseOverviewDTO,
} from './warehouse.service.types'

View File

@ -52,3 +52,54 @@ export interface CreateWarehouseLocationInput {
bin?: string | null
notes?: string | null
}
export interface UpdateWarehouseLocationInput {
code?: string
name?: string
zone?: string | null
aisle?: string | null
shelf?: string | null
bin?: string | null
notes?: string | null
isActive?: boolean
}
export interface AssetVariantBindingDTO {
id: string
assetVariantId: string
warehouseLocation: {
id: string
code: string
name: string
}
}
export interface BindVariantToLocationsInput {
variantId: string
locationIds: string[]
}
export interface UnbindVariantFromLocationInput {
variantId: string
locationId: string
}
export interface BrandMaterialBindingDTO {
id: string
brand: string
materialType: string
warehouseLocation: {
id: string
code: string
name: string
} | null
fileUrl: string | null
fileName: string | null
fileSize: number | null
}
export interface BindBrandMaterialLocationInput {
brand: string
materialType: string
warehouseLocationId: string | null
}