Merge remote-tracking branch 'origin/codex/xuxiake-mainline' into codex/wuyongjie-production-stop-special-rules-20261126

This commit is contained in:
apple 2026-11-26 13:37:10 +08:00
commit 7d1d2ece6f
5 changed files with 831 additions and 5 deletions

View File

@ -14,6 +14,8 @@ import {
type SupplierCostAssessment,
type SupplierCostGrade,
} from '@/lib/supplier-cost-assessment'
import type { ProductAssuranceSupplierInput } from '@/lib/supplier-product-assurance'
import { SupplierProductAssurancePanel } from './SupplierProductAssurancePanel'
import styles from './legacy-purchase-modules.module.css'
type Mode = 'overview' | 'evaluation' | 'alternatives' | 'profiles'
@ -27,9 +29,11 @@ type SupplierProfile = {
capabilityRows: LegacySupplierCapabilityRecord[]
performance?: LegacySupplierRecord
equipment: LegacySupplierEquipmentRecord[]
categories: string[]
materials: string[]
processes: string[]
supports: string[]
equipmentCount: number
}
function numeric(value: unknown) {
@ -117,6 +121,7 @@ function buildProfiles(store: LegacySupplierStore) {
gradeRank(right.capabilityGrade || '') - gradeRank(left.capabilityGrade || '')
|| numeric(right.capabilityScore) - numeric(left.capabilityScore),
)[0]
const profileEquipment = equipment.get(capability.supplierCode || capability.supplier) || []
return {
key,
supplier: capability.supplier,
@ -124,10 +129,12 @@ function buildProfiles(store: LegacySupplierStore) {
capability,
capabilityRows: rows,
performance: performances.get(capability.supplier),
equipment: equipment.get(capability.supplierCode || capability.supplier) || [],
materials: [...new Set(rows.flatMap((row) => tokens(row.capabilityCategoryLabel || row.category)))],
equipment: profileEquipment,
categories: [...new Set(rows.flatMap((row) => tokens(row.capabilityCategoryLabel || row.category)))],
materials: [...new Set(rows.flatMap((row) => tokens(row.material)))],
processes: [...new Set(rows.flatMap((row) => tokens(row.capabilityProcessLabel || row.process)))],
supports: [...new Set(rows.flatMap((row) => tokens(row.capabilitySupportLabel || row.supportTags)))],
equipmentCount: equipmentQuantity(profileEquipment) || numeric(capability.capabilityEquipmentCount),
} satisfies SupplierProfile
}).sort((left, right) =>
gradeRank(right.capability.comprehensiveGrade || '') - gradeRank(left.capability.comprehensiveGrade || '')
@ -211,6 +218,7 @@ export function SupplierManagementClient({
const [costError, setCostError] = useState('')
const [highCostExpanded, setHighCostExpanded] = useState(true)
const [analysisTab, setAnalysisTab] = useState<AnalysisTab>('capability')
const [assuranceTab, setAssuranceTab] = useState<'supplier' | 'product'>('supplier')
const [query, setQuery] = useState('')
const [category, setCategory] = useState('all')
const [owner, setOwner] = useState('all')
@ -231,6 +239,23 @@ export function SupplierManagementClient({
const costForProfile = (profile: SupplierProfile) =>
costByCode.get(normalizeSupplierCostName(profile.supplierCode))
|| costByName.get(normalizeSupplierCostName(profile.supplier))
const productSupplierInputs = useMemo<ProductAssuranceSupplierInput[]>(() =>
profiles.map((profile) => ({
profile: {
key: profile.key,
supplier: profile.supplier,
supplierCode: profile.supplierCode,
categories: profile.categories,
materials: profile.materials,
processes: profile.processes,
equipmentCount: profile.equipmentCount,
purchaser: profile.capability.capabilityPurchaser || '',
comprehensiveGrade: profile.capability.comprehensiveGrade || '',
capabilityGrade: profile.capability.capabilityGrade || '',
},
cost: costByCode.get(normalizeSupplierCostName(profile.supplierCode))
|| costByName.get(normalizeSupplierCostName(profile.supplier)),
})), [costByCode, costByName, profiles])
const costProfileRows = profiles.map((profile) => ({
profile,
cost: costForProfile(profile),
@ -331,12 +356,18 @@ export function SupplierManagementClient({
const alternatives = sourceProfile
? profiles.filter((profile) => profile.key !== sourceProfile.key).map((candidate) => {
const missing = sourceProfile.processes.filter((process) => !candidate.processes.includes(process))
const materialOverlap = sourceProfile.materials.filter((material) => candidate.materials.includes(material)).length
const sourceMaterials = sourceProfile.materials.length
? sourceProfile.materials
: sourceProfile.categories
const candidateMaterials = candidate.materials.length
? candidate.materials
: candidate.categories
const materialOverlap = sourceMaterials.filter((material) => candidateMaterials.includes(material)).length
const cost = costForProfile(candidate)
const costScore = cost?.grade === 'A' ? 15 : cost?.grade === 'B' ? 12 : cost?.grade === 'C' ? 6 : 0
const score = Math.round(
(sourceProfile.processes.length ? (sourceProfile.processes.length - missing.length) / sourceProfile.processes.length : 0) * 50
+ (sourceProfile.materials.length ? materialOverlap / sourceProfile.materials.length : 0) * 20
+ (sourceMaterials.length ? materialOverlap / sourceMaterials.length : 0) * 20
+ gradeRank(candidate.capability.capabilityGrade || '') * 3
+ costScore,
)
@ -410,7 +441,9 @@ export function SupplierManagementClient({
const pageDescription = mode === 'evaluation'
? '统一查看能力画像、采购成本评估和经营绩效。'
: mode === 'alternatives'
? '模拟供应商停供或份额调整,按材质和工艺覆盖度筛选完全替代与部分替代候选。'
? assuranceTab === 'product'
? '按产品类目、材质和关键工序查询现有可生产工厂,并联动采购成本评估。'
: '模拟供应商停供或份额调整,按材质和工艺覆盖度筛选完全替代与部分替代候选。'
: mode === 'profiles'
? '搜索或筛选供应商,集中查看能力、经营摘要和设备明细。'
: '按“评估能力、监控经营、保障供应、维护档案”进入对应管理场景。'
@ -599,6 +632,24 @@ export function SupplierManagementClient({
{mode === 'alternatives' ? (
<>
<div className={styles.assuranceSwitcher}>
<button
type="button"
className={`${styles.assuranceSwitchButton} ${assuranceTab === 'supplier' ? styles.assuranceSwitchActive : ''}`}
onClick={() => setAssuranceTab('supplier')}
>
供应商维度查询
</button>
<button
type="button"
className={`${styles.assuranceSwitchButton} ${assuranceTab === 'product' ? styles.assuranceSwitchActive : ''}`}
onClick={() => setAssuranceTab('product')}
>
产品类型查询
</button>
</div>
{assuranceTab === 'supplier' ? (
<>
<section className={styles.panel}>
<div className={styles.panelHeader}><div><h2>选择停供供应商</h2><p>替代结果自动排除当前供应商,优先展示覆盖全部关键工序的候选</p></div></div>
<div className={styles.handoverGrid}>
@ -627,6 +678,15 @@ export function SupplierManagementClient({
<div className={styles.tableWrap}><table className={styles.table}><thead><tr><th>匹配度</th><th>候选供应商 / 采购</th><th>综合评估 / 设备能力</th><th>采购成本评估</th><th>可承接工艺</th><th>设备规模</th><th>缺失工艺</th></tr></thead><tbody>{(rows as typeof alternatives).map((candidate) => <tr key={candidate.key}><td>{candidate.score}</td><td><span className={styles.primaryCell}>{candidate.supplier}</span><small className={styles.subCell}>{candidate.capability.capabilityPurchaser || '采购未填'}</small></td><td>综合 {candidate.capability.comprehensiveGrade || '—'} · 设备 {candidate.capability.capabilityGrade || '—'}</td><td><span className={`${styles.status} ${costGradeClass(candidate.cost?.grade || 'PENDING')}`}>{candidate.cost?.gradeLabel || '待评估'}</span><small className={styles.subCell}>{costDeviation(candidate.cost?.deviationRate ?? null)}</small></td><td>{candidate.processes.join('、') || '—'}</td><td>{equipmentQuantity(candidate.equipment) || candidate.capability.capabilityEquipmentCount || 0} 台</td><td>{candidate.missing.join('、') || '无缺口'}</td></tr>)}</tbody></table></div>
</section>
))}
</>
) : (
<SupplierProductAssurancePanel
suppliers={productSupplierInputs}
costLoading={costLoading}
costError={costError}
canDownload={canDownload}
/>
)}
</>
) : null}
</div>

View File

@ -0,0 +1,278 @@
'use client'
import { useMemo, useState } from 'react'
import { Download, Search } from 'lucide-react'
import {
buildProductAssuranceOptions,
matchProductAssuranceSuppliers,
recommendProductProcesses,
splitProductAssuranceTerms,
type ProductAssuranceMatch,
type ProductAssuranceSupplierInput,
} from '@/lib/supplier-product-assurance'
import styles from './legacy-purchase-modules.module.css'
function formatPrice(value: number | null) {
return value === null || !Number.isFinite(value) ? '—' : `¥${value.toFixed(2)}`
}
function formatGap(value: number | null) {
if (value === null || !Number.isFinite(value)) return '—'
return `${value > 0 ? '+' : ''}${(value * 100).toFixed(1)}%`
}
function costTone(grade: string) {
if (grade === 'A') return styles.green
if (grade === 'B') return styles.blue
if (grade === 'C') return styles.orange
if (grade === 'D') return styles.red
return styles.neutral
}
function exportResults(results: ProductAssuranceMatch[], queryLabel: string) {
const columns: Array<[string, (row: ProductAssuranceMatch) => string | number]> = [
['供应商', (row) => row.supplier],
['供应商编码', (row) => row.supplierCode],
['采购负责人', (row) => row.purchaser],
['匹配等级', (row) => row.matchLevel === 'complete' ? '完全满足' : '有条件满足'],
['匹配度', (row) => row.score],
['类目 / 材质', (row) => row.categoryLabel],
['匹配工艺', (row) => row.matchedProcesses.join('、')],
['缺失工艺', (row) => row.missingProcesses.join('、')],
['供应商采购价', (row) => row.supplierPrice ?? ''],
['采购基准价', (row) => row.benchmarkPrice ?? ''],
['目标采购价', (row) => row.targetPrice ?? ''],
['价格偏差', (row) => formatGap(row.priceGapRate)],
['成本等级', (row) => row.costGrade],
['设备数量', (row) => row.equipmentCount],
['综合等级', (row) => row.comprehensiveGrade],
['设备能力等级', (row) => row.capabilityGrade],
]
const escape = (value: unknown) => `"${String(value ?? '').replaceAll('"', '""')}"`
const content = `\ufeff产品需求:${queryLabel}\n${columns.map(([label]) => escape(label)).join(',')}\n${results.map((row) => columns.map(([, read]) => escape(read(row))).join(',')).join('\n')}`
const link = document.createElement('a')
link.href = URL.createObjectURL(new Blob([content], { type: 'text/csv;charset=utf-8' }))
link.download = `产品类型可生产工厂-${new Date().toISOString().slice(0, 10)}.csv`
link.click()
setTimeout(() => URL.revokeObjectURL(link.href), 1000)
}
export function SupplierProductAssurancePanel({
suppliers,
costLoading,
costError,
canDownload,
}: {
suppliers: ProductAssuranceSupplierInput[]
costLoading: boolean
costError: string
canDownload: boolean
}) {
const options = useMemo(() => buildProductAssuranceOptions(suppliers), [suppliers])
const [categoryL2, setCategoryL2] = useState('')
const [material, setMaterial] = useState('')
const [processText, setProcessText] = useState('开料、钻孔、包装')
const [targetPriceText, setTargetPriceText] = useState('')
const [submitted, setSubmitted] = useState(false)
const processes = useMemo(
() => splitProductAssuranceTerms(processText),
[processText],
)
const targetPrice = Number(targetPriceText) > 0 ? Number(targetPriceText) : null
const results = useMemo(() => matchProductAssuranceSuppliers({
suppliers,
query: {
categoryL2,
material,
processes,
targetPrice,
},
}), [categoryL2, material, processes, suppliers, targetPrice])
const completeCount = results.filter((result) => result.matchLevel === 'complete').length
const conditionalCount = results.length - completeCount
const canSearch = Boolean(categoryL2.trim() && material.trim() && processes.length)
function updateCategory(value: string) {
setCategoryL2(value)
setProcessText(recommendProductProcesses({ categoryL2: value, material }).join('、'))
setSubmitted(false)
}
function updateMaterial(value: string) {
setMaterial(value)
setProcessText(recommendProductProcesses({ categoryL2, material: value }).join('、'))
setSubmitted(false)
}
function toggleProcess(process: string) {
const current = new Set(processes)
if (current.has(process)) current.delete(process)
else current.add(process)
setProcessText([...current].join('、'))
setSubmitted(false)
}
return (
<div className={styles.assuranceQueryLayout}>
<section className={styles.panel}>
<div className={styles.panelHeader}>
<div><h2>描述产品需求</h2><p>按类目、材质和关键工序反查现有可生产工厂</p></div>
<span className={`${styles.status} ${styles.blue}`}>{options.categories.length} 个产品类目</span>
</div>
<form
className={styles.productQueryForm}
onSubmit={(event) => {
event.preventDefault()
setSubmitted(true)
}}
>
<label>
产品类目
<input
list="product-assurance-category-options"
value={categoryL2}
onChange={(event) => updateCategory(event.target.value)}
placeholder="例如:电脑桌、书架、沙发"
required
/>
<datalist id="product-assurance-category-options">
{options.categories.map((value) => <option key={value} value={value} />)}
</datalist>
</label>
<label>
材质
<input
list="product-assurance-material-options"
value={material}
onChange={(event) => updateMaterial(event.target.value)}
placeholder="例如:实木多层板、板式、钢架"
required
/>
<datalist id="product-assurance-material-options">
{options.materials.map((value) => <option key={value} value={value} />)}
</datalist>
</label>
<label className={styles.wide}>
关键工序
<input
value={processText}
onChange={(event) => {
setProcessText(event.target.value)
setSubmitted(false)
}}
placeholder="系统会根据类目和材质推荐,可人工增删"
required
/>
<small>可点击下方工艺标签增删,匹配时使用当前输入值</small>
</label>
<div className={`${styles.processSelector} ${styles.wide}`}>
{options.processes.slice(0, 30).map((process) => (
<button
key={process}
type="button"
className={`${styles.processChip} ${processes.includes(process) ? styles.processChipActive : ''}`}
onClick={() => toggleProcess(process)}
>
{process}
</button>
))}
</div>
<label>
目标采购价
<input
type="number"
min="0"
step="0.01"
value={targetPriceText}
onChange={(event) => {
setTargetPriceText(event.target.value)
setSubmitted(false)
}}
placeholder="可不填"
/>
</label>
<div className={styles.productQueryActions}>
<button className={styles.primaryButton} type="submit" disabled={!canSearch || costLoading}>
<Search size={14} />{costLoading ? '成本数据加载中…' : '查询可生产工厂'}
</button>
{canDownload ? (
<button
className={styles.button}
type="button"
disabled={!submitted || !results.length}
onClick={() => exportResults(results, `${categoryL2} / ${material}`)}
>
<Download size={14} />导出结果
</button>
) : null}
</div>
<div className={`${styles.productDataSource} ${styles.wide}`}>
<strong>数据联动</strong>
<span>产品全量档案提供材质、二级类目和历史采购价;供应商档案提供工艺与设备能力。匹配只采用“材质 + 二级类目”成本基准。</span>
</div>
{costError ? <div className={`${styles.error} ${styles.wide}`}>{costError}</div> : null}
</form>
</section>
<section className={styles.panel}>
<div className={styles.panelHeader}>
<div><h2>可生产工厂</h2><p>{submitted ? '按匹配度和采购成本排序' : '填写产品需求后查询'}</p></div>
{submitted ? (
<div className={styles.productMatchSummary}>
<span className={styles.chip}>匹配 {results.length} 家</span>
<span className={`${styles.chip} ${styles.green}`}>完全满足 {completeCount}</span>
<span className={`${styles.chip} ${styles.orange}`}>有条件满足 {conditionalCount}</span>
</div>
) : null}
</div>
{submitted ? (
results.length ? (
<div className={styles.tableWrap}>
<table className={styles.table}>
<thead><tr><th>候选供应商</th><th>匹配等级</th><th>类目 / 材质</th><th>工序与设备</th><th>采购成本评估</th><th>采购负责人</th></tr></thead>
<tbody>{results.map((result) => (
<tr key={result.key}>
<td>
<span className={styles.primaryCell}>{result.supplier}</span>
<small className={styles.subCell}>{result.supplierCode || '无编码'} · 综合 {result.comprehensiveGrade || '待评级'}</small>
</td>
<td>
<span className={`${styles.status} ${result.matchLevel === 'complete' ? styles.green : styles.orange}`}>
{result.matchLevel === 'complete' ? '完全满足' : '有条件满足'}
</span>
<small className={styles.subCell}>匹配度 {result.score}%</small>
</td>
<td>{result.categoryLabel}</td>
<td>
<span className={styles.ellipsis} title={result.matchedProcesses.join('、')}>
{result.matchedProcesses.join('、') || '工艺数据待补'}
</span>
<small className={styles.subCell}>
{result.missingProcesses.length ? `缺失:${result.missingProcesses.join('、')}` : '关键工序全覆盖'} · {result.equipmentCount} 台设备
</small>
</td>
<td>
<span className={`${styles.status} ${costTone(result.costGrade)}`}>{result.costGrade === 'PENDING' ? '待评估' : `${result.costGrade} · ${result.costGradeLabel}`}</span>
<small className={styles.subCell}>{formatPrice(result.supplierPrice)} · 基准 {formatPrice(result.benchmarkPrice)}</small>
<small className={styles.subCell}>相对目标价 {formatGap(result.priceGapRate)}</small>
</td>
<td>{result.purchaser || '未指定'}</td>
</tr>
))}</tbody>
</table>
</div>
) : (
<div className={styles.empty}>当前类目和材质下没有找到匹配工厂;可减少关键工序或检查供应商档案。</div>
)
) : (
<div className={styles.productEmptyState}>
<Search size={28} />
<strong>按产品需求一键检索</strong>
<span>类目和材质为必填条件,关键工序由系统推荐并可人工调整。</span>
</div>
)}
</section>
</div>
)
}

View File

@ -380,11 +380,68 @@
.tab { display: inline-flex; height: 30px; align-items: center; justify-content: center; border: 0; border-radius: 5px; background: transparent; padding: 0 12px; color: #71717a; font: inherit; font-size: 11px; font-weight: 600; text-decoration: none; cursor: pointer; }
.tabActive { background: #27272a; color: #fff; }
.assuranceSwitcher {
display: inline-flex;
gap: 4px;
margin-bottom: 14px;
border: 1px solid #e4e4e7;
border-radius: 8px;
background: #fff;
padding: 4px;
}
.assuranceSwitchButton {
min-height: 34px;
border: 0;
border-radius: 6px;
background: transparent;
padding: 0 16px;
color: #71717a;
font: inherit;
font-size: 11px;
font-weight: 650;
cursor: pointer;
}
.assuranceSwitchButton:hover { background: #f4f4f5; color: #27272a; }
.assuranceSwitchActive { background: #27272a; color: #fff; box-shadow: 0 4px 12px rgba(24,24,27,.15); }
.assuranceSwitchActive:hover { background: #27272a; color: #fff; }
.assuranceQueryLayout { display: grid; grid-template-columns: minmax(300px, 390px) minmax(0, 1fr); gap: 14px; }
.productQueryForm { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; padding: 14px; }
.productQueryForm label { display: grid; gap: 6px; color: #52525b; font-size: 10px; font-weight: 650; }
.productQueryForm label small { color: #8b8b92; font-size: 9px; font-weight: 400; line-height: 1.45; }
.productQueryForm label.wide,
.productQueryForm .wide { grid-column: 1 / -1; }
.productQueryForm input {
box-sizing: border-box;
width: 100%;
height: 36px;
border: 1px solid #d4d4d8;
border-radius: 5px;
background: #fff;
padding: 0 9px;
color: #27272a;
font: inherit;
font-size: 11px;
outline: none;
}
.productQueryForm input:focus { border-color: #71717a; box-shadow: 0 0 0 2px rgba(63,63,70,.08); }
.processSelector { display: flex; flex-wrap: wrap; gap: 6px; }
.processChip { border: 1px solid #d4d4d8; border-radius: 999px; background: #fff; padding: 5px 9px; color: #71717a; font: inherit; font-size: 10px; cursor: pointer; }
.processChip:hover { border-color: #a1a1aa; color: #27272a; }
.processChipActive { border-color: #27272a; background: #27272a; color: #fff; }
.productQueryActions { display: flex; align-items: end; gap: 8px; }
.productDataSource { display: grid; gap: 4px; border: 1px solid #dbeafe; border-radius: 6px; background: #f5f9ff; padding: 10px 11px; color: #52627a; font-size: 10px; line-height: 1.55; }
.productDataSource strong { color: #31517b; font-size: 10px; }
.productMatchSummary { display: flex; flex-wrap: wrap; gap: 6px; }
.productEmptyState { display: grid; min-height: 320px; place-content: center; justify-items: center; gap: 9px; color: #8b8b92; text-align: center; }
.productEmptyState strong { color: #52525b; font-size: 14px; }
.productEmptyState span { max-width: 430px; font-size: 10px; line-height: 1.6; }
@media (max-width: 1200px) {
.metrics { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.metrics.metricsFour { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.handoverGrid { grid-template-columns: 1fr; }
.handoverSummary { border-top: 1px solid #e4e4e7; border-left: 0; padding-top: 12px; padding-left: 0; }
.assuranceQueryLayout { grid-template-columns: 1fr; }
}
@media (max-width: 760px) {
@ -395,7 +452,10 @@
.groupHead { align-items: flex-start; flex-direction: column; }
.formGrid,
.handoverForm,
.productQueryForm,
.inboxGrid { grid-template-columns: 1fr; }
.formGrid label.wide { grid-column: auto; }
.formGrid > .wide { grid-column: auto; }
.productQueryForm label.wide,
.productQueryForm .wide { grid-column: auto; }
}

View File

@ -0,0 +1,136 @@
import {
buildProductAssuranceOptions,
matchProductAssuranceSuppliers,
recommendProductProcesses,
} from './supplier-product-assurance'
import type { SupplierCostAssessment } from './supplier-cost-assessment'
const costs: SupplierCostAssessment[] = [{
supplierKey: 'supplier-a',
supplierName: '甲工厂',
supplierCode: 'A001',
productCount: 10,
validPriceCount: 10,
coverageRate: 1,
medianPurchasePrice: 260,
benchmarkPurchasePrice: 270,
deviationRate: -0.037,
grade: 'A',
gradeLabel: '成本优势',
categories: [{
category: '实木多层板 / 电脑桌',
productCount: 10,
validPriceCount: 10,
supplierMedianPrice: 260,
categoryBenchmarkPrice: 270,
deviationRate: -0.037,
grade: 'A',
}],
}, {
supplierKey: 'supplier-b',
supplierName: '乙工厂',
supplierCode: 'B001',
productCount: 5,
validPriceCount: 3,
coverageRate: 0.6,
medianPurchasePrice: 280,
benchmarkPurchasePrice: 270,
deviationRate: 0.037,
grade: 'B',
gradeLabel: '成本正常',
categories: [{
category: '实木多层板 / 电脑桌',
productCount: 5,
validPriceCount: 3,
supplierMedianPrice: 280,
categoryBenchmarkPrice: 270,
deviationRate: 0.037,
grade: 'PENDING',
}],
}]
const suppliers = [
{
profile: {
key: 'a',
supplier: '甲工厂',
supplierCode: 'A001',
categories: ['板式生产'],
materials: ['实木多层板'],
processes: ['开料', '封边', '钻孔', '包装', '五金装配'],
equipmentCount: 8,
purchaser: '雁兰',
comprehensiveGrade: 'A',
capabilityGrade: 'S',
},
cost: costs[0],
},
{
profile: {
key: 'b',
supplier: '乙工厂',
supplierCode: 'B001',
categories: ['板式生产'],
materials: ['实木多层板'],
processes: ['开料', '钻孔', '包装'],
equipmentCount: 3,
purchaser: '貂蝉',
comprehensiveGrade: 'B',
capabilityGrade: 'B',
},
cost: costs[1],
},
]
describe('supplier product assurance matching', () => {
it('recommends editable processes from product category and material', () => {
expect(recommendProductProcesses({
categoryL2: '电脑桌',
material: '实木多层板',
})).toEqual(expect.arrayContaining(['开料', '封边', '钻孔', '包装', '五金装配']))
})
it('builds category and material options from supplier cost evidence', () => {
const options = buildProductAssuranceOptions(suppliers)
expect(options.categories).toContain('电脑桌')
expect(options.materials).toContain('实木多层板')
expect(options.processes).toContain('封边')
})
it('ranks complete matches before conditional matches and uses archive benchmark price', () => {
const results = matchProductAssuranceSuppliers({
suppliers,
query: {
categoryL2: '电脑桌',
material: '实木多层板',
processes: ['开料', '封边', '钻孔', '包装', '五金装配'],
targetPrice: 280,
},
})
expect(results).toHaveLength(2)
expect(results[0]).toMatchObject({
supplier: '甲工厂',
matchLevel: 'complete',
supplierPrice: 260,
benchmarkPrice: 270,
missingProcesses: [],
})
expect(results[1]).toMatchObject({
supplier: '乙工厂',
matchLevel: 'conditional',
missingProcesses: ['封边', '五金装配'],
})
})
it('excludes suppliers without matching product archive category evidence', () => {
expect(matchProductAssuranceSuppliers({
suppliers,
query: {
categoryL2: '办公椅',
material: '网布',
processes: ['裁剪', '车缝'],
targetPrice: null,
},
})).toEqual([])
})
})

View File

@ -0,0 +1,292 @@
import type {
SupplierCategoryCostAssessment,
SupplierCostAssessment,
SupplierCostGrade,
} from './supplier-cost-assessment'
import { supplierCostGradeLabel } from './supplier-cost-assessment'
export type ProductAssuranceProfile = {
key: string
supplier: string
supplierCode: string
categories: string[]
materials: string[]
processes: string[]
equipmentCount: number
purchaser: string
comprehensiveGrade: string
capabilityGrade: string
}
export type ProductAssuranceSupplierInput = {
profile: ProductAssuranceProfile
cost: SupplierCostAssessment | undefined
}
export type ProductAssuranceQuery = {
categoryL2: string
material: string
processes: string[]
targetPrice: number | null
}
export type ProductAssuranceMatch = {
key: string
supplier: string
supplierCode: string
purchaser: string
matchLevel: 'complete' | 'conditional'
score: number
categoryLabel: string
supplierPrice: number | null
benchmarkPrice: number | null
targetPrice: number | null
priceGapRate: number | null
costGrade: SupplierCostGrade
costGradeLabel: string
matchedProcesses: string[]
missingProcesses: string[]
materialSource: 'supplier-profile' | 'product-archive' | 'unknown'
equipmentCount: number
comprehensiveGrade: string
capabilityGrade: string
}
export type ProductAssuranceOptions = {
categories: string[]
materials: string[]
processes: string[]
}
const BASE_PROCESSES = ['开料', '钻孔', '包装']
const PROCESS_ALIASES: Record<string, string[]> = {
开料: ['开料', '裁切'],
钻孔: ['钻孔'],
包装: ['包装'],
封边: ['封边'],
五金装配: ['五金装配', '组装', '装配'],
砂光: ['砂光', '打磨'],
涂装: ['涂装', '饰面'],
焊接: ['焊接', '金属成型'],
喷涂: ['喷涂', '涂装'],
裁剪: ['裁剪', '裁切'],
车缝: ['车缝', '缝制'],
扪制: ['扪制', '软包'],
}
export function normalizeProductAssuranceText(value: unknown) {
return String(value ?? '')
.normalize('NFKC')
.toLowerCase()
.replace(/[\s\-_/\\|·,,。;;+()()、]/g, '')
}
export function splitProductAssuranceTerms(value: unknown) {
return [...new Set(
String(value ?? '')
.split(/[,,、;;|/\n++]+/)
.map((item) => item.trim())
.filter(Boolean),
)]
}
function includesTerm(values: readonly string[], term: string) {
const normalizedTerm = normalizeProductAssuranceText(term)
if (!normalizedTerm) return false
return values.some((value) => {
const normalizedValue = normalizeProductAssuranceText(value)
return normalizedValue === normalizedTerm
|| normalizedValue.includes(normalizedTerm)
|| normalizedTerm.includes(normalizedValue)
})
}
function includesProcess(values: readonly string[], process: string) {
return (PROCESS_ALIASES[process] || [process]).some((alias) => includesTerm(values, alias))
}
export function recommendProductProcesses(input: {
categoryL2?: string
material?: string
categoryText?: string
}) {
const material = String(input.material || '')
const category = `${input.categoryL2 || ''}${input.categoryText || ''}`
const result = new Set(BASE_PROCESSES)
if (/板|多层|密度|刨花|颗粒|生态|饰面/.test(material)) result.add('封边')
if (/实木|原木|木/.test(material) && !/板材|多层|密度|刨花/.test(material)) {
result.add('砂光')
result.add('涂装')
}
if (/钢|铁|金属|铝|合金/.test(material)) {
result.add('焊接')
result.add('喷涂')
}
if (/玻璃/.test(material)) {
result.add('钢化')
result.add('磨边')
}
if (/布|皮|海绵|软体|沙发/.test(`${material}${category}`)) {
result.add('裁剪')
result.add('车缝')
result.add('扪制')
}
if (/桌|柜|床|架|凳|椅|沙发/.test(category)) result.add('五金装配')
return [...result]
}
function costCategories(cost?: SupplierCostAssessment) {
return cost?.categories || []
}
function parseCostCategory(category: SupplierCategoryCostAssessment) {
const [materialPart, ...categoryParts] = category.category.split('/')
return {
material: materialPart.trim(),
categoryL2: categoryParts.join('/').trim(),
raw: category,
}
}
function matchingCostCategory(
cost: SupplierCostAssessment | undefined,
query: ProductAssuranceQuery,
) {
return costCategories(cost).find((category) => {
const parsed = parseCostCategory(category)
return includesTerm([parsed.categoryL2], query.categoryL2)
&& includesTerm([parsed.material], query.material)
}) || null
}
function benchmarkForQuery(
suppliers: readonly ProductAssuranceSupplierInput[],
query: ProductAssuranceQuery,
) {
const prices = suppliers.flatMap(({ cost }) =>
costCategories(cost)
.filter((category) => {
const parsed = parseCostCategory(category)
return includesTerm([parsed.categoryL2], query.categoryL2)
&& includesTerm([parsed.material], query.material)
&& category.categoryBenchmarkPrice !== null
})
.map((category) => category.categoryBenchmarkPrice as number),
)
if (!prices.length) return null
const sorted = prices.sort((left, right) => left - right)
return sorted[Math.floor(sorted.length / 2)]
}
export function buildProductAssuranceOptions(
suppliers: readonly ProductAssuranceSupplierInput[],
): ProductAssuranceOptions {
const categories = new Set<string>()
const materials = new Set<string>()
const processes = new Set<string>()
const hasProductArchiveCost = suppliers.some(({ cost }) => costCategories(cost).length > 0)
suppliers.forEach(({ profile, cost }) => {
if (!hasProductArchiveCost) {
profile.categories.forEach((value) => categories.add(value))
}
profile.materials.forEach((value) => materials.add(value))
profile.processes.forEach((value) => processes.add(value))
costCategories(cost).forEach((category) => {
const parsed = parseCostCategory(category)
if (parsed.categoryL2) categories.add(parsed.categoryL2)
if (parsed.material) materials.add(parsed.material)
})
})
const sort = (values: Set<string>) => [...values]
.filter(Boolean)
.sort((left, right) => left.localeCompare(right, 'zh-CN'))
return {
categories: sort(categories),
materials: sort(materials),
processes: sort(processes),
}
}
export function matchProductAssuranceSuppliers(input: {
suppliers: readonly ProductAssuranceSupplierInput[]
query: ProductAssuranceQuery
maxMissingProcesses?: number
}) {
const categoryQuery = input.query.categoryL2.trim()
const materialQuery = input.query.material.trim()
if (!categoryQuery || !materialQuery) return []
const benchmarkPrice = benchmarkForQuery(input.suppliers, input.query)
const maxMissingProcesses = Math.max(0, input.maxMissingProcesses ?? 2)
const gradeWeight: Record<string, number> = { S: 12, A: 10, B: 7, C: 4, D: 1 }
const results: ProductAssuranceMatch[] = []
input.suppliers.forEach(({ profile, cost }) => {
const categoryCost = matchingCostCategory(cost, input.query)
if (!categoryCost) return
const matchedProcesses = input.query.processes.filter((process) =>
includesProcess(profile.processes, process),
)
const missingProcesses = input.query.processes.filter((process) =>
!includesProcess(profile.processes, process),
)
if (missingProcesses.length > maxMissingProcesses) return
const profileMaterialMatched = includesTerm(profile.materials, materialQuery)
const materialSource = profileMaterialMatched
? 'supplier-profile'
: categoryCost
? 'product-archive'
: 'unknown'
const supplierPrice = categoryCost.supplierMedianPrice
?? cost?.medianPurchasePrice
?? null
const priceBase = input.query.targetPrice || benchmarkPrice
const priceGapRate = supplierPrice !== null && priceBase
? (supplierPrice - priceBase) / priceBase
: null
const processScore = input.query.processes.length
? matchedProcesses.length / input.query.processes.length * 25
: 25
const priceScore = priceGapRate === null
? 5
: priceGapRate <= 0
? 10
: Math.max(0, 10 - priceGapRate * 50)
const score = Math.round(Math.min(100,
45
+ processScore
+ (gradeWeight[profile.capabilityGrade.toUpperCase()] || 0)
+ (gradeWeight[profile.comprehensiveGrade.toUpperCase()] || 0) / 2
+ priceScore,
))
const complete = missingProcesses.length === 0
results.push({
key: profile.key,
supplier: profile.supplier,
supplierCode: profile.supplierCode,
purchaser: profile.purchaser,
matchLevel: complete ? 'complete' : 'conditional',
score,
categoryLabel: categoryCost.category,
supplierPrice,
benchmarkPrice,
targetPrice: input.query.targetPrice,
priceGapRate,
costGrade: categoryCost.grade,
costGradeLabel: supplierCostGradeLabel(categoryCost.grade),
matchedProcesses,
missingProcesses,
materialSource,
equipmentCount: profile.equipmentCount,
comprehensiveGrade: profile.comprehensiveGrade,
capabilityGrade: profile.capabilityGrade,
})
})
return results.sort((left, right) =>
Number(right.matchLevel === 'complete') - Number(left.matchLevel === 'complete')
|| right.score - left.score
|| (left.priceGapRate ?? Number.POSITIVE_INFINITY)
- (right.priceGapRate ?? Number.POSITIVE_INFINITY)
|| left.supplier.localeCompare(right.supplier, 'zh-CN'),
)
}