优化
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import { getOwnedBusiness, listOwnedBusiness, listOwnedBusinessHistory, saveOwnedBusinessOperations, uploadOwnedBusinessPhoto, bindOwnedBusinessPhoto, getOwnedBusinessPhotoContent } from './ownedBusiness'
|
||||
import { ownedBusinessFixture } from '../components/OwnedBusinessFixtures'
|
||||
import type { OwnedBusinessPhoto, OwnedBusinessSave } from '../ownedBusinessTypes'
|
||||
|
||||
vi.mock('@/shared/api/http', async importOriginal => {
|
||||
const actual = await importOriginal<typeof import('@/shared/api/http')>()
|
||||
return { ...actual, http: { get: vi.fn(), put: vi.fn(), post: vi.fn() }, unwrapApiResponse: (value: { data: unknown }) => value.data }
|
||||
})
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
const base = '/platform/v1/last-leg/fleet/owned-business'
|
||||
const photo: OwnedBusinessPhoto = { slot: 'FUEL_START', category: 'FUEL', fileId: '9007199254740993', fileName: 'fuel.png', contentType: 'image/png', sizeBytes: '10', uploadedAt: '2026-10-20T10:00:00Z', savedAt: null }
|
||||
describe('owned business HTTP contract', () => {
|
||||
it('uses one list response for matched statistics and keeps physical count independent of cargo rows', async () => {
|
||||
const detail = ownedBusinessFixture()
|
||||
vi.mocked(http.get).mockResolvedValue({ data: { records: [detail.row], page: '1', size: '20', total: '41', summary: { dispatchCount: '41', afterLoadingCount: '40', deliveringCount: '1', deliveredCount: '0' } } })
|
||||
const query = { page: 1, size: 20, plannedDepartureFrom: '2026-10-20T00:00:00Z', plannedDepartureTo: '2026-10-21T00:00:00Z', keyword: 'FBA-1' }
|
||||
const value = await listOwnedBusiness(query)
|
||||
expect(http.get).toHaveBeenCalledExactlyOnceWith(base, { params: query })
|
||||
expect(value.summary.dispatchCount).toBe(41); expect(value.records).toHaveLength(1); expect(value.records[0]!.actualPalletCount).toBe(1)
|
||||
})
|
||||
it('encodes the dispatch business number and preserves auxiliary/main versions independently', async () => {
|
||||
const detail = ownedBusinessFixture(); detail.row.recordVersion = '0'; detail.row.dispatchRecordVersion = '9007199254740993'
|
||||
detail.row.dispatchNo = 'DS/1'; detail.dispatch.dispatchNo = 'DS/1'
|
||||
vi.mocked(http.get).mockResolvedValue({ data: detail })
|
||||
expect((await getOwnedBusiness('DS/1')).row.dispatchRecordVersion).toBe('9007199254740993')
|
||||
expect(http.get).toHaveBeenCalledWith(`${base}/DS%2F1`, { params: undefined })
|
||||
detail.dispatch.dispatchNo = 'another'; await expect(getOwnedBusiness('DS/1')).rejects.toThrow('不一致')
|
||||
})
|
||||
it('does not convert money text, calculate a client unit price or submit a dispatch version', async () => {
|
||||
const body: OwnedBusinessSave = { recordVersion: '0', idempotencyKey: 'original-key', operations: { ...ownedBusinessFixture().row.operations, money: { currency: 'USD', amount: '9999999999999999.99' }, fuelConsumptionLitresPer100Km: '18.600' }, reason: null }
|
||||
const detail = ownedBusinessFixture(); detail.row.operations.money = body.operations.money
|
||||
vi.mocked(http.put).mockResolvedValue({ data: detail })
|
||||
const saved = await saveOwnedBusinessOperations('DS-OWN-1', body)
|
||||
expect(http.put).toHaveBeenCalledExactlyOnceWith(`${base}/DS-OWN-1/operations`, body)
|
||||
expect(body.operations.money!.amount).toBe('9999999999999999.99'); expect('dispatchRecordVersion' in body).toBe(false)
|
||||
expect(saved.row.operations.money!.amount).toBe('9999999999999999.99')
|
||||
})
|
||||
it('keeps upload and versioned file binding separate with the same prepared file identity', async () => {
|
||||
vi.mocked(http.post).mockResolvedValue({ data: photo })
|
||||
const file = new File(['image'], 'fuel.png', { type: 'image/png' })
|
||||
await uploadOwnedBusinessPhoto('DS/1', 'FUEL_START', file, 'upload-key')
|
||||
const [url, form] = vi.mocked(http.post).mock.calls[0]!
|
||||
expect(url).toBe(`${base}/DS%2F1/photos/FUEL_START/uploads`); expect((form as FormData).get('file')).toBe(file); expect((form as FormData).get('idempotencyKey')).toBe('upload-key')
|
||||
const detail = ownedBusinessFixture(); detail.row.dispatchNo = 'DS/1'; detail.dispatch.dispatchNo = 'DS/1'
|
||||
vi.mocked(http.put).mockResolvedValue({ data: detail })
|
||||
await bindOwnedBusinessPhoto('DS/1', 'FUEL_START', { recordVersion: '0', idempotencyKey: 'bind-key', fileId: photo.fileId })
|
||||
expect(http.put).toHaveBeenCalledExactlyOnceWith(`${base}/DS%2F1/photos/FUEL_START`, { recordVersion: '0', idempotencyKey: 'bind-key', fileId: photo.fileId })
|
||||
})
|
||||
it('retains the two history streams and reads historical files only at their explicit revision', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ data: { records: [{ eventSource: 'DISPATCH', recordVersion: null, dispatchRecordVersion: '9', operations: null, photos: [] }, { eventSource: 'OPERATIONS', recordVersion: '1', dispatchRecordVersion: null, operations: ownedBusinessFixture().row.operations, photos: [] }], page: '1', size: '20', total: '2' } })
|
||||
const value = await listOwnedBusinessHistory('DS/1', 1, 20)
|
||||
expect(value.records.map(record => [record.eventSource, record.recordVersion, record.dispatchRecordVersion])).toEqual([['DISPATCH',null,'9'],['OPERATIONS','1',null]])
|
||||
vi.mocked(http.get).mockResolvedValue(new Blob(['image'], { type: 'image/png' }))
|
||||
await getOwnedBusinessPhotoContent('DS/1', photo, '1')
|
||||
expect(http.get).toHaveBeenLastCalledWith(`${base}/DS%2F1/photos/FUEL_START/files/${photo.fileId}/content`, { responseType: 'blob', params: { revisionVersion: '1' } })
|
||||
})
|
||||
it('never renders JSON errors or empty bytes as a photo', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue(new Blob([JSON.stringify({ code: 'A0403', message: '拒绝读取', requestId: 'request', traceId: 'trace' })], { type: 'application/json' }))
|
||||
await expect(getOwnedBusinessPhotoContent('DS-OWN-1', photo)).rejects.toMatchObject({ code: 'A0403', requestId: 'request', traceId: 'trace' })
|
||||
vi.mocked(http.get).mockResolvedValue(new Blob([], { type: 'image/png' })); await expect(getOwnedBusinessPhotoContent('DS-OWN-1', photo)).rejects.toThrow('为空')
|
||||
await expect(uploadOwnedBusinessPhoto('DS-OWN-1','FUEL_START',new File(['text'],'bad.txt',{type:'text/plain'}),'key')).rejects.toThrow('JPG')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
import axios from 'axios'
|
||||
import { http, unwrapApiResponse, ApiResponseError, type ApiEnvelope } from '@/shared/api/http'
|
||||
import { ownedBusinessDecimal, ownedBusinessVersion, type OwnedBusinessOperations, type OwnedBusinessRow, type OwnedBusinessDetail, type OwnedBusinessList, type OwnedBusinessQuery, type OwnedBusinessSave, type OwnedBusinessBind, type OwnedBusinessPhoto, type OwnedBusinessPhotoSlot, type OwnedBusinessCommand, type OwnedBusinessHistory, type OwnedBusinessPage } from '../ownedBusinessTypes'
|
||||
|
||||
const base = '/platform/v1/last-leg/fleet/owned-business'
|
||||
const path = (no: string) => `${base}/${encodeURIComponent(no)}`
|
||||
async function get<T>(url: string, params?: object): Promise<T> { return unwrapApiResponse(await http.get<ApiEnvelope<T>, ApiEnvelope<T>>(url, { params })) }
|
||||
function count(value: unknown): number { const text = ownedBusinessVersion(value); const result = Number(text); if (!Number.isSafeInteger(result)) throw new Error('运营记录数量超出精确范围'); return result }
|
||||
function decimal(value: string | null, scale: number, precision: number): string | null {
|
||||
if (value == null) return null
|
||||
if (typeof value !== 'string' || ownedBusinessDecimal(value, scale, precision) !== value) throw new Error('运营金额或测量必须使用精确十进制字符串')
|
||||
return value
|
||||
}
|
||||
function operations(value: OwnedBusinessOperations): OwnedBusinessOperations {
|
||||
if (value.money && !['CNY','USD'].includes(value.money.currency)) throw new Error('运营金额币种无效')
|
||||
return { ...value, money: value.money ? { ...value.money, amount: decimal(value.money.amount, 2, 18)! } : null, actualDistanceMiles: decimal(value.actualDistanceMiles,3,12), fuelConsumptionLitresPer100Km: decimal(value.fuelConsumptionLitresPer100Km,3,12) }
|
||||
}
|
||||
function row(value: OwnedBusinessRow): OwnedBusinessRow {
|
||||
if (!value.dispatchNo || !['AFTER_LOADING','DELIVERING','DELIVERED'].includes(value.stage) || value.vehicle?.ownership !== 'OWNED') throw new Error('自有排车来源或阶段不完整,请重新读取')
|
||||
return { ...value, operations: operations(value.operations), unitPrice: decimal(value.unitPrice,2,18), recordVersion: ownedBusinessVersion(value.recordVersion), dispatchRecordVersion: ownedBusinessVersion(value.dispatchRecordVersion), actualPalletCount: value.actualPalletCount == null ? null : count(value.actualPalletCount), photoSummary: { loadingCount: count(value.photoSummary.loadingCount), fuelCount: count(value.photoSummary.fuelCount) } }
|
||||
}
|
||||
function detail(value: OwnedBusinessDetail): OwnedBusinessDetail { if (value.row.dispatchNo !== value.dispatch.dispatchNo) throw new Error('运营资料与原排车单不一致'); return { ...value, row: row(value.row) } }
|
||||
function command(value: OwnedBusinessCommand): OwnedBusinessCommand { return { ...value, recordVersion: value.recordVersion == null ? null : ownedBusinessVersion(value.recordVersion) } }
|
||||
export async function listOwnedBusiness(query: OwnedBusinessQuery): Promise<OwnedBusinessList> {
|
||||
const value = await get<OwnedBusinessList>(base, query)
|
||||
return { ...value, records: value.records.map(row), page: count(value.page), size: count(value.size), total: count(value.total), summary: { dispatchCount: count(value.summary.dispatchCount), afterLoadingCount: count(value.summary.afterLoadingCount), deliveringCount: count(value.summary.deliveringCount), deliveredCount: count(value.summary.deliveredCount) } }
|
||||
}
|
||||
export async function getOwnedBusiness(no: string) { const value = detail(await get<OwnedBusinessDetail>(path(no))); if (value.row.dispatchNo !== no) throw new Error('运营资料与当前排车业务号不一致'); return value }
|
||||
export async function listOwnedBusinessHistory(no: string, page: number, size: number): Promise<OwnedBusinessPage<OwnedBusinessHistory>> {
|
||||
const value = await get<OwnedBusinessPage<OwnedBusinessHistory>>(`${path(no)}/history`, { page, size })
|
||||
return { ...value, records: value.records.map(record => ({ ...record, operations: record.operations ? operations(record.operations) : null, recordVersion: record.recordVersion == null ? null : ownedBusinessVersion(record.recordVersion), dispatchRecordVersion: record.dispatchRecordVersion == null ? null : ownedBusinessVersion(record.dispatchRecordVersion) })), page: count(value.page), size: count(value.size), total: count(value.total) }
|
||||
}
|
||||
export const getOwnedBusinessCommand = (no: string, key: string) => get<OwnedBusinessCommand>(`${path(no)}/commands/${encodeURIComponent(key)}`).then(command)
|
||||
export async function saveOwnedBusinessOperations(no: string, body: OwnedBusinessSave) {
|
||||
ownedBusinessVersion(body.recordVersion)
|
||||
const value = detail(unwrapApiResponse(await http.put<ApiEnvelope<OwnedBusinessDetail>, ApiEnvelope<OwnedBusinessDetail>>(`${path(no)}/operations`, body)))
|
||||
if (value.row.dispatchNo !== no) throw new Error('运营保存结果与原排车单不一致')
|
||||
return value
|
||||
}
|
||||
export async function uploadOwnedBusinessPhoto(no: string, slot: OwnedBusinessPhotoSlot, file: File, key: string) {
|
||||
if (!['image/jpeg','image/png'].includes(file.type) || file.size <= 0) throw new Error('请选择有效的JPG或PNG图片')
|
||||
const form = new FormData(); form.append('file', file); form.append('idempotencyKey', key)
|
||||
const value = unwrapApiResponse(await http.post<ApiEnvelope<OwnedBusinessPhoto>, ApiEnvelope<OwnedBusinessPhoto>>(`${path(no)}/photos/${slot}/uploads`, form))
|
||||
if (value.slot !== slot || !value.fileId) throw new Error('上传文件与原照片分类不一致')
|
||||
return value
|
||||
}
|
||||
export async function bindOwnedBusinessPhoto(no: string, slot: OwnedBusinessPhotoSlot, body: OwnedBusinessBind) {
|
||||
ownedBusinessVersion(body.recordVersion)
|
||||
const value = detail(unwrapApiResponse(await http.put<ApiEnvelope<OwnedBusinessDetail>, ApiEnvelope<OwnedBusinessDetail>>(`${path(no)}/photos/${slot}`, body)))
|
||||
if (value.row.dispatchNo !== no) throw new Error('照片绑定结果与原排车单不一致')
|
||||
return value
|
||||
}
|
||||
async function downloadError(payload: unknown, status: number) {
|
||||
let value = payload
|
||||
if (payload instanceof Blob && payload.type.includes('json')) { try { value = JSON.parse(await payload.text()) as unknown } catch { throw new Error('图片接口返回了无法识别的错误') } }
|
||||
if (value && typeof value === 'object' && 'code' in value) { const error = value as ApiEnvelope<unknown>; throw new ApiResponseError(error.message || '图片读取失败', error.code, status, error.data, error.requestId, error.traceId) }
|
||||
}
|
||||
export async function getOwnedBusinessPhotoContent(no: string, photo: OwnedBusinessPhoto, revisionVersion?: string): Promise<Blob> {
|
||||
if (revisionVersion != null && BigInt(ownedBusinessVersion(revisionVersion)) < 1n) throw new Error('历史图片版本必须大于零')
|
||||
try {
|
||||
const blob = await http.get<Blob, Blob>(`${path(no)}/photos/${photo.slot}/files/${encodeURIComponent(photo.fileId)}/content`, { responseType: 'blob', params: revisionVersion == null ? undefined : { revisionVersion: ownedBusinessVersion(revisionVersion) } })
|
||||
await downloadError(blob, 200)
|
||||
if (!(blob instanceof Blob) || !['image/jpeg','image/png'].includes(blob.type) || !blob.size) throw new Error('图片内容为空或格式无效')
|
||||
return blob
|
||||
} catch (cause) { if (axios.isAxiosError(cause)) await downloadError(cause.response?.data, cause.response?.status || 0); throw cause }
|
||||
}
|
||||
Reference in New Issue
Block a user