feat(freight): 支持连续对话修正与部分报价计算
This commit is contained in:
parent
60c933a14e
commit
2ea3f22349
@ -13,6 +13,8 @@ export const runtime = 'nodejs'
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const maxDuration = 300
|
||||
|
||||
const MAX_MESSAGE_LENGTH = 2_000
|
||||
|
||||
async function readUpload(
|
||||
form: FormData,
|
||||
key: string,
|
||||
@ -78,6 +80,27 @@ export async function POST(request: NextRequest) {
|
||||
if (!message) {
|
||||
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '缺少原测算需求', 400, ctx.requestId)
|
||||
}
|
||||
let history: string[] = []
|
||||
const historyValue = String(form.get('history') ?? '').trim()
|
||||
if (historyValue) {
|
||||
try {
|
||||
const parsedHistory = JSON.parse(historyValue) as unknown
|
||||
if (
|
||||
!Array.isArray(parsedHistory)
|
||||
|| parsedHistory.length > 50
|
||||
|| parsedHistory.some((item) => (
|
||||
typeof item !== 'string'
|
||||
|| item.trim().length === 0
|
||||
|| item.length > MAX_MESSAGE_LENGTH
|
||||
))
|
||||
) {
|
||||
throw new Error('invalid history')
|
||||
}
|
||||
history = parsedHistory.map((item) => item.trim())
|
||||
} catch {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '对话历史格式不正确', 400, ctx.requestId)
|
||||
}
|
||||
}
|
||||
const quoteFile = form.get('quote')
|
||||
const requestedMode = String(form.get('mode') ?? '')
|
||||
const mode = requestedMode === 'EXISTING_ONLY'
|
||||
@ -117,6 +140,7 @@ export async function POST(request: NextRequest) {
|
||||
message,
|
||||
orderDetailLimit: null,
|
||||
mode,
|
||||
history,
|
||||
})
|
||||
const { result } = analysis
|
||||
const workbook = XLSX.utils.book_new()
|
||||
|
||||
@ -68,6 +68,27 @@ export async function POST(request: NextRequest) {
|
||||
if (message.length > MAX_MESSAGE_LENGTH) {
|
||||
return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, '测算需求不能超过 2000 字', 400, ctx.requestId)
|
||||
}
|
||||
let history: string[] = []
|
||||
const historyValue = String(form.get('history') ?? '').trim()
|
||||
if (historyValue) {
|
||||
try {
|
||||
const parsedHistory = JSON.parse(historyValue) as unknown
|
||||
if (
|
||||
!Array.isArray(parsedHistory)
|
||||
|| parsedHistory.length > 50
|
||||
|| parsedHistory.some((item) => (
|
||||
typeof item !== 'string'
|
||||
|| item.trim().length === 0
|
||||
|| item.length > MAX_MESSAGE_LENGTH
|
||||
))
|
||||
) {
|
||||
throw new Error('invalid history')
|
||||
}
|
||||
history = parsedHistory.map((item) => item.trim())
|
||||
} catch {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '对话历史格式不正确', 400, ctx.requestId)
|
||||
}
|
||||
}
|
||||
const quoteFile = form.get('quote')
|
||||
const requestedMode = String(form.get('mode') ?? '')
|
||||
const mode = requestedMode === 'EXISTING_ONLY'
|
||||
@ -106,6 +127,7 @@ export async function POST(request: NextRequest) {
|
||||
orderBuffer: orders.buffer,
|
||||
message,
|
||||
mode,
|
||||
history,
|
||||
})
|
||||
return jsonSuccess(result, 200, ctx.requestId)
|
||||
}, { requireAuth: true })
|
||||
|
||||
@ -157,10 +157,10 @@ function mockLimitManagementFetch(rows: SupplyChainProductArchiveRow[]) {
|
||||
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 },
|
||||
{ region: '一区', regionShare: 0.214, coveredShare: 0.214, provinceCount: 4, courierCount: 1, averageCost: 10.379 },
|
||||
{ region: '二区', regionShare: 0.485, coveredShare: 0.485, provinceCount: 10, courierCount: 1, averageCost: 20 },
|
||||
{ region: '三区', regionShare: 0.251, coveredShare: 0.251, provinceCount: 10, courierCount: 1, averageCost: 30 },
|
||||
{ region: '四区', regionShare: 0.05, coveredShare: 0.05, provinceCount: 5, courierCount: 1, averageCost: 5 },
|
||||
],
|
||||
warnings: [],
|
||||
couriers: [{
|
||||
@ -173,6 +173,7 @@ function mockLimitManagementFetch(rows: SupplyChainProductArchiveRow[]) {
|
||||
provinceCosts: [{
|
||||
province: '上海',
|
||||
region: '一区',
|
||||
provinceShare: 0.029642,
|
||||
fee: 12.5,
|
||||
chargeableWeight: 15,
|
||||
roundedWeight: 15,
|
||||
@ -586,7 +587,7 @@ describe('限价管理', () => {
|
||||
expect(screen.getByText('36')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('大货和品牌商品展示按快递维护逻辑计算的区域及全国运费', async () => {
|
||||
it('大货和品牌商品展示按快递维护逻辑计算的四区运费', async () => {
|
||||
mockLimitManagementFetch([
|
||||
makeRow({
|
||||
freightZone1: '8.5600',
|
||||
|
||||
@ -51,6 +51,7 @@ type AnalysisRequestSnapshot = {
|
||||
quoteFile: File | null
|
||||
orderFile: File
|
||||
message: string
|
||||
history: string[]
|
||||
mode: FreightAiComparisonResult['mode']
|
||||
}
|
||||
|
||||
@ -464,12 +465,14 @@ export function FreightAiComparisonTab({
|
||||
const [result, setResult] = useState<FreightAiComparisonResult | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [revision, setRevision] = useState(0)
|
||||
const [error, setError] = useState('')
|
||||
const quoteInputRef = useRef<HTMLInputElement>(null)
|
||||
const orderInputRef = useRef<HTMLInputElement>(null)
|
||||
const messageScrollRef = useRef<HTMLDivElement>(null)
|
||||
const nextMessageId = useRef(2)
|
||||
const analysisSnapshotRef = useRef<AnalysisRequestSnapshot | null>(null)
|
||||
const conversationInputsRef = useRef<string[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const container = messageScrollRef.current
|
||||
@ -511,6 +514,8 @@ export function FreightAiComparisonTab({
|
||||
setError('')
|
||||
setResult(null)
|
||||
analysisSnapshotRef.current = null
|
||||
conversationInputsRef.current = []
|
||||
setRevision(0)
|
||||
if (kind === 'quote') {
|
||||
setQuoteFile(file)
|
||||
appendAssistantMessage(`已加入新快递报价:${file.name}。${orderFile ? '两份资料都齐了,直接告诉我仓库和新快递名称即可。' : '还需要上传待测算的订单明细。'}`)
|
||||
@ -542,6 +547,7 @@ export function FreightAiComparisonTab({
|
||||
const mode: FreightAiComparisonResult['mode'] = quoteFile
|
||||
? 'COMPARE_NEW'
|
||||
: 'EXISTING_ONLY'
|
||||
const history = conversationInputsRef.current.slice(-50)
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
@ -550,6 +556,7 @@ export function FreightAiComparisonTab({
|
||||
form.append('orders', orderFile)
|
||||
form.append('message', normalizedMessage)
|
||||
form.append('mode', mode)
|
||||
if (history.length > 0) form.append('history', JSON.stringify(history))
|
||||
const response = await fetch('/api/supply-chain/limit-management/freight-ai-comparison', {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
@ -559,10 +566,13 @@ export function FreightAiComparisonTab({
|
||||
throw new Error(payload.error?.message || 'AI 比价测算失败')
|
||||
}
|
||||
setResult(payload.data.result)
|
||||
conversationInputsRef.current = [...history, normalizedMessage]
|
||||
setRevision(history.length + 1)
|
||||
analysisSnapshotRef.current = {
|
||||
quoteFile,
|
||||
orderFile,
|
||||
message: normalizedMessage,
|
||||
history,
|
||||
mode,
|
||||
}
|
||||
appendAssistantMessage(payload.data.assistantReply)
|
||||
@ -590,8 +600,10 @@ export function FreightAiComparisonTab({
|
||||
setResult(null)
|
||||
setError('')
|
||||
setExporting(false)
|
||||
setRevision(0)
|
||||
setMessage('')
|
||||
analysisSnapshotRef.current = null
|
||||
conversationInputsRef.current = []
|
||||
nextMessageId.current = 2
|
||||
setMessages([{ id: 1, role: 'assistant', text: INITIAL_MESSAGE }])
|
||||
}
|
||||
@ -614,6 +626,9 @@ export function FreightAiComparisonTab({
|
||||
form.append('orders', snapshot.orderFile)
|
||||
form.append('message', snapshot.message)
|
||||
form.append('mode', snapshot.mode)
|
||||
if (snapshot.history.length > 0) {
|
||||
form.append('history', JSON.stringify(snapshot.history))
|
||||
}
|
||||
const response = await fetch(
|
||||
'/api/supply-chain/limit-management/freight-ai-comparison/export',
|
||||
{ method: 'POST', body: form },
|
||||
@ -649,6 +664,8 @@ export function FreightAiComparisonTab({
|
||||
else setOrderFile(null)
|
||||
setResult(null)
|
||||
analysisSnapshotRef.current = null
|
||||
conversationInputsRef.current = []
|
||||
setRevision(0)
|
||||
}
|
||||
|
||||
return (
|
||||
@ -659,7 +676,14 @@ export function FreightAiComparisonTab({
|
||||
<span><Bot size={18} /></span>
|
||||
<div>
|
||||
<strong>快递策略助手</strong>
|
||||
<small><i />{canOperate ? '规则引擎已连接' : '当前为只读权限'}</small>
|
||||
<small>
|
||||
<i />
|
||||
{canOperate
|
||||
? revision > 0
|
||||
? `规则引擎已连接 · 第 ${revision} 版`
|
||||
: '规则引擎已连接'
|
||||
: '当前为只读权限'}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" title="清空对话和文件" className={styles.resetButton} onClick={resetConversation}>
|
||||
@ -755,7 +779,7 @@ export function FreightAiComparisonTab({
|
||||
</div>
|
||||
<p className={styles.orderRuleHint}>
|
||||
<CheckCircle2 size={12} />
|
||||
订单规则已启用;也可以在对话中补充“上海不发”“新北中通只限京东商城”或“只计算现有快递”
|
||||
算完可继续对话修正,例如“不对,上海可以发”“新北中通改为只限京东商城”
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@ -800,7 +824,9 @@ export function FreightAiComparisonTab({
|
||||
maxLength={2_000}
|
||||
rows={2}
|
||||
aria-label="向快递策略助手提问"
|
||||
placeholder="例如:测算睢宁仓,新快递和现有快递哪个更便宜?"
|
||||
placeholder={result
|
||||
? '对当前结果补充或修正,例如“不对,上海应该不发”'
|
||||
: '例如:测算睢宁仓,只计算现有快递'}
|
||||
disabled={!canOperate}
|
||||
onChange={(event) => setMessage(event.target.value)}
|
||||
onKeyDown={handleMessageKeyDown}
|
||||
|
||||
@ -5,6 +5,7 @@ import { Calculator, Download, LoaderCircle, Search } from 'lucide-react'
|
||||
import type { ApiResponse } from '@/server/core/types'
|
||||
import {
|
||||
FREIGHT_REGIONS,
|
||||
FREIGHT_CALCULATION_PROVINCES,
|
||||
describeFreightCourierRuleLimits,
|
||||
freightWeightRoundingLabel,
|
||||
type CourierFreightCost,
|
||||
@ -156,7 +157,7 @@ function CalculationResult({ result }: { result: FreightCalculationResult }) {
|
||||
<div><span>体积</span><strong>{displayNumber(result.volume, 3)} cm³</strong></div>
|
||||
<div><span>最长边</span><strong>{displayNumber(longestSide, 3)} cm</strong></div>
|
||||
<div>
|
||||
<span>快递数量</span>
|
||||
<span>完整覆盖快递</span>
|
||||
<strong>{result.calculatedCourierCount} / {result.courierCount}</strong>
|
||||
</div>
|
||||
<div>
|
||||
@ -177,9 +178,15 @@ function CalculationResult({ result }: { result: FreightCalculationResult }) {
|
||||
<div className={styles.regionGrid}>
|
||||
{result.regionAverages.map((region) => (
|
||||
<div key={region.region}>
|
||||
<span>{region.region} · 区域占比 {displayPercent(region.regionShare)}</span>
|
||||
<span>
|
||||
{region.region} · 区域占比 {displayPercent(region.regionShare)}
|
||||
{' · '}
|
||||
{region.provinceCount}/{FREIGHT_CALCULATION_PROVINCES.filter((row) => row.region === region.region).length} 省
|
||||
</span>
|
||||
<strong>{displayNumber(region.averageCost, 4)} 元</strong>
|
||||
<small>{region.courierCount} 个快递参与平均</small>
|
||||
<small>
|
||||
{region.courierCount} 个快递有报价 · 有效省份占比 {displayPercent(region.coveredShare)}
|
||||
</small>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@ -319,8 +326,18 @@ function BatchOverview({
|
||||
</td>
|
||||
))}
|
||||
<td>
|
||||
<span className={row.calculatedCourierCount > 0 ? styles.statusReady : styles.statusNotApplicable}>
|
||||
{row.calculatedCourierCount > 0 ? '已计算' : '无可计算快递'}
|
||||
<span className={
|
||||
row.calculatedCourierCount > 0
|
||||
? styles.statusReady
|
||||
: row.regionAverages.some((region) => region.averageCost !== null)
|
||||
? styles.statusMissing
|
||||
: styles.statusNotApplicable
|
||||
}>
|
||||
{row.calculatedCourierCount > 0
|
||||
? '已计算'
|
||||
: row.regionAverages.some((region) => region.averageCost !== null)
|
||||
? '部分报价计算'
|
||||
: '无可计算快递'}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@ -30,6 +30,46 @@ function calculationResult(barcode: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function existingAiResult() {
|
||||
return {
|
||||
result: {
|
||||
mode: 'EXISTING_ONLY',
|
||||
warehouseName: '睢宁仓',
|
||||
newCourierName: '现有快递方案',
|
||||
currentBaselineSource: 'UPLOADED_FREIGHT',
|
||||
detailTruncated: false,
|
||||
summary: {
|
||||
orderRowCount: 1,
|
||||
shipmentCount: 1,
|
||||
comparableShipmentCount: 1,
|
||||
currentTotal: 15,
|
||||
newTotal: 0,
|
||||
hybridTotal: 15,
|
||||
currentAverage: 15,
|
||||
newAverage: 0,
|
||||
newSavings: 0,
|
||||
hybridSavings: 0,
|
||||
savingsRate: 0,
|
||||
monthlyOrderCount: null,
|
||||
monthlySavings: null,
|
||||
recommendation: 'CURRENT',
|
||||
},
|
||||
provinces: [],
|
||||
orders: [],
|
||||
warnings: [],
|
||||
},
|
||||
assistantReply: '已重新生成现有快递测算。',
|
||||
parsed: {
|
||||
quoteSheet: null,
|
||||
orderSheet: 'Sheet1',
|
||||
validQuoteRows: 0,
|
||||
validOrderRows: 1,
|
||||
ignoredOrderRows: 0,
|
||||
analyzedShipments: 1,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
global.fetch = originalFetch
|
||||
})
|
||||
@ -58,10 +98,10 @@ it('在快递维护页面按商品编码执行快递测算', async () => {
|
||||
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 },
|
||||
{ region: '一区', regionShare: 0.214, coveredShare: 0.214, provinceCount: 4, courierCount: 1, averageCost: 10.379 },
|
||||
{ region: '二区', regionShare: 0.485, coveredShare: 0.485, provinceCount: 10, courierCount: 1, averageCost: 11.2 },
|
||||
{ region: '三区', regionShare: 0.251, coveredShare: 0.251, provinceCount: 10, courierCount: 1, averageCost: 12.3 },
|
||||
{ region: '四区', regionShare: 0.05, coveredShare: 0.05, provinceCount: 5, courierCount: 1, averageCost: 13.4 },
|
||||
],
|
||||
nationalAverage: 14.5678,
|
||||
warnings: [],
|
||||
@ -205,6 +245,38 @@ it('只上传订单明细时也可以发起现有快递测算', () => {
|
||||
expect(screen.getByText(/可以直接告诉我仓库,我会先计算现有快递/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('后续对话会携带前一轮指令并重新生成结果', async () => {
|
||||
const fetchMock = jest.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => (
|
||||
jsonResponse({ success: true, data: existingAiResult() })
|
||||
))
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
render(<FreightMaintenanceView canOperate canDownload />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /AI 比价/ }))
|
||||
fireEvent.change(screen.getByLabelText('上传订单明细'), {
|
||||
target: {
|
||||
files: [new File(['orders'], 'conversation-orders.xlsx', {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
})],
|
||||
},
|
||||
})
|
||||
|
||||
const input = screen.getByRole('textbox', { name: '向快递策略助手提问' })
|
||||
fireEvent.change(input, { target: { value: '测算睢宁仓,只计算现有快递' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: '发送测算需求' }))
|
||||
expect(await screen.findByText(/第 1 版/)).toBeInTheDocument()
|
||||
|
||||
fireEvent.change(input, { target: { value: '不对,上海应该不发' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: '发送测算需求' }))
|
||||
expect(await screen.findByText(/第 2 版/)).toBeInTheDocument()
|
||||
|
||||
const analysisCalls = fetchMock.mock.calls.filter(([input]) => (
|
||||
String(input).includes('/freight-ai-comparison')
|
||||
))
|
||||
const secondBody = analysisCalls.at(-1)?.[1]?.body as FormData
|
||||
expect(secondBody.get('history')).toBe(JSON.stringify(['测算睢宁仓,只计算现有快递']))
|
||||
expect(secondBody.get('message')).toBe('不对,上海应该不发')
|
||||
})
|
||||
|
||||
it('仅有查看权限时禁用测算、上传和导出操作', () => {
|
||||
render(<FreightMaintenanceView canOperate={false} canDownload={false} />)
|
||||
|
||||
|
||||
@ -79,4 +79,37 @@ describe('freight AI chat instructions', () => {
|
||||
})
|
||||
expect(parsed.manualRules.excludedProvinces).toEqual([])
|
||||
})
|
||||
|
||||
it('后续对话可以撤销停发省份并替换平台限制', () => {
|
||||
const parsed = parseFreightAiChatInstructions({
|
||||
history: [
|
||||
'上海不发',
|
||||
'新北中通只限京东商城',
|
||||
],
|
||||
message: '不对,上海应该发;新北中通改为只限拼多多',
|
||||
existingCouriers: couriers,
|
||||
orderShopSites: ['拼多多'],
|
||||
})
|
||||
|
||||
expect(parsed.manualRules.excludedProvinces).toEqual([])
|
||||
expect(parsed.manualRules.couriers).toEqual([
|
||||
expect.objectContaining({
|
||||
expressName: '新北中通',
|
||||
allowedShopSites: ['拼多多'],
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it('只算现有快递的对话状态会延续,也可重新切回新快递比较', () => {
|
||||
expect(parseFreightAiChatInstructions({
|
||||
history: ['只计算现有快递'],
|
||||
message: '不对,上海不发',
|
||||
existingCouriers: couriers,
|
||||
}).existingOnly).toBe(true)
|
||||
expect(parseFreightAiChatInstructions({
|
||||
history: ['只计算现有快递'],
|
||||
message: '改为比较新快递',
|
||||
existingCouriers: couriers,
|
||||
}).existingOnly).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@ -17,13 +17,36 @@ export type FreightAiParsedChatInstructions = {
|
||||
const EXISTING_ONLY_PATTERN =
|
||||
/(?:只|仅)(?:要|需|需要|想)?(?:计算|测算|算|看|比较)?(?:现有|当前)(?:快递|方案)|(?:不要|不用|无需|不)(?:上传|比较|计算)?(?:新快递|新报价)|只看现有/u
|
||||
|
||||
const COMPARE_NEW_PATTERN =
|
||||
/(?:(?:重新|恢复|改回|改为|应该|需要|开始).{0,12}(?:新快递|新报价).{0,8}(?:比价|比较|对比))|(?:(?:重新|恢复|改回|改为|应该|需要|开始).{0,8}(?:比较|对比).{0,8}(?:新快递|新报价))|(?:比较|对比).{0,8}新快递/u
|
||||
const NEGATIVE_SHIPPING_PATTERN = /不发|不发货|停发|不到|不派送|无法送达|不配送/u
|
||||
const PLATFORM_RESTRICTION_PATTERN = /只|仅|限|限定|平台/u
|
||||
const POSITIVE_SHIPPING_PATTERN =
|
||||
/(?:可以|可|恢复|正常|应该)(?:发|发货|派送|配送)|(?:取消|解除)(?:停发|不发)|不是不发/u
|
||||
const PLATFORM_RESTRICTION_PATTERN =
|
||||
/只|仅|限|限定|平台|应该|改为|改成|换成|不对/u
|
||||
const PLATFORM_REPLACEMENT_PATTERN = /不对|不是|改为|改成|换成|应该|只限|仅限|只发|仅发/u
|
||||
const PLATFORM_CLEAR_PATTERN = /取消.{0,8}(?:平台|限制)|不限平台|所有平台|平台不限/u
|
||||
|
||||
export function isFreightAiExistingOnlyInstruction(message: string) {
|
||||
return EXISTING_ONLY_PATTERN.test(message.normalize('NFKC'))
|
||||
}
|
||||
|
||||
export function resolveFreightAiConversationMode(
|
||||
messages: readonly string[],
|
||||
fallback: 'COMPARE_NEW' | 'EXISTING_ONLY',
|
||||
) {
|
||||
let mode: 'COMPARE_NEW' | 'EXISTING_ONLY' = fallback
|
||||
for (const source of messages) {
|
||||
const message = source.normalize('NFKC')
|
||||
if (isFreightAiExistingOnlyInstruction(message)) {
|
||||
mode = 'EXISTING_ONLY'
|
||||
} else if (COMPARE_NEW_PATTERN.test(message)) {
|
||||
mode = 'COMPARE_NEW'
|
||||
}
|
||||
}
|
||||
return mode
|
||||
}
|
||||
|
||||
function normalized(value: string | null | undefined) {
|
||||
return normalizeWarehouseName(value).toLowerCase()
|
||||
}
|
||||
@ -76,17 +99,23 @@ function mergeCourierRule(
|
||||
|
||||
export function parseFreightAiChatInstructions(input: {
|
||||
message: string
|
||||
history?: readonly string[]
|
||||
existingCouriers: readonly FreightCourierOption[]
|
||||
extraCourierNames?: readonly string[]
|
||||
orderShopSites?: readonly (string | null)[]
|
||||
}): FreightAiParsedChatInstructions {
|
||||
const message = input.message.normalize('NFKC').trim()
|
||||
const existingOnly = isFreightAiExistingOnlyInstruction(message)
|
||||
const messages = [
|
||||
...(input.history ?? []),
|
||||
input.message,
|
||||
].map((message) => message.normalize('NFKC').trim()).filter(Boolean)
|
||||
const existingOnly = resolveFreightAiConversationMode(
|
||||
messages,
|
||||
'COMPARE_NEW',
|
||||
) === 'EXISTING_ONLY'
|
||||
const manualRules: FreightAiManualRules = {
|
||||
excludedProvinces: [],
|
||||
couriers: [],
|
||||
}
|
||||
const notices: string[] = []
|
||||
const courierNames = [...new Set([
|
||||
...input.existingCouriers.map((courier) => courier.expressName),
|
||||
...(input.extraCourierNames ?? []),
|
||||
@ -105,18 +134,33 @@ export function parseFreightAiChatInstructions(input: {
|
||||
.map((site) => site.trim()),
|
||||
])]
|
||||
|
||||
// 按句号、分号、逗号拆分,但保留“上海、浙江不发”中的顿号列表。
|
||||
const clauses = message
|
||||
.split(/[。;;,,\n]+/)
|
||||
.map((clause) => clause.trim())
|
||||
.filter(Boolean)
|
||||
for (const source of messages) {
|
||||
// 按句号、分号和逗号拆分,但保留“上海、浙江不发”中的顿号列表。
|
||||
const clauses = source
|
||||
.split(/[。;;,,\n]+|(?:但是|但)/u)
|
||||
.map((clause) => clause.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
for (const clause of clauses) {
|
||||
if (/^(?:为什么|哪些|哪个|哪里)/.test(clause)) continue
|
||||
const courierName = matchingCourier(clause, courierNames)
|
||||
if (NEGATIVE_SHIPPING_PATTERN.test(clause)) {
|
||||
for (const clause of clauses) {
|
||||
if (/^(?:为什么|哪些|哪个|哪里)/.test(clause)) continue
|
||||
const courierName = matchingCourier(clause, courierNames)
|
||||
const provinces = matchingProvinces(clause)
|
||||
if (provinces.length > 0) {
|
||||
|
||||
if (POSITIVE_SHIPPING_PATTERN.test(clause) && provinces.length > 0) {
|
||||
if (courierName) {
|
||||
const rule = mergeCourierRule(manualRules.couriers, courierName)
|
||||
rule.excludedProvinces = rule.excludedProvinces.filter(
|
||||
(province) => !provinces.includes(province),
|
||||
)
|
||||
} else {
|
||||
manualRules.excludedProvinces = manualRules.excludedProvinces.filter(
|
||||
(province) => !provinces.includes(province),
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (NEGATIVE_SHIPPING_PATTERN.test(clause) && provinces.length > 0) {
|
||||
if (courierName) {
|
||||
const rule = mergeCourierRule(manualRules.couriers, courierName)
|
||||
for (const province of provinces) {
|
||||
@ -124,36 +168,57 @@ export function parseFreightAiChatInstructions(input: {
|
||||
rule.excludedProvinces.push(province)
|
||||
}
|
||||
}
|
||||
notices.push(`对话限定:${courierName} 不发货 ${provinces.join('、')}`)
|
||||
} else {
|
||||
for (const province of provinces) {
|
||||
if (!manualRules.excludedProvinces.includes(province)) {
|
||||
manualRules.excludedProvinces.push(province)
|
||||
}
|
||||
}
|
||||
notices.push(`对话限定:${provinces.join('、')} 不发货`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (courierName && PLATFORM_RESTRICTION_PATTERN.test(clause)) {
|
||||
const matchedPlatforms = matchingPlatforms(clause, platforms)
|
||||
if (matchedPlatforms.length > 0) {
|
||||
if (courierName && PLATFORM_CLEAR_PATTERN.test(clause)) {
|
||||
const rule = mergeCourierRule(manualRules.couriers, courierName)
|
||||
for (const platform of matchedPlatforms) {
|
||||
if (!rule.allowedShopSites.includes(platform)) {
|
||||
rule.allowedShopSites.push(platform)
|
||||
rule.allowedShopSites = []
|
||||
continue
|
||||
}
|
||||
|
||||
if (courierName && PLATFORM_RESTRICTION_PATTERN.test(clause)) {
|
||||
const matchedPlatforms = matchingPlatforms(clause, platforms)
|
||||
if (matchedPlatforms.length > 0) {
|
||||
const rule = mergeCourierRule(manualRules.couriers, courierName)
|
||||
if (PLATFORM_REPLACEMENT_PATTERN.test(clause)) {
|
||||
rule.allowedShopSites = [...matchedPlatforms]
|
||||
} else {
|
||||
for (const platform of matchedPlatforms) {
|
||||
if (!rule.allowedShopSites.includes(platform)) {
|
||||
rule.allowedShopSites.push(platform)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
notices.push(`对话限定:${courierName} 只发平台 ${matchedPlatforms.join('、')}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (existingOnly) {
|
||||
notices.unshift('对话识别:本次只计算现有快递')
|
||||
}
|
||||
manualRules.couriers = manualRules.couriers.filter((rule) => (
|
||||
rule.excludedProvinces.length > 0 || rule.allowedShopSites.length > 0
|
||||
))
|
||||
const notices = [
|
||||
...(existingOnly ? ['对话识别:本次只计算现有快递'] : []),
|
||||
...(manualRules.excludedProvinces.length > 0
|
||||
? [`对话限定:${manualRules.excludedProvinces.join('、')} 不发货`]
|
||||
: []),
|
||||
...manualRules.couriers.flatMap((rule) => [
|
||||
...(rule.excludedProvinces.length > 0
|
||||
? [`对话限定:${rule.expressName} 不发货 ${rule.excludedProvinces.join('、')}`]
|
||||
: []),
|
||||
...(rule.allowedShopSites.length > 0
|
||||
? [`对话限定:${rule.expressName} 只发平台 ${rule.allowedShopSites.join('、')}`]
|
||||
: []),
|
||||
]),
|
||||
]
|
||||
|
||||
return {
|
||||
existingOnly,
|
||||
|
||||
@ -349,7 +349,68 @@ describe('freight calculation', () => {
|
||||
missingProvinces: [],
|
||||
})
|
||||
expect(result.couriers[0].exclusionReasons[0]).toContain('超出限体积')
|
||||
expect(result.warnings).toContain('当前商品没有可计算快递,区域平均运费为空')
|
||||
expect(result.warnings).toContain('当前商品所有省份都没有可计算快递,区域平均运费为空')
|
||||
})
|
||||
|
||||
it('同一省份只对有报价快递取平均,缺省报价的快递在其他省继续计算', () => {
|
||||
const shipmentShareRows = FREIGHT_CALCULATION_PROVINCES.map(({ province, region }) => ({
|
||||
province,
|
||||
shipmentCount: 1,
|
||||
totalShipment: 29,
|
||||
shipmentShare: 0.01,
|
||||
region,
|
||||
regionShare: region === '一区' ? 0.214 : region === '二区' ? 0.485 : region === '三区' ? 0.251 : 0.05,
|
||||
}))
|
||||
const fourRegionRates = (['甘肃', '内蒙', '宁夏'] as const).map((province) => (
|
||||
rate({
|
||||
ruleId: `jitu-${province}`,
|
||||
expressName: '派雅极兔',
|
||||
province,
|
||||
waybillFee: 6,
|
||||
feeRate: 0,
|
||||
})
|
||||
))
|
||||
const yundaRates = (['甘肃', '内蒙', '宁夏', '青海'] as const).map((province) => (
|
||||
rate({
|
||||
ruleId: `yunda-${province}`,
|
||||
expressName: '派雅韵达',
|
||||
province,
|
||||
waybillFee: province === '青海' ? 8 : 6,
|
||||
feeRate: 0,
|
||||
})
|
||||
))
|
||||
const result = buildFreightCalculation({
|
||||
archive: {
|
||||
barcode: 'PARTIAL-RATE',
|
||||
productTag: '仓库-测试代发仓',
|
||||
inOutWarehouse: '测试代发仓',
|
||||
weight: 2.2,
|
||||
length: 48,
|
||||
width: 43,
|
||||
height: 11,
|
||||
volume: 22704,
|
||||
},
|
||||
warehouseName: '测试代发仓',
|
||||
couriers: [
|
||||
{ expressName: '派雅极兔' },
|
||||
{ expressName: '派雅韵达' },
|
||||
],
|
||||
rates: [...fourRegionRates, ...yundaRates],
|
||||
shipmentShareRows,
|
||||
now: new Date('2026-10-29T08:00:00.000Z'),
|
||||
})
|
||||
|
||||
expect(result.regionAverages.find((region) => region.region === '四区')).toMatchObject({
|
||||
provinceCount: 4,
|
||||
coveredShare: 0.04,
|
||||
courierCount: 2,
|
||||
averageCost: 6.5,
|
||||
})
|
||||
expect(result.couriers.find((courier) => courier.expressName === '派雅极兔')?.status)
|
||||
.toBe('MISSING_RATE')
|
||||
expect(result.couriers.find((courier) => courier.expressName === '派雅韵达')?.provinceCosts)
|
||||
.toHaveLength(4)
|
||||
expect(result.warnings.join(';')).toContain('缺少省份不参与该省平均')
|
||||
})
|
||||
|
||||
it('区域内省份运费先乘全国占比求和,再除以区域占比', () => {
|
||||
|
||||
@ -172,6 +172,8 @@ export type CourierFreightCost = {
|
||||
export type RegionFreightAverage = {
|
||||
region: FreightRegion
|
||||
regionShare: number
|
||||
coveredShare: number
|
||||
provinceCount: number
|
||||
courierCount: number
|
||||
averageCost: number | null
|
||||
}
|
||||
@ -1061,14 +1063,21 @@ export function calculateProvinceShareFreight(
|
||||
provinceCosts: readonly Pick<ProvinceFreightCost, 'province' | 'fee'>[],
|
||||
shareByProvince: ReadonlyMap<string, Pick<ProvinceShipmentShareRow, 'shipmentShare'>>,
|
||||
) {
|
||||
if (provinceCosts.length !== FREIGHT_CALCULATION_PROVINCES.length) return null
|
||||
if (provinceCosts.length === 0) return null
|
||||
let total = 0
|
||||
let coveredShare = 0
|
||||
for (const cost of provinceCosts) {
|
||||
const share = finiteNumber(shareByProvince.get(cost.province)?.shipmentShare)
|
||||
if (share === null) return null
|
||||
total += cost.fee * share
|
||||
coveredShare += share
|
||||
}
|
||||
return rounded(total)
|
||||
if (coveredShare <= 0) return null
|
||||
return rounded(
|
||||
provinceCosts.length === FREIGHT_CALCULATION_PROVINCES.length
|
||||
? total
|
||||
: total / coveredShare,
|
||||
)
|
||||
}
|
||||
|
||||
export function freightRateValidity(
|
||||
@ -1368,15 +1377,24 @@ function buildIndexedFreightCalculation(
|
||||
? shareByProvince.get(firstProvince)?.regionShare
|
||||
: undefined
|
||||
if (
|
||||
regionProvinceCosts.length !== regionRows.length
|
||||
regionProvinceCosts.length === 0
|
||||
|| regionShare === null
|
||||
|| regionShare === undefined
|
||||
) {
|
||||
return [region, null]
|
||||
}
|
||||
const coveredShare = regionProvinceCosts.reduce((sum, cost) => (
|
||||
sum + cost.provinceShare
|
||||
), 0)
|
||||
return [
|
||||
region,
|
||||
calculateRegionalFreight(regionProvinceCosts, shareByProvince, regionShare),
|
||||
calculateRegionalFreight(
|
||||
regionProvinceCosts,
|
||||
shareByProvince,
|
||||
regionProvinceCosts.length === regionRows.length
|
||||
? regionShare
|
||||
: coveredShare,
|
||||
),
|
||||
]
|
||||
})) as Record<FreightRegion, number | null>
|
||||
const nationalCost = calculateProvinceShareFreight(provinceCosts, shareByProvince)
|
||||
@ -1426,7 +1444,7 @@ function buildIndexedFreightCalculation(
|
||||
&& !courier.exclusionReasons.some((reason) => reason.includes('报价已过期'))
|
||||
)).length
|
||||
if (missingCourierCount > 0) {
|
||||
warnings.push(`${missingCourierCount} 个快递缺少省份费率,已从区域平均中剔除`)
|
||||
warnings.push(`${missingCourierCount} 个快递缺少部分省份费率;缺少省份不参与该省平均,其他省份继续计算`)
|
||||
}
|
||||
if (expiredRateCourierCount > 0) {
|
||||
warnings.push(`${expiredRateCourierCount} 个快递正常费率报价已过期,不参与计算`)
|
||||
@ -1434,31 +1452,67 @@ function buildIndexedFreightCalculation(
|
||||
if (notApplicableCourierCount > 0) {
|
||||
warnings.push(`${notApplicableCourierCount} 个快递因名称、商品编码/标签、重量、体积、边长或费率区间过滤,不参与平均`)
|
||||
}
|
||||
if (calculatedCouriers.length === 0) {
|
||||
warnings.push('当前商品没有可计算快递,区域平均运费为空')
|
||||
}
|
||||
|
||||
const contributingCouriers = couriers.filter((courier) => (
|
||||
courier.status !== 'NOT_APPLICABLE'
|
||||
))
|
||||
const averageProvinceCosts = FREIGHT_CALCULATION_PROVINCES.flatMap(({ province }) => {
|
||||
const costs = contributingCouriers.flatMap((courier) => {
|
||||
const cost = courier.provinceCosts.find((row) => row.province === province)
|
||||
return cost ? [cost] : []
|
||||
})
|
||||
if (costs.length === 0) return []
|
||||
return [{
|
||||
province,
|
||||
fee: costs.reduce((sum, cost) => sum + cost.fee, 0) / costs.length,
|
||||
}]
|
||||
})
|
||||
const regionAverages = FREIGHT_REGIONS.map<RegionFreightAverage>((region) => {
|
||||
const firstProvince = FREIGHT_CALCULATION_PROVINCES
|
||||
.find((province) => province.region === region)?.province
|
||||
const regionRows = FREIGHT_CALCULATION_PROVINCES
|
||||
.filter((province) => province.region === region)
|
||||
const firstProvince = regionRows[0]?.province
|
||||
const regionShare = firstProvince
|
||||
? shareByProvince.get(firstProvince)?.regionShare
|
||||
: undefined
|
||||
const costs = calculatedCouriers.flatMap((courier) => {
|
||||
const cost = courier.regionCosts[region]
|
||||
return cost === null ? [] : [cost]
|
||||
})
|
||||
const provinceAverageCosts = averageProvinceCosts.filter((cost) => (
|
||||
regionRows.some((row) => row.province === cost.province)
|
||||
))
|
||||
const coveredShare = provinceAverageCosts.reduce((sum, cost) => (
|
||||
sum + (shareByProvince.get(cost.province)?.shipmentShare ?? 0)
|
||||
), 0)
|
||||
const weightedTotal = provinceAverageCosts.reduce((sum, cost) => (
|
||||
sum + cost.fee * (shareByProvince.get(cost.province)?.shipmentShare ?? 0)
|
||||
), 0)
|
||||
const courierCount = new Set(contributingCouriers.flatMap((courier) => (
|
||||
provinceAverageCosts.some((cost) => (
|
||||
courier.provinceCosts.some((row) => row.province === cost.province)
|
||||
))
|
||||
? [courier.expressName]
|
||||
: []
|
||||
))).size
|
||||
const denominator = provinceAverageCosts.length === regionRows.length
|
||||
? regionShare ?? 0
|
||||
: coveredShare
|
||||
return {
|
||||
region,
|
||||
regionShare: regionShare ?? 0,
|
||||
courierCount: costs.length,
|
||||
averageCost: averageCourierRegionalFreight(costs),
|
||||
coveredShare: rounded(coveredShare),
|
||||
provinceCount: provinceAverageCosts.length,
|
||||
courierCount,
|
||||
averageCost: provinceAverageCosts.length > 0 && denominator > 0
|
||||
? rounded(weightedTotal / denominator)
|
||||
: null,
|
||||
}
|
||||
})
|
||||
const nationalAverage = averageCourierRegionalFreight(
|
||||
calculatedCouriers.flatMap((courier) => (
|
||||
courier.nationalCost === null ? [] : [courier.nationalCost]
|
||||
)),
|
||||
if (calculatedCouriers.length === 0) {
|
||||
if (regionAverages.every((region) => region.averageCost === null)) {
|
||||
warnings.push('当前商品所有省份都没有可计算快递,区域平均运费为空')
|
||||
} else {
|
||||
warnings.push('当前商品没有完整覆盖 29 省的快递,区域平均仅使用各省有有效报价的快递')
|
||||
}
|
||||
}
|
||||
const nationalAverage = calculateProvinceShareFreight(
|
||||
averageProvinceCosts,
|
||||
shareByProvince,
|
||||
)
|
||||
|
||||
return {
|
||||
|
||||
@ -125,4 +125,19 @@ describe('FreightAiComparisonService', () => {
|
||||
expect(result.parsed.quoteSheet).toBeNull()
|
||||
expect(result.result.warnings.join(';')).toContain('只计算现有快递')
|
||||
})
|
||||
|
||||
it('沿用前一轮资料和规则,并根据新的纠正重新生成', async () => {
|
||||
const service = new FreightAiComparisonService()
|
||||
const result = await service.analyze({
|
||||
orderBuffer: orderBuffer(),
|
||||
message: '对,上海应该不发',
|
||||
history: ['测算睢宁仓,只计算现有快递'],
|
||||
now: new Date('2026-10-28T00:00:00.000Z'),
|
||||
mode: 'EXISTING_ONLY',
|
||||
})
|
||||
|
||||
expect(result.result.mode).toBe('EXISTING_ONLY')
|
||||
expect(result.result.summary.comparableShipmentCount).toBe(0)
|
||||
expect(result.result.warnings.join(';')).toContain('上海 不发货')
|
||||
})
|
||||
})
|
||||
|
||||
@ -20,10 +20,10 @@ function result(barcode: string, fee: number): FreightCalculationResult {
|
||||
nationalAverage: fee,
|
||||
warnings: [],
|
||||
regionAverages: [
|
||||
{ region: '一区', regionShare: 0.214, courierCount: 1, averageCost: fee },
|
||||
{ region: '二区', regionShare: 0.485, courierCount: 1, averageCost: fee + 1 },
|
||||
{ region: '三区', regionShare: 0.251, courierCount: 1, averageCost: fee + 2 },
|
||||
{ region: '四区', regionShare: 0.05, courierCount: 1, averageCost: fee + 3 },
|
||||
{ region: '一区', regionShare: 0.214, coveredShare: 0.214, provinceCount: 4, courierCount: 1, averageCost: fee },
|
||||
{ region: '二区', regionShare: 0.485, coveredShare: 0.485, provinceCount: 10, courierCount: 1, averageCost: fee + 1 },
|
||||
{ region: '三区', regionShare: 0.251, coveredShare: 0.251, provinceCount: 10, courierCount: 1, averageCost: fee + 2 },
|
||||
{ region: '四区', regionShare: 0.05, coveredShare: 0.05, provinceCount: 5, courierCount: 1, averageCost: fee + 3 },
|
||||
],
|
||||
couriers: [{
|
||||
expressName: '测试快递',
|
||||
|
||||
@ -17,8 +17,8 @@ import {
|
||||
type FreightAiQuoteImport,
|
||||
} from '@/lib/freight-ai-comparison-import'
|
||||
import {
|
||||
isFreightAiExistingOnlyInstruction,
|
||||
parseFreightAiChatInstructions,
|
||||
resolveFreightAiConversationMode,
|
||||
} from '@/lib/freight-ai-chat-instructions'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import { freightConfigRepository } from '@/server/repositories/freight-config.repository'
|
||||
@ -114,15 +114,20 @@ export class FreightAiComparisonService {
|
||||
quoteBuffer?: Buffer | null
|
||||
orderBuffer: Buffer
|
||||
message: string
|
||||
history?: readonly string[]
|
||||
now?: Date
|
||||
orderDetailLimit?: number | null
|
||||
mode?: FreightAiComparisonMode
|
||||
}): Promise<FreightAiComparisonResponse> {
|
||||
const now = input.now ?? new Date()
|
||||
const explicitExistingOnly = isFreightAiExistingOnlyInstruction(input.message)
|
||||
const mode = explicitExistingOnly
|
||||
? 'EXISTING_ONLY'
|
||||
: input.mode ?? (input.quoteBuffer ? 'COMPARE_NEW' : 'EXISTING_ONLY')
|
||||
const instructionMessages = [
|
||||
...(input.history ?? []),
|
||||
input.message,
|
||||
]
|
||||
const mode = resolveFreightAiConversationMode(
|
||||
instructionMessages,
|
||||
input.mode ?? (input.quoteBuffer ? 'COMPARE_NEW' : 'EXISTING_ONLY'),
|
||||
)
|
||||
if (mode === 'COMPARE_NEW' && !input.quoteBuffer) {
|
||||
throw new AppError(ErrorCode.VALIDATION_REQUIRED_FIELD, '新快递比价请上传报价表')
|
||||
}
|
||||
@ -176,11 +181,14 @@ export class FreightAiComparisonService {
|
||||
warehouseCandidates.map((candidate) => [normalizeWarehouseName(candidate), candidate]),
|
||||
).values()]
|
||||
const warehouseName = candidateMentioned(
|
||||
input.message,
|
||||
instructionMessages.join('\n'),
|
||||
warehouseCandidates,
|
||||
normalizeWarehouseName,
|
||||
) ?? (uniqueWarehouseCandidates.length === 1 ? uniqueWarehouseCandidates[0] : null)
|
||||
?? warehouseFromMessage(input.message)
|
||||
?? [...instructionMessages]
|
||||
.reverse()
|
||||
.map(warehouseFromMessage)
|
||||
.find((value) => value !== null)
|
||||
if (!warehouseName) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_REQUIRED_FIELD,
|
||||
@ -194,7 +202,7 @@ export class FreightAiComparisonService {
|
||||
let matchingQuoteRows: FreightAiQuoteRowInput[] = []
|
||||
if (mode === 'COMPARE_NEW' && quote) {
|
||||
const detectedCourierName = candidateMentioned(
|
||||
input.message,
|
||||
instructionMessages.slice().reverse().join('\n'),
|
||||
quote.courierNames,
|
||||
normalizeWarehouseName,
|
||||
) ?? (quote.courierNames.length === 1 ? quote.courierNames[0] : null)
|
||||
@ -292,6 +300,7 @@ export class FreightAiComparisonService {
|
||||
}
|
||||
const parsedInstructions = parseFreightAiChatInstructions({
|
||||
message: input.message,
|
||||
history: input.history,
|
||||
existingCouriers,
|
||||
extraCourierNames: quote?.courierNames,
|
||||
orderShopSites: enrichedOrders.map((order) => order.shopSite),
|
||||
@ -306,7 +315,9 @@ export class FreightAiComparisonService {
|
||||
existingRates,
|
||||
newRates: mode === 'COMPARE_NEW' ? matchingQuoteRows.map((row) => row.rate) : [],
|
||||
manualRules: parsedInstructions.manualRules,
|
||||
monthlyOrderCount: parseMonthlyOrderCount(input.message),
|
||||
monthlyOrderCount: [...instructionMessages].reverse()
|
||||
.map(parseMonthlyOrderCount)
|
||||
.find((value) => value !== null) ?? null,
|
||||
now,
|
||||
})
|
||||
const warnings = [
|
||||
|
||||
@ -74,6 +74,11 @@ export function buildFreightCalculationExport(
|
||||
体积cm3: result.volume,
|
||||
物流匹配快递数: result.courierCount,
|
||||
可计算快递数: result.calculatedCourierCount,
|
||||
测算状态: result.calculatedCourierCount > 0
|
||||
? '完整覆盖'
|
||||
: result.regionAverages.some((region) => region.averageCost !== null)
|
||||
? '部分报价计算'
|
||||
: '无有效报价',
|
||||
全国平均运费: result.nationalAverage,
|
||||
...Object.fromEntries(FREIGHT_REGIONS.map((region) => [
|
||||
`${region}平均运费`,
|
||||
@ -88,11 +93,13 @@ export function buildFreightCalculationExport(
|
||||
仓库: result.warehouseName,
|
||||
区域: region.region,
|
||||
区域占比: region.regionShare,
|
||||
有效省份占比: region.coveredShare,
|
||||
有效省份数: region.provinceCount,
|
||||
参与平均快递数: region.courierCount,
|
||||
'区域平均运费(元)': region.averageCost,
|
||||
全国平均运费: result.nationalAverage,
|
||||
}))
|
||||
)), [24, 18, 10, 12, 16, 18, 16])
|
||||
)), [24, 18, 10, 12, 14, 14, 18, 18, 16])
|
||||
|
||||
addSheet(workbook, '快递区域运费', results.flatMap((result) => (
|
||||
result.couriers.map((courier) => ({
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user