feat(limit-management): consolidate limit and freight maintenance

This commit is contained in:
居居 2026-10-28 11:48:59 +08:00
parent 2af0a45e6a
commit 75adc3f7f2
62 changed files with 60249 additions and 867 deletions

View File

@ -39,6 +39,15 @@ JST_RPA_LOGIN_ID=
JST_RPA_LOGIN_PASSWORD=
JST_RPA_ATTEMPTS=3
JST_RPA_FALLBACK_BATCH_SIZE=10000
# 限价流程历史快照首次构建的追溯起点;后续只按更新时间增量同步。
LIMIT_PRICE_HISTORY_SOURCE_START=2026-01-01T00:00:00
# 产品限价页面已确认记录来源库(限价历史抽屉展示来源记录时使用)。
PROD_ARCHIVE_DB_HOST=
PROD_ARCHIVE_DB_PORT=5432
PROD_ARCHIVE_DB_NAME=
PROD_ARCHIVE_DB_USER=
PROD_ARCHIVE_DB_PASSWORD=
PROD_ARCHIVE_DB_SSL=true
# OA 新品流程看板数据源。默认 mysql;切换到 JSReportReplica 时设为 mssql。
OA_BOARD_SOURCE_DRIVER=mysql

View File

@ -0,0 +1,257 @@
{
"version": 1,
"generatedAt": "2026-10-26T08:52:26.453Z",
"sourceFile": "各省发货占比.xlsx",
"totalShipment": 10983200,
"rowCount": 31,
"rows": [
{
"province": "安徽",
"shipmentCount": 426181,
"totalShipment": 10983200,
"shipmentShare": 0.038803,
"region": "一区",
"regionShare": 0.214
},
{
"province": "江苏",
"shipmentCount": 800646,
"totalShipment": 10983200,
"shipmentShare": 0.072897,
"region": "一区",
"regionShare": 0.214
},
{
"province": "上海",
"shipmentCount": 325564,
"totalShipment": 10983200,
"shipmentShare": 0.029642,
"region": "一区",
"regionShare": 0.214
},
{
"province": "浙江",
"shipmentCount": 797004,
"totalShipment": 10983200,
"shipmentShare": 0.072566,
"region": "一区",
"regionShare": 0.214
},
{
"province": "北京",
"shipmentCount": 290861,
"totalShipment": 10983200,
"shipmentShare": 0.026482,
"region": "二区",
"regionShare": 0.485
},
{
"province": "福建",
"shipmentCount": 467880,
"totalShipment": 10983200,
"shipmentShare": 0.0426,
"region": "二区",
"regionShare": 0.485
},
{
"province": "广东",
"shipmentCount": 1820992,
"totalShipment": 10983200,
"shipmentShare": 0.165798,
"region": "二区",
"regionShare": 0.485
},
{
"province": "河北",
"shipmentCount": 424406,
"totalShipment": 10983200,
"shipmentShare": 0.038641,
"region": "二区",
"regionShare": 0.485
},
{
"province": "河南",
"shipmentCount": 546529,
"totalShipment": 10983200,
"shipmentShare": 0.04976,
"region": "二区",
"regionShare": 0.485
},
{
"province": "湖北",
"shipmentCount": 378469,
"totalShipment": 10983200,
"shipmentShare": 0.034459,
"region": "二区",
"regionShare": 0.485
},
{
"province": "湖南",
"shipmentCount": 386336,
"totalShipment": 10983200,
"shipmentShare": 0.035175,
"region": "二区",
"regionShare": 0.485
},
{
"province": "江西",
"shipmentCount": 271676,
"totalShipment": 10983200,
"shipmentShare": 0.024736,
"region": "二区",
"regionShare": 0.485
},
{
"province": "山东",
"shipmentCount": 626419,
"totalShipment": 10983200,
"shipmentShare": 0.057034,
"region": "二区",
"regionShare": 0.485
},
{
"province": "天津",
"shipmentCount": 115475,
"totalShipment": 10983200,
"shipmentShare": 0.010514,
"region": "二区",
"regionShare": 0.485
},
{
"province": "广西",
"shipmentCount": 397325,
"totalShipment": 10983200,
"shipmentShare": 0.036176,
"region": "三区",
"regionShare": 0.251
},
{
"province": "贵州",
"shipmentCount": 242963,
"totalShipment": 10983200,
"shipmentShare": 0.022121,
"region": "三区",
"regionShare": 0.251
},
{
"province": "黑龙",
"shipmentCount": 166557,
"totalShipment": 10983200,
"shipmentShare": 0.015165,
"region": "三区",
"regionShare": 0.251
},
{
"province": "吉林",
"shipmentCount": 135735,
"totalShipment": 10983200,
"shipmentShare": 0.012358,
"region": "三区",
"regionShare": 0.251
},
{
"province": "辽宁",
"shipmentCount": 257754,
"totalShipment": 10983200,
"shipmentShare": 0.023468,
"region": "三区",
"regionShare": 0.251
},
{
"province": "山西",
"shipmentCount": 177480,
"totalShipment": 10983200,
"shipmentShare": 0.016159,
"region": "三区",
"regionShare": 0.251
},
{
"province": "陕西",
"shipmentCount": 281956,
"totalShipment": 10983200,
"shipmentShare": 0.025672,
"region": "三区",
"regionShare": 0.251
},
{
"province": "四川",
"shipmentCount": 532179,
"totalShipment": 10983200,
"shipmentShare": 0.048454,
"region": "三区",
"regionShare": 0.251
},
{
"province": "云南",
"shipmentCount": 341852,
"totalShipment": 10983200,
"shipmentShare": 0.031125,
"region": "三区",
"regionShare": 0.251
},
{
"province": "重庆",
"shipmentCount": 222288,
"totalShipment": 10983200,
"shipmentShare": 0.020239,
"region": "三区",
"regionShare": 0.251
},
{
"province": "甘肃",
"shipmentCount": 144419,
"totalShipment": 10983200,
"shipmentShare": 0.013149,
"region": "四区",
"regionShare": 0.05
},
{
"province": "海南",
"shipmentCount": 148380,
"totalShipment": 10983200,
"shipmentShare": 0.01351,
"region": "四区",
"regionShare": 0.05
},
{
"province": "内蒙",
"shipmentCount": 166636,
"totalShipment": 10983200,
"shipmentShare": 0.015172,
"region": "四区",
"regionShare": 0.05
},
{
"province": "宁夏",
"shipmentCount": 47493,
"totalShipment": 10983200,
"shipmentShare": 0.004324,
"region": "四区",
"regionShare": 0.05
},
{
"province": "青海",
"shipmentCount": 39031,
"totalShipment": 10983200,
"shipmentShare": 0.003554,
"region": "四区",
"regionShare": 0.05
},
{
"province": "西藏",
"shipmentCount": 441,
"totalShipment": 10983200,
"shipmentShare": 0.00004,
"region": "未分区",
"regionShare": 0.0002471046689489402
},
{
"province": "新疆",
"shipmentCount": 2273,
"totalShipment": 10983200,
"shipmentShare": 0.000207,
"region": "未分区",
"regionShare": 0.0002471046689489402
}
]
}

File diff suppressed because it is too large Load Diff

View File

@ -35,6 +35,8 @@
"compare:product-sabc-xlsx": "tsx scripts/compare-product-sabc-xlsx.ts",
"seed:local-product-sabc-xlsx": "tsx scripts/seed-local-product-sabc-xlsx.ts",
"sync:jst-sku-product-archive": "tsx scripts/sync-jst-sku-product-archive.ts",
"import:province-shipment-share": "node scripts/import-province-shipment-share.mjs",
"sync:jst-logistics-rules": "tsx scripts/sync-jst-logistics-rules.ts",
"sync:bom-cost-reference": "tsx scripts/sync-bom-cost-reference.ts",
"backtest:bom-cost-reference": "tsx scripts/backtest-bom-cost-reference.ts",
"report:bom-cost-shadow-divergence": "tsx scripts/report-bom-cost-shadow-divergence.ts",

View File

@ -0,0 +1,22 @@
CREATE TABLE "SupplyChainManualLimitPriceBatch" (
"id" TEXT NOT NULL,
"fileName" TEXT NOT NULL,
"targetPrice" DECIMAL(18,4),
"rowCount" INTEGER NOT NULL,
"uniqueCodeCount" INTEGER NOT NULL,
"matchedBarcodeCount" INTEGER NOT NULL,
"matchedStyleCount" INTEGER NOT NULL,
"updatedLimitCount" INTEGER NOT NULL,
"codes" JSONB NOT NULL DEFAULT '[]',
"unmatchedCodes" JSONB NOT NULL DEFAULT '[]',
"invalidRows" JSONB NOT NULL DEFAULT '[]',
"conflictingStyles" JSONB NOT NULL DEFAULT '[]',
"uploadedById" TEXT NOT NULL DEFAULT '',
"uploadedByName" TEXT NOT NULL DEFAULT '',
"note" TEXT NOT NULL DEFAULT '',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SupplyChainManualLimitPriceBatch_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "SupplyChainManualLimitPriceBatch_createdAt_idx"
ON "SupplyChainManualLimitPriceBatch"("createdAt");

View File

@ -0,0 +1,22 @@
CREATE TABLE "SupplyChainLimitPriceHistorySnapshot" (
"id" TEXT NOT NULL,
"barcode" TEXT NOT NULL,
"sku" TEXT NOT NULL DEFAULT '',
"spu" TEXT NOT NULL DEFAULT '',
"flows" JSONB NOT NULL DEFAULT '[]',
"fields" JSONB NOT NULL DEFAULT '[]',
"syncedThrough" TEXT NOT NULL,
"lastSyncAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SupplyChainLimitPriceHistorySnapshot_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "SupplyChainLimitPriceHistorySnapshot_barcode_sku_spu_key"
ON "SupplyChainLimitPriceHistorySnapshot"("barcode", "sku", "spu");
CREATE INDEX "SupplyChainLimitPriceHistorySnapshot_barcode_idx"
ON "SupplyChainLimitPriceHistorySnapshot"("barcode");
CREATE INDEX "SupplyChainLimitPriceHistorySnapshot_sku_idx"
ON "SupplyChainLimitPriceHistorySnapshot"("sku");

View File

@ -5438,6 +5438,48 @@ model SupplyChainStyleLimitPrice {
updatedAt DateTime @updatedAt
}
/// 限价管理 · 负责人限价历史流程快照。首次查询保存原始流程与表单字段,
/// 后续按报表库 updateAt 水位增量刷新。
model SupplyChainLimitPriceHistorySnapshot {
id String @id @default(cuid())
barcode String
sku String @default("")
spu String @default("")
flows Json @default("[]")
fields Json @default("[]")
/// 本次快照对应的报表库时间,下一次从这里继续增量同步。
syncedThrough String
lastSyncAttemptAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([barcode, sku, spu])
@@index([barcode])
@@index([sku])
}
/// 限价管理 · 人工上传批次。最终生效价格写入 SupplyChainStyleLimitPrice(applyType=人工指定限价)。
model SupplyChainManualLimitPriceBatch {
id String @id @default(cuid())
fileName String
targetPrice Decimal? @db.Decimal(18, 4)
rowCount Int
uniqueCodeCount Int
matchedBarcodeCount Int
matchedStyleCount Int
updatedLimitCount Int
codes Json @default("[]")
unmatchedCodes Json @default("[]")
invalidRows Json @default("[]")
conflictingStyles Json @default("[]")
uploadedById String @default("")
uploadedByName String @default("")
note String @default("")
createdAt DateTime @default(now())
@@index([createdAt])
}
/// 限价流程同步 · 价格授权(同价申请 / 活动限价;供破价判定豁免与超期判定)。
model SupplyChainLimitFlowAuth {
id String @id @default(cuid())

View File

@ -0,0 +1,96 @@
#!/usr/bin/env node
import fs from 'node:fs/promises'
import path from 'node:path'
import XLSX from 'xlsx'
const inputPath = process.argv[2]?.trim()
if (!inputPath) throw new Error('请传入各省发货占比 Excel 路径')
const workbook = XLSX.readFile(path.resolve(inputPath), { cellDates: false })
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
const rawRows = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: null })
const headers = rawRows[0]?.map((value) => String(value ?? '').trim()) ?? []
const expectedHeaders = ['省份', '发货量', '总量', '发货占比', '区域', '区域占比']
if (expectedHeaders.some((header, index) => headers[index] !== header)) {
throw new Error(`Excel 表头不符合预期:${expectedHeaders.join('、')}`)
}
const rows = rawRows
.slice(1)
.filter((row) => String(row[0] ?? '').trim())
.map((row) => {
const rawRegion = String(row[4] ?? '').trim()
return {
province: String(row[0]).trim(),
shipmentCount: Number(row[1]),
totalShipment: Number(row[2]),
shipmentShare: Number(row[3]),
region: !rawRegion || rawRegion.startsWith('#') ? '未分区' : rawRegion,
regionShare: row[5] === null || row[5] === undefined || row[5] === ''
? null
: Number(row[5]),
}
})
if (!rows.length) throw new Error('Excel 中没有省份数据')
const totalShipments = rows.reduce((sum, row) => sum + row.shipmentCount, 0)
const totalShares = rows.reduce((sum, row) => sum + row.shipmentShare, 0)
const declaredTotals = new Set(rows.map((row) => row.totalShipment))
if (declaredTotals.size !== 1 || !rows.every((row) => Number.isFinite(row.shipmentCount))) {
throw new Error('各省明细的总量或发货量不一致')
}
const declaredTotal = [...declaredTotals][0]
if (totalShipments !== declaredTotal || Math.abs(totalShares - 1) > 0.000001) {
throw new Error(`明细校验失败:发货量 ${totalShipments},占比 ${totalShares}`)
}
const regionShipmentTotals = new Map()
const declaredRegionShares = new Map()
for (const row of rows) {
regionShipmentTotals.set(
row.region,
(regionShipmentTotals.get(row.region) ?? 0) + row.shipmentCount,
)
if (row.regionShare === null) continue
if (!Number.isFinite(row.regionShare) || row.regionShare < 0 || row.regionShare > 1) {
throw new Error(`区域占比不正确:${row.region} ${row.regionShare}`)
}
const existing = declaredRegionShares.get(row.region)
if (existing !== undefined && Math.abs(existing - row.regionShare) > 0.0005) {
throw new Error(`同一区域存在不同占比:${row.region} ${existing} / ${row.regionShare}`)
}
declaredRegionShares.set(row.region, row.regionShare)
}
for (const row of rows) {
row.regionShare = declaredRegionShares.get(row.region)
?? (regionShipmentTotals.get(row.region) ?? 0) / declaredTotal
}
const snapshot = {
version: 1,
generatedAt: new Date().toISOString(),
sourceFile: path.basename(inputPath),
totalShipment: declaredTotal,
rowCount: rows.length,
rows,
}
const outputPath = path.join(
process.cwd(),
'data',
'freight-config',
'province-shipment-share.json',
)
await fs.mkdir(path.dirname(outputPath), { recursive: true })
const temporaryPath = `${outputPath}.tmp`
await fs.writeFile(temporaryPath, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8')
await fs.rename(temporaryPath, outputPath)
console.log(JSON.stringify({
outputPath,
rowCount: snapshot.rowCount,
totalShipment: snapshot.totalShipment,
totalShare: totalShares,
}, null, 2))

View File

@ -0,0 +1,420 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import puppeteer, { type Browser, type Page } from 'puppeteer'
import { normalizeWarehouseName } from '@/lib/freight-calculation'
const BROWSER_URL = process.env.JST_RPA_BROWSER_URL?.trim() || 'http://127.0.0.1:9222'
const RULE_PATH = '/app/wms/LogisticsCompany/Rule/List.aspx'
const OUTPUT_PATH = path.join(
process.cwd(),
'data',
'freight-config',
'warehouse-express-rules.json',
)
const NON_SHIPPING_EXPRESS_NAMES = new Set([
'匹配错误',
'无需物流',
'自提自送',
'',
])
type LiveRule = {
name: string
lc_name: string
wh_names: string
enabled: boolean
status: string
effective_time: string
freight_type: string
rule_id: number
data: string
}
type PhysicalRuleLimits = {
minWeight: number | null
maxWeight: number | null
minVolume: number | null
maxVolume: number | null
minLongestSide: number | null
maxLongestSide: number | null
minSecondLongestSide: number | null
maxSecondLongestSide: number | null
minAmount: number | null
maxAmount: number | null
minBubbleRatio: number | null
maxBubbleRatio: number | null
minThreeSideSum: number | null
maxThreeSideSum: number | null
includedSkuIds: string
excludedSkuIds: string
includedSkuLabels: string
excludedSkuLabels: string
includedOrderLabels: string
excludedOrderLabels: string
allowedProvinces: string
allowedCities: string
allowedDistricts: string
disabledPcds: string
disabledAddressKeywords: string
systemUnreachableArea: boolean
companyIds: string
distributorFromIds: string
distributorToIds: string
orderTypes: string
shopSites: string
shopIds: string
thirdShopIds: string
excludedShopIds: string
shopDistributorCondition: string
}
type SnapshotRule = PhysicalRuleLimits & {
ruleId: string
ruleName: string
expressName: string
warehouses: string[]
effectiveTime: string
}
type SnapshotWarehouse = {
warehouseName: string
sourceWarehouseNames: string[]
expressNames: string[]
courierRules: Array<PhysicalRuleLimits & {
ruleId: string
ruleName: string
expressName: string
sourceWarehouseName: string
}>
ruleCount: number
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function splitWarehouses(value: string) {
return [...new Set(
value
.split(/[,,、]/)
.map((item) => item.trim())
.filter(Boolean),
)]
}
function numericLimit(value: unknown) {
if (value === null || value === undefined || value === '') return null
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : null
}
function textLimit(value: unknown) {
return typeof value === 'string' ? value.trim() : ''
}
function readPhysicalRuleLimits(raw: string): PhysicalRuleLimits {
let data: Record<string, unknown> = {}
try {
const parsed = JSON.parse(raw) as unknown
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
data = parsed as Record<string, unknown>
}
} catch {
// Keep the courier route even if an older JST rule has malformed detail data.
}
return {
minWeight: numericLimit(data.begin_weight),
maxWeight: numericLimit(data.end_weight),
minVolume: numericLimit(data.begin_volume),
maxVolume: numericLimit(data.end_volume),
minLongestSide: numericLimit(data.begin_max_lenght),
maxLongestSide: numericLimit(data.end_max_lenght),
minSecondLongestSide: numericLimit(data.begin_second_lenght),
maxSecondLongestSide: numericLimit(data.end_second_lenght),
minAmount: numericLimit(data.begin_amount),
maxAmount: numericLimit(data.end_amount),
minBubbleRatio: numericLimit(data.begin_bubble_ratio),
maxBubbleRatio: numericLimit(data.end_bubble_ratio),
minThreeSideSum: numericLimit(data.begin_sum),
maxThreeSideSum: numericLimit(data.end_sum),
includedSkuIds: textLimit(data.sku_id),
excludedSkuIds: textLimit(data.no_sku_id),
includedSkuLabels: textLimit(data.skuLabels),
excludedSkuLabels: textLimit(data.noSkuLabels),
includedOrderLabels: textLimit(data.labels),
excludedOrderLabels: textLimit(data.nolabels),
allowedProvinces: textLimit(data.states),
allowedCities: textLimit(data.citys),
allowedDistricts: textLimit(data.districts),
disabledPcds: textLimit(data.disable_pcds),
disabledAddressKeywords: textLimit(data.disable_address),
systemUnreachableArea: data.sys_unreachable_area === true
|| data.sys_unreachable_area === 'true',
companyIds: textLimit(data.company_ids),
distributorFromIds: textLimit(data.drp_co_id_from),
distributorToIds: textLimit(data.drp_co_id_to),
orderTypes: textLimit(data.order_type),
shopSites: textLimit(data.shop_site),
shopIds: textLimit(data.shop_ids),
thirdShopIds: textLimit(data.third_shopids),
excludedShopIds: textLimit(data.exclude_shop_ids),
shopDistributorCondition: textLimit(data.shop_drp_condition),
}
}
async function findAnyErpPage(browser: Browser) {
const pages = await browser.pages()
return pages.find((page) => page.url().startsWith('https://www.erp321.com'))
}
async function resolveOwnerCompanyId(browser: Browser) {
const envValue = process.env.JST_ERP_OWNER_CO_ID?.trim()
if (envValue) return envValue
const page = await findAnyErpPage(browser)
if (!page) throw new Error('自动化浏览器中没有聚水潭 ERP 页面')
for (const frame of page.frames()) {
const ownerCoId = await frame.evaluate(
() => (window as unknown as { ownerCoId?: unknown }).ownerCoId,
).catch(() => undefined)
if (typeof ownerCoId === 'string' && ownerCoId.trim()) return ownerCoId.trim()
}
throw new Error('无法从聚水潭页面读取 ownerCoId,请配置 JST_ERP_OWNER_CO_ID')
}
async function resolveRulePage(browser: Browser): Promise<{ page: Page; closeAfter: boolean }> {
const existing = (await browser.pages()).find(
(page) => page.url().includes(RULE_PATH) && !page.url().includes('lc_id='),
)
if (existing) return { page: existing, closeAfter: false }
const ownerCoId = await resolveOwnerCompanyId(browser)
const query = new URLSearchParams({
tab: 'cn',
owner_co_id: ownerCoId,
authorize_co_id: ownerCoId,
_c: 'jst-epaas',
epaas: 'true',
})
const page = await browser.newPage()
await page.setViewport({ width: 1470, height: 900 })
await page.goto(`https://www.erp321.com${RULE_PATH}?${query.toString()}`, {
waitUntil: 'networkidle2',
timeout: 90_000,
})
return { page, closeAfter: true }
}
async function waitForRuleTable(page: Page) {
for (let index = 0; index < 90; index += 1) {
const ready = await page.evaluate(() => {
const table = (window as unknown as {
jTable?: { Rows?: unknown[] }
}).jTable
return Boolean(table?.Rows && Array.isArray(table.Rows))
}).catch(() => false)
if (ready) return
await sleep(1_000)
}
throw new Error('聚水潭物流匹配规则表加载超时')
}
async function readVisiblePage(page: Page) {
return page.evaluate(() => {
const table = (window as unknown as {
jTable: {
Rows: Array<{ Data: LiveRule }>
}
}).jTable
const match = (document.body.innerText ?? '').match(/共\s*([\d,]+)\s*条\s*(\d+)\/(\d+)\s*页/)
return {
rules: table.Rows.map((row) => row.Data),
total: match ? Number(match[1].replaceAll(',', '')) : table.Rows.length,
page: match ? Number(match[2]) : 1,
totalPages: match ? Number(match[3]) : 1,
}
})
}
async function readAllLiveRules(page: Page) {
const all: LiveRule[] = []
const initial = await readVisiblePage(page)
if (initial.page !== 1) {
await page.evaluate(() => {
;(window as unknown as { jTable: { GotoPage: (value: number) => void } })
.jTable.GotoPage(1)
})
for (let index = 0; index < 30; index += 1) {
await sleep(500)
if ((await readVisiblePage(page)).page === 1) break
}
}
let pageNumber = 1
let totalPages = 1
do {
const current = await readVisiblePage(page)
all.push(...current.rules)
totalPages = current.totalPages
if (pageNumber >= totalPages) break
const previousFirst = current.rules[0]?.rule_id
await page.evaluate((nextPage) => {
;(window as unknown as { jTable: { GotoPage: (value: number) => void } })
.jTable.GotoPage(nextPage)
}, pageNumber + 1)
for (let index = 0; index < 30; index += 1) {
await sleep(500)
const next = await readVisiblePage(page)
if (next.page === pageNumber + 1 || next.rules[0]?.rule_id !== previousFirst) break
}
pageNumber += 1
} while (pageNumber <= totalPages)
return all
}
async function main() {
const browser = await puppeteer.connect({
browserURL: BROWSER_URL,
protocolTimeout: 120_000,
})
try {
const { page: rulePage, closeAfter } = await resolveRulePage(browser)
try {
await waitForRuleTable(rulePage)
const rows = await readAllLiveRules(rulePage)
const activeRules = rows.filter((row) => (
row.enabled === true
&& row.status === '在有效期内'
&& !NON_SHIPPING_EXPRESS_NAMES.has(String(row.lc_name ?? '').trim())
))
const rules: SnapshotRule[] = activeRules.flatMap((row) => {
const expressName = String(row.lc_name ?? '').trim()
const warehouses = splitWarehouses(String(row.wh_names ?? ''))
if (!expressName || warehouses.length === 0) return []
return [{
ruleId: String(row.rule_id),
ruleName: String(row.name ?? '').trim(),
expressName,
warehouses,
effectiveTime: String(row.effective_time ?? '').trim(),
...readPhysicalRuleLimits(String(row.data ?? '')),
}]
})
const warehouseMap = new Map<string, SnapshotWarehouse>()
for (const rule of rules) {
for (const sourceWarehouseName of rule.warehouses) {
const warehouseName = normalizeWarehouseName(sourceWarehouseName)
if (!warehouseName) continue
const warehouse = warehouseMap.get(warehouseName) ?? {
warehouseName,
sourceWarehouseNames: [],
expressNames: [],
courierRules: [],
ruleCount: 0,
}
if (!warehouse.sourceWarehouseNames.includes(sourceWarehouseName)) {
warehouse.sourceWarehouseNames.push(sourceWarehouseName)
}
if (!warehouse.expressNames.includes(rule.expressName)) {
warehouse.expressNames.push(rule.expressName)
}
if (!warehouse.courierRules.some((item) => item.ruleId === rule.ruleId)) {
warehouse.courierRules.push({
ruleId: rule.ruleId,
ruleName: rule.ruleName,
expressName: rule.expressName,
sourceWarehouseName,
minWeight: rule.minWeight,
maxWeight: rule.maxWeight,
minVolume: rule.minVolume,
maxVolume: rule.maxVolume,
minLongestSide: rule.minLongestSide,
maxLongestSide: rule.maxLongestSide,
minSecondLongestSide: rule.minSecondLongestSide,
maxSecondLongestSide: rule.maxSecondLongestSide,
minAmount: rule.minAmount,
maxAmount: rule.maxAmount,
minBubbleRatio: rule.minBubbleRatio,
maxBubbleRatio: rule.maxBubbleRatio,
minThreeSideSum: rule.minThreeSideSum,
maxThreeSideSum: rule.maxThreeSideSum,
includedSkuIds: rule.includedSkuIds,
excludedSkuIds: rule.excludedSkuIds,
includedSkuLabels: rule.includedSkuLabels,
excludedSkuLabels: rule.excludedSkuLabels,
includedOrderLabels: rule.includedOrderLabels,
excludedOrderLabels: rule.excludedOrderLabels,
allowedProvinces: rule.allowedProvinces,
allowedCities: rule.allowedCities,
allowedDistricts: rule.allowedDistricts,
disabledPcds: rule.disabledPcds,
disabledAddressKeywords: rule.disabledAddressKeywords,
systemUnreachableArea: rule.systemUnreachableArea,
companyIds: rule.companyIds,
distributorFromIds: rule.distributorFromIds,
distributorToIds: rule.distributorToIds,
orderTypes: rule.orderTypes,
shopSites: rule.shopSites,
shopIds: rule.shopIds,
thirdShopIds: rule.thirdShopIds,
excludedShopIds: rule.excludedShopIds,
shopDistributorCondition: rule.shopDistributorCondition,
})
}
warehouse.ruleCount += 1
warehouseMap.set(warehouseName, warehouse)
}
}
const warehouses = [...warehouseMap.values()]
.map((warehouse) => ({
...warehouse,
sourceWarehouseNames: warehouse.sourceWarehouseNames.sort((left, right) => (
left.localeCompare(right, 'zh-CN')
)),
expressNames: warehouse.expressNames.sort((left, right) => (
left.localeCompare(right, 'zh-CN')
)),
courierRules: warehouse.courierRules.sort((left, right) => (
left.expressName.localeCompare(right.expressName, 'zh-CN')
|| left.ruleName.localeCompare(right.ruleName, 'zh-CN')
|| Number(left.ruleId) - Number(right.ruleId)
)),
}))
.sort((left, right) => left.warehouseName.localeCompare(right.warehouseName, 'zh-CN'))
const snapshot = {
version: 3,
generatedAt: new Date().toISOString(),
source: '聚水潭 ERP · 物流匹配规则(新)',
sourceTotal: rows.length,
includedRuleCount: rules.length,
excludedRuleCount: rows.length - rules.length,
warehouseCount: warehouses.length,
warehouses,
}
await fs.mkdir(path.dirname(OUTPUT_PATH), { recursive: true })
const temporaryPath = `${OUTPUT_PATH}.tmp`
await fs.writeFile(temporaryPath, `${JSON.stringify(snapshot, null, 2)}\n`, 'utf8')
await fs.rename(temporaryPath, OUTPUT_PATH)
console.log(JSON.stringify({
outputPath: OUTPUT_PATH,
generatedAt: snapshot.generatedAt,
sourceTotal: snapshot.sourceTotal,
includedRuleCount: snapshot.includedRuleCount,
warehouseCount: snapshot.warehouseCount,
newSubeiCouriers: warehouses.find((item) => item.warehouseName === '新苏北仓')?.expressNames,
}, null, 2))
} finally {
if (closeAfter) await rulePage.close()
}
} finally {
await browser.disconnect()
}
}
void main().catch((error) => {
console.error(error instanceof Error ? error.message : error)
process.exit(1)
})

View File

@ -771,6 +771,26 @@ try {
}
// 本批限价.xlsx 的人工指定价格优先;保护范围由独立模块限定为获准的 81 个货号。
await preserveLimitFileManualPrices(client, finalLimitByStyle)
// 页面人工上传的指定限价优先级最高;每日流程同步只刷新其他来源,不能覆盖人工值。
const manualLimitRows = (await client.query(
`SELECT "styleCode", "ownerLimitPrice", "processInstanceId", "processNo",
"applyType", "initiator", "approvedAt"
FROM "SupplyChainStyleLimitPrice"
WHERE "applyType" = '人工指定限价'`,
)).rows
for (const row of manualLimitRows) {
finalLimitByStyle.set(row.styleCode, {
styleCode: row.styleCode,
ownerLimitPrice: toNumberOrNull(row.ownerLimitPrice),
processInstanceId: row.processInstanceId ?? '',
processNo: row.processNo ?? '',
applyType: '人工指定限价',
initiator: row.initiator ?? '',
approvedAt: row.approvedAt,
source: 'manual',
dateMs: row.approvedAt instanceof Date ? row.approvedAt.getTime() : null,
})
}
finalLimitSourceByStyle = new Map([...finalLimitByStyle].map(([styleCode, item]) => [styleCode, item.source]))
// 一次性写入最终生效限价(全表重建,直接 upsert 覆盖)

View File

@ -0,0 +1,24 @@
import { NextRequest } from 'next/server'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { supplyChainComboLimitService } from '@/server/services/supply-chain-combo-limit.service'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const maxDuration = 300
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await supplyChainPermissionSettingsService.getUserAccess(ctx.user, 'limitManagement')
if (!access.view) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有限价管理查看权限', 403, ctx.requestId)
}
const comboCode = request.nextUrl.searchParams.get('comboCode')?.trim() ?? ''
if (!comboCode) {
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '组合编码不能为空', 400, ctx.requestId)
}
const details = await supplyChainComboLimitService.getDetails(comboCode)
return jsonSuccess(details, 200, ctx.requestId)
}, { requireAuth: true })
}

View File

@ -0,0 +1,52 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { freightConfigService } from '@/server/services/freight-config.service'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
const freightCalculationSchema = z.object({
barcode: z.string().trim().min(1, '商品编码不能为空').max(100),
})
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const maxDuration = 180
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await supplyChainPermissionSettingsService.getUserAccess(
ctx.user,
'limitManagement',
)
if (!access.view) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有快递测算查看权限', 403, ctx.requestId)
}
await freightConfigService.warmup()
return jsonSuccess({ ready: true }, 200, ctx.requestId)
}, { requireAuth: true })
}
export async function POST(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await supplyChainPermissionSettingsService.getUserAccess(
ctx.user,
'limitManagement',
)
if (!access.view) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有快递测算查看权限', 403, ctx.requestId)
}
let payload: unknown
try {
payload = await request.json()
} catch {
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '请求内容不是有效 JSON', 400, ctx.requestId)
}
const parsed = freightCalculationSchema.safeParse(payload)
if (!parsed.success) {
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请输入商品编码', 400, ctx.requestId)
}
const result = await freightConfigService.calculateByBarcode(parsed.data.barcode)
return jsonSuccess(result, 200, ctx.requestId)
}, { requireAuth: true })
}

View File

@ -0,0 +1,35 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { supplyChainLimitPriceHistoryService } from '@/server/services/supply-chain-limit-price-history.service'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
const querySchema = z.object({
barcode: z.string().trim().min(1).max(120),
sku: z.string().trim().max(120).default(''),
spu: z.string().trim().max(120).default(''),
})
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const maxDuration = 180
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await supplyChainPermissionSettingsService.getUserAccess(ctx.user, 'limitManagement')
if (!access.view) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有限价管理查看权限', 403, ctx.requestId)
}
const parsed = querySchema.safeParse({
barcode: request.nextUrl.searchParams.get('barcode') ?? '',
sku: request.nextUrl.searchParams.get('sku') ?? '',
spu: request.nextUrl.searchParams.get('spu') ?? '',
})
if (!parsed.success) {
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '商品编码参数不正确', 400, ctx.requestId)
}
const history = await supplyChainLimitPriceHistoryService.getHistory(parsed.data)
return jsonSuccess(history, 200, ctx.requestId)
}, { requireAuth: true })
}

View File

@ -0,0 +1,62 @@
import { NextRequest } from 'next/server'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { supplyChainManualLimitService } from '@/server/services/supply-chain-manual-limit.service'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const maxDuration = 300
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await supplyChainPermissionSettingsService.getUserAccess(ctx.user, 'limitManualOverride')
if (!access.view) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有人工限价导入查看权限', 403, ctx.requestId)
}
return jsonSuccess(await supplyChainManualLimitService.listBatches(), 200, ctx.requestId)
}, { requireAuth: true })
}
export async function POST(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await supplyChainPermissionSettingsService.getUserAccess(ctx.user, 'limitManualOverride')
if (!access.edit) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有人工限价导入权限', 403, ctx.requestId)
}
const form = await request.formData().catch(() => null)
const file = form?.get('file')
if (!(file instanceof File)) {
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请选择 Excel 文件', 400, ctx.requestId)
}
if (!/\.(xlsx|xls)$/i.test(file.name)) {
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '仅支持 .xlsx 或 .xls 文件', 400, ctx.requestId)
}
if (file.size <= 0 || file.size > 10 * 1024 * 1024) {
return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, 'Excel 文件不能为空且不能超过 10MB', 400, ctx.requestId)
}
const priceText = String(form?.get('targetPrice') ?? '').trim()
const targetPrice = priceText ? Number(priceText) : null
if (targetPrice !== null && (!Number.isFinite(targetPrice) || targetPrice <= 0)) {
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '统一限价必须是有效正数', 400, ctx.requestId)
}
try {
const result = await supplyChainManualLimitService.importFile({
fileName: file.name,
content: Buffer.from(await file.arrayBuffer()),
targetPrice,
note: String(form?.get('note') ?? ''),
user: ctx.user,
})
return jsonSuccess(result, 200, ctx.requestId)
} catch (error) {
return jsonError(
ErrorCode.VALIDATION_INVALID_FORMAT,
error instanceof Error ? error.message : '人工限价导入失败',
400,
ctx.requestId,
)
}
}, { requireAuth: true })
}

View File

@ -1,40 +0,0 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { ErrorCode } from '@/server/core/errors'
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
import { freightConfigService } from '@/server/services/freight-config.service'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
const freightConfigQuerySchema = z.object({
tab: z.enum(['barcode', 'normal', 'volume']).default('barcode'),
page: z.coerce.number().int().min(1).default(1),
pageSize: z.coerce.number().int().min(20).max(200).default(50),
keyword: z.string().trim().max(100).default(''),
})
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
export const maxDuration = 180
export async function GET(request: NextRequest) {
return handleRequest(request, async (ctx) => {
const access = await supplyChainPermissionSettingsService.getUserAccess(
ctx.user,
'managementBlankPage1',
)
if (!access.view) {
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '没有运费配置查看权限', 403, ctx.requestId)
}
const parsed = freightConfigQuerySchema.safeParse({
tab: request.nextUrl.searchParams.get('tab') ?? undefined,
page: request.nextUrl.searchParams.get('page') ?? undefined,
pageSize: request.nextUrl.searchParams.get('pageSize') ?? undefined,
keyword: request.nextUrl.searchParams.get('keyword') ?? undefined,
})
if (!parsed.success) {
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '运费配置查询参数不正确', 400, ctx.requestId)
}
const result = await freightConfigService.listPage(parsed.data)
return jsonSuccess(result, 200, ctx.requestId)
}, { requireAuth: true })
}

View File

@ -15,7 +15,7 @@ jest.mock('./supply-chain-tabs', () => ({
{ path: '/supply-chain/dashboard', title: '工作台', closable: false },
{ path: '/supply-chain/management/owner-config', title: '人员信息', closable: true },
{ path: '/supply-chain/management/custom-table', title: '限价管理', closable: true },
{ path: '/supply-chain/management/blank-pages/blank-page-1', title: '空白页 1', closable: true },
{ path: '/supply-chain/management/blank-pages/blank-page-2', title: '特殊备货&特殊入库流程监控', closable: true },
],
activePath: mockActivePath,
clickTab,
@ -72,17 +72,17 @@ describe('SupplyChainTabBar owner config labels', () => {
})
it('allows each management blank page title to be renamed independently', () => {
mockActivePath = '/supply-chain/management/blank-pages/blank-page-1'
mockActivePath = '/supply-chain/management/blank-pages/blank-page-2'
render(<SupplyChainTabBar canEditOwnerConfigLabels />)
fireEvent.click(screen.getByRole('button', { name: '修改空白页 1页签名称' }))
const input = screen.getByRole('textbox', { name: '修改空白页 1页签名称' })
fireEvent.click(screen.getByRole('button', { name: '修改特殊备货&特殊入库流程监控页签名称' }))
const input = screen.getByRole('textbox', { name: '修改特殊备货&特殊入库流程监控页签名称' })
fireEvent.change(input, { target: { value: '销售目标' } })
fireEvent.blur(input)
expect(screen.getByText('销售目标')).toBeInTheDocument()
expect(JSON.parse(window.localStorage.getItem(
managementBlankPageSettingsStorageKey('blank-page-1'),
managementBlankPageSettingsStorageKey('blank-page-2'),
)!)).toEqual({ pageTitle: '销售目标' })
})
})

View File

@ -118,5 +118,6 @@ export const SUPPLY_CHAIN_ROUTE_TITLES: Record<string, string> = {
'/supply-chain/user-permissions': '用户权限',
'/supply-chain/management/owner-config': '人员信息',
'/supply-chain/management/custom-table': '限价管理',
'/supply-chain/management/freight-maintenance': '快递维护',
...Object.fromEntries(MANAGEMENT_BLANK_PAGES.map((page) => [page.route, page.label])),
}

View File

@ -118,16 +118,16 @@ describe('supply chain menu', () => {
module: '经营管理',
route: '/supply-chain/management/custom-table',
}),
expect.objectContaining({
label: '快递维护',
module: '经营管理',
route: '/supply-chain/management/freight-maintenance',
}),
expect.objectContaining({
label: '员工工时统计',
module: '经营管理',
route: '/supply-chain/management/employee-hours',
}),
expect.objectContaining({
label: '空白页 1',
module: '经营管理',
route: '/supply-chain/management/blank-pages/blank-page-1',
}),
expect.objectContaining({
label: '特殊备货&特殊入库流程监控',
module: '经营管理',

View File

@ -112,6 +112,11 @@ export const SUPPLY_CHAIN_MENU: SupplyChainMenuModule[] = [
route: '/supply-chain/management/custom-table',
targetKey: 'limitManagement',
},
{
label: '快递维护',
route: '/supply-chain/management/freight-maintenance',
targetKey: 'limitManagement',
},
{
label: '停产下架管理',
route: '/supply-chain/management/discontinuation',

View File

@ -1,100 +0,0 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { FreightConfigView } from './FreightConfigView'
const originalFetch = global.fetch
function jsonResponse(payload: unknown) {
return {
ok: true,
status: 200,
json: async () => payload,
} as unknown as Response
}
describe('FreightConfigView', () => {
beforeEach(() => {
global.fetch = jest.fn(async (input) => {
const url = new URL(String(input), 'http://localhost')
const tab = url.searchParams.get('tab')
if (tab === 'normal') {
return jsonResponse({
success: true,
data: {
tab,
rows: [{
RuleId: 101,
EffectiveStartTime: '2026-10-01 00:00:00',
EffectiveEndTime: '2026-12-31 23:59:59',
ExpressName: '测试快递',
CourierName: '测试快递公司',
StartWeight: 0,
EndWeight: 10,
Province: '江苏省',
City: '南京市',
WaybillFee: 12.5,
}],
pageInfo: { page: 1, pageSize: 50, total: 1, totalPages: 1 },
},
})
}
return jsonResponse({
success: true,
data: {
tab: 'barcode',
rows: [{
RuleId: 100,
Barcode: 'TEST001',
CourierName: '测试快递公司',
Location: '江苏省',
EffectiveStartTime: '2026-10-01 00:00:00',
EffectiveEndTime: '2026-12-31 23:59:59',
Price: 8.5,
CreateTime: '2026-09-30 12:00:00',
}],
pageInfo: { page: 1, pageSize: 50, total: 1, totalPages: 1 },
},
})
}) as unknown as typeof fetch
})
afterAll(() => {
global.fetch = originalFetch
})
it('展示三个运费页签并按页签加载对应中文表头', async () => {
render(<FreightConfigView />)
expect(await screen.findByText('TEST001')).toBeInTheDocument()
expect(screen.getByRole('button', { name: '条码运费' })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByRole('columnheader', { name: '条码' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '条码运费单价' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '正常费率' }))
expect(await screen.findByText('测试快递公司')).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '省份' })).toBeInTheDocument()
expect(screen.getByRole('columnheader', { name: '面单费' })).toBeInTheDocument()
await waitFor(() => {
expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining('tab=normal'),
expect.any(Object),
)
})
})
it('提交关键词后从第一页重新查询', async () => {
render(<FreightConfigView />)
await screen.findByText('TEST001')
fireEvent.change(screen.getByRole('textbox', { name: '搜索运费配置' }), {
target: { value: '测试' },
})
fireEvent.click(screen.getByRole('button', { name: '查询' }))
await waitFor(() => {
expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining('keyword=%E6%B5%8B%E8%AF%95'),
expect.any(Object),
)
})
})
})

View File

@ -1,243 +0,0 @@
'use client'
import { FormEvent, useEffect, useMemo, useState } from 'react'
import { ChevronLeft, ChevronRight, Database, LoaderCircle, RefreshCw, Search } from 'lucide-react'
import type { ApiResponse } from '@/server/core/types'
import {
FREIGHT_CONFIG_TABS,
getFreightConfigTab,
type FreightConfigPage,
type FreightConfigTab,
} from '@/lib/freight-config'
import styles from './freight-config.module.css'
const PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const
const EMPTY_PAGE: FreightConfigPage = {
tab: 'barcode',
rows: [],
pageInfo: { page: 1, pageSize: 50, total: 0, totalPages: 1 },
}
function displayValue(value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return '-'
return String(value)
}
export function FreightConfigView() {
const [activeTab, setActiveTab] = useState<FreightConfigTab>('barcode')
const [keyword, setKeyword] = useState('')
const [appliedKeyword, setAppliedKeyword] = useState('')
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(50)
const [result, setResult] = useState<FreightConfigPage>(EMPTY_PAGE)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [reloadKey, setReloadKey] = useState(0)
const tab = getFreightConfigTab(activeTab)
useEffect(() => {
const controller = new AbortController()
let cancelled = false
void (async () => {
setLoading(true)
setError('')
try {
const params = new URLSearchParams({
tab: activeTab,
page: String(page),
pageSize: String(pageSize),
})
if (appliedKeyword) params.set('keyword', appliedKeyword)
const response = await fetch(`/api/supply-chain/management/freight-config?${params.toString()}`, {
signal: controller.signal,
})
const payload = (await response.json()) as ApiResponse<FreightConfigPage>
if (!response.ok || !payload.success || !payload.data) {
throw new Error(payload.error?.message || '运费配置加载失败')
}
if (!cancelled) setResult(payload.data)
} catch (loadError) {
if (cancelled || controller.signal.aborted) return
setError(loadError instanceof Error ? loadError.message : '运费配置加载失败')
} finally {
if (!cancelled && !controller.signal.aborted) setLoading(false)
}
})()
return () => {
cancelled = true
controller.abort()
}
}, [activeTab, appliedKeyword, page, pageSize, reloadKey])
const tableWidth = useMemo(
() => tab.columns.reduce((sum, column) => sum + (column.width ?? 120), 0),
[tab.columns],
)
const submitSearch = (event: FormEvent) => {
event.preventDefault()
setPage(1)
setAppliedKeyword(keyword.trim())
}
const changeTab = (nextTab: FreightConfigTab) => {
if (nextTab === activeTab) return
setActiveTab(nextTab)
setKeyword('')
setAppliedKeyword('')
setPage(1)
}
return (
<main className={styles.page}>
<header className={styles.header}>
<div>
<h1>运费配置</h1>
<p>集中查询聚水潭条码运费、正常费率和体积运费配置。</p>
</div>
<div className={styles.headerBadge}>
<Database size={15} />
聚水潭报表库
</div>
</header>
<nav className={styles.tabs} aria-label="运费配置类型">
{FREIGHT_CONFIG_TABS.map((item) => (
<button
key={item.key}
type="button"
aria-pressed={activeTab === item.key}
className={activeTab === item.key ? styles.activeTab : undefined}
onClick={() => changeTab(item.key)}
>
{item.label}
</button>
))}
</nav>
<div className={styles.summary}>
<div>
<strong>{tab.label}</strong>
<span>{tab.description}</span>
</div>
<span>共 {result.pageInfo.total.toLocaleString('zh-CN')} 条</span>
</div>
<div className={styles.toolbar}>
<form className={styles.searchForm} onSubmit={submitSearch}>
<label className={styles.searchBox}>
<Search size={15} />
<input
value={keyword}
maxLength={100}
placeholder={activeTab === 'barcode' ? '搜索条码、快递公司或地区' : activeTab === 'normal' ? '搜索快递名称、公司、省份或城市' : '搜索快递公司或地区'}
aria-label="搜索运费配置"
onChange={(event) => setKeyword(event.target.value)}
/>
</label>
<button type="submit" className={styles.primaryButton} disabled={loading}>查询</button>
{appliedKeyword ? (
<button
type="button"
className={styles.secondaryButton}
onClick={() => {
setKeyword('')
setAppliedKeyword('')
setPage(1)
}}
>
清空
</button>
) : null}
</form>
<button
type="button"
className={styles.iconButton}
title="刷新"
aria-label="刷新运费配置"
onClick={() => setReloadKey((key) => key + 1)}
>
<RefreshCw size={15} className={loading ? 'animate-spin' : undefined} />
</button>
</div>
{error ? <div className={styles.error}>{error}</div> : null}
<div className={styles.tableWrap}>
{loading && result.rows.length === 0 ? (
<div className={styles.state}><LoaderCircle size={20} className="animate-spin" />正在加载运费配置…</div>
) : (
<table className={styles.table} style={{ width: tableWidth, minWidth: '100%' }}>
<thead>
<tr>
{tab.columns.map((column) => (
<th key={column.key} style={{ width: column.width ?? 120 }}>{column.label}</th>
))}
</tr>
</thead>
<tbody>
{result.rows.map((row, rowIndex) => (
<tr key={`${activeTab}-${rowIndex}-${displayValue(row.RuleId)}`}>
{tab.columns.map((column) => (
<td
key={column.key}
className={column.numeric ? styles.numericCell : undefined}
title={displayValue(row[column.key])}
>
{displayValue(row[column.key])}
</td>
))}
</tr>
))}
{!loading && result.rows.length === 0 ? (
<tr>
<td className={styles.emptyCell} colSpan={tab.columns.length}>没有符合条件的运费配置</td>
</tr>
) : null}
</tbody>
</table>
)}
</div>
<footer className={styles.pagination}>
<span>
第 {result.pageInfo.page} / {result.pageInfo.totalPages} 页
</span>
<div className={styles.paginationActions}>
<label>
每页
<select
value={pageSize}
aria-label="每页条数"
onChange={(event) => {
setPageSize(Number(event.target.value))
setPage(1)
}}
>
{PAGE_SIZE_OPTIONS.map((size) => <option key={size} value={size}>{size}</option>)}
</select>
条
</label>
<button
type="button"
title="上一页"
aria-label="上一页"
disabled={loading || result.pageInfo.page <= 1}
onClick={() => setPage((current) => Math.max(1, current - 1))}
>
<ChevronLeft size={16} />
</button>
<button
type="button"
title="下一页"
aria-label="下一页"
disabled={loading || result.pageInfo.page >= result.pageInfo.totalPages}
onClick={() => setPage((current) => Math.min(result.pageInfo.totalPages, current + 1))}
>
<ChevronRight size={16} />
</button>
</div>
</footer>
</main>
)
}

View File

@ -42,7 +42,7 @@ describe('经营管理空白页', () => {
it('非管理员只能查看,不能新增、编辑、删除或调整数量', () => {
window.localStorage.setItem(
'supply-chain.management.blank-pages.blank-page-1.rows.v1',
'supply-chain.management.blank-pages.blank-page-2.rows.v1',
JSON.stringify([{ id: 'row-1', name: '只读记录', quantity: 5, remarks: '', updatedAt: '' }]),
)
render(<ManagementBlankPageView definition={definition} canManage={false} />)

View File

@ -2,7 +2,6 @@ import { notFound, redirect } from 'next/navigation'
import { requireSession } from '@/lib/server-session'
import { getManagementBlankPage } from '@/lib/supply-chain-management-blank-pages'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
import { FreightConfigView } from '../FreightConfigView'
import { ManagementBlankPageView } from '../ManagementBlankPageView'
import { ProductSabcView } from '../ProductSabcView'
@ -38,10 +37,6 @@ export default async function ManagementBlankPage({ params }: { params: Promise<
)
if (!access.view) redirect('/supply-chain')
if (definition.key === 'blank-page-1') {
return <FreightConfigView />
}
return (
<ManagementBlankPageView
definition={definition}

View File

@ -1,344 +0,0 @@
.page {
display: flex;
min-width: 0;
min-height: 0;
flex: 1;
flex-direction: column;
background: var(--sc-bg);
color: var(--sc-ink);
}
.header {
display: flex;
min-height: 76px;
flex: none;
align-items: center;
justify-content: space-between;
gap: 18px;
border-bottom: 1px solid var(--sc-border);
background: var(--sc-surface);
padding: 12px 24px;
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.header p {
margin: 5px 0 0;
color: var(--sc-muted);
font-size: 12px;
}
.headerBadge {
display: inline-flex;
height: 30px;
align-items: center;
gap: 6px;
border: 1px solid #d4d4d8;
border-radius: 5px;
background: #fafafa;
padding: 0 10px;
color: #52525b;
font-size: 12px;
white-space: nowrap;
}
.tabs {
display: flex;
flex: none;
align-items: center;
gap: 4px;
border-bottom: 1px solid var(--sc-border);
background: #fff;
padding: 0 24px;
}
.tabs button {
position: relative;
height: 48px;
border: 0;
background: transparent;
padding: 0 14px;
color: #52525b;
font-size: 13px;
cursor: pointer;
}
.tabs button:hover {
color: #18181b;
}
.tabs .activeTab {
color: #18181b;
font-weight: 700;
}
.tabs .activeTab::after {
position: absolute;
right: 12px;
bottom: 0;
left: 12px;
height: 2px;
background: #27272a;
content: "";
}
.summary {
display: flex;
min-height: 50px;
flex: none;
align-items: center;
justify-content: space-between;
gap: 16px;
border-bottom: 1px solid #e4e4e7;
background: #fafafa;
padding: 8px 24px;
color: #71717a;
font-size: 12px;
}
.summary div {
display: flex;
min-width: 0;
align-items: baseline;
gap: 10px;
}
.summary strong {
color: #18181b;
font-size: 13px;
}
.summary span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.toolbar {
display: flex;
min-height: 56px;
flex: none;
align-items: center;
gap: 8px;
border-bottom: 1px solid #e4e4e7;
background: #fff;
padding: 10px 24px;
}
.searchForm {
display: flex;
align-items: center;
gap: 8px;
}
.searchBox {
display: flex;
width: min(420px, 42vw);
height: 34px;
align-items: center;
gap: 7px;
border: 1px solid #d4d4d8;
border-radius: 5px;
background: #fff;
padding: 0 10px;
color: #a1a1aa;
}
.searchBox input {
min-width: 0;
flex: 1;
border: 0;
background: transparent;
color: #27272a;
font: inherit;
outline: 0;
}
.primaryButton,
.secondaryButton,
.iconButton,
.paginationActions button {
display: inline-flex;
height: 34px;
align-items: center;
justify-content: center;
border: 1px solid #27272a;
border-radius: 5px;
background: #27272a;
padding: 0 12px;
color: #fff;
font-size: 12px;
cursor: pointer;
}
.secondaryButton,
.iconButton,
.paginationActions button {
border-color: #d4d4d8;
background: #fff;
color: #3f3f46;
}
.iconButton,
.paginationActions button {
width: 34px;
padding: 0;
}
.primaryButton:disabled,
.secondaryButton:disabled,
.iconButton:disabled,
.paginationActions button:disabled {
cursor: not-allowed;
opacity: .45;
}
.toolbar > .iconButton {
margin-left: auto;
}
.error {
border-bottom: 1px solid #fecaca;
background: #fff7f7;
padding: 10px 24px;
color: #b91c1c;
font-size: 12px;
}
.tableWrap {
min-height: 280px;
flex: 1;
overflow: auto;
background: #fff;
}
.table {
border-collapse: separate;
border-spacing: 0;
font-size: 12px;
}
.table th {
position: sticky;
top: 0;
z-index: 2;
height: 40px;
border-right: 1px solid #e4e4e7;
border-bottom: 1px solid #d4d4d8;
background: #eef0ef;
padding: 0 11px;
color: #52525b;
font-weight: 600;
text-align: left;
white-space: nowrap;
}
.table td {
max-width: 260px;
height: 42px;
overflow: hidden;
border-right: 1px solid #f1f1f1;
border-bottom: 1px solid #eee;
padding: 6px 11px;
color: #52525b;
text-overflow: ellipsis;
white-space: nowrap;
}
.table tbody tr:hover td {
background: #fafafa;
}
.numericCell {
text-align: right;
font-variant-numeric: tabular-nums;
}
.state,
.emptyCell {
height: 220px !important;
color: #a1a1aa !important;
text-align: center !important;
}
.state {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.pagination {
display: flex;
min-height: 50px;
flex: none;
align-items: center;
justify-content: space-between;
gap: 12px;
border-top: 1px solid var(--sc-border);
background: #fff;
padding: 8px 24px;
color: #71717a;
font-size: 12px;
}
.paginationActions {
display: flex;
align-items: center;
gap: 8px;
}
.paginationActions label {
display: flex;
align-items: center;
gap: 6px;
}
.paginationActions select {
height: 32px;
border: 1px solid #d4d4d8;
border-radius: 5px;
background: #fff;
padding: 0 7px;
color: #3f3f46;
}
@media (max-width: 720px) {
.header,
.tabs,
.summary,
.toolbar,
.pagination {
padding-right: 14px;
padding-left: 14px;
}
.header {
align-items: flex-start;
flex-direction: column;
}
.toolbar,
.searchForm {
align-items: stretch;
flex-direction: column;
}
.searchBox {
width: 100%;
}
.toolbar > .iconButton {
align-self: flex-end;
margin-left: 0;
}
.pagination {
align-items: flex-start;
flex-direction: column;
}
}

View File

@ -0,0 +1,122 @@
'use client'
import { useEffect, useState } from 'react'
import { ChevronDown, LoaderCircle } from 'lucide-react'
import type { ComboLimitDetails as ComboLimitDetailsData } from '@/lib/supply-chain-combo-limit-price'
import type { ApiResponse } from '@/server/core/types'
import styles from './limit-price.module.css'
function money(value: number | null) {
if (value === null || !Number.isFinite(value)) return '-'
return value.toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
}
export function ComboLimitDetails({
comboCode,
onClose,
}: {
comboCode: string
onClose: () => void
}) {
const [details, setDetails] = useState<ComboLimitDetailsData | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
useEffect(() => {
const controller = new AbortController()
const params = new URLSearchParams({ comboCode })
void fetch(`/api/supply-chain/limit-management/combo-limits/details?${params}`, {
cache: 'no-store',
signal: controller.signal,
})
.then(async (response) => {
const payload = await response.json() as ApiResponse<ComboLimitDetailsData>
if (!response.ok || !payload.success || !payload.data) {
throw new Error(payload.error?.message || '组合组成明细加载失败')
}
setDetails(payload.data)
})
.catch((failure) => {
if (controller.signal.aborted) return
setError(failure instanceof Error ? failure.message : '组合组成明细加载失败')
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [comboCode])
return (
<section className={styles.comboDetails} aria-label={`${comboCode}组合组成明细`}>
<div className={styles.comboDetailsHeader}>
<div>
<strong>条码明细</strong>
<span>{comboCode}</span>
{details?.creator ? <em>组合负责人:{details.creator}</em> : null}
</div>
<button type="button" onClick={onClose} aria-label="收起组合组成明细">
<ChevronDown size={15} />收起
</button>
</div>
{loading ? (
<div className={styles.comboDetailsState}>
<LoaderCircle size={16} className="animate-spin" />正在读取组合组成明细…
</div>
) : error ? (
<div className={styles.comboDetailsError}>{error}</div>
) : details && details.rows.length > 0 ? (
<div className={styles.comboDetailsScroll}>
<table className={`${styles.table} ${styles.comboDetailsTable}`}>
<colgroup>
<col style={{ width: '24%' }} />
<col style={{ width: '13%' }} />
<col style={{ width: '13%' }} />
<col style={{ width: '7%' }} />
<col style={{ width: '33%' }} />
<col style={{ width: '10%' }} />
</colgroup>
<thead>
<tr>
<th>商品编码/SKU</th>
<th>运营负责人</th>
<th>部门负责人</th>
<th className={styles.numericCell}>数量</th>
<th>商品名称</th>
<th className={styles.numericCell}>成本价</th>
</tr>
</thead>
<tbody>
{details.rows.map((row, index) => (
<tr key={`${row.sourceCode}-${index}`}>
<td>
<strong>{row.barcode || row.sourceCode}</strong>
{row.sku && row.sku !== (row.barcode || row.sourceCode) ? (
<small className={styles.comboDetailSub}>SKU:{row.sku}</small>
) : null}
{row.matchedBy === 'UNAVAILABLE' ? (
<small className={styles.comboDetailMissing}>未匹配产品档案</small>
) : null}
</td>
<td>{row.owner || '-'}</td>
<td>{row.departmentHead || '-'}</td>
<td className={styles.numericCell}>{row.quantity}</td>
<td className={styles.comboProductName}>
<strong>{row.productName}</strong>
<small>{[row.model, row.color, row.categoryTwo, row.productStatus].filter(Boolean).join(' · ')}</small>
</td>
<td className={styles.numericCell}>{money(row.costPrice)}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className={styles.comboDetailsState}>该组合没有可展示的组成明细</div>
)}
</section>
)
}

View File

@ -1,7 +1,7 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { ChevronLeft, ChevronRight, Info } from 'lucide-react'
import {
COMBO_LIMIT_FIELDS,
isComboLimitFieldKey,
@ -11,6 +11,7 @@ import {
type ComboLimitSort,
} from '@/lib/supply-chain-combo-limit-price'
import type { LimitTableColumn } from './limit-table-columns'
import { ComboLimitDetails } from './ComboLimitDetails'
import { LimitFilterSelect } from './LimitFilterSelect'
import { LimitTableHeaderCell } from './LimitTableHeaderCell'
import type { LimitTableFilterField } from './useLimitTableSettings'
@ -100,6 +101,22 @@ export function ComboLimitSection({
const [openSortKey, setOpenSortKey] = useState<string | null>(null)
const [widths, setWidths] = useState<Record<string, number>>(() => readWidths(userId))
const [liveWidths, setLiveWidths] = useState<Record<string, number> | null>(null)
const [selectedComboCode, setSelectedComboCode] = useState<string | null>(null)
const tableScrollRef = useRef<HTMLDivElement | null>(null)
const [availableWidth, setAvailableWidth] = useState(0)
useEffect(() => {
const element = tableScrollRef.current
if (!element) return undefined
setAvailableWidth(element.clientWidth)
if (typeof ResizeObserver === 'undefined') return undefined
const observer = new ResizeObserver((entries) => {
const width = entries[0]?.contentRect.width
if (width) setAvailableWidth(width)
})
observer.observe(element)
return () => observer.disconnect()
}, [])
useEffect(() => {
if (!openSortKey) return
@ -119,6 +136,12 @@ export function ComboLimitSection({
}
}, [openSortKey])
useEffect(() => {
if (selectedComboCode && !rows.some((row) => row.comboCode === selectedComboCode)) {
setSelectedComboCode(null)
}
}, [rows, selectedComboCode])
const contextFilters = useMemo(
() => filters as Record<string, string[]>,
[filters],
@ -156,6 +179,9 @@ export function ComboLimitSection({
liveWidths?.[column.key] ?? widths[column.key] ?? column.width
const totalWidth = COMBO_COLUMNS.reduce((sum, column) => sum + columnWidth(column), 0)
const fitScale = availableWidth > 0 ? availableWidth / totalWidth : 1
const fittedWidth = (column: LimitTableColumn) => Math.max(72, Math.round(columnWidth(column) * fitScale))
const fittedTotalWidth = COMBO_COLUMNS.reduce((sum, column) => sum + fittedWidth(column), 0)
const startHeaderResize = (
column: LimitTableColumn,
@ -197,7 +223,7 @@ export function ComboLimitSection({
}
return (
<>
<div className={styles.comboPanel}>
<div className={styles.filterBar}>
<span className={styles.filterHint}>筛选</span>
{topFilterFields.length === 0 && (
@ -214,6 +240,13 @@ export function ComboLimitSection({
))}
</div>
<div className={styles.comboRuleNote} role="note">
<Info size={14} />
<span>
组合负责人优先取负责人变更流程,其次取申请创建人;创建人为空时按子商品运营负责人汇总,离职人员按部门主管、部门经理接管
</span>
</div>
{activeFilterChips.length > 0 && (
<div className={styles.filterChips} aria-label="已选筛选条件">
<span className={styles.filterChipsLabel}>已选条件</span>
@ -238,14 +271,17 @@ export function ComboLimitSection({
</div>
)}
<div className={styles.tableScroll}>
<div
ref={tableScrollRef}
className={`${styles.tableScroll} ${styles.comboTableScroll}`}
>
<table
className={`${styles.table} ${loading && rows.length > 0 ? styles.tableLoading : ''}`}
style={{ width: Math.max(totalWidth, 880) }}
className={`${styles.table} ${styles.comboTable} ${loading && rows.length > 0 ? styles.tableLoading : ''}`}
style={{ width: fittedTotalWidth }}
>
<colgroup>
{COMBO_COLUMNS.map((column) => (
<col key={column.key} style={{ width: columnWidth(column) }} />
<col key={column.key} style={{ width: fittedWidth(column) }} />
))}
</colgroup>
<thead>
@ -297,7 +333,22 @@ export function ComboLimitSection({
<tr className={styles.stateRow}><td colSpan={COMBO_COLUMNS.length}>没有符合条件的组合限价</td></tr>
)}
{rows.map((row) => (
<tr key={row.comboCode}>
<tr
key={row.comboCode}
className={selectedComboCode === row.comboCode ? styles.selectedComboRow : styles.clickableComboRow}
tabIndex={0}
aria-selected={selectedComboCode === row.comboCode}
onClick={() => setSelectedComboCode((current) => (
current === row.comboCode ? null : row.comboCode
))}
onKeyDown={(event) => {
if (event.key !== 'Enter' && event.key !== ' ') return
event.preventDefault()
setSelectedComboCode((current) => (
current === row.comboCode ? null : row.comboCode
))
}}
>
{COMBO_COLUMNS.map((column) => {
const value = isComboLimitFieldKey(column.key) ? row[column.key] : ''
return (
@ -315,6 +366,14 @@ export function ComboLimitSection({
</table>
</div>
{selectedComboCode ? (
<ComboLimitDetails
key={selectedComboCode}
comboCode={selectedComboCode}
onClose={() => setSelectedComboCode(null)}
/>
) : null}
<div className={styles.pagination}>
<button
type="button"
@ -364,6 +423,6 @@ export function ComboLimitSection({
条
</span>
</div>
</>
</div>
)
}

View File

@ -142,6 +142,56 @@ function mockLimitManagementFetch(rows: SupplyChainProductArchiveRow[]) {
},
})
}
if (url.includes('/api/supply-chain/limit-management/freight-calculation')) {
return jsonResponse({
success: true,
data: {
barcode: 'TEST001',
productTag: '仓库-睢宁仓,快递-普通',
warehouseName: '睢宁仓',
weight: 15,
length: 100,
width: 40,
height: 3,
volume: 12000,
courierCount: 1,
calculatedCourierCount: 1,
regionAverages: [
{ region: '一区', regionShare: 0.214, courierCount: 1, averageCost: 10.379 },
{ region: '二区', regionShare: 0.485, courierCount: 1, averageCost: 20 },
{ region: '三区', regionShare: 0.251, courierCount: 1, averageCost: 30 },
{ region: '四区', regionShare: 0.05, courierCount: 1, averageCost: 5 },
],
warnings: [],
couriers: [{
expressName: '睢宁宿迁圆通',
status: 'CALCULATED',
missingProvinces: [],
exclusionReasons: [],
matchedRules: [],
regionCosts: { 一区: 10.379, 二区: 20, 三区: 30, 四区: 5 },
provinceCosts: [{
province: '上海',
region: '一区',
fee: 12.5,
chargeableWeight: 15,
roundedWeight: 15,
actualWeight: 15,
volumeWeight: 2,
waybillFee: 3.8,
deductWeight: 0,
feeRate: 0.58,
minimumFee: 0,
roundingRule: 0,
volumeWeightDivisor: 6000,
rawFee: 12.5,
effectiveStartTime: '2026-09-20T00:00:00.000Z',
ruleId: '100',
}],
}],
},
})
}
if (url.includes('/api/supply-chain/limit-management/options')) {
return jsonResponse({
success: true,
@ -174,6 +224,65 @@ function mockLimitManagementFetch(rows: SupplyChainProductArchiveRow[]) {
},
})
}
if (url.includes('/api/supply-chain/limit-management/combo-limits/details')) {
return jsonResponse({
success: true,
data: {
comboCode: 'COMBO-AB',
creator: '运营甲',
rows: [
{
sourceCode: 'A',
barcode: 'A',
sku: 'SKU-A',
quantity: 1,
productName: '商品 A',
imageUrl: '',
model: 'A-MODEL',
color: '白色',
categoryTwo: '桌类',
productStatus: '销售',
owner: '运营甲',
departmentHead: '部门负责人甲',
costPrice: 10,
ownerLimitPrice: 50,
nonOwnerLimitPrice: 60,
jxLimitPrice: 13.51,
alibabaPageLimitPrice: 55.8,
distributorPrice89: 49.66,
distributorPrice85: 47.43,
distributorPrice80: 44.64,
ownerLimitSubtotal: 50,
matchedBy: 'BARCODE',
},
{
sourceCode: 'B',
barcode: 'B',
sku: 'SKU-B',
quantity: 1,
productName: '商品 B',
imageUrl: '',
model: 'B-MODEL',
color: '黑色',
categoryTwo: '椅类',
productStatus: '销售',
owner: '运营乙',
departmentHead: '部门负责人乙',
costPrice: 8,
ownerLimitPrice: 19,
nonOwnerLimitPrice: 29,
jxLimitPrice: 10.81,
alibabaPageLimitPrice: 26.97,
distributorPrice89: 24,
distributorPrice85: 22.92,
distributorPrice80: 21.58,
ownerLimitSubtotal: 19,
matchedBy: 'BARCODE',
},
],
},
})
}
if (url.includes('/api/supply-chain/limit-management/combo-limits')) {
return jsonResponse({
success: true,
@ -193,6 +302,68 @@ function mockLimitManagementFetch(rows: SupplyChainProductArchiveRow[]) {
},
})
}
if (url.includes('/api/supply-chain/limit-management/manual-limits')) {
return jsonResponse({
success: true,
data: [],
})
}
if (url.includes('/api/supply-chain/limit-management/limit-price-history')) {
return jsonResponse({
success: true,
data: {
barcode: 'DH-CZ00010101',
sku: 'DH-CZ000101',
spu: 'DH-CZ0001',
current: {
price: '1299.00',
processNo: 'FLOW-CURRENT',
processInstanceId: 'flow-current',
applyType: '调整原货号限价',
initiator: '运营甲',
approvedAt: '2026-10-20T02:00:00.000Z',
},
records: [
{
processInstanceId: 'flow-current',
businessId: 'FLOW-CURRENT',
title: '10-19+运营甲提交的新品限价及限价调整',
templateName: '新品限价及限价调整',
status: '已完成',
result: '同意',
initiator: '运营甲',
createdAt: '2026-10-19 18:16:00',
finishedAt: '2026-10-19 19:20:00',
applyType: '调整原货号限价',
reason: '原材料成本下降,按最新比价结果调整',
price: '1299.00',
startDate: '2026-10-19',
endDate: '2026-12-31',
sourceTable: '限价调整明细表',
attachments: ['竞品比价记录.xlsx'],
},
{
processInstanceId: 'flow-attachment',
businessId: 'FLOW-ATTACHMENT',
title: '09-28+运营乙提交的新品限价流程',
templateName: '新品限价流程',
status: '已完成',
result: '同意',
initiator: '运营乙',
createdAt: '2026-09-28 10:00:00',
finishedAt: '2026-09-28 11:00:00',
applyType: '新品首次定价',
reason: '新品首次定价',
price: '',
startDate: '',
endDate: '',
sourceTable: '',
attachments: ['新品限价附件.xlsx'],
},
],
},
})
}
if (url.includes('/api/supply-chain/limit-management/products')) {
return jsonResponse({
success: true,
@ -288,6 +459,20 @@ describe('限价管理', () => {
expect(await screen.findByRole('button', { name: '导出组合限价' })).toBeInTheDocument()
})
it('人工限价导入入口仅对有专用操作权限的用户展示', async () => {
const withoutPermission = render(<CustomTableView canEdit userId="user-a" />)
await screen.findByText('测试岩板餐桌')
expect(screen.queryByRole('button', { name: '人工限价导入' })).not.toBeInTheDocument()
withoutPermission.unmount()
render(<CustomTableView canEdit canManageManualLimits userId="user-a" />)
await screen.findByText('测试岩板餐桌')
fireEvent.click(screen.getByRole('button', { name: '人工限价导入' }))
expect(await screen.findByRole('dialog', { name: '人工限价导入' })).toBeInTheDocument()
expect(screen.getByLabelText('选择人工限价 Excel 文件')).toBeInTheDocument()
expect(screen.getByPlaceholderText('文件无价格列时填写,例如 49')).toBeInTheDocument()
})
it('品牌商品旁展示组合限价页,并只展示组合编码与限价价格字段', async () => {
render(<CustomTableView canEdit canExport userId="user-a" />)
await screen.findByText('测试岩板餐桌')
@ -300,6 +485,9 @@ describe('限价管理', () => {
}
expect(screen.getByText('69.00')).toBeInTheDocument()
expect(screen.getByText('运营甲')).toBeInTheDocument()
expect(screen.getByRole('note')).toHaveTextContent(
'组合负责人优先取负责人变更流程,其次取申请创建人;创建人为空时按子商品运营负责人汇总,离职人员按部门主管、部门经理接管',
)
expect(document.querySelectorAll('[data-limit-filter]')).toHaveLength(2)
expect(screen.getByRole('button', { name: '筛选运营负责人' })).toBeInTheDocument()
expect((screen.getByRole('columnheader', { name: /^组合编码/ }) as HTMLElement).style.top).toBe('0px')
@ -309,6 +497,25 @@ describe('限价管理', () => {
expect(columnLabels.indexOf('运营负责人')).toBe(columnLabels.indexOf('组合编码') + 1)
expect(screen.queryByRole('button', { name: '导出明细' })).not.toBeInTheDocument()
fireEvent.click(screen.getByText('COMBO-AB'))
const detailRegion = await screen.findByRole('region', { name: 'COMBO-AB组合组成明细' })
expect(within(detailRegion).getByText('商品 A')).toBeInTheDocument()
expect(within(detailRegion).getByText('商品 B')).toBeInTheDocument()
expect(within(detailRegion).getAllByRole('columnheader').map((cell) => cell.textContent?.trim())).toEqual([
'商品编码/SKU',
'运营负责人',
'部门负责人',
'数量',
'商品名称',
'成本价',
])
expect(within(detailRegion).getByText('运营甲')).toBeInTheDocument()
expect(within(detailRegion).getByText('部门负责人甲')).toBeInTheDocument()
expect(within(detailRegion).getByText('运营乙')).toBeInTheDocument()
expect(within(detailRegion).getByText('部门负责人乙')).toBeInTheDocument()
expect(within(detailRegion).getByText('10.00')).toBeInTheDocument()
expect(within(detailRegion).getByText('8.00')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: '导出组合限价' }))
await waitFor(() => {
const exportCall = (global.fetch as jest.Mock).mock.calls
@ -379,6 +586,32 @@ describe('限价管理', () => {
expect(screen.getByText('36')).toBeInTheDocument()
})
it('点击负责人限价后打开历史流程侧边栏,并展示调价原因与有效期', async () => {
render(<CustomTableView canEdit userId="user-a" />)
await screen.findByText('测试岩板餐桌')
fireEvent.click(screen.getByRole('button', {
name: '查看DH-CZ00010101负责人限价历史流程',
}))
const drawer = await screen.findByRole('dialog', { name: '负责人限价历史流程' })
await within(drawer).findByText('原材料成本下降,按最新比价结果调整')
expect(within(drawer).getAllByText('1299.00 元')).toHaveLength(2)
expect(within(drawer).getByText('2026-10-19 至 2026-12-31')).toBeInTheDocument()
expect(within(drawer).getByText('附件:竞品比价记录.xlsx')).toBeInTheDocument()
expect(within(drawer).getByText('附件:新品限价附件.xlsx')).toBeInTheDocument()
const historyRequest = (global.fetch as jest.Mock).mock.calls
.map((call) => String(call[0]))
.find((url) => url.includes('/limit-price-history'))
expect(historyRequest).toContain('barcode=DH-CZ00010101')
expect(historyRequest).toContain('sku=DH-CZ000101')
expect(historyRequest).toContain('spu=DH-CZ0001')
fireEvent.click(within(drawer).getByRole('button', { name: '关闭负责人限价历史' }))
expect(screen.queryByRole('dialog', { name: '负责人限价历史流程' })).not.toBeInTheDocument()
})
it('列设置可以勾选字段、调整顺序,并且不影响其他用户', async () => {
const view = render(<CustomTableView canEdit userId="user-a" />)
await screen.findByText('测试岩板餐桌')
@ -540,4 +773,17 @@ describe('限价管理', () => {
expect(screen.queryByText('审核要点(仅审核人可见)')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '通过' })).not.toBeInTheDocument()
})
it('快递测算已迁出限价管理页面', async () => {
render(<CustomTableView canEdit canViewRuleConfig userId="user-a" />)
await screen.findByText('测试岩板餐桌')
const nav = screen.getByRole('navigation', { name: '限价管理页面' })
expect(within(nav).getAllByRole('button').map((button) => button.textContent?.trim())).toEqual([
'限价',
'破价订单审核',
'规则配置',
])
expect(within(nav).queryByRole('button', { name: '快递测算' })).not.toBeInTheDocument()
})
})

View File

@ -10,12 +10,14 @@ export function CustomTableView({
userId,
canExport = false,
canViewRuleConfig = false,
canManageManualLimits = false,
}: {
canEdit: boolean
userId: string
/** 「限价管理 · 下载」:没有下载权限时不展示导出入口 */
canExport?: boolean
canViewRuleConfig?: boolean
canManageManualLimits?: boolean
}) {
const [primaryTab, setPrimaryTab] = useState<'limits' | 'breach' | 'rules'>('limits')
@ -42,7 +44,13 @@ export function CustomTableView({
)}
</nav>
{primaryTab === 'limits' && <LimitPriceTab userId={userId} canExport={canExport} />}
{primaryTab === 'limits' && (
<LimitPriceTab
userId={userId}
canExport={canExport}
canManageManualLimits={canManageManualLimits}
/>
)}
{primaryTab === 'breach' && <BreachOrderTab canExport={canExport} />}
{primaryTab === 'rules' && canViewRuleConfig && <RuleConfigTab />}
</main>

View File

@ -1,7 +1,7 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react'
import { ChevronLeft, ChevronRight, RefreshCw, Upload } from 'lucide-react'
import type { ApiResponse } from '@/server/core/types'
import type {
ProductArchiveFilterOptions,
@ -33,6 +33,8 @@ import { useLimitPriceData } from './useLimitPriceData'
import { useComboLimitData } from './useComboLimitData'
import { ComboLimitSection } from './ComboLimitSection'
import type { ComboLimitFilters, ComboLimitSort } from '@/lib/supply-chain-combo-limit-price'
import { ManualLimitImportDialog } from './ManualLimitImportDialog'
import { OwnerLimitPriceHistoryDrawer } from './OwnerLimitPriceHistoryDrawer'
import styles from './limit-price.module.css'
type ProductKind = 'bulk' | 'brand' | 'combo'
@ -124,10 +126,17 @@ function LimitCell({
row,
column,
onPreviewImage,
onOpenOwnerLimitHistory,
}: {
row: SupplyChainProductArchiveRow
column: LimitTableColumn
onPreviewImage: (image: string, title: string) => void
onOpenOwnerLimitHistory: (target: {
barcode: string
sku: string
spu: string
price: string
}) => void
}) {
if (column.kind === 'image') {
return <LimitProductImageCell row={row} onPreview={onPreviewImage} />
@ -142,10 +151,36 @@ function LimitCell({
if (column.key === 'productStatus') {
return <span className={`${styles.statusChip} ${STATUS_CLASS[value] ?? styles.statusPaused}`}>{value}</span>
}
if (column.key === 'ownerLimitPrice') {
return (
<button
type="button"
className={styles.limitHistoryButton}
aria-label={`查看${row.barcode}负责人限价历史流程`}
title="点击查看负责人限价历史流程"
onClick={() => onOpenOwnerLimitHistory({
barcode: row.barcode,
sku: row.sku,
spu: row.spu,
price: value,
})}
>
{value}
</button>
)
}
return <span title={value}>{value}</span>
}
export function LimitPriceTab({ userId, canExport = false }: { userId: string; canExport?: boolean }) {
export function LimitPriceTab({
userId,
canExport = false,
canManageManualLimits = false,
}: {
userId: string
canExport?: boolean
canManageManualLimits?: boolean
}) {
const {
settings,
hydrated,
@ -182,6 +217,13 @@ export function LimitPriceTab({ userId, canExport = false }: { userId: string; c
direction: 'desc',
})
const [openSortKey, setOpenSortKey] = useState<string | null>(null)
const [manualLimitOpen, setManualLimitOpen] = useState(false)
const [limitHistoryTarget, setLimitHistoryTarget] = useState<{
barcode: string
sku: string
spu: string
price: string
} | null>(null)
// 大货/品牌两个子界面的划分依据:品牌字段(含顾家/索菲亚/朴美 → 品牌;其余 → 大货)
useEffect(() => {
@ -511,6 +553,15 @@ export function LimitPriceTab({ userId, canExport = false }: { userId: string; c
>
<RefreshCw size={15} className={activeLoading ? 'animate-spin' : undefined} />
</button>
{canManageManualLimits && (
<button
type="button"
className={styles.exportButton}
onClick={() => setManualLimitOpen(true)}
>
<Upload size={14} />人工限价导入
</button>
)}
{productKind !== 'combo' && canExport && (
<>
<button
@ -719,7 +770,12 @@ export function LimitPriceTab({ userId, canExport = false }: { userId: string; c
key={column.key}
className={`${styles.bodyTd} ${column.numeric ? styles.numericCell : ''}`}
>
<LimitCell row={row} column={column} onPreviewImage={(image, title) => setImagePreview({ image, title })} />
<LimitCell
row={row}
column={column}
onPreviewImage={(image, title) => setImagePreview({ image, title })}
onOpenOwnerLimitHistory={setLimitHistoryTarget}
/>
</td>
))}
</tr>
@ -780,8 +836,26 @@ export function LimitPriceTab({ userId, canExport = false }: { userId: string; c
title={imagePreview?.title ?? ''}
onClose={() => setImagePreview(null)}
/>
{limitHistoryTarget ? (
<OwnerLimitPriceHistoryDrawer
key={`${limitHistoryTarget.barcode}:${limitHistoryTarget.sku}:${limitHistoryTarget.spu}`}
barcode={limitHistoryTarget.barcode}
sku={limitHistoryTarget.sku}
spu={limitHistoryTarget.spu}
displayPrice={limitHistoryTarget.price}
onClose={() => setLimitHistoryTarget(null)}
/>
) : null}
</>
)}
<ManualLimitImportDialog
open={manualLimitOpen}
onClose={() => setManualLimitOpen(false)}
onImported={() => {
reload()
comboData.reload()
}}
/>
</section>
)
}

View File

@ -0,0 +1,153 @@
'use client'
import { useEffect, useState } from 'react'
import { Upload, X } from 'lucide-react'
import type { ApiResponse } from '@/server/core/types'
import type { ManualLimitImportResult } from '@/lib/supply-chain-manual-limit'
import styles from './limit-price.module.css'
type Batch = {
id: string
fileName: string
targetPrice: number | null
rowCount: number
updatedLimitCount: number
uploadedByName: string
note: string
createdAt: string
}
export function ManualLimitImportDialog({
open,
onClose,
onImported,
}: {
open: boolean
onClose: () => void
onImported: () => void
}) {
const [file, setFile] = useState<File | null>(null)
const [targetPrice, setTargetPrice] = useState('')
const [note, setNote] = useState('')
const [busy, setBusy] = useState(false)
const [message, setMessage] = useState('')
const [result, setResult] = useState<ManualLimitImportResult | null>(null)
const [history, setHistory] = useState<Batch[]>([])
useEffect(() => {
if (!open) return
const controller = new AbortController()
void (async () => {
try {
const response = await fetch('/api/supply-chain/limit-management/manual-limits', {
signal: controller.signal,
})
const payload = (await response.json()) as ApiResponse<Batch[]>
if (response.ok && payload.success && payload.data) setHistory(payload.data)
} catch {}
})()
return () => controller.abort()
}, [open])
if (!open) return null
const submit = async () => {
if (!file) {
setMessage('请选择 Excel 文件')
return
}
setBusy(true)
setMessage('')
setResult(null)
try {
const form = new FormData()
form.append('file', file)
if (targetPrice.trim()) form.append('targetPrice', targetPrice.trim())
form.append('note', note.trim())
const response = await fetch('/api/supply-chain/limit-management/manual-limits', {
method: 'POST',
body: form,
})
const payload = (await response.json()) as ApiResponse<ManualLimitImportResult>
if (!response.ok || !payload.success || !payload.data) {
throw new Error(payload.error?.message || '人工限价导入失败')
}
setResult(payload.data)
setMessage(`导入完成:更新 ${payload.data.updatedLimitCount} 个货号限价`)
const historyResponse = await fetch('/api/supply-chain/limit-management/manual-limits')
const historyPayload = (await historyResponse.json()) as ApiResponse<Batch[]>
if (historyPayload.success && historyPayload.data) setHistory(historyPayload.data)
onImported()
} catch (error) {
setMessage(error instanceof Error ? error.message : '人工限价导入失败')
} finally {
setBusy(false)
}
}
return (
<div className={styles.drawerBackdrop} onMouseDown={(event) => { if (event.target === event.currentTarget) onClose() }}>
<aside className={styles.drawer} role="dialog" aria-modal="true" aria-label="人工限价导入">
<header className={styles.drawerHeader}>
<div>
<h2>人工限价导入</h2>
<p>读取「商品编码」列,可按文件中的「限价价格」或统一限价写入;人工限价优先于流程同步。</p>
</div>
<button type="button" className={styles.iconButton} aria-label="关闭人工限价导入" onClick={onClose}><X size={16} /></button>
</header>
<div className={styles.drawerBody}>
<label className={styles.filterFieldRow}>
<Upload size={15} />
<span>{file?.name || '选择 Excel 文件'}</span>
<input
type="file"
accept=".xlsx,.xls"
aria-label="选择人工限价 Excel 文件"
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
/>
</label>
<p className={styles.drawerHint}>读取首张工作表,必须包含「商品编码」;可选列:限价价格 / 负责人限价 / 限价。</p>
<label className={styles.filterFieldRow}>
<span>统一限价</span>
<input
inputMode="decimal"
value={targetPrice}
placeholder="文件无价格列时填写,例如 49"
onChange={(event) => setTargetPrice(event.target.value.replace(/[^\d.]/g, ''))}
/>
</label>
<label className={styles.filterFieldRow}>
<span>备注</span>
<input value={note} maxLength={500} placeholder="填写本次人工限价原因" onChange={(event) => setNote(event.target.value)} />
</label>
{message && <p className={result ? styles.exportHint : styles.errorState}>{message}</p>}
{result && (
<div className={styles.drawerHint}>
商品编码 {result.uniqueCodeCount} 个,匹配条码 {result.matchedBarcodeCount} 个,更新货号 {result.updatedLimitCount} 个。
{result.unmatchedCodes.length ? ` 未匹配:${result.unmatchedCodes.slice(0, 10).join('、')}${result.unmatchedCodes.length > 10 ? '…' : ''}` : ''}
{result.invalidRows.length ? ` 无效行 ${result.invalidRows.length} 条。` : ''}
{result.conflictingStyles.length ? ` 同货号冲突 ${result.conflictingStyles.length} 个。` : ''}
</div>
)}
{history.length > 0 && (
<div>
<div className={styles.groupHeaderRow}>最近导入</div>
{history.slice(0, 5).map((batch) => (
<div key={batch.id} className={styles.drawerHint}>
{new Date(batch.createdAt).toLocaleString('zh-CN', { hour12: false })} · {batch.uploadedByName} · {batch.fileName} · 更新 {batch.updatedLimitCount} 个
{batch.targetPrice !== null ? ` · ¥${batch.targetPrice}` : ''}
</div>
))}
</div>
)}
</div>
<footer className={styles.drawerFooter}>
<button type="button" className={styles.secondaryButton} onClick={onClose}>关闭</button>
<button type="button" className={styles.primaryButton} disabled={busy || !file} onClick={() => void submit()}>
<Upload size={14} />{busy ? '导入中…' : '开始导入'}
</button>
</footer>
</aside>
</div>
)
}

View File

@ -0,0 +1,66 @@
import { render, screen } from '@testing-library/react'
import { OwnerLimitPriceHistoryDrawer } from './OwnerLimitPriceHistoryDrawer'
const originalFetch = global.fetch
afterEach(() => {
global.fetch = originalFetch
})
it('按货号展示无流程记录,并说明当前价格来自产品限价页面', async () => {
global.fetch = jest.fn(async () => ({
ok: true,
json: async () => ({
success: true,
data: {
barcode: 'CZ014006N3125V01',
sku: 'CZ014006',
spu: 'CZ0140',
current: {
price: '2141.80',
processNo: '',
processInstanceId: '',
applyType: '产品限价页面',
initiator: '',
approvedAt: '2026-07-14T07:45:10.000Z',
},
sourceRecord: {
sourceTable: 'external.product_catalog_wide_v1',
productBusinessKey: 'CZ0140',
skuCode: 'CZ014006',
skuName: '款式一 220/90/75 黑色',
barcode: 'CZ014006N3125V01',
limitPriceStatus: 'CONFIRMED',
limitPriceApplicable: true,
limitPriceConfirmed: true,
expectedDailyLimitPrice: '2141.8',
expectedLimitGrossMarginRate: '40',
nonSpuOwnerLimitPrice: '2336.8',
limitConfirmedAt: '2026-07-13T23:45:10.952Z',
limitSourceProductBusinessKey: '其他品牌-普通大货:CZ0140',
limitSourceSkuBusinessKey: '其他品牌-普通大货:CZ0140:CZ014006',
updatedAt: '2026-07-15T22:51:42.768Z',
},
records: [],
},
}),
})) as unknown as typeof fetch
render(
<OwnerLimitPriceHistoryDrawer
barcode="CZ014006N3125V01"
sku="CZ014006"
spu="CZ0140"
displayPrice="2141.80"
onClose={jest.fn()}
/>,
)
expect(await screen.findByText('价格来源')).toBeInTheDocument()
expect(screen.getByText('产品限价页面 · 货号 CZ014006')).toBeInTheDocument()
expect(screen.getByText('取自 external.product_catalog_wide_v1 中该货号的已确认限价记录')).toBeInTheDocument()
expect(screen.getByText('已确认')).toBeInTheDocument()
expect(screen.queryByText('2336.8 元')).not.toBeInTheDocument()
expect(screen.queryByText('款式一 220/90/75 黑色')).not.toBeInTheDocument()
expect(screen.queryByText(/未查到货号/)).not.toBeInTheDocument()
})

View File

@ -0,0 +1,163 @@
'use client'
import { useEffect, useState } from 'react'
import { History, LoaderCircle, X } from 'lucide-react'
import type { LimitPriceHistoryResult } from '@/lib/supply-chain-limit-price-history'
import type { ApiResponse } from '@/server/core/types'
import styles from './limit-price.module.css'
function displayDate(value: string) {
if (!value) return '-'
const normalized = value.includes('T') ? value : value.replace(' ', 'T')
const date = new Date(normalized)
if (Number.isNaN(date.getTime())) return value
return new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date)
}
export function OwnerLimitPriceHistoryDrawer({
barcode,
sku,
spu,
displayPrice,
onClose,
}: {
barcode: string
sku: string
spu: string
displayPrice: string
onClose: () => void
}) {
const [history, setHistory] = useState<LimitPriceHistoryResult | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
useEffect(() => {
const controller = new AbortController()
const params = new URLSearchParams({ barcode, sku, spu })
void fetch(`/api/supply-chain/limit-management/limit-price-history?${params}`, {
cache: 'no-store',
signal: controller.signal,
})
.then(async (response) => {
const payload = await response.json() as ApiResponse<LimitPriceHistoryResult>
if (!response.ok || !payload.success || !payload.data) {
throw new Error(payload.error?.message || '负责人限价历史加载失败')
}
setHistory(payload.data)
})
.catch((failure) => {
if (!controller.signal.aborted) {
setError(failure instanceof Error ? failure.message : '负责人限价历史加载失败')
}
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [barcode, sku, spu])
return (
<div className={styles.historyBackdrop} role="presentation" onMouseDown={(event) => {
if (event.target === event.currentTarget) onClose()
}}>
<aside className={styles.historyDrawer} role="dialog" aria-modal="true" aria-label="负责人限价历史流程">
<header className={styles.historyHeader}>
<div>
<strong><History size={16} />负责人限价历史流程</strong>
<span>{barcode}</span>
<small>{sku ? `SKU:${sku}` : ''}{spu ? ` SPU:${spu}` : ''}</small>
</div>
<button type="button" onClick={onClose} aria-label="关闭负责人限价历史">
<X size={17} />
</button>
</header>
<div className={styles.historyCurrent}>
<span>当前负责人限价</span>
<strong>{history?.current?.price ?? displayPrice} 元</strong>
{history?.current ? (
<small>
{history.current.applyType || '限价流程'} · {history.current.processNo || '-'}
{history.current.initiator ? ` · ${history.current.initiator}` : ''}
</small>
) : null}
</div>
<div className={styles.historyBody}>
{loading ? (
<div className={styles.historyState}>
<LoaderCircle size={18} className="animate-spin" />正在读取限价流程记录…
</div>
) : error ? (
<div className={styles.historyError}>{error}</div>
) : history ? (
<>
{history.sourceRecord ? (
<section className={styles.historySource}>
<header>
<div>
<strong>价格来源</strong>
<span>产品限价页面 · 货号 {history.sourceRecord.skuCode || history.sku}</span>
</div>
<b>{history.sourceRecord.limitPriceStatus === 'CONFIRMED' ? '已确认' : history.sourceRecord.limitPriceStatus || '-'}</b>
</header>
<p>取自 {history.sourceRecord.sourceTable} 中该货号的已确认限价记录</p>
</section>
) : null}
{history.records.length > 0 ? (
<div className={styles.historyTimeline}>
{history.records.map((record, index) => (
<article
key={`${record.processInstanceId}-${record.sourceTable}-${index}`}
className={record.businessId === history.current?.processNo ? styles.historyCurrentRecord : undefined}
>
<div className={styles.historyRecordHead}>
<div>
<strong>{record.templateName}</strong>
<span>{record.title}</span>
</div>
<b className={record.status === '已完成' ? styles.historyCompleted : styles.historyOtherStatus}>
{record.status}{record.result ? ` · ${record.result}` : ''}
</b>
</div>
<div className={styles.historyPriceRow}>
<span>流程限价</span>
<strong>{record.price ? `${record.price} 元` : '以附件/产品限价页面为准'}</strong>
</div>
<dl className={styles.historyFacts}>
<div><dt>申请类型</dt><dd>{record.applyType || '-'}</dd></div>
<div><dt>调整原因</dt><dd>{record.reason || '-'}</dd></div>
<div><dt>发起人</dt><dd>{record.initiator || '-'}</dd></div>
<div><dt>流程号</dt><dd>{record.businessId || '-'}</dd></div>
<div><dt>发起时间</dt><dd>{displayDate(record.createdAt)}</dd></div>
<div><dt>完成时间</dt><dd>{displayDate(record.finishedAt)}</dd></div>
<div><dt>有效期</dt><dd>{[record.startDate, record.endDate].filter(Boolean).join(' 至 ') || '-'}</dd></div>
<div><dt>来源明细</dt><dd>{record.sourceTable || '-'}</dd></div>
</dl>
{record.attachments.length > 0 ? (
<p className={styles.historyAttachments}>附件:{record.attachments.join(';')}</p>
) : null}
</article>
))}
</div>
) : history.sourceRecord ? null : (
<div className={styles.historyState}>
未查到货号 {history.sku} 的负责人限价流程记录
</div>
)}
</>
) : (
<div className={styles.historyState}>未查到负责人限价历史记录</div>
)}
</div>
</aside>
</div>
)
}

View File

@ -1,4 +1,9 @@
.tabPanel{display:flex;min-width:0;min-height:0;flex:1;flex-direction:column;background:#fff}
.comboPanel{display:flex;min-width:0;min-height:0;flex:1;flex-direction:column;overflow:hidden;background:#fff}
.comboTableScroll{width:100%;height:100%}
.comboTable{min-height:100%}
.comboRuleNote{display:flex;flex:0 0 auto;align-items:flex-start;gap:7px;border-bottom:1px solid #e4e4e7;background:#fffbeb;padding:8px 24px;color:#92400e;font-size:11px;line-height:1.55}
.comboRuleNote svg{flex:0 0 auto;margin-top:1px;color:#b45309}
.toolbar{display:flex;flex-wrap:wrap;min-height:52px;align-items:center;gap:10px;border-bottom:1px solid #e4e4e7;background:#fafafa;padding:9px 24px}
.segmented{display:inline-flex;height:32px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;padding:2px}
.segmented button{min-width:82px;border:0;border-radius:3px;background:transparent;color:#71717a;font-size:12px;cursor:pointer}
@ -34,6 +39,8 @@
.switchKnob{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:#fff;transition:transform .15s}
.switchOn .switchKnob{transform:translateX(16px)}
.filterBar{display:flex;flex-wrap:wrap;align-items:center;gap:8px;border-bottom:1px solid #e4e4e7;background:#fff;padding:9px 24px}
.filterBarLeading{display:flex;align-items:center;gap:6px}
.filterBarActions{display:flex;align-items:center;gap:6px;margin-left:auto}
.filterHint{color:#a1a1aa;font-size:11px}
.filterSelect{position:relative}
.filterTrigger{display:inline-flex;height:30px;max-width:220px;align-items:center;gap:6px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;padding:0 9px;color:#52525b;font-size:12px;cursor:pointer}
@ -52,6 +59,8 @@
.filterFooter{display:flex;flex:0 0 auto;align-items:center;justify-content:space-between;gap:8px;border-top:1px solid #f0f0f1;margin-top:5px;padding-top:6px}
.linkButton{border:0;background:transparent;color:#52525b;font-size:11px;cursor:pointer;padding:2px 4px}
.linkButton:hover{color:#18181b;text-decoration:underline}
.limitHistoryButton{border:0;background:transparent;padding:0;color:#1d4ed8;font:inherit;font-variant-numeric:tabular-nums;text-decoration:underline;text-decoration-style:dotted;text-underline-offset:3px;cursor:pointer}
.limitHistoryButton:hover{color:#1e40af}
.tableScroll{position:relative;min-height:0;flex:1;overflow:auto;background:#fff}
.table{border-collapse:separate;border-spacing:0;table-layout:fixed;background:#fff;font-size:12px}
.tableLoading{opacity:.55;transition:opacity .15s ease}
@ -87,6 +96,8 @@
.rowCompact .bodyTd{height:32px}
.numericCell{text-align:right}
.placeholderCell{color:#c4c4c8}
.clickableComboRow{cursor:pointer}
.selectedComboRow td{background:#eff6ff!important}
.table tbody tr:hover td{background:#fafafa}
.statusChip{display:inline-flex;height:22px;align-items:center;border-radius:4px;padding:0 7px;font-size:11px;font-weight:600}
.statusOnSale{background:#ecfdf3;color:#15803d}
@ -106,6 +117,24 @@
.pageTotal{color:#3f3f46}
.paginationSummary{display:inline-flex;align-items:center;gap:6px;color:#52525b;white-space:nowrap}
.pageSizeSelect{height:28px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;padding:0 24px 0 8px;color:#52525b;font-size:12px;outline:0}
.comboDetails{display:flex;min-height:0;flex:0 1 auto;flex-direction:column;border-top:2px solid #d4d4d8;background:#fff}
.comboDetailsHeader{display:flex;min-height:42px;flex:0 0 auto;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid #e4e4e7;background:#f4f6f8;padding:0 14px}
.comboDetailsHeader>div{display:flex;min-width:0;align-items:center;gap:12px;color:#52525b;font-size:11px}
.comboDetailsHeader strong{color:#18181b;font-size:12px}
.comboDetailsHeader span{overflow:hidden;max-width:45vw;text-overflow:ellipsis;white-space:nowrap}
.comboDetailsHeader em{color:#71717a;font-style:normal}
.comboDetailsHeader button{display:inline-flex;height:28px;flex:0 0 auto;align-items:center;gap:4px;border:1px solid #d4d4d8;border-radius:4px;background:#fff;padding:0 9px;color:#52525b;font-size:11px;cursor:pointer}
.comboDetailsHeader button:hover{background:#fafafa}
.comboDetailsState,.comboDetailsError{display:flex;min-height:96px;align-items:center;justify-content:center;gap:7px;color:#71717a;font-size:12px}
.comboDetailsError{color:#b91c1c}
.comboDetailsScroll{min-height:0;max-height:300px;overflow:auto}
.comboDetailsTable{width:100%;min-width:1080px}
.comboDetailsTable td{height:52px;white-space:nowrap}
.comboDetailsTable .comboProductName{min-width:280px;max-width:380px;white-space:normal}
.comboProductName strong,.comboProductName small,.comboDetailSub,.comboDetailMissing{display:block}
.comboProductName strong{color:#3f3f46;font-size:11px;font-weight:600;line-height:1.35}
.comboProductName small,.comboDetailSub{margin-top:3px;color:#a1a1aa;font-size:10px;font-weight:400;line-height:1.35}
.comboDetailMissing{margin-top:3px;color:#b45309;font-size:10px}
.drawerBackdrop{position:fixed;inset:0;z-index:90;display:flex;justify-content:flex-end;background:rgba(24,24,27,.34)}
.drawer{display:flex;width:min(420px,100%);height:100%;flex-direction:column;background:#fff;box-shadow:-14px 0 40px rgba(24,24,27,.18)}
.drawerHeader{display:flex;min-height:62px;flex:0 0 auto;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid #e4e4e7;padding:0 18px}
@ -113,6 +142,46 @@
.drawerHeader p{margin:4px 0 0;color:#71717a;font-size:11px}
.drawerBody{min-height:0;flex:1;overflow-y:auto;padding:12px 14px 18px}
.drawerFooter{display:flex;flex:0 0 auto;align-items:center;justify-content:space-between;gap:10px;border-top:1px solid #e4e4e7;background:#fafafa;padding:10px 18px}
.historyBackdrop{position:fixed;inset:0;z-index:140;display:flex;justify-content:flex-end;background:rgba(24,24,27,.34)}
.historyDrawer{display:flex;width:min(680px,100%);height:100%;flex-direction:column;background:#f6f7f7;box-shadow:-16px 0 48px rgba(24,24,27,.2)}
.historyHeader{display:flex;min-height:72px;flex:0 0 auto;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid #e4e4e7;background:#fff;padding:10px 18px}
.historyHeader>div{display:flex;min-width:0;flex-direction:column;gap:3px}
.historyHeader strong{display:inline-flex;align-items:center;gap:7px;color:#18181b;font-size:15px}
.historyHeader span{color:#3f3f46;font-size:12px;font-weight:600}
.historyHeader small{color:#a1a1aa;font-size:10px}
.historyHeader button{display:flex;width:30px;height:30px;flex:0 0 auto;align-items:center;justify-content:center;border:1px solid #e4e4e7;border-radius:5px;background:#fff;color:#71717a;cursor:pointer}
.historyCurrent{display:grid;flex:0 0 auto;grid-template-columns:1fr auto;align-items:center;gap:3px 12px;border-bottom:1px solid #e4e4e7;background:#eff6ff;padding:12px 18px}
.historyCurrent span{color:#64748b;font-size:11px}
.historyCurrent strong{grid-row:1/3;grid-column:2;color:#1d4ed8;font-size:22px;font-variant-numeric:tabular-nums}
.historyCurrent small{color:#64748b;font-size:10px}
.historyBody{min-height:0;flex:1;overflow-y:auto;padding:14px 18px 20px}
.historyState,.historyError{display:flex;min-height:180px;align-items:center;justify-content:center;gap:8px;color:#71717a;font-size:12px}
.historyError{color:#b91c1c}
.historySource{margin-bottom:12px;border:1px solid #bfdbfe;border-radius:6px;background:#fff;padding:12px}
.historySource>header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}
.historySource>header>div{display:flex;min-width:0;flex-direction:column;gap:3px}
.historySource>header strong{color:#18181b;font-size:13px}
.historySource>header span{color:#71717a;font-size:10px;overflow-wrap:anywhere}
.historySource>header b{flex:0 0 auto;border-radius:999px;background:#ecfdf5;padding:3px 8px;color:#047857;font-size:10px}
.historySource>p{margin:10px 0 0;border-radius:5px;background:#eff6ff;padding:8px 10px;color:#475569;font-size:11px;line-height:1.55}
.historyTimeline{display:flex;flex-direction:column;gap:10px}
.historyTimeline article{border:1px solid #e4e4e7;border-left:3px solid #cbd5e1;border-radius:6px;background:#fff;padding:11px 12px}
.historyTimeline article.historyCurrentRecord{border-color:#93c5fd;border-left-color:#1d4ed8;background:#f8fbff;box-shadow:0 0 0 1px rgba(29,78,216,.08)}
.historyRecordHead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}
.historyRecordHead>div{display:flex;min-width:0;flex-direction:column;gap:3px}
.historyRecordHead strong{color:#18181b;font-size:12px}
.historyRecordHead span{color:#71717a;font-size:10px;line-height:1.45}
.historyCompleted,.historyOtherStatus{flex:0 0 auto;border-radius:999px;padding:3px 8px;font-size:10px;font-weight:600;white-space:nowrap}
.historyCompleted{background:#ecfdf5;color:#047857}
.historyOtherStatus{background:#fff7ed;color:#c2410c}
.historyPriceRow{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:9px;border-radius:5px;background:#f8fafc;padding:7px 9px}
.historyPriceRow span{color:#71717a;font-size:10px}
.historyPriceRow strong{color:#18181b;font-size:14px;font-variant-numeric:tabular-nums}
.historyFacts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px 14px;margin:10px 0 0}
.historyFacts div{display:grid;grid-template-columns:66px minmax(0,1fr);gap:6px}
.historyFacts dt{color:#a1a1aa;font-size:10px}
.historyFacts dd{margin:0;color:#52525b;font-size:10px;line-height:1.45;overflow-wrap:anywhere}
.historyAttachments{margin:9px 0 0;border-top:1px dashed #e4e4e7;padding-top:7px;color:#a16207;font-size:10px;line-height:1.5}
.secondaryButton{display:inline-flex;height:32px;align-items:center;gap:6px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;padding:0 12px;color:#3f3f46;font-size:12px;cursor:pointer}
.secondaryButton:hover{border-color:#71717a;background:#f4f4f5}
.primaryButton{display:inline-flex;height:32px;align-items:center;gap:6px;border:1px solid #27272a;border-radius:5px;background:#27272a;padding:0 12px;color:#fff;font-size:12px;cursor:pointer}
@ -140,4 +209,6 @@
.search{width:100%;order:-1}
.resultCount{display:none}
.pagination{padding:8px 14px}
.historyDrawer{width:100%}
.historyFacts{grid-template-columns:1fr}
}

View File

@ -68,7 +68,7 @@ export const LIMIT_TABLE_COLUMNS: LimitTableColumn[] = [
// 限价
{ key: 'ownerLimitPrice', label: '负责人限价', group: 'limit', width: 110, kind: 'archive', prop: 'opsPriceLimit', numeric: true, filterKey: 'opsPriceLimit' },
{ key: 'nonOwnerLimitPriceNew', label: '非负责人限价', group: 'limit', width: 140, kind: 'archive', prop: 'nonOwnerLimitPriceNew', numeric: true },
{ key: 'nonOwnerLimitPriceNew', label: '非负责人限价(新)', group: 'limit', width: 140, kind: 'archive', prop: 'nonOwnerLimitPriceNew', numeric: true },
{ key: 'jxLimitPrice', label: '京喜限价', group: 'limit', width: 106, kind: 'archive', prop: 'jxLimitPrice', numeric: true },
{ key: 'alibabaPageLimitPrice', label: '阿里页面限价', group: 'limit', width: 122, kind: 'archive', prop: 'alibabaPageLimitPrice', numeric: true },
{ key: 'distributorPrice89', label: '分销商89折', group: 'limit', width: 116, kind: 'archive', prop: 'distributorPrice89', numeric: true },

View File

@ -3,6 +3,8 @@ import { requireSession } from '@/lib/server-session'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
import { CustomTableView } from './CustomTableView'
export const metadata = { title: '限价管理 · 供应链中心' }
export default async function CustomTablePage() {
const { authUser } = await requireSession('/login')
const access = await supplyChainPermissionSettingsService.getUserAccess(
@ -12,12 +14,14 @@ export default async function CustomTablePage() {
if (!access.view) redirect('/supply-chain')
const ruleAccess = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'breachRuleConfig')
const manualLimitAccess = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'limitManualOverride')
return (
<CustomTableView
canEdit={access.edit}
canExport={access.download}
userId={authUser.id}
canViewRuleConfig={ruleAccess.view}
canManageManualLimits={manualLimitAccess.edit}
/>
)
}

View File

@ -0,0 +1,328 @@
'use client'
import { FormEvent, useEffect, useState } from 'react'
import { Calculator, LoaderCircle, Search } from 'lucide-react'
import type { ApiResponse } from '@/server/core/types'
import {
FREIGHT_REGIONS,
describeFreightCourierRuleLimits,
freightWeightRoundingLabel,
type CourierFreightCost,
type FreightCalculationResult,
} from '@/lib/freight-calculation'
import styles from './freight-calculation.module.css'
function displayNumber(value: number | null | undefined, digits = 2) {
if (value === null || value === undefined || !Number.isFinite(value)) return '-'
return value.toLocaleString('zh-CN', {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
})
}
function displayPercent(value: number) {
return new Intl.NumberFormat('zh-CN', {
style: 'percent',
minimumFractionDigits: 2,
maximumFractionDigits: 4,
}).format(value)
}
function displayDateTime(value: string | null) {
if (!value) return '-'
const date = new Date(value)
if (Number.isNaN(date.getTime())) return value
return new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date)
}
function courierReasonText(courier: CourierFreightCost) {
if (courier.exclusionReasons.length > 0) return courier.exclusionReasons.join(';')
if (courier.missingProvinces.length > 0) {
return `缺少有效费率:${courier.missingProvinces.join('、')}`
}
return ''
}
function CourierCalculationDetails({ courier }: { courier: CourierFreightCost }) {
return (
<section className={styles.detailSection}>
<div className={styles.sectionHeading}>
<strong>{courier.expressName} · 29 省计费明细</strong>
<span>先通过多规则限重、限体积、限长边,再取当前有效的最新费率</span>
</div>
{courier.matchedRules.length > 0 ? (
<div className={styles.ruleSummary}>
<strong>聚水潭多规则匹配已通过</strong>
{courier.matchedRules.map((rule) => (
<span key={rule.ruleId}>
{rule.ruleName}:{describeFreightCourierRuleLimits(rule)}
</span>
))}
</div>
) : null}
<div className={styles.detailTableScroll}>
<table className={styles.table}>
<thead>
<tr>
<th>省份</th>
<th>区域</th>
<th className={styles.numericCell}>面单费</th>
<th className={styles.numericCell}>费率</th>
<th className={styles.numericCell}>扣重</th>
<th className={styles.numericCell}>最低收费</th>
<th className={styles.numericCell}>计泡/体积</th>
<th>取整规则</th>
<th className={styles.numericCell}>计费重量</th>
<th className={styles.numericCell}>扣重后计算值</th>
<th className={styles.numericCell}>省份运费</th>
<th>生效开始时间</th>
</tr>
</thead>
<tbody>
{courier.provinceCosts.map((row) => (
<tr key={`${courier.expressName}-${row.province}`}>
<td>{row.province}</td>
<td>{row.region}</td>
<td className={styles.numericCell}>{displayNumber(row.waybillFee, 2)}</td>
<td className={styles.numericCell}>{displayNumber(row.feeRate, 4)}</td>
<td className={styles.numericCell}>{displayNumber(row.deductWeight, 2)}</td>
<td className={styles.numericCell}>{displayNumber(row.minimumFee, 2)}</td>
<td className={styles.numericCell}>{displayNumber(row.volumeWeight, 4)}</td>
<td>{freightWeightRoundingLabel(row.roundingRule)}</td>
<td className={styles.numericCell}>{displayNumber(row.roundedWeight, 4)}</td>
<td className={styles.numericCell}>{displayNumber(row.rawFee, 4)}</td>
<td className={styles.numericCell}>{displayNumber(row.fee, 4)}</td>
<td>{displayDateTime(row.effectiveStartTime)}</td>
</tr>
))}
{courier.exclusionReasons.length > 0 || courier.missingProvinces.length > 0 ? (
<tr>
<td colSpan={12} className={styles.missingCell}>
{courier.status === 'NOT_APPLICABLE'
? courier.exclusionReasons.join(';')
: `缺少有效费率:${courier.missingProvinces.join('、')}`}
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</section>
)
}
function CalculationResult({ result }: { result: FreightCalculationResult }) {
const firstCalculated = result.couriers.find((courier) => courier.status === 'CALCULATED')
const [manualSelectedExpressName, setSelectedExpressName] = useState<string | null>(null)
const selectedExpressName = manualSelectedExpressName
&& result.couriers.some((courier) => courier.expressName === manualSelectedExpressName)
? manualSelectedExpressName
: firstCalculated?.expressName ?? result.couriers[0]?.expressName ?? ''
const selectedCourier = result.couriers.find(
(courier) => courier.expressName === selectedExpressName,
)
const dimensions = [result.length, result.width, result.height]
.filter((value): value is number => value !== null && Number.isFinite(value))
const longestSide = dimensions.length > 0 ? Math.max(...dimensions) : null
return (
<div className={styles.result}>
<div className={styles.productFacts}>
<div><span>商品编码</span><strong>{result.barcode}</strong></div>
<div><span>商品标签(限价同源)</span><strong>{result.productTag || '-'}</strong></div>
<div><span>发货仓库</span><strong>{result.warehouseName}</strong></div>
<div><span>重量</span><strong>{displayNumber(result.weight, 3)} kg</strong></div>
<div><span>体积</span><strong>{displayNumber(result.volume, 3)} cm³</strong></div>
<div><span>最长边</span><strong>{displayNumber(longestSide, 3)} cm</strong></div>
<div>
<span>快递数量</span>
<strong>{result.calculatedCourierCount} / {result.courierCount}</strong>
</div>
</div>
{result.warnings.map((warning) => (
<div key={warning} className={styles.warning}>{warning}</div>
))}
<section className={styles.regionSummary}>
<div className={styles.sectionHeading}>
<strong>商品编码区域平均运费</strong>
<span>省份运费求和 × 区域占比后,再除以可计算快递数</span>
</div>
<div className={styles.regionGrid}>
{result.regionAverages.map((region) => (
<div key={region.region}>
<span>{region.region} · 区域占比 {displayPercent(region.regionShare)}</span>
<strong>{displayNumber(region.averageCost, 4)} 元</strong>
<small>{region.courierCount} 个快递参与平均</small>
</div>
))}
</div>
</section>
<section className={styles.courierSection}>
<div className={styles.sectionHeading}>
<strong>各快递区域运费</strong>
<span>点击快递名称查看 29 省计费过程</span>
</div>
<div className={styles.detailTableScroll}>
<table className={styles.table}>
<thead>
<tr>
<th>快递名称</th>
{FREIGHT_REGIONS.map((region) => (
<th key={region} className={styles.numericCell}>{region}运费</th>
))}
<th>状态 / 不计算原因</th>
</tr>
</thead>
<tbody>
{result.couriers.map((courier) => (
<tr
key={courier.expressName}
className={courier.expressName === selectedExpressName ? styles.selectedRow : undefined}
>
<td>
<button
type="button"
className={styles.linkButton}
onClick={() => setSelectedExpressName(courier.expressName)}
>
{courier.expressName}
</button>
</td>
{FREIGHT_REGIONS.map((region) => (
<td key={region} className={styles.numericCell}>
{displayNumber(courier.regionCosts[region], 4)}
</td>
))}
<td>
<span className={
courier.status === 'CALCULATED'
? styles.statusReady
: courier.status === 'MISSING_RATE'
? styles.statusMissing
: styles.statusNotApplicable
}>
{courier.status === 'CALCULATED'
? '已计算'
: courier.status === 'MISSING_RATE'
? `缺 ${courier.missingProvinces.length} 省费率`
: courier.exclusionReasons.some((reason) => reason.includes('报价已过期'))
? '报价已过期'
: courier.exclusionReasons.some((reason) => reason.includes('按业务规则剔除计算'))
? '业务剔除'
: '规则不适用'}
</span>
{courier.status !== 'CALCULATED' ? (
<small className={styles.reasonCell}>{courierReasonText(courier)}</small>
) : null}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
{selectedCourier ? <CourierCalculationDetails courier={selectedCourier} /> : null}
</div>
)
}
export function FreightCalculationTab() {
const [barcode, setBarcode] = useState('')
const [result, setResult] = useState<FreightCalculationResult | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
const controller = new AbortController()
void fetch('/api/supply-chain/limit-management/freight-calculation', {
method: 'GET',
cache: 'no-store',
signal: controller.signal,
}).catch(() => undefined)
return () => controller.abort()
}, [])
const calculate = async (event: FormEvent) => {
event.preventDefault()
const normalizedBarcode = barcode.trim()
if (!normalizedBarcode) {
setError('请输入商品编码')
return
}
setLoading(true)
setError('')
try {
const response = await fetch('/api/supply-chain/limit-management/freight-calculation', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ barcode: normalizedBarcode }),
})
const payload = (await response.json()) as ApiResponse<FreightCalculationResult>
if (!response.ok || !payload.success || !payload.data) {
throw new Error(payload.error?.message || '快递运费计算失败')
}
setResult(payload.data)
} catch (calculationFailure) {
setResult(null)
setError(
calculationFailure instanceof Error ? calculationFailure.message : '快递运费计算失败',
)
} finally {
setLoading(false)
}
}
return (
<section className={styles.panel} aria-label="快递测算">
<div className={styles.toolbar}>
<form className={styles.searchForm} onSubmit={calculate}>
<label className={styles.searchBox}>
<Search size={15} />
<input
value={barcode}
maxLength={100}
placeholder="输入商品编码"
aria-label="商品编码"
onChange={(event) => setBarcode(event.target.value)}
/>
</label>
<button type="submit" className={styles.primaryButton} disabled={loading}>
<Calculator size={15} />
{loading ? '计算中' : '计算'}
</button>
</form>
<span className={styles.scopeNote}>
限价商品档案 → 标签仓库 → 多规则限重/体积/长边过滤 → 29 省费率 → 区域占比平均
</span>
</div>
{error ? <div className={styles.error}>{error}</div> : null}
{loading ? (
<div className={styles.state}>
<LoaderCircle size={20} className="animate-spin" />
正在读取产品档案、仓库快递和 29 省费率…
</div>
) : result ? (
<CalculationResult result={result} />
) : (
<div className={styles.empty}>
<Calculator size={24} />
<strong>输入商品编码开始测算</strong>
<span>超出快递限重、体积或最长边的商品会标注具体原因并从区域平均中剔除。</span>
</div>
)}
</section>
)
}

View File

@ -0,0 +1,106 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { FreightMaintenanceView } from './FreightMaintenanceView'
const originalFetch = global.fetch
function jsonResponse(payload: unknown) {
return {
ok: true,
status: 200,
json: async () => payload,
} as unknown as Response
}
afterAll(() => {
global.fetch = originalFetch
})
it('在快递维护页面按商品编码执行快递测算', async () => {
global.fetch = jest.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input)
if (!url.includes('/api/supply-chain/limit-management/freight-calculation')) {
throw new Error(`unexpected fetch: ${url}`)
}
if (init?.method !== 'POST') {
return jsonResponse({ success: true, data: { ready: true } })
}
return jsonResponse({
success: true,
data: {
barcode: 'TEST001',
productTag: '仓库-睢宁仓,快递-普通',
warehouseName: '睢宁仓',
weight: 15,
length: 100,
width: 40,
height: 3,
volume: 12000,
courierCount: 1,
calculatedCourierCount: 1,
regionAverages: [
{ region: '一区', regionShare: 0.214, courierCount: 1, averageCost: 10.379 },
{ region: '二区', regionShare: 0.485, courierCount: 1, averageCost: 11.2 },
{ region: '三区', regionShare: 0.251, courierCount: 1, averageCost: 12.3 },
{ region: '四区', regionShare: 0.05, courierCount: 1, averageCost: 13.4 },
],
warnings: [],
couriers: [{
expressName: '睢宁宿迁圆通',
status: 'CALCULATED',
missingProvinces: [],
exclusionReasons: [],
matchedRules: [{
ruleId: 'rule-1',
ruleName: '睢宁仓-普通',
sourceWarehouseName: '睢宁仓',
minWeight: null,
maxWeight: 20,
minVolume: null,
maxVolume: null,
minLongestSide: null,
maxLongestSide: null,
minSecondLongestSide: null,
maxSecondLongestSide: null,
}],
regionCosts: { 一区: 10.379, 二区: 11.2, 三区: 12.3, 四区: 13.4 },
provinceCosts: [{
province: '上海',
region: '一区',
fee: 12.5,
rawFee: 12.5,
chargeableWeight: 15,
roundedWeight: 15,
actualWeight: 15,
volumeWeight: 2,
waybillFee: 3.8,
deductWeight: 0,
feeRate: 0.58,
minimumFee: 0,
roundingRule: 0,
volumeWeightDivisor: 6000,
effectiveStartTime: '2026-09-20T00:00:00.000Z',
ruleId: '100',
}],
}],
},
})
}) as unknown as typeof fetch
render(<FreightMaintenanceView />)
expect(screen.getByRole('heading', { name: '快递维护' })).toBeInTheDocument()
fireEvent.change(screen.getByRole('textbox', { name: '商品编码' }), {
target: { value: 'TEST001' },
})
fireEvent.click(screen.getByRole('button', { name: '计算' }))
expect(await screen.findByText('睢宁仓')).toBeInTheDocument()
expect(screen.getByText('10.3790 元')).toBeInTheDocument()
expect(screen.getByRole('button', { name: '睢宁宿迁圆通' })).toBeInTheDocument()
await waitFor(() => {
expect(global.fetch).toHaveBeenCalledWith(
'/api/supply-chain/limit-management/freight-calculation',
expect.objectContaining({ method: 'POST' }),
)
})
})

View File

@ -0,0 +1,18 @@
import { FreightCalculationTab } from './FreightCalculationTab'
import styles from '../custom-table/limit-management.module.css'
export function FreightMaintenanceView() {
return (
<main className={styles.page}>
<header className={styles.pageHeader}>
<div>
<h1>快递维护</h1>
<p>按商品编码维护仓库快递、费率规则和全国 29 省运费测算。</p>
</div>
</header>
<div className={styles.workspace}>
<FreightCalculationTab />
</div>
</main>
)
}

View File

@ -0,0 +1,393 @@
.panel {
display: flex;
min-width: 0;
min-height: 0;
flex: 1;
flex-direction: column;
background: #f6f7f7;
}
.toolbar {
display: flex;
min-height: 58px;
flex: 0 0 auto;
align-items: center;
gap: 12px;
border-bottom: 1px solid #e4e4e7;
background: #fafafa;
padding: 10px 24px;
}
.searchForm {
display: flex;
align-items: center;
gap: 8px;
}
.searchBox {
display: flex;
width: min(380px, 36vw);
height: 34px;
align-items: center;
gap: 7px;
border: 1px solid #d4d4d8;
border-radius: 5px;
background: #fff;
padding: 0 10px;
color: #a1a1aa;
}
.searchBox:focus-within {
border-color: #71717a;
box-shadow: 0 0 0 2px rgba(63, 63, 70, .08);
}
.searchBox input {
min-width: 0;
flex: 1;
border: 0;
outline: 0;
background: transparent;
color: #27272a;
font: inherit;
font-size: 12px;
}
.primaryButton {
display: inline-flex;
height: 34px;
align-items: center;
justify-content: center;
gap: 6px;
border: 1px solid #27272a;
border-radius: 5px;
background: #27272a;
padding: 0 13px;
color: #fff;
font-size: 12px;
cursor: pointer;
}
.primaryButton:disabled {
cursor: not-allowed;
opacity: .45;
}
.scopeNote {
margin-left: auto;
color: #71717a;
font-size: 11px;
white-space: nowrap;
}
.error {
border-bottom: 1px solid #fecaca;
background: #fff7f7;
padding: 9px 24px;
color: #b91c1c;
font-size: 12px;
}
.result {
min-height: 0;
flex: 1;
overflow: auto;
padding: 16px 24px 24px;
}
.productFacts {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
border: 1px solid #e4e4e7;
border-radius: 6px;
background: #fafafa;
}
.productFacts > div {
display: flex;
min-width: 0;
flex-direction: column;
gap: 5px;
border-right: 1px solid #e4e4e7;
padding: 11px 13px;
}
.productFacts > div:last-child {
border-right: 0;
}
.productFacts span {
color: #71717a;
font-size: 11px;
}
.productFacts strong {
overflow: hidden;
color: #27272a;
font-size: 13px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.warning {
margin-top: 10px;
border: 1px solid #fde68a;
border-radius: 5px;
background: #fffbeb;
padding: 8px 11px;
color: #92400e;
font-size: 12px;
}
.regionSummary,
.courierSection,
.detailSection {
margin-top: 16px;
}
.sectionHeading {
display: flex;
min-height: 34px;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #71717a;
font-size: 12px;
}
.sectionHeading strong {
color: #27272a;
font-size: 13px;
}
.sectionHeading span {
text-align: right;
}
.ruleSummary {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 8px;
border: 1px solid #dbeafe;
border-radius: 6px;
background: #eff6ff;
padding: 9px 11px;
color: #475569;
font-size: 11px;
line-height: 1.55;
}
.ruleSummary strong {
color: #1e3a8a;
font-size: 12px;
}
.regionGrid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
}
.regionGrid > div {
display: flex;
min-width: 0;
flex-direction: column;
gap: 5px;
border: 1px solid #e4e4e7;
border-radius: 6px;
background: #fff;
padding: 12px;
}
.regionGrid span,
.regionGrid small {
color: #71717a;
font-size: 11px;
}
.regionGrid strong {
color: #18181b;
font-size: 18px;
font-variant-numeric: tabular-nums;
font-weight: 650;
}
.detailTableScroll {
max-height: 420px;
overflow: auto;
border: 1px solid #e4e4e7;
border-radius: 6px;
background: #fff;
}
.table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
font-size: 12px;
}
.table th {
position: sticky;
top: 0;
z-index: 2;
height: 40px;
border-bottom: 1px solid #d4d4d8;
background: #eef0ef;
padding: 0 11px;
color: #52525b;
font-size: 11px;
font-weight: 600;
text-align: left;
white-space: nowrap;
}
.table td {
height: 42px;
border-bottom: 1px solid #eeeeef;
padding: 6px 11px;
color: #52525b;
white-space: nowrap;
}
.table tbody tr:hover td {
background: #fafafa;
}
.numericCell {
text-align: right !important;
font-variant-numeric: tabular-nums;
}
.selectedRow td {
background: #f4f4f5;
}
.linkButton {
border: 0;
background: transparent;
padding: 0;
color: #1d4ed8;
font: inherit;
text-align: left;
cursor: pointer;
}
.linkButton:hover {
text-decoration: underline;
}
.statusReady,
.statusMissing,
.statusNotApplicable {
display: inline-flex;
align-items: center;
border-radius: 999px;
padding: 2px 8px;
font-size: 11px;
white-space: nowrap;
}
.statusReady {
background: #ecfdf5;
color: #047857;
}
.statusMissing {
background: #fff7ed;
color: #c2410c;
}
.statusNotApplicable {
background: #f4f4f5;
color: #52525b;
}
.reasonCell {
display: block;
min-width: 280px;
max-width: 520px;
margin-top: 4px;
overflow: hidden;
color: #a16207;
font-size: 10px;
line-height: 1.45;
text-overflow: ellipsis;
white-space: nowrap;
}
.missingCell {
color: #b45309 !important;
text-align: left !important;
white-space: normal !important;
}
.state,
.empty {
display: flex;
min-height: 280px;
flex: 1;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 8px;
color: #a1a1aa;
font-size: 12px;
}
.empty strong {
color: #52525b;
font-size: 14px;
}
.empty span {
max-width: 520px;
color: #71717a;
line-height: 1.6;
text-align: center;
}
@media (max-width: 720px) {
.toolbar {
align-items: stretch;
flex-direction: column;
padding-right: 14px;
padding-left: 14px;
}
.searchForm {
align-items: stretch;
flex-direction: column;
}
.searchBox {
width: 100%;
}
.scopeNote {
margin-left: 0;
white-space: normal;
}
.result {
padding-right: 14px;
padding-left: 14px;
}
.regionGrid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.sectionHeading {
align-items: flex-start;
flex-direction: column;
padding: 6px 0;
}
.sectionHeading span {
text-align: left;
}
}

View File

@ -0,0 +1,17 @@
import { redirect } from 'next/navigation'
import { requireSession } from '@/lib/server-session'
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
import { FreightMaintenanceView } from './FreightMaintenanceView'
export const metadata = { title: '快递维护 · 供应链中心' }
export default async function FreightMaintenancePage() {
const { authUser } = await requireSession('/login')
const access = await supplyChainPermissionSettingsService.getUserAccess(
authUser,
'limitManagement',
)
if (!access.view) redirect('/supply-chain')
return <FreightMaintenanceView />
}

View File

@ -0,0 +1,418 @@
import {
FREIGHT_CALCULATION_PROVINCES,
applyWeightRounding,
averageCourierRegionalFreight,
buildFreightCalculation,
calculateProvinceFreight,
calculateRegionalFreight,
describeFreightCourierRuleLimits,
evaluateFreightCourierRules,
freightRateValidity,
freightCourierRuleProvinceRestrictionReason,
freightCourierNameExclusionReason,
normalizeFreightProvince,
parseWarehouseFromProductTag,
selectLatestApplicableRate,
freightWeightRoundingLabel,
type FreightCourierRuleLimit,
type FreightRateRecord,
} from './freight-calculation'
function rate(overrides: Partial<FreightRateRecord> = {}): FreightRateRecord {
return {
ruleId: '1',
expressName: '睢宁宿迁圆通',
province: '上海',
effectiveStartTime: '2026-09-20T00:00:00.000Z',
effectiveEndTime: '2029-12-31T00:00:00.000Z',
startWeight: 3,
endWeight: 35,
startVolume: 0,
endVolume: 99999999,
startLength: 0,
endLength: 99999999,
waybillFee: 3.8,
deductWeight: 0,
feeRate: 0.58,
minimumFee: 0,
roundingRule: 0,
volumeWeightDivisor: 6000,
...overrides,
}
}
function courierRule(
overrides: Partial<FreightCourierRuleLimit> = {},
): FreightCourierRuleLimit {
return {
ruleId: '216452',
ruleName: '山东青岗集仓-曹县德邦小件',
sourceWarehouseName: '简尚-山东青岗集仓',
minWeight: null,
maxWeight: 10,
minVolume: null,
maxVolume: 120000,
minLongestSide: null,
maxLongestSide: 160,
minSecondLongestSide: null,
maxSecondLongestSide: null,
...overrides,
}
}
describe('freight calculation', () => {
it('从商品标签解析仓库,并按重量与体积较大值计算运费', () => {
expect(parseWarehouseFromProductTag('快递-普通,仓库-睢宁仓')).toBe('睢宁仓')
expect(parseWarehouseFromProductTag('仓库-山东景瓴十方代发仓')).toBe('山东景瓴十方代发仓')
expect(calculateProvinceFreight({
weight: 15,
volume: 12000,
waybillFee: 3.8,
feeRate: 0.58,
volumeWeightDivisor: 6000,
})).toEqual({
chargeableWeight: 15,
roundedWeight: 15,
rawFee: 12.5,
fee: 12.5,
})
expect(calculateProvinceFreight({
weight: 2,
volume: 12000,
waybillFee: 3.8,
feeRate: 0.58,
volumeWeightDivisor: 6000,
})).toEqual({
chargeableWeight: 2,
roundedWeight: 2,
rawFee: 4.96,
fee: 4.96,
})
})
it('扣重参与计费,并与最低收费取较大值', () => {
expect(calculateProvinceFreight({
weight: 2.1,
volume: 8666.375,
waybillFee: 15.5,
deductWeight: -15,
feeRate: 0.75,
minimumFee: 15.5,
volumeWeightDivisor: 8000,
}).chargeableWeight).toBe(2.1)
expect(calculateProvinceFreight({
weight: 2.1,
volume: 8666.375,
waybillFee: 15.5,
deductWeight: -15,
feeRate: 0.75,
minimumFee: 15.5,
volumeWeightDivisor: 8000,
}).roundedWeight).toBe(2.1)
expect(calculateProvinceFreight({
weight: 2.1,
volume: 8666.375,
waybillFee: 15.5,
deductWeight: -15,
feeRate: 0.75,
minimumFee: 15.5,
volumeWeightDivisor: 8000,
}).rawFee).toBeCloseTo(5.825)
expect(calculateProvinceFreight({
weight: 2.1,
volume: 8666.375,
waybillFee: 15.5,
deductWeight: -15,
feeRate: 0.75,
minimumFee: 15.5,
volumeWeightDivisor: 8000,
}).fee).toBe(15.5)
})
it('按聚水潭进位规则调整计费重量', () => {
expect(applyWeightRounding(2.1, 0)).toBe(2.1)
expect(applyWeightRounding(2.1, 4)).toBe(3)
expect(applyWeightRounding(2.4, 1)).toBe(2)
expect(applyWeightRounding(2.5, 1)).toBe(3)
expect(applyWeightRounding(2.1, 8)).toBe(2.5)
expect(applyWeightRounding(29.3, 1)).toBe(29)
expect(applyWeightRounding(29.5, 1)).toBe(30)
expect(applyWeightRounding(29.3, 4)).toBe(30)
expect(applyWeightRounding(29.3, 8)).toBe(29.5)
expect(freightWeightRoundingLabel(0)).toBe('不进位')
expect(freightWeightRoundingLabel(1)).toBe('个位-四舍五入')
expect(freightWeightRoundingLabel(4)).toBe('个位-进位')
expect(freightWeightRoundingLabel(8)).toBe('0.5进位')
})
it('按聚水潭多规则限制先过滤快递并写明超限原因', () => {
const rule = courierRule()
expect(describeFreightCourierRuleLimits(rule)).toContain('重量')
expect(describeFreightCourierRuleLimits(rule)).toContain('120,000')
expect(evaluateFreightCourierRules({
rules: [rule],
weight: 10,
volume: 120000,
length: 160,
width: 80,
height: 20,
})).toMatchObject({
applicable: true,
exclusionReasons: [],
})
const excluded = evaluateFreightCourierRules({
rules: [rule],
weight: 29.3,
volume: 291200,
length: 180,
width: 80,
height: 20,
})
expect(excluded.applicable).toBe(false)
expect(excluded.exclusionReasons).toHaveLength(1)
expect(excluded.exclusionReasons[0]).toContain('超出限重:29.3 kg > 10 kg')
expect(excluded.exclusionReasons[0]).toContain('超出限体积:291,200 cm³ > 120,000 cm³')
expect(excluded.exclusionReasons[0]).toContain('超出最长边限制:180 cm > 160 cm')
})
it('名称包含京东自营或京喜的快递按业务规则剔除', () => {
expect(freightCourierNameExclusionReason('京东自营快递贝壳家'))
.toBe('快递名称包含“京东自营”,按业务规则剔除计算')
expect(freightCourierNameExclusionReason('京喜京东快运'))
.toBe('快递名称包含“京喜”,按业务规则剔除计算')
expect(freightCourierNameExclusionReason('曹县京东快运')).toBeNull()
})
it('校验商品、订单上下文和到达省份限定条件', () => {
const rule = courierRule({
includedSkuIds: 'OTHER001',
includedSkuLabels: '快递-品牌货号',
shopSites: '京东商城',
allowedProvinces: '上海,江苏省',
})
const evaluation = evaluateFreightCourierRules({
rules: [rule],
barcode: 'SZ021705N371V01',
productTag: '快递-普通,仓库-山东青岗集仓',
weight: 2,
volume: 1000,
length: 20,
width: 10,
height: 5,
})
expect(evaluation.applicable).toBe(false)
expect(evaluation.exclusionReasons[0]).toContain('不在限定商品范围内')
expect(evaluation.exclusionReasons[0]).toContain('不满足限定商品标签')
const contextOnly = evaluateFreightCourierRules({
rules: [courierRule({ shopSites: '京东商城' })],
barcode: 'SZ021705N371V01',
productTag: '快递-普通,仓库-山东青岗集仓',
weight: 2,
volume: 1000,
length: 20,
width: 10,
height: 5,
})
expect(contextOnly.applicable).toBe(true)
expect(freightCourierRuleProvinceRestrictionReason({
rule,
province: '上海',
})).toBeNull()
expect(freightCourierRuleProvinceRestrictionReason({
rule,
province: '浙江',
})).toContain('限定到达省份不包含浙江')
})
it('同快递有多条匹配规则时只要一条满足即保留快递', () => {
const result = evaluateFreightCourierRules({
rules: [
courierRule({ ruleId: 'small', ruleName: '小件规则' }),
courierRule({
ruleId: 'large',
ruleName: '大件规则',
maxWeight: 60,
maxVolume: 600000,
maxLongestSide: 220,
}),
],
weight: 29.3,
volume: 291200,
length: 180,
width: 80,
height: 20,
})
expect(result.applicable).toBe(true)
expect(result.matchedRules.map((rule) => rule.ruleId)).toEqual(['large'])
})
it('全部快递被多规则过滤时仍返回结果和具体原因', () => {
const shipmentShareRows = FREIGHT_CALCULATION_PROVINCES.map(({ province, region }) => ({
province,
shipmentCount: 1,
totalShipment: 29,
shipmentShare: 1 / 29,
region,
regionShare: region === '一区' ? 0.214 : region === '二区' ? 0.485 : region === '三区' ? 0.251 : 0.05,
}))
const result = buildFreightCalculation({
archive: {
barcode: 'SZ021705N371V01',
productTag: '快递-普通,仓库-山东青岗集仓',
inOutWarehouse: '山东青岗集仓',
weight: 29.3,
length: 180,
width: 80,
height: 20,
volume: 291200,
},
warehouseName: '山东青岗集仓',
couriers: [{
expressName: '曹县德邦小件',
rules: [courierRule()],
}],
rates: [],
shipmentShareRows,
now: new Date('2026-10-27T08:00:00.000Z'),
})
expect(result.calculatedCourierCount).toBe(0)
expect(result.regionAverages.every((region) => region.averageCost === null)).toBe(true)
expect(result.couriers[0]).toMatchObject({
expressName: '曹县德邦小件',
status: 'NOT_APPLICABLE',
missingProvinces: [],
})
expect(result.couriers[0].exclusionReasons[0]).toContain('超出限体积')
expect(result.warnings).toContain('当前商品没有可计算快递,区域平均运费为空')
})
it('同一区域按区域占比计算,再对快递取平均', () => {
const firstCourier = calculateRegionalFreight([12.5, 10, 15, 11], 0.214)
const secondCourier = 12
expect(firstCourier).toBe(10.379)
expect(averageCourierRegionalFreight([firstCourier, secondCourier])).toBe(11.1895)
})
it('同一快递和省份只取当前有效且生效开始时间最新的费率', () => {
const now = new Date('2026-10-26T08:00:00.000Z')
const selected = selectLatestApplicableRate({
rates: [
rate({ ruleId: '1', waybillFee: 3.7 }),
rate({
ruleId: '2',
waybillFee: 3.8,
effectiveStartTime: '2026-10-01T00:00:00.000Z',
}),
rate({
ruleId: '3',
waybillFee: 9.9,
effectiveStartTime: '2026-11-01T00:00:00.000Z',
}),
rate({ ruleId: '4', province: '江苏省', waybillFee: 8.8 }),
],
expressName: '睢宁宿迁圆通',
province: '上海',
weight: 15,
volume: 12000,
longestSide: 44.5,
now,
})
expect(selected?.ruleId).toBe('2')
})
it('最新执行日期的报价已过期时使用次新有效报价', () => {
const now = new Date('2026-10-26T08:00:00.000Z')
const selected = selectLatestApplicableRate({
rates: [
rate({
ruleId: 'expired-newest',
waybillFee: 9.9,
effectiveStartTime: '2026-10-20T00:00:00.000Z',
effectiveEndTime: '2026-10-25T00:00:00.000Z',
}),
rate({
ruleId: 'active-older',
waybillFee: 4.2,
effectiveStartTime: '2025-01-01T00:00:00.000Z',
effectiveEndTime: '2027-12-31T00:00:00.000Z',
}),
],
expressName: '睢宁宿迁圆通',
province: '上海',
weight: 15,
volume: 12000,
longestSide: 44.5,
now,
})
expect(selected?.ruleId).toBe('active-older')
})
it('全部报价已过期时不计算并返回过期提示', () => {
const now = new Date('2026-10-26T08:00:00.000Z')
const expiredRate = rate({
ruleId: 'expired',
effectiveStartTime: '2025-01-01T00:00:00.000Z',
effectiveEndTime: '2026-01-01T00:00:00.000Z',
})
expect(freightRateValidity(expiredRate, now)).toBe('EXPIRED')
const shipmentShareRows = FREIGHT_CALCULATION_PROVINCES.map(({ province, region }) => ({
province,
shipmentCount: 1,
totalShipment: 29,
shipmentShare: 1 / 29,
region,
regionShare: region === '一区' ? 0.214 : region === '二区' ? 0.485 : region === '三区' ? 0.251 : 0.05,
}))
const result = buildFreightCalculation({
archive: {
barcode: 'TEST-EXPIRED',
productTag: '仓库-睢宁仓,快递-普通',
inOutWarehouse: '睢宁仓',
weight: 2,
length: 20,
width: 10,
height: 5,
volume: 1000,
},
warehouseName: '睢宁仓',
couriers: [{ expressName: '睢宁宿迁圆通' }],
rates: [expiredRate],
shipmentShareRows,
now,
})
expect(result.couriers[0].status).toBe('NOT_APPLICABLE')
expect(result.couriers[0].exclusionReasons[0]).toContain('正常费率报价已过期')
expect(result.warnings).toContain('1 个快递正常费率报价已过期,不参与计算')
})
it('长边不满足超长规则时,优先选择普通长度费率', () => {
const now = new Date('2026-10-26T08:00:00.000Z')
const selected = selectLatestApplicableRate({
rates: [
rate({ ruleId: '10', startWeight: 0, startLength: 0, endLength: 160, waybillFee: 6.8 }),
rate({ ruleId: '20', startWeight: 0, startLength: 160, endLength: 99999999, waybillFee: 16.8 }),
],
expressName: '睢宁宿迁圆通',
province: '上海',
weight: 2.1,
volume: 8666.375,
longestSide: 44.5,
now,
})
expect(selected?.ruleId).toBe('10')
})
it('统一费率表里的省市别名到发货占比省份', () => {
expect(normalizeFreightProvince('江苏省')).toBe('江苏')
expect(normalizeFreightProvince('杭州市')).toBe('浙江')
expect(normalizeFreightProvince('内蒙古自治区')).toBe('内蒙')
expect(normalizeFreightProvince('恩施土家族苗族自治州')).toBe('湖北')
})
})

File diff suppressed because it is too large Load Diff

View File

@ -49,6 +49,37 @@ export type ComboLimitPage = {
}
}
export type ComboLimitComponentDetail = {
sourceCode: string
barcode: string
sku: string
quantity: number
productName: string
imageUrl: string
model: string
color: string
categoryTwo: string
productStatus: string
owner: string
departmentHead: string
costPrice: number | null
ownerLimitPrice: number | null
nonOwnerLimitPrice: number | null
jxLimitPrice: number | null
alibabaPageLimitPrice: number | null
distributorPrice89: number | null
distributorPrice85: number | null
distributorPrice80: number | null
ownerLimitSubtotal: number | null
matchedBy: 'BARCODE' | 'SKU' | 'UNAVAILABLE'
}
export type ComboLimitDetails = {
comboCode: string
creator: string
rows: ComboLimitComponentDetail[]
}
export type ComboLimitOptionResult = {
field: ComboLimitFieldKey
values: string[]
@ -70,6 +101,37 @@ function roundPrice(value: number) {
return Math.round((value + Number.EPSILON) * 100) / 100
}
export function deriveComboComponentPrices(
ownerLimitPrice: number | null,
costPrice: number | null,
) {
if (ownerLimitPrice === null || !Number.isFinite(ownerLimitPrice)) {
return {
nonOwnerLimitPrice: null,
jxLimitPrice: null,
alibabaPageLimitPrice: null,
distributorPrice89: null,
distributorPrice85: null,
distributorPrice80: null,
}
}
const nonOwnerLimitPrice = roundPrice(
ownerLimitPrice
+ Math.max(ownerLimitPrice * 0.05, 10),
)
const alibabaPageLimitPrice = roundPrice(nonOwnerLimitPrice * 0.93)
return {
nonOwnerLimitPrice,
jxLimitPrice: costPrice !== null && costPrice > 0
? roundPrice(costPrice / 0.74)
: null,
alibabaPageLimitPrice,
distributorPrice89: roundPrice(alibabaPageLimitPrice * 0.89),
distributorPrice85: roundPrice(alibabaPageLimitPrice * 0.85),
distributorPrice80: roundPrice(alibabaPageLimitPrice * 0.8),
}
}
export function formatComboLimitPrice(value: number | null | undefined) {
return typeof value === 'number' && Number.isFinite(value) ? roundPrice(value).toFixed(2) : ''
}

View File

@ -0,0 +1,184 @@
import {
buildLimitPriceWorkflowRecords,
mergeLimitPriceWorkflowSnapshots,
type LimitPriceWorkflowFieldInput,
type LimitPriceWorkflowInput,
} from './supply-chain-limit-price-history'
const targetBarcode = 'GBGJ-SZ024401N1441V01'
const targetSku = 'GBGJ-SZ024401'
const targetSpu = 'GBGJ-SZ0244'
function flow(overrides: Partial<LimitPriceWorkflowInput>): LimitPriceWorkflowInput {
return {
processInstanceId: 'flow-1',
businessId: '202610191816000088378',
title: '10-19+醉夏提交的新品限价及限价调整',
status: 'COMPLETED',
result: 'agree',
originatorUserId: 'user-1',
createAt: '2026-10-19 18:16:00',
finishTime: '2026-10-19 19:20:00',
...overrides,
}
}
function field(overrides: Partial<LimitPriceWorkflowFieldInput>): LimitPriceWorkflowFieldInput {
return {
processInstanceId: 'flow-1',
componentType: 'TextField',
name: '',
value: '',
...overrides,
}
}
describe('负责人限价历史流程解析', () => {
it('增量同步只替换有更新的流程及其字段,保留其他快照', () => {
const merged = mergeLimitPriceWorkflowSnapshots({
existing: {
flows: [
flow({ processInstanceId: 'flow-changed', businessId: 'FLOW-1', createAt: '2026-10-01 10:00:00' }),
flow({ processInstanceId: 'flow-kept', businessId: 'FLOW-2', createAt: '2026-09-01 10:00:00' }),
],
fields: [
field({ processInstanceId: 'flow-changed', name: '调整理由', value: '旧原因' }),
field({ processInstanceId: 'flow-kept', name: '调整理由', value: '保留原因' }),
],
},
incoming: {
flows: [
flow({ processInstanceId: 'flow-changed', businessId: 'FLOW-1', createAt: '2026-10-01 10:00:00' }),
],
fields: [
field({ processInstanceId: 'flow-changed', name: '调整理由', value: '更新原因' }),
],
},
syncedThrough: '2026-10-28T12:00:00',
})
expect(merged.flows.map((item) => item.processInstanceId)).toEqual(['flow-changed', 'flow-kept'])
expect(merged.fields).toEqual([
expect.objectContaining({ processInstanceId: 'flow-kept', value: '保留原因' }),
expect.objectContaining({ processInstanceId: 'flow-changed', value: '更新原因' }),
])
expect(merged.syncedThrough).toBe('2026-10-28T12:00:00')
})
it('仅保留命中商品编码的流程明细,并提取原因、限价、有效期和附件', () => {
const table = JSON.stringify([
{
rowValue: [
{ label: '商品编码', value: targetBarcode },
{ label: ['开始时间', '结束时间'], value: ['2026-10-19', '2026-12-31'] },
{ label: '调整后限价', value: '439' },
{ label: '调整理由', value: '竞品同款降价,重新核定限价' },
],
},
{
rowValue: [
{ label: '商品编码', value: 'GBGJ-SZ024401N1442V01' },
{ label: 'SPU', value: targetSpu },
{ label: '调整后限价', value: '999' },
{ label: '调整理由', value: '不应展示的其他商品' },
],
},
])
const records = buildLimitPriceWorkflowRecords({
barcode: targetBarcode,
sku: targetSku,
spu: targetSpu,
currentProcessNo: '202610191816000088378',
flows: [flow({})],
fields: [
field({ name: '申请类型', value: '调整原货号限价' }),
field({ name: '调整理由', value: '流程级原因' }),
field({ name: '限价附件', value: JSON.stringify([{ fileName: '竞品比价.xlsx' }]) }),
field({ name: '限价调整明细表', componentType: 'TableField', value: table }),
],
})
expect(records).toHaveLength(1)
expect(records[0]).toMatchObject({
templateName: '新品限价及限价调整',
status: '已完成',
result: '同意',
initiator: '醉夏',
applyType: '调整原货号限价',
reason: '竞品同款降价,重新核定限价',
price: '439',
startDate: '2026-10-19',
endDate: '2026-12-31',
sourceTable: '限价调整明细表',
attachments: ['竞品比价.xlsx'],
})
})
it('新品限价流程没有线上明细时保留附件流程,并按发起时间倒序返回', () => {
const records = buildLimitPriceWorkflowRecords({
barcode: targetBarcode,
sku: targetSku,
spu: targetSpu,
currentProcessNo: '202610081643000269370',
flows: [
flow({
processInstanceId: 'flow-old',
businessId: '202609281652000089380',
title: '09-28+章男提交的新品限价及限价调整',
createAt: '2026-09-28 16:52:00',
}),
flow({
processInstanceId: 'flow-attachment',
businessId: '202610081643000269370',
title: '10-08+醉夏提交的新品限价流程',
createAt: '2026-10-08 16:43:00',
}),
],
fields: [
field({
processInstanceId: 'flow-attachment',
name: '调整理由',
value: '新品首次定价',
}),
field({
processInstanceId: 'flow-attachment',
name: '限价附件',
value: JSON.stringify([{ fileName: '新品限价明细.xlsx' }]),
}),
field({
processInstanceId: 'flow-old',
name: '限价明细表',
componentType: 'TableField',
value: JSON.stringify([
{
rowValue: [
{ label: 'SPU', value: targetSpu },
{ label: '货号(非商品编码)', value: targetSku },
{ label: '期望日常限价', value: '499' },
],
},
{
rowValue: [
{ label: 'SPU', value: targetSpu },
{ label: '货号(非商品编码)', value: 'GBGJ-SZ024402' },
{ label: '期望日常限价', value: '619' },
],
},
]),
}),
],
})
expect(records.map((record) => record.businessId)).toEqual([
'202610081643000269370',
'202609281652000089380',
])
expect(records[0]).toMatchObject({
templateName: '新品限价流程',
reason: '新品首次定价',
price: '',
attachments: ['新品限价明细.xlsx'],
})
expect(records[1].price).toBe('499')
})
})

View File

@ -0,0 +1,354 @@
export type LimitPriceWorkflowRecord = {
processInstanceId: string
businessId: string
title: string
templateName: string
status: string
result: string
initiator: string
createdAt: string
finishedAt: string
applyType: string
reason: string
price: string
startDate: string
endDate: string
sourceTable: string
attachments: string[]
}
export type LimitPriceHistoryResult = {
barcode: string
sku: string
spu: string
sourceRecord: LimitPricePageSourceRecord | null
current: {
price: string
processNo: string
processInstanceId: string
applyType: string
initiator: string
approvedAt: string
} | null
records: LimitPriceWorkflowRecord[]
}
export type LimitPricePageSourceRecord = {
sourceTable: string
productBusinessKey: string
skuCode: string
skuName: string
barcode: string
limitPriceStatus: string
limitPriceApplicable: boolean
limitPriceConfirmed: boolean
expectedDailyLimitPrice: string
expectedLimitGrossMarginRate: string
nonSpuOwnerLimitPrice: string
limitConfirmedAt: string
limitSourceProductBusinessKey: string
limitSourceSkuBusinessKey: string
updatedAt: string
}
export type LimitPriceWorkflowInput = {
processInstanceId: string
businessId: string
title: string
status: string
result: string
originatorUserId: string
createAt: string
finishTime: string
updatedAt?: string
}
export type LimitPriceWorkflowFieldInput = {
processInstanceId: string
componentType: string
name: string
value: string
}
export type LimitPriceWorkflowSnapshot = {
flows: LimitPriceWorkflowInput[]
fields: LimitPriceWorkflowFieldInput[]
syncedThrough: string
}
export function mergeLimitPriceWorkflowSnapshots(input: {
existing: Pick<LimitPriceWorkflowSnapshot, 'flows' | 'fields'>
incoming: Pick<LimitPriceWorkflowSnapshot, 'flows' | 'fields'>
syncedThrough: string
}): LimitPriceWorkflowSnapshot {
const flowsByProcess = new Map(
input.existing.flows.map((flow) => [flow.processInstanceId, flow]),
)
for (const flow of input.incoming.flows) {
flowsByProcess.set(flow.processInstanceId, flow)
}
const refreshedProcessIds = new Set(
input.incoming.flows.map((flow) => flow.processInstanceId),
)
return {
flows: [...flowsByProcess.values()].sort((left, right) => (
new Date(right.createAt).getTime() - new Date(left.createAt).getTime()
|| right.businessId.localeCompare(left.businessId)
)),
fields: [
...input.existing.fields.filter(
(field) => !refreshedProcessIds.has(field.processInstanceId),
),
...input.incoming.fields,
],
syncedThrough: input.syncedThrough,
}
}
const TEMPLATE_NAMES = [
'新品限价及限价调整',
'新品限价流程',
'各中心特殊限价需求申请',
'GB特殊限价需求申请',
] as const
function text(value: unknown) {
return String(value ?? '').trim()
}
function flowTemplate(title: string) {
return TEMPLATE_NAMES.find((name) => title.includes(name)) ?? title
}
function flowInitiator(title: string) {
return title.match(/\+(.+?)提交的/)?.[1]?.trim() ?? ''
}
function statusLabel(value: string) {
return ({
COMPLETED: '已完成',
RUNNING: '进行中',
TERMINATED: '已终止',
CANCELED: '已取消',
DRAFT: '草稿',
} as Record<string, string>)[value] ?? value
}
function resultLabel(value: string) {
return ({ agree: '同意', refuse: '拒绝' } as Record<string, string>)[value] ?? value
}
function attachmentNames(value: string) {
if (!value) return []
try {
const parsed = JSON.parse(value) as unknown
if (Array.isArray(parsed)) {
return parsed.flatMap((item) => {
const name = text((item as { fileName?: unknown })?.fileName)
return name ? [name] : []
})
}
} catch {}
return []
}
function firstValue(values: Map<string, string>, labels: readonly string[]) {
for (const label of labels) {
const value = values.get(label)?.trim()
if (value) return value
}
return ''
}
function parseTableRows(value: string) {
try {
const parsed = JSON.parse(value) as unknown
if (!Array.isArray(parsed)) return []
return parsed.flatMap((row, index) => {
const cells = (row as { rowValue?: Array<Record<string, unknown>> })?.rowValue ?? []
const values = new Map<string, string>()
for (const cell of cells) {
const labels = Array.isArray(cell.label) ? cell.label : [cell.label]
labels.forEach((label, labelIndex) => {
const key = text(label)
if (!key) return
const raw = Array.isArray(cell.value) ? cell.value[labelIndex] : cell.value
values.set(key, text(raw))
})
}
return [{ values, rowNumber: index + 1 }]
})
} catch {
return []
}
}
function normalizedIdentifierTokens(value: string) {
return value
.trim()
.toLocaleUpperCase()
.split(/[\s,,;;|/]+/)
.filter(Boolean)
}
type WorkflowTableRow = {
values: Map<string, string>
rowNumber: number
}
type IdentifierDimension = 'barcode' | 'sku' | 'spu'
function identifierDimension(label: string): IdentifierDimension | null {
const normalized = label.trim()
if (/^SPU(?:编码)?$/i.test(normalized)) return 'spu'
if (/货号|SKU/i.test(normalized)) return 'sku'
if (/商品编码|条码|barcode/i.test(normalized)) return 'barcode'
return null
}
function tableRowsMatchingProduct(
rows: WorkflowTableRow[],
input: { barcode: string; sku: string; spu: string },
) {
const dimensions: Array<{
dimension: IdentifierDimension
targets: string[]
}> = [
{
dimension: 'sku',
targets: [input.sku],
},
{
dimension: 'barcode',
targets: [input.barcode, input.sku],
},
{
dimension: 'spu',
targets: [input.spu],
},
]
for (const candidate of dimensions) {
const targets = new Set(
candidate.targets
.flatMap(normalizedIdentifierTokens),
)
if (targets.size === 0) continue
const rowsWithDimension = rows.flatMap((row) => {
const values = [...row.values.entries()]
.filter(([label]) => identifierDimension(label) === candidate.dimension)
.flatMap(([, value]) => normalizedIdentifierTokens(value))
return values.length > 0 ? [{ row, values }] : []
})
if (rowsWithDimension.length === 0) continue
return rowsWithDimension
.filter(({ values }) => values.some((value) => targets.has(value)))
.map(({ row }) => row)
}
const identifiers = new Set(
[input.barcode, input.sku]
.flatMap(normalizedIdentifierTokens),
)
if (identifiers.size === 0) return []
return rows.filter((row) => (
[...row.values.entries()]
.filter(([label]) => !/SPU/i.test(label))
.flatMap(([, value]) => normalizedIdentifierTokens(value))
.some((value) => identifiers.has(value))
))
}
export function buildLimitPriceWorkflowRecords(input: {
barcode: string
sku: string
spu: string
currentProcessNo?: string
flows: readonly LimitPriceWorkflowInput[]
fields: readonly LimitPriceWorkflowFieldInput[]
}): LimitPriceWorkflowRecord[] {
const fieldsByFlow = new Map<string, LimitPriceWorkflowFieldInput[]>()
for (const field of input.fields) {
const list = fieldsByFlow.get(field.processInstanceId) ?? []
list.push(field)
fieldsByFlow.set(field.processInstanceId, list)
}
const records: LimitPriceWorkflowRecord[] = []
for (const flow of input.flows) {
const fields = fieldsByFlow.get(flow.processInstanceId) ?? []
const templateName = flowTemplate(flow.title)
const scalar = new Map(
fields
.filter((field) => field.componentType !== 'TableField')
.map((field) => [field.name, field.value] as const),
)
const attachments = fields.flatMap((field) => (
/附件/.test(field.name) ? attachmentNames(field.value) : []
))
const applyType = firstValue(scalar, ['申请类型'])
const reason = firstValue(scalar, ['调整理由', '修改原因', '原因', '备注'])
let matched = 0
for (const field of fields.filter((item) => item.componentType === 'TableField')) {
const tableRows = parseTableRows(field.value)
const matchingRows = tableRowsMatchingProduct(tableRows, input)
for (const row of matchingRows) {
matched += 1
records.push({
processInstanceId: flow.processInstanceId,
businessId: flow.businessId,
title: flow.title,
templateName,
status: statusLabel(flow.status),
result: resultLabel(flow.result),
initiator: flowInitiator(flow.title) || flow.originatorUserId,
createdAt: flow.createAt,
finishedAt: flow.finishTime,
applyType,
reason: firstValue(row.values, ['调整理由', '修改原因', '原因', '备注']) || reason,
price: firstValue(row.values, [
'调整后限价',
'期望日常限价',
'最低售价',
'期望限价价格',
'当前限价',
'报备价格(商家到手价)',
'期望活动限价',
]),
startDate: firstValue(row.values, ['开始时间', '活动开始时间']),
endDate: firstValue(row.values, ['结束时间', '活动结束时间']),
sourceTable: field.name,
attachments,
})
}
}
if (
matched === 0
&& (
templateName === '新品限价流程'
|| flow.businessId === input.currentProcessNo?.trim()
)
) {
records.push({
processInstanceId: flow.processInstanceId,
businessId: flow.businessId,
title: flow.title,
templateName,
status: statusLabel(flow.status),
result: resultLabel(flow.result),
initiator: flowInitiator(flow.title) || flow.originatorUserId,
createdAt: flow.createAt,
finishedAt: flow.finishTime,
applyType,
reason,
price: '',
startDate: '',
endDate: '',
sourceTable: '',
attachments,
})
}
}
return records.sort((left, right) => (
new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime()
|| right.businessId.localeCompare(left.businessId)
))
}

View File

@ -5,9 +5,8 @@ import {
} from './supply-chain-management-blank-pages'
describe('经营管理空白页注册表', () => {
it('提供三个空白子页面', () => {
it('提供两个空白子页面', () => {
expect(MANAGEMENT_BLANK_PAGES.map((page) => page.label)).toEqual([
'空白页 1',
'特殊备货&特殊入库流程监控',
'商品SABC打标',
])

View File

@ -5,11 +5,6 @@ export type ManagementBlankPageDefinition = {
}
export const MANAGEMENT_BLANK_PAGES: readonly ManagementBlankPageDefinition[] = [
{
key: 'blank-page-1',
label: '空白页 1',
route: '/supply-chain/management/blank-pages/blank-page-1',
},
{
key: 'blank-page-2',
label: '特殊备货&特殊入库流程监控',

View File

@ -0,0 +1,15 @@
export const MANUAL_LIMIT_APPLY_TYPE = '人工指定限价'
export type ManualLimitImportResult = {
batchId: string
fileName: string
targetPrice: number | null
rowCount: number
uniqueCodeCount: number
matchedBarcodeCount: number
matchedStyleCount: number
updatedLimitCount: number
unmatchedCodes: string[]
invalidRows: Array<{ rowNumber: number; code: string; message: string }>
conflictingStyles: Array<{ styleCode: string; prices: number[] }>
}

View File

@ -5,6 +5,7 @@ export function getSupplyChainPermissionTargetForPath(pathname: string): SupplyC
if (pathname === '/supply-chain/management/modular-product-processing-orders') return 'modularProductProcessingOrders' as const
if (pathname === '/supply-chain/management/owner-config') return 'ownerConfig' as const
if (pathname === '/supply-chain/management/custom-table') return 'limitManagement' as const
if (pathname === '/supply-chain/management/freight-maintenance') return 'limitManagement' as const
if (pathname === '/supply-chain/management/discontinuation') return 'discontinuationManagement' as const
if (pathname === '/supply-chain/management/front-warehouse-inventory') return 'frontWarehouseInventory' as const
if (pathname === '/supply-chain/management/front-warehouse-order') return 'frontWarehouseInventory' as const
@ -235,6 +236,12 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method:
action: method.toUpperCase() === 'GET' ? ('view' as const) : ('edit' as const),
}
}
if (pathname.startsWith('/api/supply-chain/limit-management/manual-limits')) {
return {
targetKey: 'limitManualOverride' as const,
action: method.toUpperCase() === 'GET' ? ('view' as const) : ('edit' as const),
}
}
// 限价管理:数据复用产品全量档案,接口使用独立的限价查看权限。
if (pathname.startsWith('/api/supply-chain/limit-management')) {
return { targetKey: 'limitManagement' as const, action: 'view' as const }

View File

@ -290,6 +290,15 @@ describe('supply chain permission settings', () => {
})
it('maps limit management data to the business management node', () => {
expect(
getSupplyChainPermissionTargetForPath('/supply-chain/management/freight-maintenance'),
).toBe('limitManagement')
expect(
getSupplyChainApiPermissionRequirement('/api/supply-chain/limit-management/manual-limits', 'GET'),
).toEqual({ targetKey: 'limitManualOverride', action: 'view' })
expect(
getSupplyChainApiPermissionRequirement('/api/supply-chain/limit-management/manual-limits', 'POST'),
).toEqual({ targetKey: 'limitManualOverride', action: 'edit' })
expect(
getSupplyChainApiPermissionRequirement('/api/supply-chain/limit-management/products', 'GET'),
).toEqual({ targetKey: 'limitManagement', action: 'view' })
@ -304,10 +313,10 @@ describe('supply chain permission settings', () => {
).toEqual({ targetKey: 'limitManagement', action: 'view' })
})
it('maps freight configuration queries to the dedicated management page permission', () => {
it('maps freight maintenance route to the limit management permission', () => {
expect(
getSupplyChainApiPermissionRequirement('/api/supply-chain/management/freight-config', 'GET'),
).toEqual({ targetKey: 'managementBlankPage1', action: 'view' })
getSupplyChainPermissionTargetForPath('/supply-chain/management/freight-maintenance'),
).toBe('limitManagement')
})
it('maps new product pages to their permission nodes', () => {

View File

@ -4,6 +4,7 @@ export type SupplyChainPermissionTargetKey =
| 'businessManagement'
| 'ownerConfig'
| 'limitManagement'
| 'limitManualOverride'
| 'discontinuationManagement'
| 'discontinuationPenalties'
| 'modularProductProcessingOrders'
@ -78,6 +79,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGETS: SupplyChainPermissionTarget[] = [
{ key: 'dashboard', label: '工作台', description: '供应链工作台总览' },
{ key: 'ownerConfig', label: '人员信息', description: '人员目录查看与导出' },
{ key: 'limitManagement', label: '限价管理', description: '限价查询与维护' },
{ key: 'limitManualOverride', label: '限价管理 · 人工限价导入', description: '通过 Excel 为指定商品编码设置人工限价' },
{ key: 'discontinuationManagement', label: '停产下架管理', description: '停产下架管理页面入口(默认全员可见)' },
{ key: 'businessManagement', label: '清货管理', description: '清货池、任务审核、月度评分与清货复盘入口' },
{ key: 'discontinuationPenalties', label: '停产下架 · 申诉审核', description: '审核未下架监控申诉(仅操作权限生效)' },
@ -150,6 +152,7 @@ export const SUPPLY_CHAIN_PERMISSION_EXTRA_TARGETS: Record<string, SupplyChainPe
'departmentDistributionConfig',
// 限价管理 · 规则配置(页面内的动作权限,只出现在权限配置里)
'breachRuleConfig',
'limitManualOverride',
'discontinuationPenalties',
'clearanceOperation',
'clearanceReview',

View File

@ -1,6 +1,54 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import sql from 'mssql'
import { prisma } from '@/lib/prisma'
import {
FREIGHT_CALCULATION_PROVINCES,
normalizeWarehouseName,
type FreightCourierOption,
type FreightCourierRuleLimit,
type FreightProductArchiveSnapshot,
type FreightRateRecord,
type ProvinceShipmentShareRow,
} from '@/lib/freight-calculation'
import type { FreightConfigRow, FreightConfigTab } from '@/lib/freight-config'
type ProvinceShipmentShareSnapshot = {
version: number
generatedAt: string
sourceFile: string
totalShipment: number
rowCount: number
rows: ProvinceShipmentShareRow[]
}
type SnapshotCourierRule = FreightCourierRuleLimit & {
expressName: string
}
type WarehouseExpressRuleSnapshot = {
version: number
generatedAt: string
warehouses: Array<{
warehouseName: string
expressNames: string[]
courierRules?: SnapshotCourierRule[]
}>
}
const PROVINCE_SHARE_PATH = path.join(
process.cwd(),
'data',
'freight-config',
'province-shipment-share.json',
)
const WAREHOUSE_EXPRESS_RULE_PATH = path.join(
process.cwd(),
'data',
'freight-config',
'warehouse-express-rules.json',
)
function requiredEnv(name: string) {
const value = process.env[name]?.trim()
if (!value) throw new Error(`Missing required environment variable: ${name}`)
@ -61,24 +109,48 @@ const SOURCES: Record<FreightConfigTab, {
export class FreightConfigRepository {
private pool: sql.ConnectionPool | null = null
private poolPromise: Promise<sql.ConnectionPool> | null = null
private rateCache = new Map<string, {
expiresAt: number
rows: FreightRateRecord[]
}>()
private warehouseCourierCache = new Map<string, {
expiresAt: number
fileMtimeMs: number
rows: FreightCourierOption[]
}>()
private async getPool() {
if (this.pool?.connected) return this.pool
this.pool = await new sql.ConnectionPool({
server: requiredEnv('JST_REPORT_DB_HOST'),
port: Number(process.env.JST_REPORT_DB_PORT?.trim() || '1433'),
database: requiredEnv('JST_REPORT_DB_NAME'),
user: requiredEnv('JST_REPORT_DB_USER'),
password: requiredEnv('JST_REPORT_DB_PASSWORD'),
options: {
encrypt: booleanEnv('JST_REPORT_DB_ENCRYPT', true),
trustServerCertificate: booleanEnv('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE', true),
},
connectionTimeout: 20_000,
requestTimeout: 180_000,
pool: { min: 0, max: 3, idleTimeoutMillis: 30_000 },
}).connect()
return this.pool
if (!this.poolPromise) {
this.poolPromise = new sql.ConnectionPool({
server: requiredEnv('JST_REPORT_DB_HOST'),
port: Number(process.env.JST_REPORT_DB_PORT?.trim() || '1433'),
database: requiredEnv('JST_REPORT_DB_NAME'),
user: requiredEnv('JST_REPORT_DB_USER'),
password: requiredEnv('JST_REPORT_DB_PASSWORD'),
options: {
encrypt: booleanEnv('JST_REPORT_DB_ENCRYPT', true),
trustServerCertificate: booleanEnv('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE', true),
},
connectionTimeout: 20_000,
requestTimeout: 180_000,
pool: { min: 1, max: 3, idleTimeoutMillis: 5 * 60_000 },
}).connect().then((pool) => {
this.pool = pool
return pool
}).finally(() => {
this.poolPromise = null
})
}
return this.poolPromise
}
async warmup() {
await Promise.allSettled([
this.getPool().then((pool) => pool.request().query('SELECT 1 AS ready')),
prisma.$queryRawUnsafe('SELECT 1 AS ready'),
])
}
async listPage(input: {
@ -121,10 +193,215 @@ export class FreightConfigRepository {
}
}
async findProductArchiveSnapshot(
barcode: string,
): Promise<FreightProductArchiveSnapshot | null> {
const normalizedBarcode = barcode.trim()
if (!normalizedBarcode) return null
const record = await prisma.supplyChainProductArchive.findFirst({
where: {
barcode: {
equals: normalizedBarcode,
mode: 'insensitive',
},
},
select: {
barcode: true,
productTag: true,
inOutWarehouse: true,
weight: true,
length: true,
width: true,
height: true,
volume: true,
},
})
if (!record) return null
return {
barcode: record.barcode,
productTag: record.productTag,
inOutWarehouse: record.inOutWarehouse,
weight: record.weight === null ? null : Number(record.weight),
length: record.length === null ? null : Number(record.length),
width: record.width === null ? null : Number(record.width),
height: record.height === null ? null : Number(record.height),
volume: record.volume === null ? null : Number(record.volume),
}
}
async findCouriersByWarehouse(input: {
warehouseName: string
}): Promise<FreightCourierOption[]> {
const warehouseName = normalizeWarehouseName(input.warehouseName)
if (!warehouseName) return []
const fileStat = await fs.stat(WAREHOUSE_EXPRESS_RULE_PATH).catch(() => null)
const cached = this.warehouseCourierCache.get(warehouseName)
if (
cached
&& fileStat
&& cached.fileMtimeMs === fileStat.mtimeMs
&& cached.expiresAt > Date.now()
) {
return cached.rows
}
let raw: string
try {
raw = await fs.readFile(WAREHOUSE_EXPRESS_RULE_PATH, 'utf8')
} catch {
throw new Error('物流匹配规则尚未同步,请先执行 npm run sync:jst-logistics-rules')
}
const snapshot = JSON.parse(raw) as WarehouseExpressRuleSnapshot
if (![1, 2, 3].includes(snapshot.version) || !Array.isArray(snapshot.warehouses)) {
throw new Error('物流匹配规则快照格式不正确')
}
const warehouse = snapshot.warehouses.find(
(item) => item.warehouseName === warehouseName,
)
if (snapshot.version >= 2 && warehouse && !Array.isArray(warehouse.courierRules)) {
throw new Error(`物流匹配规则快照缺少仓库“${warehouseName}”的快递明细`)
}
const rulesByExpressName = new Map<string, FreightCourierRuleLimit[]>()
for (const rule of warehouse?.courierRules ?? []) {
const expressName = normalizeWarehouseName(rule.expressName)
if (!expressName) continue
const rules = rulesByExpressName.get(expressName) ?? []
rules.push(rule)
rulesByExpressName.set(expressName, rules)
}
const rows = (warehouse?.expressNames ?? [])
.map((expressName) => ({
expressName: expressName.trim(),
rules: rulesByExpressName.get(normalizeWarehouseName(expressName)) ?? [],
}))
.filter((row) => row.expressName)
this.warehouseCourierCache.set(warehouseName, {
expiresAt: Date.now() + 10 * 60_000,
fileMtimeMs: fileStat?.mtimeMs ?? 0,
rows,
})
return rows
}
async findApplicableRates(input: {
expressNames: readonly string[]
}): Promise<FreightRateRecord[]> {
const expressNames = [...new Set(input.expressNames.map((value) => value.trim()).filter(Boolean))]
if (expressNames.length === 0) return []
const cacheKey = expressNames
.map((value) => normalizeWarehouseName(value))
.sort((left, right) => left.localeCompare(right, 'zh-CN'))
.join('\u0000')
const cached = this.rateCache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) return cached.rows
const schema = safeIdentifier(
process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt',
'JST_REPORT_DB_SCHEMA',
)
const provinces = FREIGHT_CALCULATION_PROVINCES
.map(({ province }) => `N'${province.replaceAll("'", "''")}'`)
.join(',')
const pool = await this.getPool()
const request = pool.request()
expressNames.forEach((expressName, index) => {
request.input(`expressName${index}`, sql.NVarChar(200), expressName)
})
const placeholders = expressNames.map((_, index) => `@expressName${index}`).join(',')
const result = await request.query<{
RuleId: string | number
ExpressName: string
Province: string
EffectiveStartTime: Date | string
EffectiveEndTime: Date | string
StartWeight: string | null
EndWeight: string | null
StartVolume: string | null
EndVolume: string | null
StartLength: string | null
EndLength: string | null
WaybillFee: string | null
DeductWeight: string | null
FeeRate: string | null
MinimumFee: string | null
RoundingRule: number | string | null
VolumeWeightDivisor: string | null
}>(`
SELECT
RuleId,
LTRIM(RTRIM(ExpressName)) AS ExpressName,
LTRIM(RTRIM(Province)) AS Province,
EffectiveStartTime,
EffectiveEndTime,
StartWeight,
EndWeight,
StartVolume,
EndVolume,
StartLength,
EndLength,
WaybillFee,
DeductWeight,
FeeRate,
MinimumFee,
RoundingRule,
VolumeWeightDivisor
FROM [${schema}].[fys_freightRate_view]
WHERE ExpressName IN (${placeholders})
AND LTRIM(RTRIM(Province)) IN (${provinces})
AND EffectiveStartTime <= GETDATE()
ORDER BY ExpressName, Province, EffectiveStartTime DESC, RuleId DESC
`)
const rows = result.recordset.map((row) => ({
ruleId: String(row.RuleId),
expressName: String(row.ExpressName ?? '').trim(),
province: String(row.Province ?? '').trim(),
effectiveStartTime: new Date(row.EffectiveStartTime).toISOString(),
effectiveEndTime: new Date(row.EffectiveEndTime).toISOString(),
startWeight: row.StartWeight === null ? null : Number(row.StartWeight),
endWeight: row.EndWeight === null ? null : Number(row.EndWeight),
startVolume: row.StartVolume === null ? null : Number(row.StartVolume),
endVolume: row.EndVolume === null ? null : Number(row.EndVolume),
startLength: row.StartLength === null ? null : Number(row.StartLength),
endLength: row.EndLength === null ? null : Number(row.EndLength),
waybillFee: row.WaybillFee === null ? null : Number(row.WaybillFee),
deductWeight: row.DeductWeight === null ? null : Number(row.DeductWeight),
feeRate: row.FeeRate === null ? null : Number(row.FeeRate),
minimumFee: row.MinimumFee === null ? null : Number(row.MinimumFee),
roundingRule: row.RoundingRule === null ? null : Number(row.RoundingRule),
volumeWeightDivisor: row.VolumeWeightDivisor === null
? null
: Number(row.VolumeWeightDivisor),
}))
if (this.rateCache.size >= 30) {
const oldestKey = this.rateCache.keys().next().value
if (oldestKey) this.rateCache.delete(oldestKey)
}
this.rateCache.set(cacheKey, {
expiresAt: Date.now() + 30_000,
rows,
})
return rows
}
async readProvinceShipmentShareSnapshot(): Promise<ProvinceShipmentShareSnapshot> {
let raw: string
try {
raw = await fs.readFile(PROVINCE_SHARE_PATH, 'utf8')
} catch {
throw new Error('各省发货占比数据尚未导入')
}
const snapshot = JSON.parse(raw) as ProvinceShipmentShareSnapshot
if (snapshot.version !== 1 || !Array.isArray(snapshot.rows)) {
throw new Error('各省发货占比数据格式不正确')
}
return snapshot
}
async close() {
if (!this.pool) return
await this.pool.close()
this.pool = null
this.poolPromise = null
this.rateCache.clear()
this.warehouseCourierCache.clear()
}
}

View File

@ -3,12 +3,37 @@ import type { ComboLimitAggregate } from '@/lib/supply-chain-combo-limit-price'
export type ComboLimitPricedProduct = {
barcode: string
sku?: string
spu?: string
productStatus: string
opsHead: string
departmentHead?: string
ownerLimitPrice: number
costPrice: number | null
}
export type ComboSourceDetailRow = {
creator: string
procode: string
quantity: number
productName: string
picture: string
retailPrice: number | null
model: string
color: string
categoryTwo: string
sourceCostPrice: number | null
}
export type ComboOwnerChangeAssignment = {
scope: 'SKU' | 'SPU'
code: string
owner: string
approvedAt: number
businessId: string
source: string
}
function requiredEnv(name: string) {
const value = process.env[name]?.trim()
if (!value) throw new Error(`Missing required environment variable: ${name}`)
@ -22,6 +47,10 @@ function safeIdentifier(value: string, label: string) {
class JstComboLimitSourceRepository {
private pool: sql.ConnectionPool | null = null
private ownerChangeCache: {
expiresAt: number
rows: ComboOwnerChangeAssignment[]
} | null = null
private async getPool() {
if (this.pool?.connected) return this.pool
@ -43,100 +72,276 @@ class JstComboLimitSourceRepository {
}
/**
* 只返回所有子项都能匹配到负责人限价的组合。
* 数量和负责人/非负责人限价在 SQL Server 内聚合,避免把数万条组合明细逐行传到应用层。
* 组合编码和子商品来自 op_ComboProCodeApplication / op_ComboProCodeDetail。
* 同一组合编码有多条申请时取最新一条,负责人直接取该申请的 creator。
* 只返回所有子项都能匹配负责人限价的组合。
*/
async listCompleteComboLimits(products: ComboLimitPricedProduct[]): Promise<ComboLimitAggregate[]> {
async listCompleteComboLimits(
products: ComboLimitPricedProduct[],
): Promise<Array<ComboLimitAggregate & { componentCodes: string[] }>> {
if (!products.length) return []
const schema = safeIdentifier(process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt', 'JST_REPORT_DB_SCHEMA')
const pool = await this.getPool()
const result = await pool.request()
.input('products', sql.NVarChar(sql.MAX), JSON.stringify(products))
.query<{
combineCode: string
opsHeadList: string | null
itemCount: number
costCount: number
ownerTotal: number
nonOwnerTotal: number
costTotal: number | null
}>(`
WITH prices AS (
const result = await pool.request().query<{
comboCode: string
creator: string | null
procode: string | null
num: number
}>(`
WITH rankedApplications AS (
SELECT
barcode,
opsHead,
ownerPrice,
costPrice
FROM OPENJSON(@products)
WITH (
barcode nvarchar(120) '$.barcode',
opsHead nvarchar(60) '$.opsHead',
ownerPrice decimal(18,4) '$.ownerLimitPrice',
costPrice decimal(18,4) '$.costPrice'
)
),
comboItemTotals AS (
SELECT combine_sku_id, COUNT(*) AS itemCount
FROM [${schema}].[jst_comboProductItem]
WHERE combine_sku_id IS NOT NULL
AND LTRIM(RTRIM(CAST(combine_sku_id AS nvarchar(200)))) <> ''
AND qty > 0
GROUP BY combine_sku_id
),
comboPrices AS (
SELECT
i.combine_sku_id,
COUNT(*) AS matchedCount,
COUNT(p.costPrice) AS costCount,
STRING_AGG(
CASE WHEN LTRIM(RTRIM(p.opsHead)) <> '' THEN p.opsHead END,
N'、'
) AS opsHeadList,
SUM(p.ownerPrice * i.qty) AS ownerTotal,
SUM((
p.ownerPrice
+ CASE WHEN p.ownerPrice * 0.05 > 10 THEN p.ownerPrice * 0.05 ELSE 10 END
) * i.qty) AS nonOwnerTotal,
SUM(p.costPrice * i.qty) AS costTotal
FROM [${schema}].[jst_comboProductItem] i
JOIN prices p ON p.barcode = CAST(i.src_sku_id AS nvarchar(120))
WHERE i.combine_sku_id IS NOT NULL
AND LTRIM(RTRIM(CAST(i.combine_sku_id AS nvarchar(200)))) <> ''
AND i.qty > 0
GROUP BY i.combine_sku_id
guid,
LTRIM(RTRIM(comboSkuCode)) AS comboCode,
LTRIM(RTRIM(creator)) AS creator,
createTime,
ROW_NUMBER() OVER (
PARTITION BY LTRIM(RTRIM(comboSkuCode))
ORDER BY createTime DESC, Id DESC
) AS rowNumber
FROM [${schema}].[op_ComboProCodeApplication]
WHERE ISNULL(isDel, 0) = 0
AND NULLIF(LTRIM(RTRIM(comboSkuCode)), N'') IS NOT NULL
)
SELECT
CAST(cp.combine_sku_id AS nvarchar(200)) AS combineCode,
CAST(cp.opsHeadList AS nvarchar(1000)) AS opsHeadList,
CAST(t.itemCount AS int) AS itemCount,
CAST(cp.costCount AS int) AS costCount,
CAST(cp.ownerTotal AS decimal(28,4)) AS ownerTotal,
CAST(cp.nonOwnerTotal AS decimal(28,4)) AS nonOwnerTotal,
CAST(cp.costTotal AS decimal(28,4)) AS costTotal
FROM comboPrices cp
JOIN comboItemTotals t ON t.combine_sku_id = cp.combine_sku_id
WHERE cp.matchedCount = t.itemCount
a.comboCode,
a.creator,
LTRIM(RTRIM(d.procode)) AS procode,
d.num
FROM rankedApplications a
INNER JOIN [${schema}].[op_ComboProCodeDetail] d
ON d.hid = a.guid
AND ISNULL(d.isDel, 0) = 0
WHERE a.rowNumber = 1
AND ISNULL(d.num, 0) > 0
`)
const priceByBarcode = new Map<string, ComboLimitPricedProduct>()
const priceBySku = new Map<string, ComboLimitPricedProduct>()
for (const product of [...products].sort((left, right) => left.barcode.localeCompare(right.barcode))) {
const barcode = product.barcode.trim().toLocaleUpperCase()
const sku = String(product.sku ?? '').trim().toLocaleUpperCase()
if (barcode) priceByBarcode.set(barcode, product)
if (sku && !priceBySku.has(sku)) priceBySku.set(sku, product)
}
type ComboAccumulator = {
creator: string
itemCount: number
unmatchedCount: number
costCount: number
ownerTotal: number
nonOwnerTotal: number
costTotal: number
componentCodes: Set<string>
}
const combos = new Map<string, ComboAccumulator>()
for (const row of result.recordset) {
const comboCode = String(row.comboCode ?? '').trim()
if (!comboCode) continue
const procode = String(row.procode ?? '').trim().toLocaleUpperCase()
const product = priceByBarcode.get(procode) ?? priceBySku.get(procode)
const num = Math.max(0, Number(row.num) || 0)
if (!num) continue
const combo = combos.get(comboCode) ?? {
creator: String(row.creator ?? '').trim(),
itemCount: 0,
unmatchedCount: 0,
costCount: 0,
ownerTotal: 0,
nonOwnerTotal: 0,
costTotal: 0,
componentCodes: new Set<string>(),
}
combo.itemCount += 1
if (procode) combo.componentCodes.add(procode)
if (!product) {
combo.unmatchedCount += 1
} else {
combo.ownerTotal += product.ownerLimitPrice * num
combo.nonOwnerTotal += (
product.ownerLimitPrice
+ (product.ownerLimitPrice * 0.05 > 10 ? product.ownerLimitPrice * 0.05 : 10)
) * num
if (product.costPrice !== null) {
combo.costCount += 1
combo.costTotal += product.costPrice * num
}
}
combos.set(comboCode, combo)
}
return [...combos.entries()]
.filter(([, combo]) => combo.itemCount > 0 && combo.unmatchedCount === 0)
.map(([combineCode, combo]) => ({
combineCode,
opsHead: combo.creator,
itemCount: combo.itemCount,
costCount: combo.costCount,
ownerTotal: combo.ownerTotal,
nonOwnerTotal: combo.nonOwnerTotal,
costTotal: combo.costCount === combo.itemCount ? combo.costTotal : null,
componentCodes: [...combo.componentCodes],
}))
}
async getComboDetails(comboCode: string): Promise<Array<ComboSourceDetailRow & { comboCode: string }>> {
const normalizedComboCode = comboCode.trim()
if (!normalizedComboCode) return []
const schema = safeIdentifier(process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt', 'JST_REPORT_DB_SCHEMA')
const pool = await this.getPool()
const result = await pool.request()
.input('comboCode', sql.NVarChar(200), normalizedComboCode)
.query<{
comboCode: string
creator: string | null
procode: string | null
quantity: number
productName: string | null
picture: string | null
retailPrice: number | string | null
model: string | null
color: string | null
categoryTwo: string | null
sourceCostPrice: number | string | null
}>(`
WITH latestApplication AS (
SELECT TOP 1
guid,
LTRIM(RTRIM(comboSkuCode)) AS comboCode,
LTRIM(RTRIM(creator)) AS creator
FROM [${schema}].[op_ComboProCodeApplication]
WHERE ISNULL(isDel, 0) = 0
AND LTRIM(RTRIM(comboSkuCode)) = @comboCode
ORDER BY createTime DESC, Id DESC
)
SELECT
a.comboCode,
a.creator,
LTRIM(RTRIM(d.procode)) AS procode,
d.num AS quantity,
d.skuname AS productName,
d.picture,
d.retailPrice,
d.model,
d.color,
d.categoryTwo,
d.costPrice AS sourceCostPrice
FROM latestApplication a
INNER JOIN [${schema}].[op_ComboProCodeDetail] d
ON d.hid = a.guid
AND ISNULL(d.isDel, 0) = 0
WHERE ISNULL(d.num, 0) > 0
ORDER BY d.Id
`)
return result.recordset.map((row) => ({
combineCode: String(row.combineCode ?? '').trim(),
opsHead: [...new Set(
String(row.opsHeadList ?? '')
.split('、')
.map((value) => value.trim())
.filter(Boolean),
)].join('、'),
itemCount: Number(row.itemCount),
costCount: Number(row.costCount),
ownerTotal: Number(row.ownerTotal),
nonOwnerTotal: Number(row.nonOwnerTotal),
costTotal: row.costTotal === null ? null : Number(row.costTotal),
})).filter((row) => row.combineCode)
comboCode: String(row.comboCode ?? '').trim(),
creator: String(row.creator ?? '').trim(),
procode: String(row.procode ?? '').trim(),
quantity: Number(row.quantity ?? 0),
productName: String(row.productName ?? '').trim(),
picture: String(row.picture ?? '').trim(),
retailPrice: row.retailPrice === null ? null : Number(row.retailPrice),
model: String(row.model ?? '').trim(),
color: String(row.color ?? '').trim(),
categoryTwo: String(row.categoryTwo ?? '').trim(),
sourceCostPrice: row.sourceCostPrice === null ? null : Number(row.sourceCostPrice),
}))
}
async listOwnerChangeAssignments(): Promise<ComboOwnerChangeAssignment[]> {
if (this.ownerChangeCache && this.ownerChangeCache.expiresAt > Date.now()) {
return this.ownerChangeCache.rows
}
const schema = safeIdentifier(process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt', 'JST_REPORT_DB_SCHEMA')
const pool = await this.getPool()
const result = await pool.request().query<{
businessId: string
title: string
createAt: Date | string
fieldName: string
value: string
}>(`
SELECT
w.businessId,
w.title,
w.createAt,
s.name AS fieldName,
CAST(s.value AS nvarchar(max)) AS value
FROM [${schema}].[ding_Workflow] w
INNER JOIN [${schema}].[ding_WorkflowScheme] s
ON s.processInstanceId = w.processInstanceId
WHERE w.status = 'COMPLETED'
AND w.result = 'agree'
AND s.componentType = 'TableField'
AND (
w.title LIKE N'%SKU负责人销售计划申请和调整%'
OR w.title LIKE N'%调整SPU负责人流程%'
)
ORDER BY w.createAt, w.businessId, s.id
`)
const latest = new Map<string, ComboOwnerChangeAssignment>()
const assign = (assignment: ComboOwnerChangeAssignment) => {
if (!assignment.code || !assignment.owner) return
const key = `${assignment.scope}:${assignment.code.toLocaleUpperCase()}`
const current = latest.get(key)
if (!current || assignment.approvedAt >= current.approvedAt) latest.set(key, assignment)
}
for (const row of result.recordset) {
const title = String(row.title ?? '')
let table: unknown
try {
table = JSON.parse(String(row.value ?? ''))
} catch {
continue
}
if (!Array.isArray(table)) continue
const approvedAt = new Date(row.createAt).getTime()
for (const tableRow of table) {
const cells = (tableRow as { rowValue?: Array<Record<string, unknown>> })?.rowValue ?? []
const record = new Map<string, string>()
for (const cell of cells) {
const labels = Array.isArray(cell.label) ? cell.label : [cell.label]
labels.forEach((label, index) => {
const key = String(label ?? '').trim()
if (!key) return
const raw = Array.isArray(cell.value) ? cell.value[index] : cell.value
record.set(key, String(raw ?? '').trim())
})
}
if (title.includes('SKU负责人销售计划申请和调整')) {
assign({
scope: 'SKU',
code: record.get('SKU') ?? '',
owner: record.get('修改后SKU负责人') ?? '',
approvedAt: Number.isFinite(approvedAt) ? approvedAt : 0,
businessId: String(row.businessId ?? ''),
source: 'SKU负责人销售计划申请和调整',
})
}
if (title.includes('调整SPU负责人流程') || title.includes('SKU负责人销售计划申请和调整')) {
assign({
scope: 'SPU',
code: record.get('SPU') ?? '',
owner: record.get('修改后SPU负责人') ?? '',
approvedAt: Number.isFinite(approvedAt) ? approvedAt : 0,
businessId: String(row.businessId ?? ''),
source: title.includes('调整SPU负责人流程')
? '调整SPU负责人流程'
: 'SKU负责人销售计划申请和调整',
})
}
}
}
const rows = [...latest.values()]
this.ownerChangeCache = {
expiresAt: Date.now() + 5 * 60_000,
rows,
}
return rows
}
async close() {
if (!this.pool) return
await this.pool.close()
this.pool = null
this.ownerChangeCache = null
}
}

View File

@ -0,0 +1,113 @@
import { randomUUID } from 'node:crypto'
import { Prisma } from '@prisma/client'
import type { LimitPriceWorkflowSnapshot } from '@/lib/supply-chain-limit-price-history'
import { prisma } from '@/lib/prisma'
export type StoredLimitPriceHistorySnapshot = LimitPriceWorkflowSnapshot & {
lastSyncAttemptAt: Date
}
type SnapshotKey = {
barcode: string
sku: string
spu: string
}
type SnapshotRow = {
flows: unknown
fields: unknown
syncedThrough: string
lastSyncAttemptAt: Date | string
}
function jsonArray<T>(value: unknown): T[] {
const parsed = typeof value === 'string'
? JSON.parse(value) as unknown
: value
return Array.isArray(parsed) ? parsed as T[] : []
}
class SupplyChainLimitPriceHistorySnapshotRepository {
async findByProduct(input: SnapshotKey): Promise<StoredLimitPriceHistorySnapshot | null> {
const rows = await prisma.$queryRaw<SnapshotRow[]>(Prisma.sql`
SELECT
"flows",
"fields",
"syncedThrough",
"lastSyncAttemptAt"
FROM "SupplyChainLimitPriceHistorySnapshot"
WHERE "barcode" = ${input.barcode}
AND "sku" = ${input.sku}
AND "spu" = ${input.spu}
LIMIT 1
`)
const row = rows[0]
if (!row) return null
return {
flows: jsonArray<LimitPriceWorkflowSnapshot['flows'][number]>(row.flows),
fields: jsonArray<LimitPriceWorkflowSnapshot['fields'][number]>(row.fields),
syncedThrough: row.syncedThrough,
lastSyncAttemptAt: new Date(row.lastSyncAttemptAt),
}
}
async markSyncAttempt(input: SnapshotKey) {
await prisma.$executeRaw(Prisma.sql`
UPDATE "SupplyChainLimitPriceHistorySnapshot"
SET
"lastSyncAttemptAt" = CURRENT_TIMESTAMP,
"updatedAt" = CURRENT_TIMESTAMP
WHERE "barcode" = ${input.barcode}
AND "sku" = ${input.sku}
AND "spu" = ${input.spu}
`)
}
async save(
input: SnapshotKey,
snapshot: LimitPriceWorkflowSnapshot,
) {
const key = {
barcode: input.barcode,
sku: input.sku,
spu: input.spu,
}
const flows = JSON.stringify(snapshot.flows)
const fields = JSON.stringify(snapshot.fields)
await prisma.$executeRaw(Prisma.sql`
INSERT INTO "SupplyChainLimitPriceHistorySnapshot" (
"id",
"barcode",
"sku",
"spu",
"flows",
"fields",
"syncedThrough",
"lastSyncAttemptAt",
"createdAt",
"updatedAt"
)
VALUES (
${randomUUID()},
${key.barcode},
${key.sku},
${key.spu},
CAST(${flows} AS jsonb),
CAST(${fields} AS jsonb),
${snapshot.syncedThrough},
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
)
ON CONFLICT ("barcode", "sku", "spu") DO UPDATE SET
"flows" = EXCLUDED."flows",
"fields" = EXCLUDED."fields",
"syncedThrough" = EXCLUDED."syncedThrough",
"lastSyncAttemptAt" = CURRENT_TIMESTAMP,
"updatedAt" = CURRENT_TIMESTAMP
`)
}
}
export const supplyChainLimitPriceHistorySnapshotRepository =
new SupplyChainLimitPriceHistorySnapshotRepository()

View File

@ -0,0 +1,173 @@
import sql from 'mssql'
import type {
LimitPriceWorkflowFieldInput,
LimitPriceWorkflowInput,
LimitPriceWorkflowSnapshot,
} from '@/lib/supply-chain-limit-price-history'
const DEFAULT_INITIAL_SOURCE_START = '2026-01-01T00:00:00'
function requiredEnv(name: string) {
const value = process.env[name]?.trim()
if (!value) throw new Error(`Missing required environment variable: ${name}`)
return value
}
function initialSourceStart() {
const value = process.env.LIMIT_PRICE_HISTORY_SOURCE_START?.trim()
|| DEFAULT_INITIAL_SOURCE_START
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(value)) {
throw new Error('LIMIT_PRICE_HISTORY_SOURCE_START 必须是 YYYY-MM-DDTHH:mm:ss 格式')
}
return value
}
function safeIdentifier(value: string) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
throw new Error('JST_REPORT_DB_SCHEMA is not a valid SQL Server identifier')
}
return value
}
class SupplyChainLimitPriceHistoryRepository {
private pool: sql.ConnectionPool | null = null
private cache = new Map<string, {
expiresAt: number
snapshot: LimitPriceWorkflowSnapshot
}>()
private async getPool() {
if (this.pool?.connected) return this.pool
this.pool = await new sql.ConnectionPool({
server: requiredEnv('JST_REPORT_DB_HOST'),
port: Number(process.env.JST_REPORT_DB_PORT?.trim() || '1433'),
database: requiredEnv('JST_REPORT_DB_NAME'),
user: requiredEnv('JST_REPORT_DB_USER'),
password: requiredEnv('JST_REPORT_DB_PASSWORD'),
options: {
encrypt: (process.env.JST_REPORT_DB_ENCRYPT?.trim() || 'true') !== 'false',
trustServerCertificate: (process.env.JST_REPORT_DB_TRUST_SERVER_CERTIFICATE?.trim() || 'true') !== 'false',
},
pool: { min: 0, max: 3, idleTimeoutMillis: 30_000 },
requestTimeout: 120_000,
connectionTimeout: 20_000,
}).connect()
return this.pool
}
async findByProduct(input: {
barcode: string
sku: string
spu: string
currentProcessNo: string
since?: string | null
}): Promise<LimitPriceWorkflowSnapshot> {
const cacheKey = JSON.stringify(input)
const cached = this.cache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) return cached.snapshot
const schema = safeIdentifier(process.env.JST_REPORT_DB_SCHEMA?.trim() || 'rpt')
const pool = await this.getPool()
const sourceNow = (await pool.request().query<{ sourceNow: string }>(`
SELECT CONVERT(varchar(33), SYSDATETIME(), 126) AS sourceNow
`)).recordset[0]?.sourceNow
if (!sourceNow) throw new Error('无法读取限价流程报表库时间')
const request = pool.request()
const matchConditions: string[] = []
const currentProcessNo = input.currentProcessNo.trim()
if (currentProcessNo) {
request.input('currentProcessNo', sql.NVarChar(200), currentProcessNo)
matchConditions.push('w.businessId = @currentProcessNo')
}
const productIdentifiers: Array<[string, string]> = []
if (input.sku.trim()) {
productIdentifiers.push(['sku', input.sku])
} else if (input.barcode.trim()) {
productIdentifiers.push(['barcode', input.barcode])
} else if (input.spu.trim()) {
productIdentifiers.push(['spu', input.spu])
}
const identifierConditions: string[] = []
for (const [name, rawValue] of productIdentifiers) {
const value = rawValue.trim()
if (!value) continue
request.input(name, sql.NVarChar(220), `%${value}%`)
identifierConditions.push(`matched.value LIKE @${name}`)
}
if (identifierConditions.length > 0) {
matchConditions.push(`EXISTS (
SELECT 1
FROM [${schema}].[ding_WorkflowScheme] matched
WHERE matched.processInstanceId = w.processInstanceId
AND (${identifierConditions.join(' OR ')})
)`)
}
if (matchConditions.length === 0) {
const snapshot = { flows: [], fields: [], syncedThrough: sourceNow }
this.cache.set(cacheKey, { expiresAt: Date.now() + 5 * 60_000, snapshot })
return snapshot
}
const since = input.since ?? null
const lowerBound = since ?? initialSourceStart()
request.input('lowerBound', sql.NVarChar(33), lowerBound)
const flows = (await request.query<LimitPriceWorkflowInput>(`
SELECT
w.processInstanceId,
w.businessId,
w.title,
w.status,
w.result,
CONVERT(varchar(80), w.originatorUserId) AS originatorUserId,
CONVERT(varchar(19), w.createAt, 120) AS createAt,
CONVERT(varchar(19), w.finishTime, 120) AS finishTime,
CONVERT(varchar(33), ISNULL(w.updateAt, w.createAt), 126) AS updatedAt
FROM [${schema}].[ding_Workflow] w
WHERE (
w.title LIKE N'%新品限价及限价调整%'
OR w.title LIKE N'%新品限价流程%'
OR w.title LIKE N'%各中心特殊限价需求申请%'
OR w.title LIKE N'%GB特殊限价需求申请%'
)
AND (${matchConditions.join(' OR ')})
AND ISNULL(w.updateAt, w.createAt) ${since ? '>' : '>='} CONVERT(datetime2, @lowerBound)
ORDER BY w.createAt DESC
`)).recordset
if (flows.length === 0) {
const snapshot = { flows: [], fields: [], syncedThrough: sourceNow }
this.cache.set(cacheKey, { expiresAt: Date.now() + 5 * 60_000, snapshot })
return snapshot
}
const fieldRequest = pool.request()
const placeholders = flows.map((flow, index) => {
const name = `flow${index}`
fieldRequest.input(name, sql.NVarChar(120), flow.processInstanceId)
return `@${name}`
})
const fields = (await fieldRequest.query<LimitPriceWorkflowFieldInput>(`
SELECT
processInstanceId,
componentType,
name,
CAST(value AS nvarchar(max)) AS value
FROM [${schema}].[ding_WorkflowScheme]
WHERE processInstanceId IN (${placeholders.join(',')})
ORDER BY processInstanceId, id
`)).recordset
const snapshot = { flows, fields, syncedThrough: sourceNow }
if (this.cache.size >= 100) {
const oldest = this.cache.keys().next().value
if (oldest) this.cache.delete(oldest)
}
this.cache.set(cacheKey, { expiresAt: Date.now() + 5 * 60_000, snapshot })
return snapshot
}
async close() {
if (!this.pool) return
await this.pool.close()
this.pool = null
this.cache.clear()
}
}
export const supplyChainLimitPriceHistoryRepository =
new SupplyChainLimitPriceHistoryRepository()

View File

@ -0,0 +1,127 @@
import pg from 'pg'
import type { LimitPricePageSourceRecord } from '@/lib/supply-chain-limit-price-history'
type SourceRow = {
product_business_key: string
sku_code: string
sku_name: string
barcode: string
limit_price_status: string
limit_price_applicable: boolean
limit_price_confirmed: boolean
expected_daily_limit_price: string
expected_limit_gross_margin_rate: string
non_spu_owner_limit_price: string
limit_confirmed_at: Date | string | null
limit_source_product_business_key: string
limit_source_sku_business_key: string
updated_at: Date | string | null
}
function isoDate(value: Date | string | null) {
if (!value) return ''
const date = value instanceof Date ? value : new Date(value)
return Number.isNaN(date.getTime()) ? '' : date.toISOString()
}
class SupplyChainLimitPricePageSourceRepository {
private pool: pg.Pool | null = null
private cache = new Map<string, {
expiresAt: number
record: LimitPricePageSourceRecord | null
}>()
private getPool() {
const host = process.env.PROD_ARCHIVE_DB_HOST?.trim()
if (!host) return null
if (this.pool) return this.pool
this.pool = new pg.Pool({
host,
port: Number(process.env.PROD_ARCHIVE_DB_PORT?.trim() || '5432'),
database: process.env.PROD_ARCHIVE_DB_NAME?.trim(),
user: process.env.PROD_ARCHIVE_DB_USER?.trim(),
password: process.env.PROD_ARCHIVE_DB_PASSWORD,
ssl: process.env.PROD_ARCHIVE_DB_SSL?.trim() === 'false'
? false
: { rejectUnauthorized: false },
max: 2,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 15_000,
})
return this.pool
}
async findByProduct(input: {
sku: string
barcode: string
}): Promise<LimitPricePageSourceRecord | null> {
const sku = input.sku.trim()
const barcode = input.barcode.trim()
if (!sku && !barcode) return null
const cacheKey = `${sku}\u0000${barcode}`
const cached = this.cache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) return cached.record
const pool = this.getPool()
if (!pool) return null
const result = await pool.query<SourceRow>(`
SELECT
btrim("product_business_key") AS product_business_key,
btrim("sku_code") AS sku_code,
btrim("sku_name") AS sku_name,
btrim("barcode") AS barcode,
btrim("limit_price_status") AS limit_price_status,
"limit_price_applicable",
"limit_price_confirmed",
btrim("expected_daily_limit_price") AS expected_daily_limit_price,
btrim("expected_limit_gross_margin_rate") AS expected_limit_gross_margin_rate,
btrim("non_spu_owner_limit_price") AS non_spu_owner_limit_price,
"limit_confirmed_at",
btrim("limit_source_product_business_key") AS limit_source_product_business_key,
btrim("limit_source_sku_business_key") AS limit_source_sku_business_key,
"updated_at"
FROM external.product_catalog_wide_v1
WHERE btrim("sku_code") = $1
OR ($2 <> '' AND btrim("barcode") = $2)
ORDER BY
CASE WHEN btrim("sku_code") = $1 THEN 0 ELSE 1 END,
"limit_confirmed_at" DESC NULLS LAST
LIMIT 1
`, [sku, barcode])
const row = result.rows[0]
const record = row
? {
sourceTable: 'external.product_catalog_wide_v1',
productBusinessKey: row.product_business_key ?? '',
skuCode: row.sku_code ?? '',
skuName: row.sku_name ?? '',
barcode: row.barcode ?? '',
limitPriceStatus: row.limit_price_status ?? '',
limitPriceApplicable: row.limit_price_applicable,
limitPriceConfirmed: row.limit_price_confirmed,
expectedDailyLimitPrice: row.expected_daily_limit_price ?? '',
expectedLimitGrossMarginRate: row.expected_limit_gross_margin_rate ?? '',
nonSpuOwnerLimitPrice: row.non_spu_owner_limit_price ?? '',
limitConfirmedAt: isoDate(row.limit_confirmed_at),
limitSourceProductBusinessKey: row.limit_source_product_business_key ?? '',
limitSourceSkuBusinessKey: row.limit_source_sku_business_key ?? '',
updatedAt: isoDate(row.updated_at),
}
: null
if (this.cache.size >= 100) {
const oldest = this.cache.keys().next().value
if (oldest) this.cache.delete(oldest)
}
this.cache.set(cacheKey, { expiresAt: Date.now() + 5 * 60_000, record })
return record
}
async close() {
if (!this.pool) return
await this.pool.end()
this.pool = null
this.cache.clear()
}
}
export const supplyChainLimitPricePageSourceRepository =
new SupplyChainLimitPricePageSourceRepository()

View File

@ -18,6 +18,8 @@ function aggregate(combineCode: string, ownerTotal: number) {
}
}
const emptyOwnerDirectory = async () => new Map()
describe('SupplyChainComboLimitService', () => {
it('caches the aggregated combo rows and supports an explicit refresh', async () => {
const repository = {
@ -30,7 +32,7 @@ describe('SupplyChainComboLimitService', () => {
{ barcode: 'B', productStatus: '销售', opsHead: '运营乙', ownerLimitPrice: 19, costPrice: 10 },
])
let now = 1_000
const service = new SupplyChainComboLimitService(repository, loader, () => now)
const service = new SupplyChainComboLimitService(repository, loader, () => now, emptyOwnerDirectory)
const first = await service.listPage({ page: 1, pageSize: 50 })
now += 1_000
@ -58,6 +60,7 @@ describe('SupplyChainComboLimitService', () => {
repository,
jest.fn().mockResolvedValue([{ barcode: 'A', productStatus: '销售', opsHead: '运营甲', ownerLimitPrice: 50, costPrice: 10 }]),
() => 1_000,
emptyOwnerDirectory,
)
const result = await service.listOptions({
@ -85,6 +88,7 @@ describe('SupplyChainComboLimitService', () => {
{ barcode: 'A', productStatus: '销售', opsHead: '运营甲', ownerLimitPrice: 50, costPrice: 10 },
]),
() => 1_000,
emptyOwnerDirectory,
)
const rows = await service.listAll({
@ -104,7 +108,7 @@ describe('SupplyChainComboLimitService', () => {
{ barcode: 'STOPPED', productStatus: '停产', opsHead: '运营乙', ownerLimitPrice: 19, costPrice: 10 },
{ barcode: 'DISCONTINUED', productStatus: '退市', opsHead: '运营丙', ownerLimitPrice: 20, costPrice: 10 },
])
const service = new SupplyChainComboLimitService(repository, loader, () => 1_000)
const service = new SupplyChainComboLimitService(repository, loader, () => 1_000, emptyOwnerDirectory)
await service.listPage({ page: 1, pageSize: 50 })
@ -112,4 +116,127 @@ describe('SupplyChainComboLimitService', () => {
{ barcode: 'ACTIVE', productStatus: '销售', opsHead: '运营甲', ownerLimitPrice: 50, costPrice: 10 },
])
})
it('优先使用负责人变更流程,creator为空时回退子商品负责人并处理离职接管', async () => {
const repository = {
listCompleteComboLimits: jest.fn().mockResolvedValue([{
...aggregate('COMBO-FALLBACK', 69),
opsHead: '',
componentCodes: ['A', 'SKU-B'],
}]),
listOwnerChangeAssignments: jest.fn().mockResolvedValue([
{
scope: 'SKU',
code: 'A',
owner: '离职负责人',
approvedAt: 100,
businessId: 'SKU-FLOW',
source: 'SKU负责人销售计划申请和调整',
},
{
scope: 'SPU',
code: 'SPU-B',
owner: '变更后负责人',
approvedAt: 200,
businessId: 'SPU-FLOW',
source: '调整SPU负责人流程',
},
]),
}
const directory = async () => new Map([
['离职负责人', {
name: '离职负责人',
employmentStatus: '离职' as const,
departmentOwner: '部门主管',
generalOwner: '部门经理',
}],
['变更后负责人', {
name: '变更后负责人',
employmentStatus: '在职' as const,
departmentOwner: '',
generalOwner: '',
}],
])
const service = new SupplyChainComboLimitService(
repository,
jest.fn().mockResolvedValue([
{ barcode: 'A', sku: 'SKU-A', spu: 'SPU-A', productStatus: '销售', opsHead: '原负责人A', ownerLimitPrice: 50, costPrice: 10 },
{ barcode: 'B', sku: 'SKU-B', spu: 'SPU-B', productStatus: '销售', opsHead: '原负责人B', ownerLimitPrice: 19, costPrice: 8 },
]),
() => 1_000,
directory,
)
const page = await service.listPage({ page: 1, pageSize: 50 })
expect(page.rows[0].opsHead).toBe('部门主管、变更后负责人')
})
it('loads combination component details with separate costs and prices', async () => {
const repository = {
listCompleteComboLimits: jest.fn(),
getComboDetails: jest.fn().mockResolvedValue([
{
comboCode: 'COMBO-AB',
creator: '组合创建人',
procode: 'A',
quantity: 1,
productName: '商品 A',
picture: '',
retailPrice: 100,
model: 'A-MODEL',
color: '白色',
categoryTwo: '桌类',
sourceCostPrice: 10,
},
{
comboCode: 'COMBO-AB',
creator: '组合创建人',
procode: 'SKU-B',
quantity: 2,
productName: '商品 B',
picture: '',
retailPrice: 50,
model: 'B-MODEL',
color: '黑色',
categoryTwo: '椅类',
sourceCostPrice: 8,
},
]),
}
const service = new SupplyChainComboLimitService(
repository,
jest.fn().mockResolvedValue([
{ barcode: 'A', sku: 'SKU-A', productStatus: '销售', opsHead: '运营甲', departmentHead: '部门负责人甲', ownerLimitPrice: 50, costPrice: 10 },
{ barcode: 'B', sku: 'SKU-B', productStatus: '销售', opsHead: '运营乙', departmentHead: '部门负责人乙', ownerLimitPrice: 19, costPrice: 8 },
]),
() => 1_000,
emptyOwnerDirectory,
)
const details = await service.getDetails('COMBO-AB')
expect(details.creator).toBe('组合创建人')
expect(details.rows).toHaveLength(2)
expect(details.rows[0]).toMatchObject({
barcode: 'A',
quantity: 1,
costPrice: 10,
ownerLimitPrice: 50,
owner: '运营甲',
departmentHead: '部门负责人甲',
matchedBy: 'BARCODE',
})
expect(details.rows[1]).toMatchObject({
barcode: 'B',
sku: 'SKU-B',
quantity: 2,
costPrice: 8,
ownerLimitPrice: 19,
owner: '运营乙',
departmentHead: '部门负责人乙',
ownerLimitSubtotal: 38,
matchedBy: 'SKU',
})
})
})

View File

@ -0,0 +1,196 @@
import { prisma } from '@/lib/prisma'
import { supplyChainLimitPricePageSourceRepository } from '@/server/repositories/supply-chain-limit-price-page-source.repository'
import { supplyChainLimitPriceHistoryRepository } from '@/server/repositories/supply-chain-limit-price-history.repository'
import { supplyChainLimitPriceHistorySnapshotRepository } from '@/server/repositories/supply-chain-limit-price-history-snapshot.repository'
import { SupplyChainLimitPriceHistoryService } from '../supply-chain-limit-price-history.service'
jest.mock('@/lib/prisma', () => ({
prisma: {
supplyChainStyleLimitPrice: {
findUnique: jest.fn(),
},
},
}))
jest.mock('@/server/repositories/supply-chain-limit-price-history.repository', () => ({
supplyChainLimitPriceHistoryRepository: {
findByProduct: jest.fn(),
},
}))
jest.mock('@/server/repositories/supply-chain-limit-price-page-source.repository', () => ({
supplyChainLimitPricePageSourceRepository: {
findByProduct: jest.fn(),
},
}))
jest.mock('@/server/repositories/supply-chain-limit-price-history-snapshot.repository', () => ({
supplyChainLimitPriceHistorySnapshotRepository: {
findByProduct: jest.fn(),
markSyncAttempt: jest.fn(),
save: jest.fn(),
},
}))
const remoteRepository = jest.mocked(supplyChainLimitPriceHistoryRepository)
const sourceRepository = jest.mocked(supplyChainLimitPricePageSourceRepository)
const snapshotRepository = jest.mocked(supplyChainLimitPriceHistorySnapshotRepository)
const prismaMock = jest.mocked(prisma)
const product = {
barcode: 'GBGJ-SZ024401N1441V01',
sku: 'GBGJ-SZ024401',
spu: 'GBGJ-SZ0244',
}
function remoteSnapshot(reason = '新品限价') {
return {
flows: [{
processInstanceId: 'flow-1',
businessId: '202610191816000088378',
title: '10-19+运营甲提交的新品限价流程',
status: 'COMPLETED',
result: 'agree',
originatorUserId: 'user-1',
createAt: '2026-10-19 18:16:00',
finishTime: '2026-10-19 19:20:00',
updatedAt: '2026-10-19T19:20:00',
}],
fields: [{
processInstanceId: 'flow-1',
componentType: 'TextField',
name: '调整理由',
value: reason,
}],
syncedThrough: '2026-10-28T12:00:00',
}
}
async function flushBackgroundTask() {
await new Promise((resolve) => setTimeout(resolve, 0))
await new Promise((resolve) => setTimeout(resolve, 0))
}
beforeEach(() => {
jest.clearAllMocks()
prismaMock.supplyChainStyleLimitPrice.findUnique.mockResolvedValue(null)
snapshotRepository.findByProduct.mockResolvedValue(null)
snapshotRepository.markSyncAttempt.mockResolvedValue(undefined)
snapshotRepository.save.mockResolvedValue(undefined)
sourceRepository.findByProduct.mockResolvedValue(null)
})
describe('负责人限价历史快照服务', () => {
it('首次查询读取报表库并保存商品快照', async () => {
remoteRepository.findByProduct.mockResolvedValue(remoteSnapshot())
const service = new SupplyChainLimitPriceHistoryService()
const history = await service.getHistory(product)
expect(remoteRepository.findByProduct).toHaveBeenCalledWith({
...product,
currentProcessNo: '',
})
expect(snapshotRepository.save).toHaveBeenCalledWith(
product,
expect.objectContaining({ syncedThrough: '2026-10-28T12:00:00' }),
)
expect(history.records[0]).toMatchObject({
reason: '新品限价',
processInstanceId: 'flow-1',
})
})
it('已有新鲜快照时直接返回,不访问报表库', async () => {
snapshotRepository.findByProduct.mockResolvedValue({
...remoteSnapshot('快照原因'),
lastSyncAttemptAt: new Date(),
})
const service = new SupplyChainLimitPriceHistoryService()
const history = await service.getHistory(product)
expect(history.records[0].reason).toBe('快照原因')
expect(remoteRepository.findByProduct).not.toHaveBeenCalled()
expect(snapshotRepository.save).not.toHaveBeenCalled()
})
it('快照超过刷新间隔后在后台按水位增量更新', async () => {
snapshotRepository.findByProduct.mockResolvedValue({
...remoteSnapshot('旧原因'),
lastSyncAttemptAt: new Date(Date.now() - 5 * 60_000),
})
remoteRepository.findByProduct.mockResolvedValue({
...remoteSnapshot('新原因'),
flows: [],
fields: [],
syncedThrough: '2026-10-28T12:01:00',
})
const service = new SupplyChainLimitPriceHistoryService()
const history = await service.getHistory(product)
await flushBackgroundTask()
expect(history.records[0].reason).toBe('旧原因')
expect(remoteRepository.findByProduct).toHaveBeenCalledWith({
...product,
currentProcessNo: '',
since: '2026-10-28T12:00:00',
})
expect(snapshotRepository.save).toHaveBeenCalledWith(
product,
expect.objectContaining({
flows: expect.arrayContaining([
expect.objectContaining({ processInstanceId: 'flow-1' }),
]),
syncedThrough: '2026-10-28T12:01:00',
}),
)
})
it('产品限价页面来源会返回原始确认记录', async () => {
prismaMock.supplyChainStyleLimitPrice.findUnique.mockResolvedValue({
ownerLimitPrice: '2141.8',
processNo: '',
processInstanceId: '',
applyType: '产品限价页面',
initiator: '',
approvedAt: new Date('2026-07-14T07:45:10.000Z'),
} as never)
snapshotRepository.findByProduct.mockResolvedValue({
...remoteSnapshot(),
flows: [],
fields: [],
lastSyncAttemptAt: new Date(),
})
sourceRepository.findByProduct.mockResolvedValue({
sourceTable: 'external.product_catalog_wide_v1',
productBusinessKey: 'CZ0140',
skuCode: 'GBGJ-SZ024401',
skuName: '测试商品',
barcode: 'GBGJ-SZ024401N1441V01',
limitPriceStatus: 'CONFIRMED',
limitPriceApplicable: true,
limitPriceConfirmed: true,
expectedDailyLimitPrice: '2141.8',
expectedLimitGrossMarginRate: '40',
nonSpuOwnerLimitPrice: '2336.8',
limitConfirmedAt: '2026-07-13T23:45:10.952Z',
limitSourceProductBusinessKey: '其他品牌-普通大货:CZ0140',
limitSourceSkuBusinessKey: '其他品牌-普通大货:CZ0140:GBGJ-SZ024401',
updatedAt: '2026-07-15T22:51:42.768Z',
})
const service = new SupplyChainLimitPriceHistoryService()
const history = await service.getHistory(product)
expect(sourceRepository.findByProduct).toHaveBeenCalledWith({
sku: product.sku,
barcode: product.barcode,
})
expect(history.sourceRecord).toMatchObject({
expectedDailyLimitPrice: '2141.8',
limitConfirmedAt: '2026-07-13T23:45:10.952Z',
})
})
})

View File

@ -1,7 +1,23 @@
import type { FreightConfigPage, FreightConfigTab } from '@/lib/freight-config'
import {
buildFreightCalculation,
evaluateFreightCourierRules,
freightCourierNameExclusionReason,
parseWarehouseFromProductTag,
type FreightCourierOption,
type FreightCalculationResult,
} from '@/lib/freight-calculation'
import { AppError, ErrorCode } from '@/server/core/errors'
import { freightConfigRepository } from '@/server/repositories/freight-config.repository'
export class FreightConfigService {
async warmup() {
await Promise.allSettled([
freightConfigRepository.warmup(),
freightConfigRepository.readProvinceShipmentShareSnapshot(),
])
}
async listPage(input: {
tab: FreightConfigTab
page: number
@ -27,6 +43,86 @@ export class FreightConfigService {
},
}
}
async calculateByBarcode(barcode: string): Promise<FreightCalculationResult> {
// 与限价明细同源:直接读取 SupplyChainProductArchive,从 productTag 解析标签仓库。
const archive = await freightConfigRepository.findProductArchiveSnapshot(barcode)
if (!archive) {
throw new AppError(ErrorCode.RESOURCE_NOT_FOUND, `商品编码 ${barcode.trim()} 不在产品全量档案中`)
}
const warehouseName = parseWarehouseFromProductTag(archive.productTag)
if (!warehouseName) {
throw new AppError(
ErrorCode.VALIDATION_FAILED,
`商品编码 ${archive.barcode} 的商品标签中没有“仓库-xxx”`,
)
}
const weight = Number(archive.weight)
const volume = Number(archive.volume)
if (archive.weight === null || !Number.isFinite(weight) || weight < 0) {
throw new AppError(
ErrorCode.VALIDATION_FAILED,
`商品编码 ${archive.barcode} 缺少有效重量`,
)
}
if (archive.volume === null || !Number.isFinite(volume) || volume < 0) {
throw new AppError(
ErrorCode.VALIDATION_FAILED,
`商品编码 ${archive.barcode} 缺少有效体积`,
)
}
let couriers: FreightCourierOption[]
try {
couriers = await freightConfigRepository.findCouriersByWarehouse({
warehouseName,
})
} catch (error) {
throw new AppError(
ErrorCode.SYSTEM_INTERNAL,
error instanceof Error ? error.message : '物流匹配规则读取失败',
)
}
if (couriers.length === 0) {
throw new AppError(
ErrorCode.RESOURCE_NOT_FOUND,
`没有查到仓库“${warehouseName}”可发货的快递`,
)
}
const eligibleCouriers = couriers.filter((courier) => (
!freightCourierNameExclusionReason(courier.expressName)
&& evaluateFreightCourierRules({
rules: courier.rules,
weight,
volume,
length: archive.length,
width: archive.width,
height: archive.height,
barcode: archive.barcode,
productTag: archive.productTag,
}).applicable
))
const [rates, shipmentShare] = await Promise.all([
freightConfigRepository.findApplicableRates({
expressNames: eligibleCouriers.map((courier) => courier.expressName),
}),
freightConfigRepository.readProvinceShipmentShareSnapshot(),
])
try {
return buildFreightCalculation({
archive,
warehouseName,
couriers,
rates,
shipmentShareRows: shipmentShare.rows,
now: new Date(),
})
} catch (error) {
throw new AppError(
ErrorCode.VALIDATION_FAILED,
error instanceof Error ? error.message : '快递运费计算失败',
)
}
}
}
export const freightConfigService = new FreightConfigService()

View File

@ -2,13 +2,14 @@ import { prisma } from '@/lib/prisma'
import {
buildComboLimitRow,
comboLimitOptions,
deriveComboComponentPrices,
filterComboLimitRows,
isComboComponentEligible,
paginateComboLimitRows,
sortComboLimitRows,
type ComboLimitAggregate,
type ComboLimitFieldKey,
type ComboLimitFilters,
type ComboLimitDetails,
type ComboLimitPage,
type ComboLimitRow,
type ComboLimitSort,
@ -16,10 +17,23 @@ import {
import {
jstComboLimitSourceRepository,
type ComboLimitPricedProduct,
type ComboOwnerChangeAssignment,
} from '@/server/repositories/jst-combo-limit-source.repository'
import { supplyChainManagementOwnerConfigService } from './supply-chain-management-owner-config.service'
type ComboSourceRepository = Pick<typeof jstComboLimitSourceRepository, 'listCompleteComboLimits'>
type ComboSourceRepository = {
listCompleteComboLimits: typeof jstComboLimitSourceRepository.listCompleteComboLimits
getComboDetails?: typeof jstComboLimitSourceRepository.getComboDetails
listOwnerChangeAssignments?: typeof jstComboLimitSourceRepository.listOwnerChangeAssignments
}
type PricedProductLoader = () => Promise<ComboLimitPricedProduct[]>
type OwnerDirectoryEntry = {
name: string
employmentStatus: '在职' | '离职'
departmentOwner: string
generalOwner: string
}
type OwnerDirectoryLoader = () => Promise<Map<string, OwnerDirectoryEntry>>
const CACHE_TTL_MS = 5 * 60_000
@ -30,8 +44,11 @@ type CacheEntry = {
type PriceSourceRow = {
barcode: string
sku: string
spu: string
productStatus: string
opsHead: string
departmentHead: string | null
ownerLimitPrice: string | number
costPrice: string | null
}
@ -45,8 +62,11 @@ async function loadPricedArchiveProducts(): Promise<ComboLimitPricedProduct[]> {
const rows = await prisma.$queryRaw<PriceSourceRow[]>`
SELECT
a."barcode" AS "barcode",
a."sku" AS "sku",
a."spu" AS "spu",
a."productStatus" AS "productStatus",
a."opsHead" AS "opsHead",
a."opsDeptHead" AS "departmentHead",
l."ownerLimitPrice"::text AS "ownerLimitPrice",
a."costPrice" AS "costPrice"
FROM "SupplyChainProductArchive" a
@ -59,30 +79,155 @@ async function loadPricedArchiveProducts(): Promise<ComboLimitPricedProduct[]> {
if (!barcode || !Number.isFinite(ownerLimitPrice) || ownerLimitPrice <= 0) return []
return [{
barcode,
sku: String(row.sku ?? '').trim(),
spu: String(row.spu ?? '').trim(),
productStatus: String(row.productStatus ?? '').trim(),
opsHead: String(row.opsHead ?? '').trim(),
departmentHead: String(row.departmentHead ?? '').trim(),
ownerLimitPrice,
costPrice: parseCostPrice(row.costPrice),
}]
})
}
async function loadOwnerDirectoryOverview(): Promise<Map<string, OwnerDirectoryEntry>> {
const { items } = await supplyChainManagementOwnerConfigService.listDirectoryOptions()
const byName = new Map<string, OwnerDirectoryEntry>()
for (const item of items) {
const name = item.name.trim()
if (!name) continue
const candidate: OwnerDirectoryEntry = {
name,
employmentStatus: item.employmentStatus,
departmentOwner: item.departmentOwner.trim(),
generalOwner: item.generalOwner.trim(),
}
const existing = byName.get(name)
if (!existing || existing.employmentStatus === '离职' && candidate.employmentStatus === '在职') {
byName.set(name, candidate)
}
}
return byName
}
function resolveActiveOwner(
ownerName: string,
directory: Map<string, OwnerDirectoryEntry>,
) {
const name = ownerName.trim()
if (!name) return ''
const employee = directory.get(name)
if (!employee || employee.employmentStatus !== '离职') return name
return employee.departmentOwner && employee.departmentOwner !== name
? employee.departmentOwner
: employee.generalOwner && employee.generalOwner !== name
? employee.generalOwner
: ''
}
export class SupplyChainComboLimitService {
private cache: CacheEntry | null = null
private inFlight: Promise<ComboLimitRow[]> | null = null
private ownerChangesCache: {
expiresAt: number
bySku: Map<string, ComboOwnerChangeAssignment>
bySpu: Map<string, ComboOwnerChangeAssignment>
} | null = null
private ownerDirectoryCache: {
expiresAt: number
byName: Map<string, OwnerDirectoryEntry>
} | null = null
constructor(
private readonly repository: ComboSourceRepository = jstComboLimitSourceRepository,
private readonly loadPricedProducts: PricedProductLoader = loadPricedArchiveProducts,
private readonly now: () => number = Date.now,
private readonly loadOwnerDirectory: OwnerDirectoryLoader = loadOwnerDirectoryOverview,
) {}
private async loadOwnerChanges() {
const now = this.now()
if (this.ownerChangesCache && this.ownerChangesCache.expiresAt > now) {
return this.ownerChangesCache
}
const rows = this.repository.listOwnerChangeAssignments
? await this.repository.listOwnerChangeAssignments()
: []
const bySku = new Map<string, ComboOwnerChangeAssignment>()
const bySpu = new Map<string, ComboOwnerChangeAssignment>()
for (const row of rows) {
const target = row.scope === 'SKU' ? bySku : bySpu
target.set(row.code.trim().toLocaleUpperCase(), row)
}
this.ownerChangesCache = {
expiresAt: now + CACHE_TTL_MS,
bySku,
bySpu,
}
return this.ownerChangesCache
}
private async loadOwnerDirectorySnapshot() {
const now = this.now()
if (this.ownerDirectoryCache && this.ownerDirectoryCache.expiresAt > now) {
return this.ownerDirectoryCache.byName
}
const byName = await this.loadOwnerDirectory()
this.ownerDirectoryCache = {
expiresAt: now + CACHE_TTL_MS,
byName,
}
return byName
}
private createProductLookup(products: ComboLimitPricedProduct[]) {
const byBarcode = new Map<string, ComboLimitPricedProduct>()
const bySku = new Map<string, ComboLimitPricedProduct>()
for (const product of [...products].sort((left, right) => left.barcode.localeCompare(right.barcode))) {
const barcode = product.barcode.trim().toLocaleUpperCase()
const sku = String(product.sku ?? '').trim().toLocaleUpperCase()
if (barcode) byBarcode.set(barcode, product)
if (sku && !bySku.has(sku)) bySku.set(sku, product)
}
return { byBarcode, bySku }
}
private async computeRows() {
const ownerDataPromise = Promise.all([
this.loadOwnerChanges(),
this.loadOwnerDirectorySnapshot(),
])
const products = (await this.loadPricedProducts())
.filter((product) => isComboComponentEligible(product.productStatus))
const aggregates: ComboLimitAggregate[] = await this.repository.listCompleteComboLimits(products)
const aggregates = await this.repository.listCompleteComboLimits(products)
const [{ bySku: ownerChangesBySku, bySpu: ownerChangesBySpu }, ownerDirectory] = await ownerDataPromise
const { byBarcode: productByBarcode, bySku: productBySku } = this.createProductLookup(products)
const resolveComponentOwner = (code: string, comboCreator: string) => {
const normalizedCode = code.trim().toLocaleUpperCase()
const product = productByBarcode.get(normalizedCode) ?? productBySku.get(normalizedCode)
const changedOwner = ownerChangesBySku.get(normalizedCode)
?? (product?.spu
? ownerChangesBySpu.get(product.spu.trim().toLocaleUpperCase())
: undefined)
const rawOwner = changedOwner?.owner
|| comboCreator
|| product?.opsHead
|| ''
return resolveActiveOwner(rawOwner, ownerDirectory)
}
return aggregates
.map(buildComboLimitRow)
.map((aggregate) => {
const codes = (aggregate.componentCodes?.length ?? 0) > 0
? aggregate.componentCodes
: [aggregate.opsHead]
const owner = [...new Set(
codes.map((code) => resolveComponentOwner(code, aggregate.opsHead)).filter(Boolean),
)].join('、')
return buildComboLimitRow({
...aggregate,
opsHead: owner || resolveActiveOwner(aggregate.opsHead, ownerDirectory),
})
})
.sort((left, right) => left.comboCode.localeCompare(right.comboCode, 'zh-Hans-CN', { numeric: true }))
}
@ -139,6 +284,78 @@ export class SupplyChainComboLimitService {
delete filters[input.field]
return comboLimitOptions(filterComboLimitRows(rows, filters), input.field, input)
}
async getDetails(comboCode: string): Promise<ComboLimitDetails> {
const normalizedCode = comboCode.trim()
if (!normalizedCode) return { comboCode: '', creator: '', rows: [] }
if (!this.repository.getComboDetails) {
throw new Error('组合明细数据源未配置')
}
const [details, products, ownerChanges, ownerDirectory] = await Promise.all([
this.repository.getComboDetails(normalizedCode),
this.loadPricedProducts(),
this.loadOwnerChanges(),
this.loadOwnerDirectorySnapshot(),
])
const eligibleProducts = products.filter((product) => (
isComboComponentEligible(product.productStatus)
))
const { byBarcode, bySku } = this.createProductLookup(eligibleProducts)
const comboCreator = details[0]?.creator ?? ''
const rows = details.map((detail) => {
const sourceCode = detail.procode.trim()
const key = sourceCode.toLocaleUpperCase()
const barcodeProduct = byBarcode.get(key)
const skuProduct = bySku.get(key)
const product = barcodeProduct ?? skuProduct
const ownerLimitPrice = product?.ownerLimitPrice ?? null
const costPrice = product?.costPrice ?? detail.sourceCostPrice
const derived = deriveComboComponentPrices(ownerLimitPrice, costPrice)
const changedOwner = ownerChanges.bySku.get(key)
?? (product?.spu
? ownerChanges.bySpu.get(product.spu.trim().toLocaleUpperCase())
: undefined)
const owner = resolveActiveOwner(
changedOwner?.owner || product?.opsHead || '',
ownerDirectory,
)
const departmentHead = String(product?.departmentHead ?? '').trim()
|| ownerDirectory.get(owner)?.departmentOwner
|| ownerDirectory.get(changedOwner?.owner.trim() ?? '')?.departmentOwner
|| ''
return {
sourceCode,
barcode: product?.barcode ?? (barcodeProduct ? sourceCode : ''),
sku: String(product?.sku ?? (skuProduct ? sourceCode : '')).trim(),
quantity: detail.quantity,
productName: detail.productName || product?.barcode || sourceCode,
imageUrl: detail.picture,
model: detail.model,
color: detail.color,
categoryTwo: detail.categoryTwo,
productStatus: product?.productStatus ?? '',
owner,
departmentHead,
costPrice,
ownerLimitPrice,
...derived,
ownerLimitSubtotal: ownerLimitPrice === null
? null
: Math.round((ownerLimitPrice * detail.quantity + Number.EPSILON) * 100) / 100,
matchedBy: barcodeProduct
? 'BARCODE' as const
: skuProduct
? 'SKU' as const
: 'UNAVAILABLE' as const,
}
})
return {
comboCode: details[0]?.comboCode ?? normalizedCode,
creator: resolveActiveOwner(comboCreator, ownerDirectory)
|| [...new Set(rows.map((row) => row.owner).filter(Boolean))].join('、'),
rows,
}
}
}
export const supplyChainComboLimitService = new SupplyChainComboLimitService()

View File

@ -0,0 +1,155 @@
import {
buildLimitPriceWorkflowRecords,
mergeLimitPriceWorkflowSnapshots,
type LimitPriceHistoryResult,
type LimitPriceWorkflowSnapshot,
} from '@/lib/supply-chain-limit-price-history'
import { prisma } from '@/lib/prisma'
import { supplyChainLimitPricePageSourceRepository } from '@/server/repositories/supply-chain-limit-price-page-source.repository'
import { supplyChainLimitPriceHistoryRepository } from '@/server/repositories/supply-chain-limit-price-history.repository'
import {
supplyChainLimitPriceHistorySnapshotRepository,
type StoredLimitPriceHistorySnapshot,
} from '@/server/repositories/supply-chain-limit-price-history-snapshot.repository'
const SNAPSHOT_REFRESH_INTERVAL_MS = 60_000
export class SupplyChainLimitPriceHistoryService {
private initialLoads = new Map<string, Promise<LimitPriceWorkflowSnapshot>>()
private backgroundRefreshes = new Map<string, Promise<void>>()
async getHistory(input: {
barcode: string
sku: string
spu: string
}): Promise<LimitPriceHistoryResult> {
const barcode = input.barcode.trim()
const sku = input.sku.trim()
const spu = input.spu.trim()
const [currentLimit, storedSnapshot] = await Promise.all([
sku
? prisma.supplyChainStyleLimitPrice.findUnique({
where: { styleCode: sku },
select: {
ownerLimitPrice: true,
processNo: true,
processInstanceId: true,
applyType: true,
initiator: true,
approvedAt: true,
},
})
: Promise.resolve(null),
supplyChainLimitPriceHistorySnapshotRepository.findByProduct({ barcode, sku, spu }),
])
const snapshot = storedSnapshot ?? await this.loadInitialSnapshot({
barcode,
sku,
spu,
currentProcessNo: currentLimit?.processNo ?? '',
})
if (storedSnapshot) {
this.refreshSnapshotInBackground(
{ barcode, sku, spu },
storedSnapshot,
currentLimit?.processNo ?? '',
)
}
const records = buildLimitPriceWorkflowRecords({
barcode,
sku,
spu,
currentProcessNo: currentLimit?.processNo ?? '',
flows: snapshot.flows,
fields: snapshot.fields,
})
const sourceRecord = currentLimit?.applyType === '产品限价页面'
? await supplyChainLimitPricePageSourceRepository.findByProduct({ sku, barcode })
.catch((error) => {
console.warn('产品限价页面来源记录读取失败', error)
return null
})
: null
return {
barcode,
sku,
spu,
sourceRecord,
current: currentLimit && currentLimit.ownerLimitPrice !== null
? {
price: Number(currentLimit.ownerLimitPrice).toFixed(2),
processNo: currentLimit.processNo,
processInstanceId: currentLimit.processInstanceId,
applyType: currentLimit.applyType,
initiator: currentLimit.initiator,
approvedAt: currentLimit.approvedAt?.toISOString() ?? '',
}
: null,
records,
}
}
private snapshotKey(input: { barcode: string; sku: string; spu: string }) {
return JSON.stringify([input.barcode, input.sku, input.spu])
}
private loadInitialSnapshot(input: {
barcode: string
sku: string
spu: string
currentProcessNo: string
}) {
const key = this.snapshotKey(input)
const existing = this.initialLoads.get(key)
if (existing) return existing
const load = (async () => {
const snapshot = await supplyChainLimitPriceHistoryRepository.findByProduct(input)
await supplyChainLimitPriceHistorySnapshotRepository.save({
barcode: input.barcode,
sku: input.sku,
spu: input.spu,
}, snapshot)
return snapshot
})().finally(() => {
this.initialLoads.delete(key)
})
this.initialLoads.set(key, load)
return load
}
private refreshSnapshotInBackground(
key: { barcode: string; sku: string; spu: string },
snapshot: StoredLimitPriceHistorySnapshot,
currentProcessNo: string,
) {
if (Date.now() - snapshot.lastSyncAttemptAt.getTime() < SNAPSHOT_REFRESH_INTERVAL_MS) {
return
}
const snapshotKey = this.snapshotKey(key)
if (this.backgroundRefreshes.has(snapshotKey)) return
const refresh = (async () => {
await supplyChainLimitPriceHistorySnapshotRepository.markSyncAttempt(key)
const incoming = await supplyChainLimitPriceHistoryRepository.findByProduct({
...key,
currentProcessNo,
since: snapshot.syncedThrough,
})
const merged = mergeLimitPriceWorkflowSnapshots({
existing: snapshot,
incoming,
syncedThrough: incoming.syncedThrough,
})
await supplyChainLimitPriceHistorySnapshotRepository.save(key, merged)
})()
.catch((error) => {
console.warn('负责人限价历史快照增量刷新失败', error)
})
.finally(() => {
this.backgroundRefreshes.delete(snapshotKey)
})
this.backgroundRefreshes.set(snapshotKey, refresh)
}
}
export const supplyChainLimitPriceHistoryService =
new SupplyChainLimitPriceHistoryService()

View File

@ -0,0 +1,195 @@
import * as XLSX from 'xlsx'
import { Prisma } from '@prisma/client'
import { randomUUID } from 'node:crypto'
import { prisma } from '@/lib/prisma'
import type { AuthUser } from '@/server/core/types'
import {
MANUAL_LIMIT_APPLY_TYPE,
type ManualLimitImportResult,
} from '@/lib/supply-chain-manual-limit'
const CODE_HEADERS = ['商品编码', '条码', 'SKU条码']
const PRICE_HEADERS = ['限价价格', '负责人限价', '限价']
function normalizeHeader(value: string) {
return value.replace(/\s+/g, '').trim()
}
function cellText(value: unknown) {
return String(value ?? '').trim()
}
function parsePrice(value: unknown) {
const parsed = Number(String(value ?? '').replace(/[^\d.-]/g, ''))
return Number.isFinite(parsed) && parsed > 0 ? parsed : null
}
function readRows(content: Buffer) {
const workbook = XLSX.read(content, { type: 'buffer' })
const sheet = workbook.Sheets[workbook.SheetNames[0]]
if (!sheet) throw new Error('Excel 文件没有工作表')
const rawRows = XLSX.utils.sheet_to_json<Record<string, unknown>>(sheet, { defval: '' })
return rawRows.map((raw, index) => {
const row = Object.fromEntries(
Object.entries(raw).map(([key, value]) => [normalizeHeader(key), value]),
)
const codeHeader = CODE_HEADERS.find((header) => Object.hasOwn(row, header))
const priceHeader = PRICE_HEADERS.find((header) => Object.hasOwn(row, header))
return {
rowNumber: index + 2,
code: codeHeader ? cellText(row[codeHeader]) : '',
price: priceHeader ? parsePrice(row[priceHeader]) : null,
}
})
}
async function findArchivesByBarcode(codes: string[]) {
const rows: Array<{ barcode: string; sku: string }> = []
for (let index = 0; index < codes.length; index += 5000) {
rows.push(...await prisma.supplyChainProductArchive.findMany({
where: { barcode: { in: codes.slice(index, index + 5000) } },
select: { barcode: true, sku: true },
}))
}
return rows
}
export class SupplyChainManualLimitService {
async importFile(input: {
fileName: string
content: Buffer
targetPrice: number | null
note: string
user: AuthUser
}): Promise<ManualLimitImportResult> {
const parsedRows = readRows(input.content)
const invalidRows: ManualLimitImportResult['invalidRows'] = []
const codePrices = new Map<string, Set<number>>()
let rowCount = 0
for (const row of parsedRows) {
if (!row.code && !row.price) continue
rowCount += 1
if (!row.code) {
invalidRows.push({ rowNumber: row.rowNumber, code: '', message: '商品编码为空' })
continue
}
const price = row.price ?? input.targetPrice
if (price === null || price === undefined || price <= 0) {
invalidRows.push({ rowNumber: row.rowNumber, code: row.code, message: '限价价格为空或不是有效正数' })
continue
}
const prices = codePrices.get(row.code) ?? new Set<number>()
prices.add(price)
codePrices.set(row.code, prices)
}
const uniqueCodes = [...codePrices.keys()]
if (!uniqueCodes.length) throw new Error('Excel 中没有可导入的商品编码')
const conflictingCodes = [...codePrices].filter(([, prices]) => prices.size > 1)
for (const [code, prices] of conflictingCodes) {
invalidRows.push({
rowNumber: 0,
code,
message: `同一商品编码存在多个限价:${[...prices].join('、')}`,
})
}
const validCodes = uniqueCodes.filter((code) => (codePrices.get(code)?.size ?? 0) === 1)
const archives = await findArchivesByBarcode(validCodes)
const archiveByBarcode = new Map(archives.map((row) => [row.barcode.trim(), row]))
const unmatchedCodes = validCodes.filter((code) => !archiveByBarcode.has(code))
const stylePrices = new Map<string, Set<number>>()
for (const code of validCodes) {
const archive = archiveByBarcode.get(code)
if (!archive) continue
const styleCode = archive.sku.trim()
if (!styleCode) continue
const prices = stylePrices.get(styleCode) ?? new Set<number>()
for (const price of codePrices.get(code) ?? []) prices.add(price)
stylePrices.set(styleCode, prices)
}
const conflictingStyles = [...stylePrices]
.filter(([, prices]) => prices.size > 1)
.map(([styleCode, prices]) => ({ styleCode, prices: [...prices] }))
const conflictingStyleSet = new Set(conflictingStyles.map((row) => row.styleCode))
const effectiveStyles = [...stylePrices]
.filter(([styleCode, prices]) => prices.size === 1 && !conflictingStyleSet.has(styleCode))
if (!effectiveStyles.length) throw new Error('没有可更新的商品限价')
const now = new Date()
const batchId = randomUUID()
await prisma.$transaction(async (tx) => {
await tx.supplyChainManualLimitPriceBatch.create({
data: {
id: batchId,
fileName: input.fileName.slice(0, 255),
targetPrice: input.targetPrice === null ? null : new Prisma.Decimal(input.targetPrice),
rowCount,
uniqueCodeCount: uniqueCodes.length,
matchedBarcodeCount: uniqueCodes.length - unmatchedCodes.length,
matchedStyleCount: stylePrices.size,
updatedLimitCount: effectiveStyles.length,
codes: uniqueCodes,
unmatchedCodes,
invalidRows,
conflictingStyles,
uploadedById: input.user.id,
uploadedByName: input.user.name,
note: input.note.trim().slice(0, 500),
},
})
for (const [styleCode, prices] of effectiveStyles) {
const price = [...prices][0]
await tx.supplyChainStyleLimitPrice.upsert({
where: { styleCode },
create: {
styleCode,
ownerLimitPrice: new Prisma.Decimal(price),
processInstanceId: '',
processNo: '',
applyType: MANUAL_LIMIT_APPLY_TYPE,
initiator: input.user.name,
approvedAt: now,
},
update: {
ownerLimitPrice: new Prisma.Decimal(price),
processInstanceId: '',
processNo: '',
applyType: MANUAL_LIMIT_APPLY_TYPE,
initiator: input.user.name,
approvedAt: now,
},
})
}
})
return {
batchId,
fileName: input.fileName,
targetPrice: input.targetPrice,
rowCount,
uniqueCodeCount: uniqueCodes.length,
matchedBarcodeCount: uniqueCodes.length - unmatchedCodes.length,
matchedStyleCount: stylePrices.size,
updatedLimitCount: effectiveStyles.length,
unmatchedCodes,
invalidRows,
conflictingStyles,
}
}
async listBatches() {
const rows = await prisma.supplyChainManualLimitPriceBatch.findMany({
orderBy: { createdAt: 'desc' },
take: 20,
})
return rows.map((row) => ({
...row,
targetPrice: row.targetPrice === null ? null : Number(row.targetPrice),
}))
}
}
export const supplyChainManualLimitService = new SupplyChainManualLimitService()