merge: bring 24h pickup menu and freight export updates into main
This commit is contained in:
commit
7ffc6d11bd
@ -0,0 +1,159 @@
|
||||
import { Readable } from 'node:stream'
|
||||
|
||||
const mockHandleRequest = jest.fn()
|
||||
const mockJsonError = jest.fn()
|
||||
const mockGetUserAccess = jest.fn()
|
||||
const mockOpenExport = jest.fn()
|
||||
|
||||
jest.mock('@/server/core/response', () => ({
|
||||
handleRequest: (...args: unknown[]) => mockHandleRequest(...args),
|
||||
jsonError: (...args: unknown[]) => mockJsonError(...args),
|
||||
}))
|
||||
|
||||
jest.mock('@/server/services/supply-chain-permission-settings.service', () => ({
|
||||
supplyChainPermissionSettingsService: {
|
||||
getUserAccess: (...args: unknown[]) => mockGetUserAccess(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
jest.mock('@/server/services/freight-ai-raw-export.service', () => ({
|
||||
freightAiRawExportService: {
|
||||
open: (...args: unknown[]) => mockOpenExport(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
const { POST } = require('./route')
|
||||
|
||||
function request(body: Record<string, unknown> = {
|
||||
message: '帮我导出昨天的发货数据',
|
||||
}) {
|
||||
return {
|
||||
headers: new Headers({ 'content-type': 'application/json' }),
|
||||
json: async () => body,
|
||||
}
|
||||
}
|
||||
|
||||
function context(user: Record<string, unknown>, requestId = 'req-raw-export') {
|
||||
return {
|
||||
requestId,
|
||||
user,
|
||||
}
|
||||
}
|
||||
|
||||
describe('POST freight AI raw export', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockJsonError.mockImplementation((code, message, status, requestId) => ({
|
||||
code,
|
||||
message,
|
||||
status,
|
||||
requestId,
|
||||
}))
|
||||
mockGetUserAccess.mockResolvedValue({
|
||||
view: true,
|
||||
download: true,
|
||||
edit: true,
|
||||
})
|
||||
mockOpenExport.mockResolvedValue({
|
||||
fileName: '快递原始发货数据-昨天-全部仓库-20261204-1034.xlsx',
|
||||
stream: Readable.from([Buffer.from('xlsx-content')]),
|
||||
completion: Promise.resolve({}),
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects ordinary users before opening the data source', async () => {
|
||||
mockHandleRequest.mockImplementation(async (_request: unknown, handler: (ctx: unknown) => unknown) => (
|
||||
handler(context({
|
||||
id: 'user-1',
|
||||
role: 'USER',
|
||||
businessRoles: ['OPERATIONS'],
|
||||
status: 'ACTIVE',
|
||||
}))
|
||||
))
|
||||
|
||||
const response = await POST(request() as never)
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 403,
|
||||
message: 'AI 比价仅对管理员和经管开放',
|
||||
})
|
||||
expect(mockOpenExport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects AI users without freight download permission', async () => {
|
||||
mockHandleRequest.mockImplementation(async (_request: unknown, handler: (ctx: unknown) => unknown) => (
|
||||
handler(context({
|
||||
id: 'management-1',
|
||||
role: 'USER',
|
||||
businessRoles: ['MANAGEMENT'],
|
||||
status: 'ACTIVE',
|
||||
}))
|
||||
))
|
||||
mockGetUserAccess.mockResolvedValue({
|
||||
view: true,
|
||||
download: false,
|
||||
edit: true,
|
||||
})
|
||||
|
||||
const response = await POST(request() as never)
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 403,
|
||||
message: '没有快递维护下载权限',
|
||||
})
|
||||
expect(mockOpenExport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('streams a private XLSX file for allowed users', async () => {
|
||||
mockHandleRequest.mockImplementation(async (_request: unknown, handler: (ctx: unknown) => unknown) => (
|
||||
handler(context({
|
||||
id: 'management-1',
|
||||
role: 'USER',
|
||||
businessRoles: ['MANAGEMENT'],
|
||||
status: 'ACTIVE',
|
||||
}))
|
||||
))
|
||||
|
||||
const response = await POST(request({
|
||||
message: '帮我导出昨天的发货数据',
|
||||
history: ['之前的问题'],
|
||||
}) as never)
|
||||
|
||||
expect(mockGetUserAccess).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'management-1' }),
|
||||
'freightMaintenance',
|
||||
)
|
||||
expect(mockOpenExport).toHaveBeenCalledWith({
|
||||
message: '帮我导出昨天的发货数据',
|
||||
history: ['之前的问题'],
|
||||
})
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('Content-Type')).toContain('spreadsheetml.sheet')
|
||||
expect(response.headers.get('Content-Disposition')).toContain(
|
||||
encodeURIComponent('快递原始发货数据-昨天-全部仓库-20261204-1034.xlsx'),
|
||||
)
|
||||
expect(response.headers.get('Cache-Control')).toContain('no-store')
|
||||
})
|
||||
|
||||
it('rejects malformed history before opening the data source', async () => {
|
||||
mockHandleRequest.mockImplementation(async (_request: unknown, handler: (ctx: unknown) => unknown) => (
|
||||
handler(context({
|
||||
id: 'management-1',
|
||||
role: 'USER',
|
||||
businessRoles: ['MANAGEMENT'],
|
||||
status: 'ACTIVE',
|
||||
}))
|
||||
))
|
||||
|
||||
const response = await POST(request({
|
||||
message: '帮我导出昨天的发货数据',
|
||||
history: [''],
|
||||
}) as never)
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 400,
|
||||
message: '对话历史格式不正确',
|
||||
})
|
||||
expect(mockOpenExport).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,83 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { Readable } from 'node:stream'
|
||||
import { canAccessFreightAiComparison } from '@/lib/freight-maintenance-permissions'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError } from '@/server/core/response'
|
||||
import { freightAiRawExportService } from '@/server/services/freight-ai-raw-export.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
|
||||
const MAX_MESSAGE_LENGTH = 2_000
|
||||
|
||||
export const runtime = 'nodejs'
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const maxDuration = 3_600
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
if (!canAccessFreightAiComparison(ctx.user)) {
|
||||
return jsonError(
|
||||
ErrorCode.AUTH_PERMISSION_DENIED,
|
||||
'AI 比价仅对管理员和经管开放',
|
||||
403,
|
||||
ctx.requestId,
|
||||
)
|
||||
}
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
ctx.user,
|
||||
'freightMaintenance',
|
||||
)
|
||||
if (!access.download) {
|
||||
return jsonError(
|
||||
ErrorCode.AUTH_PERMISSION_DENIED,
|
||||
'没有快递维护下载权限',
|
||||
403,
|
||||
ctx.requestId,
|
||||
)
|
||||
}
|
||||
|
||||
const payload = await request.json().catch(() => null) as {
|
||||
message?: unknown
|
||||
history?: unknown
|
||||
} | null
|
||||
const message = typeof payload?.message === 'string' ? payload.message.trim() : ''
|
||||
if (!message) {
|
||||
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请输入导出需求', 400, ctx.requestId)
|
||||
}
|
||||
if (message.length > MAX_MESSAGE_LENGTH) {
|
||||
return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, '导出需求不能超过 2000 字', 400, ctx.requestId)
|
||||
}
|
||||
const history = payload?.history
|
||||
if (
|
||||
history !== undefined
|
||||
&& (
|
||||
!Array.isArray(history)
|
||||
|| history.length > 50
|
||||
|| history.some((item) => (
|
||||
typeof item !== 'string'
|
||||
|| item.trim().length === 0
|
||||
|| item.length > MAX_MESSAGE_LENGTH
|
||||
))
|
||||
)
|
||||
) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '对话历史格式不正确', 400, ctx.requestId)
|
||||
}
|
||||
|
||||
const result = await freightAiRawExportService.open({
|
||||
message,
|
||||
history: (history as string[] | undefined)?.map((item) => item.trim()),
|
||||
})
|
||||
return new NextResponse(
|
||||
Readable.toWeb(result.stream) as ReadableStream<Uint8Array>,
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(result.fileName)}`,
|
||||
'Cache-Control': 'private, no-store',
|
||||
'X-Accel-Buffering': 'no',
|
||||
'X-Request-Id': ctx.requestId,
|
||||
},
|
||||
},
|
||||
)
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -84,7 +84,7 @@ describe('SupplyChainSidebar', () => {
|
||||
).toHaveAttribute('aria-current', 'page')
|
||||
})
|
||||
|
||||
it('shows the 24h accessory version below the finished-product entry', () => {
|
||||
it('shows the 24h accessory version between the finished version and limit management', () => {
|
||||
usePathnameMock.mockReturnValue(
|
||||
'/supply-chain/management/pickup-24h-timeliness/accessory',
|
||||
)
|
||||
@ -92,14 +92,21 @@ describe('SupplyChainSidebar', () => {
|
||||
render(<SupplyChainSidebar visibleTargetKeys={[
|
||||
'pickup24hTimeliness',
|
||||
'pickup24hTimelinessAccessory',
|
||||
'limitManagement',
|
||||
]} />)
|
||||
|
||||
const finishedVersion = screen.getByRole('link', { name: '24h揽收及时率' })
|
||||
const accessoryVersion = screen.getByRole('link', { name: '24h揽收及时率(配件版)' })
|
||||
const limitManagement = screen.getByRole('link', { name: '限价管理' })
|
||||
expect(
|
||||
finishedVersion.compareDocumentPosition(accessoryVersion)
|
||||
& Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
).toBeTruthy()
|
||||
expect(
|
||||
accessoryVersion.compareDocumentPosition(limitManagement)
|
||||
& Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
).toBeTruthy()
|
||||
expect(accessoryVersion.closest('.sc-submenu-children')).toBeNull()
|
||||
expect(accessoryVersion).toHaveAttribute('aria-current', 'page')
|
||||
})
|
||||
|
||||
|
||||
@ -133,10 +133,11 @@ describe('supply chain menu', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('nests the 24h accessory version below the finished-product entry', () => {
|
||||
it('places the 24h accessory version between the finished version and limit management', () => {
|
||||
const items = flattenSupplyChainMenu(filterSupplyChainMenu([
|
||||
'pickup24hTimeliness',
|
||||
'pickup24hTimelinessAccessory',
|
||||
'limitManagement',
|
||||
]))
|
||||
|
||||
expect(items).toEqual([
|
||||
@ -147,9 +148,14 @@ describe('supply chain menu', () => {
|
||||
}),
|
||||
expect.objectContaining({
|
||||
label: '24h揽收及时率(配件版)',
|
||||
path: '经营管理 / 24h揽收及时率 / 24h揽收及时率(配件版)',
|
||||
path: '经营管理 / 24h揽收及时率(配件版)',
|
||||
route: '/supply-chain/management/pickup-24h-timeliness/accessory',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
label: '限价管理',
|
||||
path: '经营管理 / 限价管理',
|
||||
route: '/supply-chain/management/custom-table',
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
@ -140,11 +140,6 @@ export const SUPPLY_CHAIN_MENU: SupplyChainMenuModule[] = [
|
||||
route: '/supply-chain/management/modular-product-processing-orders',
|
||||
targetKey: 'modularProductProcessingOrders',
|
||||
},
|
||||
{
|
||||
label: '限价管理',
|
||||
route: '/supply-chain/management/custom-table',
|
||||
targetKey: 'limitManagement',
|
||||
},
|
||||
{
|
||||
label: '快递维护',
|
||||
route: '/supply-chain/management/freight-maintenance',
|
||||
@ -200,13 +195,16 @@ export const SUPPLY_CHAIN_MENU: SupplyChainMenuModule[] = [
|
||||
label: '24h揽收及时率',
|
||||
route: '/supply-chain/management/pickup-24h-timeliness',
|
||||
targetKey: 'pickup24hTimeliness',
|
||||
children: [
|
||||
{
|
||||
label: '24h揽收及时率(配件版)',
|
||||
route: '/supply-chain/management/pickup-24h-timeliness/accessory',
|
||||
targetKey: 'pickup24hTimelinessAccessory',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: '24h揽收及时率(配件版)',
|
||||
route: '/supply-chain/management/pickup-24h-timeliness/accessory',
|
||||
targetKey: 'pickup24hTimelinessAccessory',
|
||||
},
|
||||
{
|
||||
label: '限价管理',
|
||||
route: '/supply-chain/management/custom-table',
|
||||
targetKey: 'limitManagement',
|
||||
},
|
||||
{
|
||||
label: '每日快递承运量看板',
|
||||
|
||||
@ -0,0 +1,103 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { FreightAiComparisonTab } from './FreightAiComparisonTab'
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalCreateObjectURL = URL.createObjectURL
|
||||
const originalRevokeObjectURL = URL.revokeObjectURL
|
||||
|
||||
function fileResponse() {
|
||||
return {
|
||||
ok: true,
|
||||
headers: new Headers({
|
||||
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent('快递原始发货数据-昨天-全部仓库.xlsx')}`,
|
||||
}),
|
||||
blob: async () => new Blob(['xlsx-content']),
|
||||
} as Response
|
||||
}
|
||||
|
||||
describe('FreightAiComparisonTab raw data export', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear()
|
||||
Object.defineProperty(URL, 'createObjectURL', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: jest.fn(() => 'blob:freight-raw-export'),
|
||||
})
|
||||
Object.defineProperty(URL, 'revokeObjectURL', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: jest.fn(),
|
||||
})
|
||||
jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
globalThis.fetch = originalFetch
|
||||
URL.createObjectURL = originalCreateObjectURL
|
||||
URL.revokeObjectURL = originalRevokeObjectURL
|
||||
})
|
||||
|
||||
it('routes a data-only request to raw export without calling the comparison engine', async () => {
|
||||
const fetchMock = jest.fn().mockResolvedValue(fileResponse())
|
||||
globalThis.fetch = fetchMock
|
||||
render(
|
||||
<FreightAiComparisonTab
|
||||
canOperate
|
||||
canDownload
|
||||
chatStorageKey="freight-ai-raw-export-test"
|
||||
/>,
|
||||
)
|
||||
|
||||
const composer = screen.getByLabelText('向快递策略助手提问')
|
||||
fireEvent.change(composer, { target: { value: '帮我导出昨天的发货数据' } })
|
||||
fireEvent.keyDown(composer, { key: 'Enter', code: 'Enter' })
|
||||
|
||||
await screen.findByText(/已生成并下载/)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/supply-chain/limit-management/freight-ai-comparison/raw-export',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: '帮我导出昨天的发货数据',
|
||||
history: [],
|
||||
}),
|
||||
}),
|
||||
)
|
||||
expect(fetchMock).not.toHaveBeenCalledWith(
|
||||
'/api/supply-chain/limit-management/freight-ai-comparison',
|
||||
expect.anything(),
|
||||
)
|
||||
expect(HTMLAnchorElement.prototype.click).toHaveBeenCalledTimes(1)
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:freight-raw-export')
|
||||
expect(screen.getByText('帮我导出昨天的发货数据')).toBeInTheDocument()
|
||||
expect(screen.getByText(/每张数据表最多 1,000,000 行/)).toBeInTheDocument()
|
||||
await waitFor(() => {
|
||||
expect(window.localStorage.getItem('freight-ai-raw-export-test'))
|
||||
.toContain('帮我导出昨天的发货数据')
|
||||
})
|
||||
})
|
||||
|
||||
it('does not download raw data when the account lacks download permission', async () => {
|
||||
const fetchMock = jest.fn()
|
||||
globalThis.fetch = fetchMock
|
||||
render(
|
||||
<FreightAiComparisonTab
|
||||
canOperate
|
||||
canDownload={false}
|
||||
chatStorageKey="freight-ai-raw-export-no-download"
|
||||
/>,
|
||||
)
|
||||
|
||||
const composer = screen.getByLabelText('向快递策略助手提问')
|
||||
fireEvent.change(composer, { target: { value: '帮我导出昨天的发货数据' } })
|
||||
fireEvent.keyDown(composer, { key: 'Enter', code: 'Enter' })
|
||||
|
||||
await screen.findByText(/这次没有完成导出:当前账号没有快递维护下载权限/)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(HTMLAnchorElement.prototype.click).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@ -22,9 +22,11 @@ import { FormEvent, KeyboardEvent, useEffect, useRef, useState } from 'react'
|
||||
import type { ApiResponse } from '@/server/core/types'
|
||||
import {
|
||||
FREIGHT_AI_QUOTE_FILE_MAX_BYTES,
|
||||
FREIGHT_AI_RAW_EXPORT_MAX_ROWS,
|
||||
type FreightAiComparisonResult,
|
||||
type FreightAiOrderComparison,
|
||||
} from '@/lib/freight-ai-comparison'
|
||||
import { isFreightAiRawOrderExportIntent } from '@/lib/freight-ai-raw-order-export'
|
||||
import styles from './freight-ai-comparison.module.css'
|
||||
|
||||
type ChatMessage = {
|
||||
@ -72,12 +74,14 @@ const INITIAL_MESSAGE = [
|
||||
'告诉我发货仓、时间范围和新快递名称,我会直接从聚水潭数据库拉取真实的发货订单并测算;没有指定仓库时默认查询全部仓库,并按订单来源仓分别套用现有快递规则。',
|
||||
'新快递报价可以直接上传,也可以不上传;不上传时会读取聚水潭费率库。报价只用于本次比价,不写回费率库。',
|
||||
'例如:“测算睢宁仓近三个月的发货数据,用山东顺丰干配和现有快递做对比。”没有指定时间时默认近三个月;只说“现有快递”时只计算现有方案。',
|
||||
'如果只想拿原始数据,可以直接说“导出昨天的发货数据”或“导出全部仓库昨天的发货数据”。中文表头会保留原始字段名,不改字段、不做运费计算。',
|
||||
].join('\n\n')
|
||||
|
||||
const QUICK_PROMPTS = [
|
||||
'测算睢宁仓近三个月的发货数据,只计算现有快递',
|
||||
'测算睢宁仓近三个月的发货数据,用山东顺丰干配和现有快递做对比',
|
||||
'分析睢宁仓近三个月发货数据中各省份的现有快递运费',
|
||||
'导出昨天全部仓库的发货数据',
|
||||
]
|
||||
|
||||
function formatFileSize(size: number) {
|
||||
@ -90,6 +94,20 @@ function isSupportedQuoteFile(file: File) {
|
||||
return /\.(xlsx|xls|csv)$/i.test(file.name)
|
||||
}
|
||||
|
||||
async function downloadResponse(response: Response, fallbackFileName: string) {
|
||||
const blob = await response.blob()
|
||||
const disposition = response.headers.get('Content-Disposition') ?? ''
|
||||
const encodedName = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
|
||||
const fileName = encodedName ? decodeURIComponent(encodedName) : fallbackFileName
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = fileName
|
||||
anchor.click()
|
||||
URL.revokeObjectURL(url)
|
||||
return fileName
|
||||
}
|
||||
|
||||
function displayMoney(value: number | null | undefined) {
|
||||
if (value === null || value === undefined || !Number.isFinite(value)) return '-'
|
||||
return value.toLocaleString('zh-CN', {
|
||||
@ -481,6 +499,7 @@ export function FreightAiComparisonTab({
|
||||
const [message, setMessage] = useState('')
|
||||
const [result, setResult] = useState<FreightAiComparisonResult | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [rawExporting, setRawExporting] = useState(false)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [revision, setRevision] = useState(0)
|
||||
const [error, setError] = useState('')
|
||||
@ -617,9 +636,36 @@ export function FreightAiComparisonTab({
|
||||
setMessage('')
|
||||
setError('')
|
||||
const history = conversationInputsRef.current.slice(-50)
|
||||
const rawExport = isFreightAiRawOrderExportIntent([...history, normalizedMessage])
|
||||
|
||||
setLoading(true)
|
||||
setRawExporting(rawExport)
|
||||
try {
|
||||
if (rawExport) {
|
||||
if (!canDownload) throw new Error('当前账号没有快递维护下载权限')
|
||||
const response = await fetch(
|
||||
'/api/supply-chain/limit-management/freight-ai-comparison/raw-export',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: normalizedMessage,
|
||||
history,
|
||||
}),
|
||||
},
|
||||
)
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null) as ApiResponse<never> | null
|
||||
throw new Error(payload?.error?.message || '原始发货数据导出失败')
|
||||
}
|
||||
const fileName = await downloadResponse(response, '快递原始发货数据.xlsx')
|
||||
conversationInputsRef.current = [...history, normalizedMessage]
|
||||
appendAssistantMessage(
|
||||
`已生成并下载“${fileName}”。文件只导出聚水潭原始数据,不做运费计算;所有源字段均保留,每张数据表最多 ${FREIGHT_AI_RAW_EXPORT_MAX_ROWS.toLocaleString('zh-CN')} 行。`,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const form = new FormData()
|
||||
form.append('message', normalizedMessage)
|
||||
if (history.length > 0) form.append('history', JSON.stringify(history))
|
||||
@ -644,11 +690,14 @@ export function FreightAiComparisonTab({
|
||||
} catch (analysisFailure) {
|
||||
const text = analysisFailure instanceof Error
|
||||
? analysisFailure.message
|
||||
: 'AI 比价测算失败'
|
||||
: rawExport
|
||||
? '原始发货数据导出失败'
|
||||
: 'AI 比价测算失败'
|
||||
setError(text)
|
||||
appendAssistantMessage(`这次没有完成测算:${text}`)
|
||||
appendAssistantMessage(`${rawExport ? '这次没有完成导出' : '这次没有完成测算'}:${text}`)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setRawExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
@ -668,6 +717,7 @@ export function FreightAiComparisonTab({
|
||||
setQuoteFile(null)
|
||||
setResult(null)
|
||||
setError('')
|
||||
setRawExporting(false)
|
||||
setExporting(false)
|
||||
setRevision(0)
|
||||
setMessage('')
|
||||
@ -707,18 +757,10 @@ export function FreightAiComparisonTab({
|
||||
const payload = await response.json().catch(() => null) as ApiResponse<never> | null
|
||||
throw new Error(payload?.error?.message || '完整明细导出失败')
|
||||
}
|
||||
const blob = await response.blob()
|
||||
const disposition = response.headers.get('Content-Disposition') ?? ''
|
||||
const encodedName = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
|
||||
const fileName = encodedName
|
||||
? decodeURIComponent(encodedName)
|
||||
: `${result?.warehouseName ?? '快递'}-${result?.newCourierName ?? 'AI比价'}-完整明细.xlsx`
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = fileName
|
||||
anchor.click()
|
||||
URL.revokeObjectURL(url)
|
||||
await downloadResponse(
|
||||
response,
|
||||
`${result?.warehouseName ?? '快递'}-${result?.newCourierName ?? 'AI比价'}-完整明细.xlsx`,
|
||||
)
|
||||
appendAssistantMessage('完整订单明细已生成并下载。汇总金额按聚水潭查到的全部订单计算。')
|
||||
} catch (exportFailure) {
|
||||
const text = exportFailure instanceof Error ? exportFailure.message : '完整明细导出失败'
|
||||
@ -762,7 +804,9 @@ export function FreightAiComparisonTab({
|
||||
<div className={styles.dataSourcePanel}>
|
||||
<div className={styles.dataSourceHeading}>
|
||||
<span>01 / 数据源(订单自动 · 报价可选)</span>
|
||||
<small>近三个月 · 最多 10 万行</small>
|
||||
<small>
|
||||
测算 ≤ 10 万行 · 原始导出单表 ≤ {FREIGHT_AI_RAW_EXPORT_MAX_ROWS.toLocaleString('zh-CN')} 行
|
||||
</small>
|
||||
</div>
|
||||
<div className={styles.dataSourceGrid}>
|
||||
<div className={styles.dataSourceCard}>
|
||||
@ -844,7 +888,12 @@ export function FreightAiComparisonTab({
|
||||
{loading ? (
|
||||
<div className={`${styles.assistantMessage} ${styles.typingMessage}`}>
|
||||
<span className={styles.miniBot}><Bot size={13} /></span>
|
||||
<p><LoaderCircle size={13} className="animate-spin" /> 正在从聚水潭读取发货数据并重新测算…</p>
|
||||
<p>
|
||||
<LoaderCircle size={13} className="animate-spin" />
|
||||
{rawExporting
|
||||
? ' 正在从聚水潭读取原始发货数据并生成 Excel…'
|
||||
: ' 正在从聚水潭读取发货数据并重新测算…'}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@ -15,6 +15,7 @@ import {
|
||||
|
||||
export const FREIGHT_AI_MAX_QUOTE_ROWS = 5_000
|
||||
export const FREIGHT_AI_MAX_ORDER_ROWS = 100_000
|
||||
export const FREIGHT_AI_RAW_EXPORT_MAX_ROWS = 1_000_000
|
||||
export const FREIGHT_AI_QUOTE_FILE_MAX_BYTES = 10 * 1024 * 1024
|
||||
export const FREIGHT_AI_ORDER_FILE_MAX_BYTES = 50 * 1024 * 1024
|
||||
export const FREIGHT_AI_ANALYSIS_ORDER_DETAIL_LIMIT = 5_000
|
||||
|
||||
@ -0,0 +1,46 @@
|
||||
import {
|
||||
FREIGHT_RAW_ORDER_TABLES,
|
||||
isFreightAiRawOrderExportIntent,
|
||||
rawFreightColumnHeader,
|
||||
} from './freight-ai-raw-order-export'
|
||||
|
||||
describe('freight AI raw order export', () => {
|
||||
it('uses Chinese headers while retaining every source field name', () => {
|
||||
const orders = FREIGHT_RAW_ORDER_TABLES.find((table) => table.key === 'normalOrders')!
|
||||
|
||||
expect(rawFreightColumnHeader(orders, 'so_id'))
|
||||
.toBe('普通订单-线上订单号(so_id)')
|
||||
expect(rawFreightColumnHeader(orders, 'vendor_private_field'))
|
||||
.toBe('普通订单-扩展字段(vendor_private_field)')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['帮我导出昨天的发货数据'],
|
||||
['导出昨天全部仓库的发货数据'],
|
||||
['下载 2026-12-01 到 2026-12-02 的订单原始数据'],
|
||||
['把出库数据导出给我'],
|
||||
])('recognizes data-only export requests: %s', (message) => {
|
||||
expect(isFreightAiRawOrderExportIntent([message])).toBe(true)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['帮我计算昨天的发货数据'],
|
||||
['导出比价结果'],
|
||||
['测算昨天全部仓库的发货数据'],
|
||||
['导出订单并比较新快递和现有快递'],
|
||||
['导出订单做运费测算'],
|
||||
])('does not route calculations through raw export: %s', (message) => {
|
||||
expect(isFreightAiRawOrderExportIntent([message])).toBe(false)
|
||||
})
|
||||
|
||||
it('uses the latest instruction when a conversation changes its goal', () => {
|
||||
expect(isFreightAiRawOrderExportIntent([
|
||||
'帮我测算昨天的发货数据',
|
||||
'改成导出昨天的订单',
|
||||
])).toBe(true)
|
||||
expect(isFreightAiRawOrderExportIntent([
|
||||
'帮我导出昨天的订单',
|
||||
'改成和现有快递比较',
|
||||
])).toBe(false)
|
||||
})
|
||||
})
|
||||
179
furniture-3d-system/src/lib/freight-ai-raw-order-export.ts
Normal file
179
furniture-3d-system/src/lib/freight-ai-raw-order-export.ts
Normal file
@ -0,0 +1,179 @@
|
||||
export type FreightRawOrderTableKey =
|
||||
| 'normalOrders'
|
||||
| 'normalItems'
|
||||
| 'normalWarehouses'
|
||||
| 'qmcustOrders'
|
||||
| 'qmcustItems'
|
||||
| 'qmcustWarehouses'
|
||||
|
||||
export type FreightRawOrderTableDefinition = {
|
||||
key: FreightRawOrderTableKey
|
||||
sheetName: string
|
||||
prefix: string
|
||||
}
|
||||
|
||||
export const FREIGHT_RAW_ORDER_TABLES: readonly FreightRawOrderTableDefinition[] = [
|
||||
{ key: 'normalOrders', sheetName: '普通-订单主表', prefix: '普通订单' },
|
||||
{ key: 'normalItems', sheetName: '普通-商品明细', prefix: '普通商品' },
|
||||
{ key: 'normalWarehouses', sheetName: '普通-仓库信息', prefix: '普通仓库' },
|
||||
{ key: 'qmcustOrders', sheetName: '奇门-订单主表', prefix: '奇门订单' },
|
||||
{ key: 'qmcustItems', sheetName: '奇门-商品明细', prefix: '奇门商品' },
|
||||
{ key: 'qmcustWarehouses', sheetName: '奇门-仓库信息', prefix: '奇门仓库' },
|
||||
]
|
||||
|
||||
const RAW_FIELD_LABELS: Record<string, string> = {
|
||||
Id: 'ID',
|
||||
oi_id: '明细ID',
|
||||
sku_id: '商品编码',
|
||||
i_id: '款式编码',
|
||||
shop_sku_id: '店铺商品编码',
|
||||
shop_i_id: '店铺款式编码',
|
||||
properties_value: '规格属性',
|
||||
amount: '金额',
|
||||
base_price: '原价',
|
||||
qty: '数量',
|
||||
name: '名称',
|
||||
price: '单价',
|
||||
outer_oi_id: '外部明细ID',
|
||||
refund_id: '退款单号',
|
||||
refund_qty: '退款数量',
|
||||
refund_status: '退款状态',
|
||||
raw_so_id: '原始订单号',
|
||||
is_presale: '是否预售',
|
||||
is_gift: '是否赠品',
|
||||
item_status: '商品状态',
|
||||
send_warehouse: '发货仓ID',
|
||||
item_pay_amount: '明细实付金额',
|
||||
referrer_id: '推荐人ID',
|
||||
discount_rate: '折扣率',
|
||||
pic: '商品图片',
|
||||
sku_type: '商品类型',
|
||||
remark: '备注',
|
||||
src_combine_sku_id: '源组合商品编码',
|
||||
item_ext_data: '明细扩展数据',
|
||||
buyer_paid_amount: '买家实付金额',
|
||||
seller_income_amount: '卖家实收金额',
|
||||
o_id: '订单内部ID',
|
||||
co_id: '公司ID',
|
||||
shop_id: '店铺ID',
|
||||
so_id: '线上订单号',
|
||||
order_date: '下单时间',
|
||||
shop_status: '店铺状态',
|
||||
question_type: '问题类型',
|
||||
question_desc: '问题描述',
|
||||
status: '状态',
|
||||
receiver_country: '收货国家',
|
||||
receiver_state: '收货省份',
|
||||
receiver_city: '收货城市',
|
||||
receiver_district: '收货区县',
|
||||
receiver_address: '收货地址',
|
||||
receiver_town: '收货街道',
|
||||
receiver_zip: '邮政编码',
|
||||
buyer_id: '买家ID',
|
||||
send_date: '发货时间',
|
||||
pay_amount: '应付金额',
|
||||
freight: '运费',
|
||||
f_freight: '实际运费',
|
||||
weight: '重量',
|
||||
f_weight: '实际重量',
|
||||
buyer_message: '买家留言',
|
||||
invoice_title: '发票抬头',
|
||||
is_cod: '是否货到付款',
|
||||
type: '订单类型',
|
||||
shop_site: '订单平台',
|
||||
free_amount: '优惠金额',
|
||||
paid_amount: '实付金额',
|
||||
pay_date: '付款时间',
|
||||
outer_pay_id: '外部支付ID',
|
||||
modified: '店铺更新时间',
|
||||
order_from: '订单来源',
|
||||
shop_name: '店铺名称',
|
||||
seller_flag: '卖家标记',
|
||||
plan_delivery_date: '计划发货日期',
|
||||
lc_id: '物流公司ID',
|
||||
l_id: '物流单ID',
|
||||
logistics_company: '快递公司',
|
||||
tag: '标签',
|
||||
wms_co_id: '仓库ID',
|
||||
currency: '币种',
|
||||
node: '流程节点',
|
||||
labels: '订单标签',
|
||||
drp_co_id_from: '所属商家ID',
|
||||
is_split: '是否拆单',
|
||||
is_merge: '是否合并',
|
||||
creator_name: '创建人',
|
||||
buyer_tax_no: '买家税号',
|
||||
invoice_type: '发票类型',
|
||||
sign_time: '签收时间',
|
||||
skus: '商品信息',
|
||||
end_time: '结束时间',
|
||||
receiver_email: '收货邮箱',
|
||||
referrer_name: '推荐人',
|
||||
created: '创建时间',
|
||||
shipment: '发货信息',
|
||||
open_id: '开放ID',
|
||||
outer_as_id: '外部售后ID',
|
||||
ts: '时间戳',
|
||||
link_o_id: '关联订单ID',
|
||||
merge_so_id: '合并订单号',
|
||||
outer_so_id: '外部订单号',
|
||||
drp_co_id_to: '分销商ID',
|
||||
shop_buyer_id: '店铺买家ID',
|
||||
receiver_name: '收货人',
|
||||
receiver_mobile: '收货手机',
|
||||
receiver_phone: '收货电话',
|
||||
ext_datas: '扩展数据',
|
||||
as_id: '售后ID',
|
||||
un_lid: '退款物流ID',
|
||||
chosen_channel: '选择渠道',
|
||||
drp_from: '分销来源',
|
||||
drp_to: '分销去向',
|
||||
glasses: '眼镜数据',
|
||||
createTime: '创建时间',
|
||||
updateTime: '更新时间',
|
||||
batch_id: '批次ID',
|
||||
produced_date: '生产日期',
|
||||
drp_price: '分销价格',
|
||||
lwh_id: '发货仓ID',
|
||||
lwh_name: '发货仓名称',
|
||||
direct_parent_order_id: '直接父订单ID',
|
||||
invoice_data: '发票数据',
|
||||
drp_info: '分销信息',
|
||||
invoice_amount: '发票金额',
|
||||
oaid: 'OA ID',
|
||||
platform_free_amount: '平台优惠金额',
|
||||
pay_free_amount: '支付优惠金额',
|
||||
referrer_free_amount: '推荐优惠金额',
|
||||
shop_free_amount: '店铺优惠金额',
|
||||
local_created: '本地创建时间',
|
||||
local_updated: '本地更新时间',
|
||||
is_main: '是否主仓',
|
||||
remark1: '备注1',
|
||||
remark2: '备注2',
|
||||
}
|
||||
|
||||
export function rawFreightFieldLabel(columnName: string) {
|
||||
return RAW_FIELD_LABELS[columnName] ?? '扩展字段'
|
||||
}
|
||||
|
||||
export function rawFreightColumnHeader(
|
||||
table: Pick<FreightRawOrderTableDefinition, 'prefix'>,
|
||||
columnName: string,
|
||||
) {
|
||||
return `${table.prefix}-${rawFreightFieldLabel(columnName)}(${columnName})`
|
||||
}
|
||||
|
||||
export function isFreightAiRawOrderExportIntent(messages: readonly string[]) {
|
||||
const message = messages
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((item) => item.normalize('NFKC').trim())
|
||||
.find(Boolean)
|
||||
if (!message) return false
|
||||
if (!/(?:导出|下载)/u.test(message)) return false
|
||||
if (!/(?:订单|发货|出库)/u.test(message)) return false
|
||||
if (/(?:比价|对比|比较|运费计算|测算|计算运费|平均运费|新快递|现有快递|哪个更便宜)/u.test(message)) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
import sql from 'mssql'
|
||||
import type { FreightAiOrderDateField } from '@/lib/freight-ai-database-query'
|
||||
import type { FreightRawOrderTableKey } from '@/lib/freight-ai-raw-order-export'
|
||||
|
||||
export type JstFreightWarehouse = {
|
||||
warehouseName: string
|
||||
@ -30,6 +31,11 @@ export type JstFreightOrderSourceRow = {
|
||||
currentFreight: number | null
|
||||
}
|
||||
|
||||
export type JstFreightRawColumn = {
|
||||
name: string
|
||||
dataType: string
|
||||
}
|
||||
|
||||
function requiredEnv(name: string) {
|
||||
const value = process.env[name]?.trim()
|
||||
if (!value) throw new Error(`Missing required environment variable: ${name}`)
|
||||
@ -79,6 +85,15 @@ function dateOnly(value: string, label: string) {
|
||||
return value
|
||||
}
|
||||
|
||||
const RAW_TABLE_NAMES: Record<FreightRawOrderTableKey, string> = {
|
||||
normalOrders: 'jst_Orders',
|
||||
normalItems: 'jst_OrderItem',
|
||||
normalWarehouses: 'jst_warehouseInfo',
|
||||
qmcustOrders: 'jst_qmcust_orderlist',
|
||||
qmcustItems: 'jst_qmcust_orderlist_item',
|
||||
qmcustWarehouses: 'jst_warehouseInfo',
|
||||
}
|
||||
|
||||
export class JstFreightOrderSourceRepository {
|
||||
private pool: sql.ConnectionPool | null = null
|
||||
|
||||
@ -254,6 +269,190 @@ export class JstFreightOrderSourceRepository {
|
||||
return rows.slice(0, maxRows)
|
||||
}
|
||||
|
||||
async listRawTableColumns(tableKey: FreightRawOrderTableKey): Promise<JstFreightRawColumn[]> {
|
||||
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('schema', sql.NVarChar(128), schema)
|
||||
.input('tableName', sql.NVarChar(128), RAW_TABLE_NAMES[tableKey])
|
||||
.query<{ columnName: string; dataType: string }>(`
|
||||
SELECT COLUMN_NAME AS columnName, DATA_TYPE AS dataType
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName
|
||||
ORDER BY ORDINAL_POSITION
|
||||
`)
|
||||
return result.recordset.map((row) => ({
|
||||
name: String(row.columnName),
|
||||
dataType: String(row.dataType),
|
||||
}))
|
||||
}
|
||||
|
||||
async streamRawOrderTable(input: {
|
||||
tableKey: FreightRawOrderTableKey
|
||||
dateFrom: string
|
||||
dateTo: string
|
||||
dateField: FreightAiOrderDateField
|
||||
warehouseIds: readonly number[]
|
||||
warehouseNames?: readonly string[]
|
||||
maxRows: number
|
||||
columns?: readonly JstFreightRawColumn[]
|
||||
onRow: (row: Record<string, unknown>) => void
|
||||
}): Promise<{ rowCount: number; columns: JstFreightRawColumn[] }> {
|
||||
const columns = input.columns
|
||||
? [...input.columns]
|
||||
: await this.listRawTableColumns(input.tableKey)
|
||||
const dateColumn = input.dateField === 'SEND_DATE' ? 'send_date' : 'pay_date'
|
||||
const warehouseIds = integerList(input.warehouseIds).split(',')
|
||||
const warehouseNames = sqlStringList(input.warehouseNames ?? [])
|
||||
const dateFrom = dateOnly(input.dateFrom, 'dateFrom')
|
||||
const dateTo = dateOnly(input.dateTo, 'dateTo')
|
||||
const maxRows = Math.max(1, Math.min(1_000_000, Math.trunc(input.maxRows)))
|
||||
const pool = await this.getPool()
|
||||
const seen = new Set<string>()
|
||||
let rowCount = 0
|
||||
const warehouseIdChunkSize = 30
|
||||
|
||||
for (
|
||||
let chunkStart = 0;
|
||||
chunkStart < warehouseIds.length && rowCount < maxRows;
|
||||
chunkStart += warehouseIdChunkSize
|
||||
) {
|
||||
const chunkIds = warehouseIds.slice(chunkStart, chunkStart + warehouseIdChunkSize)
|
||||
const warehouseIdList = chunkIds.join(',')
|
||||
const warehouseIdStrings = chunkIds.map((id) => `N'${id}'`).join(',')
|
||||
const remaining = maxRows - rowCount
|
||||
let selectFrom = ''
|
||||
switch (input.tableKey) {
|
||||
case 'normalOrders':
|
||||
selectFrom = `
|
||||
SELECT TOP (${remaining}) o.*
|
||||
FROM dbo.jst_Orders o WITH (NOLOCK)
|
||||
WHERE (
|
||||
o.wms_co_id IN (${warehouseIdList})
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM dbo.jst_OrderItem i WITH (NOLOCK)
|
||||
WHERE i.o_id = o.o_id AND i.send_warehouse IN (${warehouseIdList})
|
||||
)
|
||||
)
|
||||
AND o.${dateColumn} >= '${dateFrom}'
|
||||
AND o.${dateColumn} < DATEADD(day, 1, '${dateTo}')
|
||||
`
|
||||
break
|
||||
case 'normalItems':
|
||||
selectFrom = `
|
||||
SELECT TOP (${remaining}) i.*
|
||||
FROM dbo.jst_OrderItem i WITH (NOLOCK)
|
||||
JOIN dbo.jst_Orders o WITH (NOLOCK) ON o.o_id = i.o_id
|
||||
WHERE COALESCE(NULLIF(i.send_warehouse, 0), o.wms_co_id) IN (${warehouseIdList})
|
||||
AND o.${dateColumn} >= '${dateFrom}'
|
||||
AND o.${dateColumn} < DATEADD(day, 1, '${dateTo}')
|
||||
AND ISNULL(i.qty, 0) > 0
|
||||
`
|
||||
break
|
||||
case 'normalWarehouses':
|
||||
case 'qmcustWarehouses':
|
||||
selectFrom = `
|
||||
SELECT TOP (${remaining}) w.*
|
||||
FROM dbo.jst_warehouseInfo w WITH (NOLOCK)
|
||||
WHERE w.wms_co_id IN (${warehouseIdList})
|
||||
`
|
||||
break
|
||||
case 'qmcustOrders':
|
||||
selectFrom = `
|
||||
SELECT TOP (${remaining}) o.*
|
||||
FROM dbo.jst_qmcust_orderlist o WITH (NOLOCK)
|
||||
WHERE (
|
||||
o.wms_co_id IN (${warehouseIdList})
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM dbo.jst_qmcust_orderlist_item i WITH (NOLOCK)
|
||||
WHERE i.o_id = o.o_id
|
||||
AND (
|
||||
LTRIM(RTRIM(i.lwh_id)) IN (${warehouseIdStrings})
|
||||
${warehouseNames ? `OR LTRIM(RTRIM(i.lwh_name)) IN (${warehouseNames})` : ''}
|
||||
)
|
||||
)
|
||||
)
|
||||
AND o.${dateColumn} >= '${dateFrom}'
|
||||
AND o.${dateColumn} < DATEADD(day, 1, '${dateTo}')
|
||||
`
|
||||
break
|
||||
case 'qmcustItems':
|
||||
selectFrom = `
|
||||
SELECT TOP (${remaining}) i.*
|
||||
FROM dbo.jst_qmcust_orderlist_item i WITH (NOLOCK)
|
||||
JOIN dbo.jst_qmcust_orderlist o WITH (NOLOCK) ON o.o_id = i.o_id
|
||||
WHERE (
|
||||
LTRIM(RTRIM(i.lwh_id)) IN (${warehouseIdStrings})
|
||||
OR o.wms_co_id IN (${warehouseIdList})
|
||||
${warehouseNames ? `OR LTRIM(RTRIM(i.lwh_name)) IN (${warehouseNames})` : ''}
|
||||
)
|
||||
AND o.${dateColumn} >= '${dateFrom}'
|
||||
AND o.${dateColumn} < DATEADD(day, 1, '${dateTo}')
|
||||
AND ISNULL(i.qty, 0) > 0
|
||||
`
|
||||
break
|
||||
}
|
||||
const primaryKey = input.tableKey.endsWith('Items')
|
||||
? 'oi_id'
|
||||
: input.tableKey.endsWith('Warehouses')
|
||||
? 'wms_co_id'
|
||||
: 'o_id'
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const request = pool.request()
|
||||
let cancelled = false
|
||||
let settled = false
|
||||
const fail = (error: unknown) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
try {
|
||||
request.cancel()
|
||||
} catch {
|
||||
// Keep the original stream error.
|
||||
}
|
||||
reject(error instanceof Error ? error : new Error(String(error)))
|
||||
}
|
||||
request.stream = true
|
||||
request.requestTimeout = 3_600_000
|
||||
request.on('row', (row: Record<string, unknown>) => {
|
||||
if (settled || rowCount >= maxRows) return
|
||||
const key = String(row[primaryKey] ?? '')
|
||||
if (key && seen.has(key)) return
|
||||
if (key) seen.add(key)
|
||||
try {
|
||||
input.onRow(row)
|
||||
} catch (error) {
|
||||
fail(error)
|
||||
return
|
||||
}
|
||||
rowCount += 1
|
||||
if (rowCount >= maxRows) {
|
||||
cancelled = true
|
||||
request.cancel()
|
||||
}
|
||||
})
|
||||
request.on('error', (error) => {
|
||||
if (settled) return
|
||||
if (cancelled) {
|
||||
settled = true
|
||||
resolve()
|
||||
} else {
|
||||
fail(error)
|
||||
}
|
||||
})
|
||||
request.on('done', () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve()
|
||||
})
|
||||
void request.query(openQuery(selectFrom)).catch(fail)
|
||||
})
|
||||
}
|
||||
return { rowCount, columns }
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (!this.pool) return
|
||||
await this.pool.close()
|
||||
|
||||
@ -0,0 +1,155 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
import { Writable } from 'node:stream'
|
||||
import { FREIGHT_AI_RAW_EXPORT_MAX_ROWS } from '@/lib/freight-ai-comparison'
|
||||
import { FREIGHT_RAW_ORDER_TABLES } from '@/lib/freight-ai-raw-order-export'
|
||||
|
||||
const mockListWarehouses = jest.fn()
|
||||
const mockListRawTableColumns = jest.fn()
|
||||
const mockStreamRawOrderTable = jest.fn()
|
||||
|
||||
jest.mock('@/server/repositories/jst-freight-order-source.repository', () => ({
|
||||
jstFreightOrderSourceRepository: {
|
||||
listWarehouses: (...args: unknown[]) => mockListWarehouses(...args),
|
||||
listRawTableColumns: (...args: unknown[]) => mockListRawTableColumns(...args),
|
||||
streamRawOrderTable: (...args: unknown[]) => mockStreamRawOrderTable(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
const {
|
||||
freightAiRawExportFileName,
|
||||
writeFreightAiRawExportWorkbook,
|
||||
} = require('../freight-ai-raw-export.service') as typeof import('../freight-ai-raw-export.service')
|
||||
|
||||
function writableCollector() {
|
||||
const chunks: Buffer[] = []
|
||||
const stream = new Writable({
|
||||
write(chunk, _encoding, callback) {
|
||||
chunks.push(Buffer.from(chunk))
|
||||
callback()
|
||||
},
|
||||
})
|
||||
return {
|
||||
stream,
|
||||
content: () => Buffer.concat(chunks),
|
||||
}
|
||||
}
|
||||
|
||||
describe('freight AI raw export service', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockListWarehouses.mockResolvedValue([
|
||||
{ warehouseName: '睢宁仓', wmsCoId: 11 },
|
||||
{ warehouseName: '新苏北仓', wmsCoId: 12 },
|
||||
])
|
||||
mockListRawTableColumns.mockImplementation(async (tableKey: string) => {
|
||||
if (tableKey === 'normalWarehouses' || tableKey === 'qmcustWarehouses') {
|
||||
return [
|
||||
{ name: 'wms_co_id', dataType: 'int' },
|
||||
{ name: 'name', dataType: 'nvarchar' },
|
||||
]
|
||||
}
|
||||
return [
|
||||
{ name: 'o_id', dataType: 'bigint' },
|
||||
{ name: 'so_id', dataType: 'nvarchar' },
|
||||
{ name: 'source_only_field', dataType: 'nvarchar' },
|
||||
]
|
||||
})
|
||||
mockStreamRawOrderTable.mockImplementation(async (input: {
|
||||
tableKey: string
|
||||
onRow: (row: Record<string, unknown>) => void
|
||||
}) => {
|
||||
const row = input.tableKey.endsWith('Warehouses')
|
||||
? { wms_co_id: 11, name: '睢宁仓' }
|
||||
: { o_id: 101, so_id: 'SO-101', source_only_field: '保留字段值' }
|
||||
input.onRow(row)
|
||||
return {
|
||||
rowCount: 1,
|
||||
columns: await mockListRawTableColumns(input.tableKey),
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('exports yesterday for all warehouses with Chinese headers and every source column', async () => {
|
||||
const output = writableCollector()
|
||||
const result = await writeFreightAiRawExportWorkbook({
|
||||
output: output.stream,
|
||||
message: '帮我导出昨天全部仓库的发货数据',
|
||||
now: new Date('2026-12-04T02:00:00.000Z'),
|
||||
})
|
||||
|
||||
expect(result.query).toMatchObject({
|
||||
startDate: '2026-12-03',
|
||||
endDate: '2026-12-03',
|
||||
dateField: 'SEND_DATE',
|
||||
rangeLabel: '昨天',
|
||||
})
|
||||
expect(result.allWarehouses).toBe(true)
|
||||
expect(mockStreamRawOrderTable).toHaveBeenCalledTimes(FREIGHT_RAW_ORDER_TABLES.length)
|
||||
for (const call of mockStreamRawOrderTable.mock.calls) {
|
||||
expect(call[0]).toMatchObject({
|
||||
warehouseIds: [11, 12],
|
||||
warehouseNames: [],
|
||||
dateFrom: '2026-12-03',
|
||||
dateTo: '2026-12-03',
|
||||
maxRows: FREIGHT_AI_RAW_EXPORT_MAX_ROWS,
|
||||
})
|
||||
}
|
||||
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.load(output.content() as never)
|
||||
expect(workbook.worksheets.map((sheet) => sheet.name)).toEqual([
|
||||
...FREIGHT_RAW_ORDER_TABLES.map((table) => table.sheetName),
|
||||
'导出说明',
|
||||
])
|
||||
const orders = workbook.getWorksheet('普通-订单主表')!
|
||||
expect(orders.getRow(1).values).toEqual([
|
||||
undefined,
|
||||
'普通订单-订单内部ID(o_id)',
|
||||
'普通订单-线上订单号(so_id)',
|
||||
'普通订单-扩展字段(source_only_field)',
|
||||
])
|
||||
expect(orders.getRow(2).values).toEqual([
|
||||
undefined,
|
||||
101,
|
||||
'SO-101',
|
||||
'保留字段值',
|
||||
])
|
||||
})
|
||||
|
||||
it('chooses a single warehouse when only one warehouse is mentioned', async () => {
|
||||
const output = writableCollector()
|
||||
const result = await writeFreightAiRawExportWorkbook({
|
||||
output: output.stream,
|
||||
message: '导出睢宁仓昨天的发货数据',
|
||||
now: new Date('2026-12-04T02:00:00.000Z'),
|
||||
})
|
||||
|
||||
expect(result.allWarehouses).toBe(false)
|
||||
expect(result.warehouses).toEqual([{ warehouseName: '睢宁仓', wmsCoId: 11 }])
|
||||
expect(mockStreamRawOrderTable.mock.calls[0][0]).toMatchObject({
|
||||
warehouseIds: [11],
|
||||
warehouseNames: ['睢宁仓'],
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the warehouse change that appears later in the conversation', async () => {
|
||||
const output = writableCollector()
|
||||
const result = await writeFreightAiRawExportWorkbook({
|
||||
output: output.stream,
|
||||
history: ['导出全部仓库昨天的发货数据'],
|
||||
message: '改成睢宁仓,再导出一次',
|
||||
now: new Date('2026-12-04T02:00:00.000Z'),
|
||||
})
|
||||
|
||||
expect(result.allWarehouses).toBe(false)
|
||||
expect(result.warehouses).toEqual([{ warehouseName: '睢宁仓', wmsCoId: 11 }])
|
||||
})
|
||||
|
||||
it('uses a readable Chinese file name', () => {
|
||||
expect(freightAiRawExportFileName({
|
||||
rangeLabel: '昨天',
|
||||
warehouseLabel: '全部仓库',
|
||||
now: new Date('2026-12-04T02:34:00.000Z'),
|
||||
})).toBe('快递原始发货数据-昨天-全部仓库-20261204-1034.xlsx')
|
||||
})
|
||||
})
|
||||
@ -0,0 +1,295 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
import { PassThrough, Readable, Writable } from 'node:stream'
|
||||
import { parseFreightAiDatabaseQuery } from '@/lib/freight-ai-database-query'
|
||||
import { FREIGHT_AI_RAW_EXPORT_MAX_ROWS } from '@/lib/freight-ai-comparison'
|
||||
import {
|
||||
FREIGHT_RAW_ORDER_TABLES,
|
||||
rawFreightColumnHeader,
|
||||
type FreightRawOrderTableDefinition,
|
||||
} from '@/lib/freight-ai-raw-order-export'
|
||||
import { normalizeWarehouseName } from '@/lib/freight-calculation'
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import {
|
||||
jstFreightOrderSourceRepository,
|
||||
type JstFreightRawColumn,
|
||||
type JstFreightWarehouse,
|
||||
} from '@/server/repositories/jst-freight-order-source.repository'
|
||||
|
||||
function warehouseFromMessage(message: string) {
|
||||
return message.match(/([\u4e00-\u9fffA-Za-z0-9_-]{2,30}?仓)/u)?.[1]?.trim() ?? null
|
||||
}
|
||||
|
||||
async function resolveWarehouses(message: string, history: readonly string[]) {
|
||||
const warehouses = await jstFreightOrderSourceRepository.listWarehouses()
|
||||
if (warehouses.length === 0) {
|
||||
throw new AppError(ErrorCode.RESOURCE_NOT_FOUND, '聚水潭仓库列表为空')
|
||||
}
|
||||
const combinedMessage = [...history, message].join('\n')
|
||||
const normalizedCombinedMessage = normalizeWarehouseName(combinedMessage)
|
||||
const allWarehouseIndexes = [
|
||||
...normalizedCombinedMessage.matchAll(/全部仓库|所有仓库|全仓/gu),
|
||||
].map((match) => match.index ?? -1)
|
||||
const lastAllWarehouseIndex = Math.max(-1, ...allWarehouseIndexes)
|
||||
const candidate = warehouses
|
||||
.map((warehouse) => {
|
||||
const normalized = normalizeWarehouseName(warehouse.warehouseName)
|
||||
return {
|
||||
warehouse,
|
||||
normalized,
|
||||
index: normalized ? normalizedCombinedMessage.lastIndexOf(normalized) : -1,
|
||||
}
|
||||
})
|
||||
.filter((item) => item.index >= 0)
|
||||
.sort((left, right) => (
|
||||
right.index - left.index
|
||||
|| right.normalized.length - left.normalized.length
|
||||
))[0]
|
||||
?.warehouse
|
||||
const candidateIndex = candidate
|
||||
? normalizedCombinedMessage.lastIndexOf(normalizeWarehouseName(candidate.warehouseName))
|
||||
: -1
|
||||
if (candidate && candidateIndex >= lastAllWarehouseIndex) {
|
||||
return { warehouses: [candidate], allWarehouses: false }
|
||||
}
|
||||
if (lastAllWarehouseIndex >= 0) {
|
||||
return { warehouses, allWarehouses: true }
|
||||
}
|
||||
|
||||
const extracted = warehouseFromMessage(message)
|
||||
if (!extracted) return { warehouses, allWarehouses: true }
|
||||
const normalized = normalizeWarehouseName(extracted)
|
||||
const matched = warehouses.find((warehouse) => (
|
||||
normalizeWarehouseName(warehouse.warehouseName) === normalized
|
||||
)) ?? warehouses.find((warehouse) => (
|
||||
normalizeWarehouseName(warehouse.warehouseName).includes(normalized)
|
||||
))
|
||||
if (!matched) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_REQUIRED_FIELD,
|
||||
`没有在聚水潭仓库中找到“${extracted}”`,
|
||||
)
|
||||
}
|
||||
return { warehouses: [matched], allWarehouses: false }
|
||||
}
|
||||
|
||||
function rawCellValue(value: unknown): ExcelJS.CellValue {
|
||||
if (value === null || value === undefined) return null
|
||||
if (value instanceof Date) return value
|
||||
if (typeof value === 'bigint') return value.toString()
|
||||
if (Buffer.isBuffer(value)) return value.toString('base64')
|
||||
if (typeof value === 'object') return JSON.stringify(value)
|
||||
if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
|
||||
return value
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
function columnNumberFormat(column: JstFreightRawColumn) {
|
||||
const dataType = column.dataType.toLowerCase()
|
||||
if (dataType === 'date' || dataType === 'datetime' || dataType === 'smalldatetime') {
|
||||
return 'yyyy-mm-dd hh:mm:ss'
|
||||
}
|
||||
if (dataType === 'decimal' || dataType === 'numeric' || dataType === 'float' || dataType === 'real') {
|
||||
return '0.####'
|
||||
}
|
||||
if (dataType === 'money' || dataType === 'smallmoney') {
|
||||
return '0.00'
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function stamp(now: Date) {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
}).formatToParts(now)
|
||||
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]))
|
||||
return `${values.year}${values.month}${values.day}-${values.hour}${values.minute}`
|
||||
}
|
||||
|
||||
export function freightAiRawExportFileName(input: {
|
||||
rangeLabel: string
|
||||
warehouseLabel: string
|
||||
now?: Date
|
||||
}) {
|
||||
return `快递原始发货数据-${input.rangeLabel}-${input.warehouseLabel}-${stamp(input.now ?? new Date())}.xlsx`
|
||||
.replace(/[\\/:*?"<>|]/g, '-')
|
||||
}
|
||||
|
||||
export type PreparedFreightAiRawExport = {
|
||||
query: ReturnType<typeof parseFreightAiDatabaseQuery>
|
||||
warehouses: JstFreightWarehouse[]
|
||||
allWarehouses: boolean
|
||||
fileName: string
|
||||
}
|
||||
|
||||
export async function prepareFreightAiRawExport(input: {
|
||||
message: string
|
||||
history?: readonly string[]
|
||||
now?: Date
|
||||
}): Promise<PreparedFreightAiRawExport> {
|
||||
const now = input.now ?? new Date()
|
||||
const messages = [...(input.history ?? []), input.message]
|
||||
const query = parseFreightAiDatabaseQuery({ messages, now })
|
||||
const resolved = await resolveWarehouses(input.message, input.history ?? [])
|
||||
return {
|
||||
query,
|
||||
warehouses: resolved.warehouses,
|
||||
allWarehouses: resolved.allWarehouses,
|
||||
fileName: freightAiRawExportFileName({
|
||||
rangeLabel: query.rangeLabel,
|
||||
warehouseLabel: resolved.allWarehouses
|
||||
? '全部仓库'
|
||||
: resolved.warehouses.map((warehouse) => warehouse.warehouseName).join('-'),
|
||||
now,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async function buildSheet(input: {
|
||||
workbook: ExcelJS.stream.xlsx.WorkbookWriter
|
||||
table: FreightRawOrderTableDefinition
|
||||
query: ReturnType<typeof parseFreightAiDatabaseQuery>
|
||||
warehouses: readonly JstFreightWarehouse[]
|
||||
allWarehouses: boolean
|
||||
}) {
|
||||
const columns = await jstFreightOrderSourceRepository.listRawTableColumns(input.table.key)
|
||||
const sheet = input.workbook.addWorksheet(input.table.sheetName, {
|
||||
views: [{ state: 'frozen', ySplit: 1 }],
|
||||
})
|
||||
sheet.columns = columns.map((column, index) => ({
|
||||
header: rawFreightColumnHeader(input.table, column.name),
|
||||
key: `column_${index + 1}`,
|
||||
width: 20,
|
||||
style: columnNumberFormat(column)
|
||||
? { numFmt: columnNumberFormat(column) }
|
||||
: undefined,
|
||||
}))
|
||||
const header = sheet.getRow(1)
|
||||
header.font = { bold: true, color: { argb: 'FF27423D' } }
|
||||
header.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE8F4EF' } }
|
||||
header.alignment = { vertical: 'middle', horizontal: 'center' }
|
||||
header.height = 30
|
||||
header.commit()
|
||||
|
||||
const result = await jstFreightOrderSourceRepository.streamRawOrderTable({
|
||||
tableKey: input.table.key,
|
||||
dateFrom: input.query.startDate,
|
||||
dateTo: input.query.endDate,
|
||||
dateField: input.query.dateField,
|
||||
warehouseIds: input.warehouses.map((warehouse) => warehouse.wmsCoId),
|
||||
warehouseNames: input.allWarehouses
|
||||
? []
|
||||
: input.warehouses.map((warehouse) => warehouse.warehouseName),
|
||||
maxRows: FREIGHT_AI_RAW_EXPORT_MAX_ROWS,
|
||||
columns,
|
||||
onRow: (row) => {
|
||||
sheet.addRow(columns.map((column) => rawCellValue(row[column.name]))).commit()
|
||||
},
|
||||
})
|
||||
sheet.commit()
|
||||
return {
|
||||
table: input.table,
|
||||
columns: columns.length,
|
||||
rows: result.rowCount,
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeFreightAiRawExportWorkbook(input: {
|
||||
output: Writable
|
||||
message: string
|
||||
history?: readonly string[]
|
||||
now?: Date
|
||||
prepared?: PreparedFreightAiRawExport
|
||||
}) {
|
||||
const prepared = input.prepared ?? await prepareFreightAiRawExport(input)
|
||||
const query = prepared.query
|
||||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||||
stream: input.output,
|
||||
useStyles: true,
|
||||
useSharedStrings: false,
|
||||
})
|
||||
const summaries: Array<{
|
||||
table: FreightRawOrderTableDefinition
|
||||
columns: number
|
||||
rows: number
|
||||
}> = []
|
||||
for (const table of FREIGHT_RAW_ORDER_TABLES) {
|
||||
summaries.push(await buildSheet({
|
||||
workbook,
|
||||
table,
|
||||
query,
|
||||
warehouses: prepared.warehouses,
|
||||
allWarehouses: prepared.allWarehouses,
|
||||
}))
|
||||
}
|
||||
|
||||
const summarySheet = workbook.addWorksheet('导出说明')
|
||||
summarySheet.columns = [
|
||||
{ header: '项目', key: 'label', width: 24 },
|
||||
{ header: '内容', key: 'value', width: 90 },
|
||||
]
|
||||
summarySheet.getRow(1).font = { bold: true }
|
||||
summarySheet.addRow(['导出时间范围', `${query.startDate} 至 ${query.endDate}(${query.rangeLabel})`]).commit()
|
||||
summarySheet.addRow(['日期字段', query.dateField === 'SEND_DATE' ? '发货时间' : '付款时间']).commit()
|
||||
summarySheet.addRow([
|
||||
'仓库范围',
|
||||
prepared.allWarehouses
|
||||
? '全部仓库'
|
||||
: prepared.warehouses.map((warehouse) => warehouse.warehouseName).join('、'),
|
||||
]).commit()
|
||||
summarySheet.addRow(['单表行数上限', FREIGHT_AI_RAW_EXPORT_MAX_ROWS.toLocaleString('zh-CN')]).commit()
|
||||
for (const summary of summaries) {
|
||||
summarySheet.addRow([
|
||||
summary.table.sheetName,
|
||||
`字段 ${summary.columns} 个,导出 ${summary.rows.toLocaleString('zh-CN')} 行`,
|
||||
]).commit()
|
||||
}
|
||||
summarySheet.addRow(['字段口径', '原始视图全部字段保留;表头为中文并附原始字段名']).commit()
|
||||
summarySheet.commit()
|
||||
await workbook.commit()
|
||||
|
||||
return {
|
||||
query,
|
||||
warehouses: prepared.warehouses,
|
||||
allWarehouses: prepared.allWarehouses,
|
||||
summaries,
|
||||
fileName: prepared.fileName,
|
||||
}
|
||||
}
|
||||
|
||||
export async function openFreightAiRawExport(input: {
|
||||
message: string
|
||||
history?: readonly string[]
|
||||
now?: Date
|
||||
}) {
|
||||
const prepared = await prepareFreightAiRawExport(input)
|
||||
const output = new PassThrough({ highWaterMark: 1024 * 1024 })
|
||||
output.on('error', () => undefined)
|
||||
const completion = writeFreightAiRawExportWorkbook({
|
||||
output,
|
||||
message: input.message,
|
||||
history: input.history,
|
||||
now: input.now,
|
||||
prepared,
|
||||
}).catch((error: unknown) => {
|
||||
output.destroy(error instanceof Error ? error : new Error(String(error)))
|
||||
throw error
|
||||
})
|
||||
void completion.catch(() => undefined)
|
||||
return {
|
||||
fileName: prepared.fileName,
|
||||
stream: output as Readable,
|
||||
completion,
|
||||
}
|
||||
}
|
||||
|
||||
export const freightAiRawExportService = {
|
||||
open: openFreightAiRawExport,
|
||||
write: writeFreightAiRawExportWorkbook,
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user